示例#1
0
        private Compilation AddProjectReferences(IExecutionContext context, List <ISymbol> symbols, Compilation compilation)
        {
            // Generate a single Workspace and add all of the projects to it
            StringWriter        log          = new StringWriter();
            AnalyzerManager     manager      = new AnalyzerManager(log);
            AdhocWorkspace      workspace    = new AdhocWorkspace();
            IEnumerable <IFile> projectFiles = context.FileSystem.GetInputFiles(_projectGlobs)
                                               .Where(x => x.Path.Extension == ".csproj" && x.Exists);
            List <Project> projects = new List <Project>();

            foreach (IFile projectFile in projectFiles)
            {
                Project project = workspace.CurrentSolution.Projects.FirstOrDefault(x => new FilePath(x.FilePath).Equals(projectFile.Path));
                if (project != null)
                {
                    Trace.Verbose($"Project {projectFile.Path.FullPath} was already in the workspace");
                }
                else
                {
                    Trace.Verbose($"Creating workspace project for {projectFile.Path.FullPath}");
                    ProjectAnalyzer analyzer = manager.GetProject(projectFile.Path.FullPath);
                    ReadWorkspace.CompileProjectAndTrace(analyzer, log);
                    project = analyzer.AddToWorkspace(workspace);
                    if (!project.Documents.Any())
                    {
                        Trace.Warning($"Project at {projectFile.Path.FullPath} contains no documents, which may be an error (check previous log output for any MSBuild warnings)");
                    }
                }
                projects.Add(project);
            }
            compilation = AddProjectReferences(projects, symbols, compilation);
            return(compilation);
        }
示例#2
0
        public void Exec(string projectFilePath)
        {
            //string projectFilePath = @"C:\Users\USER\source\repos\ClassLibrary1\ClassLibrary1\ClassLibrary1.csproj";
            string          projectDirectory = Path.GetDirectoryName(projectFilePath);
            var             manager          = new AnalyzerManager();
            ProjectAnalyzer analyzer         = manager.GetProject(projectFilePath);

            using (var workspace = new AdhocWorkspace())
            {
                Project roslynProject = analyzer.AddToWorkspace(workspace);
                if (roslynProject.Language != LanguageNames.CSharp)
                {
                    throw new NotSupportedException($"The language: {roslynProject.Language} is not supported.");
                }

                var                        sourceCode    = "namespace Foo{public class Foo{ }}";
                Compilation                compilation   = roslynProject.GetCompilationAsync().Result;
                SyntaxTree                 stree         = CSharpSyntaxTree.ParseText(sourceCode);
                SyntaxNode                 root          = stree.GetCompilationUnitRoot();
                UsingDirectiveSyntax[]     usings        = (root as CompilationUnitSyntax).Usings.ToArray();
                NamespaceDeclarationSyntax namespaceNode = root.DescendantNodes().OfType <NamespaceDeclarationSyntax>().FirstOrDefault();
                root = namespaceNode.WithName(SyntaxFactory.ParseName(compilation.GetEntryPoint(System.Threading.CancellationToken.None).ContainingNamespace.ToString()));
                root = (root as NamespaceDeclarationSyntax).AddUsings(usings);
                string fileName = GetFileName(root);
                fileName = Path.ChangeExtension(fileName, "cs");
                string filePath = Path.Combine(projectDirectory, fileName);
                File.WriteAllText(filePath, root.ToFullString());

                var documentId = DocumentId.CreateNewId(roslynProject.Id);
                var docInfo    = DocumentInfo.Create(documentId, fileName, filePath: filePath);
                //await _addDocumentToProjectService.AddDocumentToProject(docInfo, projectFilePath).ConfigureAwait(false);
            }
        }
示例#3
0
        static void Main(string project, string[] transformers)
        {
            AnalyzerManager manager   = new AnalyzerManager();
            ProjectAnalyzer analyzer  = manager.GetProject(project);
            AdhocWorkspace  workspace = new AdhocWorkspace();

            analyzer.SetGlobalProperty("BuildingFromCodeGeneration", "true");
            var Project = analyzer.AddToWorkspace(workspace, true);

            if (Project is null)
            {
                throw new ArgumentException($"Project is null. ({project})");
            }
            var resolver = new CSharpAutofacResolver();
            var Engine   = new CSharpCodeGenerationEngine(Project, resolver);

            foreach (var item in transformers)
            {
                var assembly    = LoadAssembly(item);
                var transformer = LoadTransformer(assembly, Engine);
                transformer.Transform();
            }
            var changes = Engine.CurrentProject.GetChanges(Project);

            Procces(Engine, project, changes.GetAddedDocuments(), "Added");
            var changedDocs = changes.GetChangedDocuments(false).Where(x => Engine.CurrentProject.GetDocument(x).GetTextChangesAsync(Project.GetDocument(x)).Result.Any());

            Procces(Engine, project, changedDocs, "Updated");
        }
示例#4
0
        public static Task <CodeGenerator> CreateAsync(string projectFilePath)
        {
            AnalyzerManager manager   = new AnalyzerManager();
            ProjectAnalyzer analyzer  = manager.GetProject(projectFilePath);
            AdhocWorkspace  workspace = new AdhocWorkspace();
            Project         project   = analyzer.AddToWorkspace(workspace);

            return(Task.FromResult(new CodeGenerator(project)));
        }
示例#5
0
        public Workspace LoadWorkspace(IEnumerable <string> projectFilePaths)
        {
            var workspace = new AdhocWorkspace();

            foreach (var filePath in projectFilePaths)
            {
                ProjectAnalyzer analyzer = _analyzerManager.GetProject(filePath);
                analyzer.AddToWorkspace(workspace);
            }

            return(workspace);
        }
        public async Task LoadAndAnalyzeProjectAsync(FileInfo projectFile, FileInfo configFileInfo, AnalyzerReport report)
        {
            AnalyzerManager manager  = new AnalyzerManager();
            ProjectAnalyzer analyzer = manager.GetProject(projectFile.FullName);

            AdhocWorkspace workspace = new AdhocWorkspace();
            Project        project   = analyzer.AddToWorkspace(workspace);

            var analyzerDictionary = LoadConfigFile(configFileInfo);
            var analyzers          = this.GetAnalyzers(analyzerDictionary);

            await AnalyzeProject(project, analyzers, report);
        }
示例#7
0
        private static Project GetProject()
        {
            var             projectPath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "Examples", "CommandTests", "CommandTests.csproj"));
            AnalyzerManager manager     = new AnalyzerManager();
            ProjectAnalyzer analyzer    = manager.GetProject(projectPath);
            AdhocWorkspace  workspace   = new AdhocWorkspace();

            analyzer.AddBinaryLogger("binarylogtests.binlog");
            var project = analyzer.AddToWorkspace(workspace);

            if (project is null || !project.HasDocuments)
            {
                throw new Exception("Error loading project, check binarylogtests.binlog file for errors.");
            }
            return(project);
        }
示例#8
0
        private Microsoft.CodeAnalysis.Project GetRoslynProject(GenProject genProject)
        {
            string proj        = genProject.GenProjSetting.Project;
            var    analyzerKey = _analyzerManager.Projects.Keys
                                 .FirstOrDefault(key => key.Contains($"{proj}.csproj"));

            if (analyzerKey == null)
            {
                throw new InvalidOperationException($"Project: {proj} not found.");
            }

            ProjectAnalyzer analyzer = _analyzerManager.Projects[analyzerKey];

            Microsoft.CodeAnalysis.Project roslynProject = analyzer.AddToWorkspace(_workspace);
            return(roslynProject);
        }