Exemple #1
0
        public List <string> GetCSCodeFiles(string projPath)
        {
            AnalyzerManager manager = new AnalyzerManager();
            var             pro     = manager.GetProject(projPath);

            var pro2 = pro.Load();

            List <string> outP = new List <string>()
            {
            };

            foreach (var item in pro2.Items)
            {
                if (item.ItemType == "Compile")
                {
                    outP.Add(item.EvaluatedInclude);
                }
            }

            return(outP);
        }
Exemple #2
0
        public DependencyGraph Analyze(string projectPath, string framework = null)
        {
            var analyzerManager = new AnalyzerManager(new AnalyzerManagerOptions
            {
                LoggerFactory = _loggerFactory
            });

            if (string.IsNullOrWhiteSpace(projectPath))
            {
                throw new ArgumentException(nameof(projectPath));
            }

            if (!File.Exists(projectPath))
            {
                throw new ArgumentException("Project path does not exist.", nameof(projectPath));
            }

            var projectAnalyzer = analyzerManager.GetProject(projectPath);

            return(CreateBuilder(projectAnalyzer, projectPath, null, framework).Build());
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var analyzerManager = new AnalyzerManager();
            var projectAnalyzer = analyzerManager.GetProject(@"D:\workshop\ConsoleApp1\ConsoleApp1\ConsoleApp1.csproj");

            var analyzerResults = projectAnalyzer.Build().First();

            Console.WriteLine($"{analyzerResults.References.Length} references");
            Console.WriteLine($"{analyzerResults.SourceFiles.Length} source files");

            Console.WriteLine();
            foreach (var file in analyzerResults.SourceFiles)
            {
                Console.WriteLine(file);
            }

            var workspace = projectAnalyzer.GetWorkspace();

            var project     = workspace.CurrentSolution.Projects.First();
            var compilation = project.GetCompilationAsync().Result;

            var diagnostics = compilation.GetDiagnostics();

            foreach (var error in diagnostics.Where(l => l.Severity > DiagnosticSeverity.Hidden))
            {
                Console.WriteLine(error);
            }

            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                var root = (CompilationUnitSyntax)syntaxTree.GetRoot();
                var text = root.GetText();

                Console.WriteLine();
                Console.WriteLine(Path.GetFileName(syntaxTree.FilePath));
                Console.WriteLine(text.GetSubText(root.Span));

                var semanticModel = compilation.GetSemanticModel(syntaxTree);
            }
        }
Exemple #4
0
        private AnalyzerResult Build(AnalyzerManager manager, Project project, string?tfm)
        {
            _console.Write("   -> Analyzing ");
            _console.ForegroundColor = ConsoleColor.Cyan;
            _console.Write(project.Name);
            _console.ResetColor();

            if (!string.IsNullOrWhiteSpace(tfm))
            {
                _console.ForegroundColor = ConsoleColor.DarkGray;
                _console.Write(" (");
                _console.Write(tfm);
                _console.Write(")");
                _console.ResetColor();
                _console.WriteLine();
            }

            var projectAnalyzer = manager.GetProject(project.Path);
            var results         = (IEnumerable <AnalyzerResult>)projectAnalyzer.Build();

            if (!string.IsNullOrWhiteSpace(tfm))
            {
                var closest = results.GetNearestFrameworkMoniker(tfm);
                results = results.Where(p => p.TargetFramework.Equals(closest, StringComparison.OrdinalIgnoreCase));
            }

            var result = results.FirstOrDefault();

            if (string.IsNullOrWhiteSpace(tfm))
            {
                _console.ForegroundColor = ConsoleColor.DarkGray;
                _console.Write(" (");
                _console.Write(result.TargetFramework);
                _console.ForegroundColor = ConsoleColor.DarkGray;
                _console.WriteLine(")");
                _console.ResetColor();
            }

            return(result);
        }
Exemple #5
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(new AnalyzerManagerOptions
            {
                LogWriter = 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);
                    if (context.Bool(CodeAnalysisKeys.OutputBuildLog))
                    {
                        analyzer.WithBinaryLog();
                    }
                    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);
        }
Exemple #6
0
        protected async Task <AnalyzerResult> DesignTimeBuild()
        {
            using (var operation = _log.OnEnterAndConfirmOnExit())
            {
                AnalyzerResult result;
                var            csProj    = this.GetProjectFile();
                var            logWriter = new StringWriter();

                using (await FileLock.TryCreateAsync(Directory))
                {
                    var manager = new AnalyzerManager(new AnalyzerManagerOptions
                    {
                        LogWriter = logWriter
                    });
                    var analyzer = manager.GetProject(csProj.FullName);
                    analyzer.AddBinaryLogger(Path.Combine(Directory.FullName, DesignTimeBuildBinlogFileName));
                    var languageVersion = csProj.SuggestedLanguageVersion();
                    analyzer.SetGlobalProperty("langVersion", languageVersion);
                    result = analyzer.Build().Results.First();
                }

                DesignTimeBuildResult = result;
                LastDesignTimeBuild   = Clock.Current.Now();
                if (result.Succeeded == false)
                {
                    var logData = logWriter.ToString();
                    File.WriteAllText(
                        LastBuildErrorLogFile.FullName,
                        string.Join(Environment.NewLine, "Design Time Build Error", logData));
                }
                else if (LastBuildErrorLogFile.Exists)
                {
                    LastBuildErrorLogFile.Delete();
                }

                operation.Succeed();

                return(result);
            }
        }
 static void Main(string[] args)
 {
     try
     {
         System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += (ctx, name) =>
         {
             Console.WriteLine($"asm name={name}");
             return(null);
         };
         // another workaround, read required assemblies before compile.
         foreach (var dllname in new string[] { "NuGet.Versioning", "NuGet.Common", "NuGet.Frameworks" })
         {
             const string sdkdir = @"C:\Program Files\dotnet\sdk\2.1.300";
             System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(sdkdir, $"{dllname}.dll"));
         }
         var manageropts = new AnalyzerManagerOptions();
         manageropts.LogWriter       = Console.Out;
         manageropts.LoggerVerbosity = LoggerVerbosity.Normal;
         var manager  = new AnalyzerManager(manageropts);
         var analyzer = manager.GetProject(args[0]);
         var project  = analyzer.Compile();
         if (project != null)
         {
             foreach (var x in project.Items)
             {
                 var meta = x.Metadata.Select(y => $"{y.Name}={y.EvaluatedValue}");
                 Console.WriteLine($"{x.ItemType},{string.Join("|", meta)}");
             }
         }
         else
         {
             Console.WriteLine($"project instance is null");
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"{e}");
     }
 }
Exemple #8
0
        public static async Task <Compilation> GetCompilationFromProject(string csprojPath, params string[] preprocessorSymbols)
        {
            var analyzerOptions = new AnalyzerManagerOptions();
            // analyzerOptions.LogWriter = Console.Out;

            var manager         = new AnalyzerManager();
            var projectAnalyzer = manager.GetProject(csprojPath); // addproj
            // projectAnalyzer.AddBuildLogger(new Microsoft.Build.Logging.ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity.Minimal));

            var workspace = manager.GetWorkspaceWithPreventBuildEvent();

            workspace.WorkspaceFailed += WorkSpaceFailed;
            var project = workspace.CurrentSolution.Projects.First();

            project = project
                      .WithParseOptions((project.ParseOptions as CSharpParseOptions).WithPreprocessorSymbols(preprocessorSymbols))
                      .WithCompilationOptions((project.CompilationOptions as CSharpCompilationOptions).WithAllowUnsafe(true));

            var compilation = await project.GetCompilationAsync().ConfigureAwait(false);

            return(compilation);
        }
Exemple #9
0
        public Task <IProjectInfo> ReadProjectAsync(string path, IProgress <string> progress)
        {
            return(Task.Run <IProjectInfo>(() =>
            {
                var analyzerManager = new AnalyzerManager();

                // TODO: This should add debug symbols to the build, which we can then access
                // via Cecil according to https://github.com/jbevain/cecil/wiki/Debug-symbols
                analyzerManager.SetGlobalProperty("Configuration", "Debug");

                var projectAnalyzer = analyzerManager.GetProject(path);
                progress.Report($"Building {Path.GetFileName(path)}");
                var analyzerResult = projectAnalyzer.Build(new EnvironmentOptions
                {
                    DesignTime = false,
                    Restore = true
                })
                                     .First();

                return new ProjectInfo(analyzerResult);
            }));
        }
Exemple #10
0
        private static async Task RunAsync(string projectPath, CancellationToken cancellationToken)
        {
            var converters = new ConverterBase[]
            {
                new MSTestToXUnitConverter(),
                new TestAssertTrueOrFalseConverter(),
                new AssertArgumentOrderConverter(),
            };

            AnalyzerManager manager          = new AnalyzerManager();
            ProjectAnalyzer analyzer         = manager.GetProject(projectPath);
            Encoding        s_utf8WithoutBom = new UTF8Encoding(false);

            using (var workspace = analyzer.GetWorkspace())
            {
                var originalSolution = workspace.CurrentSolution;
                var project          = originalSolution.Projects.FirstOrDefault();
                foreach (var converter in converters)
                {
                    var newSolution = await converter.ProcessAsync(project, cancellationToken);

                    newSolution.GetChanges(originalSolution).GetProjectChanges().ToList().ForEach(proj =>
                    {
                        var changedDocumentIds = proj.GetChangedDocuments(true).ToList();
                        changedDocumentIds.ForEach(documentId =>
                        {
                            var document = newSolution.GetDocument(documentId);
                            var text     = document.GetTextAsync();
                            using (var writer = new StreamWriter(document.FilePath, append: false, encoding: text.Result.Encoding ?? s_utf8WithoutBom))
                            {
                                text.Result.Write(writer);
                            }
                        });
                    });
                    //workspace.TryApplyChanges(project.Solution);
                }
            }
        }
Exemple #11
0
        public async Task <Compilation> CompileAsync()
        {
            var manager = new AnalyzerManager();
            var project = manager.GetProject(testProjectCsproj);

            var workspace     = new AdhocWorkspace();
            var roslynProject = project.AddToWorkspace(workspace);
            var compilation   = await roslynProject.GetCompilationAsync();

            var diagnostics = compilation.GetDiagnostics();

            foreach (var diagnostic in diagnostics)
            {
                testContext.WriteLine(diagnostic.GetMessage());
            }

            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                Assert.Fail("Test project build failed!");
            }

            return(compilation);
        }
        public ConfigurationReader(string configurationProjectDirectory)
        {
            if (!Directory.Exists(configurationProjectDirectory))
            {
                throw new ArgumentException($"Directory {configurationProjectDirectory} does not exist");
            }

            var csProjPath = Directory.EnumerateFiles(configurationProjectDirectory, "*.csproj").SingleOrDefault();

            if (string.IsNullOrEmpty(csProjPath))
            {
                throw new ArgumentException($"Could not find csproj file in {configurationProjectDirectory} directory");
            }

            var manager  = new AnalyzerManager();
            var analyzer = manager.GetProject(csProjPath);

            analyzer.SetGlobalProperty("IsRunningHotPathAllocationAnalyzerConfiguration", "true");

            var workspace = new AdhocWorkspace();

            _configurationProject = analyzer.AddToWorkspace(workspace);
        }
        public void CompilesProject(EnvironmentPreference preference, string solutionPath, string projectPath)
        {
            // Given
            StringWriter    log     = new StringWriter();
            AnalyzerManager manager = new AnalyzerManager(solutionPath, new AnalyzerManagerOptions
            {
                LogWriter       = log,
                LoggerVerbosity = Verbosity
            });
            ProjectAnalyzer    analyzer = manager.GetProject(projectPath);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // Set some enviornment variables to make it seem like we're not in a CI build
            // Sometimes this messes up libraries like SourceLink since we're building as part of a test and not for CI
            options.EnvironmentVariables.Add("APPVEYOR", "False");
            options.EnvironmentVariables.Add("ContinuousIntegrationBuild", null);
            options.EnvironmentVariables.Add("CI", "False");
            options.EnvironmentVariables.Add("CI_LINUX", "False");
            options.EnvironmentVariables.Add("CI_WINDOWS", "False");

            // When
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj");
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin");
            analyzer.IgnoreFaultyImports = false;
            if (BinaryLog)
            {
                analyzer.AddBinaryLogger($@"E:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog");
            }
            AnalyzerResults results = analyzer.Build(options);

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.ShouldAllBe(x => x.OverallSuccess, log.ToString());
        }
Exemple #14
0
        /// <summary>
        /// Creates the project info from the msBuild project
        /// </summary>
        /// <param name="msBuildProj">The ms Build project</param>
        /// <returns>The project info</returns>
        protected override ProjectInfo CreateProjectInfo(MsBuild.Project msBuildProj)
        {
            AnalyzerManager mgr          = new AnalyzerManager();
            ProjectAnalyzer projAnalyzer = mgr.GetProject(ProjectPath);
            AdhocWorkspace  workspace    = projAnalyzer.GetWorkspace(true);          // This doesn't seems to work either way
            Project         proj         = workspace.CurrentSolution.Projects.First();

            StringBuilder builder = new StringBuilder();

            IEnumerable <MsBuild.ProjectItem> compile = msBuildProj.Items.Where(itm => itm.ItemType == "Compile");

            foreach (MsBuild.ProjectItem item in compile)
            {
                builder.Append($"{item.EvaluatedInclude} ");
            }

            // /out provides a name
            builder.Append($"/out:{new FileInfo(msBuildProj.FullPath).Name} ");

            // target: TODO: What does this do?
            builder.Append("/target:library ");

            ProjectInfo info = CommandLineProject.CreateProjectInfo(
                proj.Name,
                LanguageNames.CSharp,
                CommandLineParser.SplitCommandLineIntoArguments(builder.ToString(), true),
                msBuildProj.DirectoryPath,
                null);

            // Add the references found by buildalyzer
            info = info.WithFilePath(msBuildProj.FullPath)
                   .WithMetadataReferences(proj.MetadataReferences)
                   .WithAnalyzerReferences(proj.AnalyzerReferences);


            return(info);
        }
Exemple #15
0
        private static void RunGeneration(string[] args, string projectPath)
        {
            AnalyzerManager  mgr          = new AnalyzerManager();
            IProjectAnalyzer projAnalyzer = mgr.GetProject(projectPath);

            using (Workspace workspace = projAnalyzer.GetWorkspace(true))
            {
                ProjectId mainProjId = workspace.CurrentSolution.Projects
                                       .Where(pr => pr.FilePath == projectPath).FirstOrDefault()?.Id;
                ProjectParser   parser = new ProjectParser(workspace, mainProjId);
                ScriptGenEngine engine = new ScriptGenEngine();
                var             result = engine.GenerateScripts(new ScriptGenerationParameters()
                {
                    ProjectPath  = projectPath,
                    TypeIterator = parser,
                    Force        = args.HasSwitch(ForceSwitch)
                });

                if (!result.Success)
                {
                    Console.WriteLine(result.ErrorMessage);
                }
            }
        }
Exemple #16
0
        static async Task Main(string[] args)
        {
            var manager   = new AnalyzerManager();
            var analyzer  = manager.GetProject("tests/MyApp1/MyApp1.csproj");
            var rs        = analyzer.GetWorkspace();
            var workspace = new AdhocWorkspace();

            analyzer.AddToWorkspace(workspace);

            var project = workspace.CurrentSolution.Projects.First();
            var docs    = project.Documents;

            foreach (var item in docs)
            {
                Console.WriteLine(item.FilePath);
            }

            var deps = project.MetadataReferences;

            foreach (var item in deps)
            {
                Console.WriteLine(item.Display);
            }
        }
Exemple #17
0
        private async Task OnExecute()
        {
            var logger = new Logger();

            // Load C# project

            var manager   = new AnalyzerManager();
            var analyzer  = manager.GetProject(Project);
            var workspace = analyzer.GetWorkspace();
            var project   = workspace.CurrentSolution.Projects.First();

            // Code generation

            var translator = new Translator();
            var generator  = new Generator(translator, logger)
            {
                PythonDir = this.PythonDir
            };
            var newProject = await generator.Generate(project);

            // Save project changes

            // NB : This should work to save changes? Maybe isn't implemented with Buildalyzer?
            // bool success = workspace.TryApplyChanges(newProject.Solution);

            var projectChanges = newProject.GetChanges(project);

            foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
            {
                var document     = newProject.GetDocument(changedDocumentId);
                var documentRoot = await document.GetSyntaxRootAsync();

                var code = documentRoot.ToFullString();
                File.WriteAllText(document.FilePath, code);
            }
        }
Exemple #18
0
        static IEnumerable <string> CreateJsonRefList()
        {
            var projPath = Path.Combine(Helper.ProjectFolder, "src", "ReamQuery.Server", "ReamQuery.Server.csproj");

            Console.WriteLine("Project file: {0} (exists: {1})", projPath, File.Exists(projPath));
            var lf = new LoggerFactory();

            lf.AddConsole();
            var manager  = new AnalyzerManager(lf, LoggerVerbosity.Minimal);
            var analyzer = manager.GetProject(projPath);

            analyzer.Load();
            var refs = analyzer.GetReferences();

            if (refs.Count() != refs.Distinct().Count())
            {
                throw new InvalidOperationException("Unexpected duplicates");
            }
            var json     = JsonConvert.SerializeObject(refs.Select(x => Path.GetFileName(x)), Formatting.Indented);
            var jsonPath = Path.Combine(Helper.ProjectFolder, "src", "ReamQuery.Resources", "ReferenceList.json");

            File.WriteAllText(jsonPath, json);
            return(refs);
        }
Exemple #19
0
        private static async Task PerformMigration(CliOptions options)
        {
            if (string.IsNullOrEmpty(options.SolutionPath) &&
                string.IsNullOrEmpty(options.MigrationPath))
            {
                Console.WriteLine("Either project or sulution path must be provided.");
                return;
            }

            var workspace = new AdhocWorkspace();

            if (!string.IsNullOrEmpty(options.SolutionPath))
            {
                Console.WriteLine("Loading solution:");
                var manager = new AnalyzerManager(options.SolutionPath);
                foreach (var p in manager.Projects.Values)
                {
                    Console.WriteLine($"Loading project: {p.ProjectFile.Path}");
                    p.AddToWorkspace(workspace);
                }
            }
            else
            {
                Console.WriteLine("Loading project");
                var manager = new AnalyzerManager();
                manager.GetProject(options.ProjectPath).AddToWorkspace(workspace);
            }

            Console.WriteLine("Loading migration file");
            var migration = MigrationLoader.FromPath(options.MigrationPath);

            var timer = Stopwatch.StartNew();
            await Task.WhenAll(workspace.CurrentSolution.Projects.Select(async project =>
            {
                Console.WriteLine($"Migrating project {project.Name}");

                var compilation = (CSharpCompilation)await project.GetCompilationAsync();

                await Task.WhenAll(compilation.SyntaxTrees.Select(async tree =>
                {
                    var annotatedTree = tree.WithRootAndOptions(
                        new AnnotationVisitor().Visit(await tree.GetRootAsync()),
                        tree.Options);

                    compilation = compilation.ReplaceSyntaxTree(tree, annotatedTree);

                    if (options.Verbose)
                    {
                        Console.WriteLine("Running migration on " + tree.FilePath);
                    }

                    var context = new MigrationContext();
                    context.Populate(compilation, annotatedTree);

                    var ast = migration.Apply(annotatedTree, context);

                    if (ast != annotatedTree)
                    {
                        await File.WriteAllTextAsync(tree.FilePath, ast.ToString());
                    }
                }));
            }));

            Console.WriteLine("Migration took: " + timer.Elapsed);
        }
Exemple #20
0
        static async Task Main(string[] args)
        {
            // Buildalyzerのルート
            var manager = new AnalyzerManager();

            // slnを指定してまるっと持ってくるでもいいんですが、とりあえずcsproj単品で並べてみた。
            // 解析対象となる対象のプロジェクトと、参照としてのUniRxのプロジェクトを登録(Getすると同時に登録も行われるという仕様……)
            manager.GetProject(@"C:\***\UniRx.csproj");
            manager.GetProject(@"C:\***\UniRx.Async.csproj");
            manager.GetProject(@"C:\***\Assembly-CSharp.csproj");

            // 登録されたプロジェクト群からAdhocWorkspaceを作成
            var workspace     = manager.GetWorkspace();
            var targetProject = workspace.CurrentSolution.Projects.First(x => x.Name == "Assembly-CSharp");

            // コンパイル結果みたいなのを取得
            var compilation = await targetProject.GetCompilationAsync();

            // 比較対象の型シンボルをCompilationから持ってくる
            var observableSymbol = compilation.GetTypeByMetadataName("UniRx.Observable");

            // 収集
            var methods = new List <IMethodSymbol>();

            foreach (var tree in compilation.SyntaxTrees)
            {
                // Syntax -> Symbol変換するためのModelの取得
                var semanticModel = compilation.GetSemanticModel(tree);

                // シンタックスツリーからメソッド呼び出しだけを抜き出し
                var invocationExpressions = tree.GetRoot()
                                            .DescendantNodes()
                                            .OfType <InvocationExpressionSyntax>();

                foreach (var expr in invocationExpressions)
                {
                    // その中からUniRx.Observableに属するメソッドのみを抽出
                    var methodSymbol = semanticModel.GetSymbolInfo(expr).Symbol as IMethodSymbol;
                    if (methodSymbol?.ContainingType == observableSymbol)
                    {
                        methods.Add(methodSymbol);
                    }
                }
            }

            // 解析
            Console.WriteLine("## TotalCount:" + methods.Count);

            var grouping = methods
                           .Select(x => x.OriginalDefinition) // Foo -> Fooへ変換
                           .Select(x => x.Name)               // 今回はメソッド名だけ取る(オーバーロードの違いは無視)
                           .GroupBy(x => x)
                           .OrderByDescending(x => x.Count())
                           .Select(x => new { MethodName = x.Key, Count = x.Count() })
                           .ToArray();

            // マークダウンの表で出力
            Console.WriteLine("| メソッド名| 呼び出し数 |");
            Console.WriteLine("| --- | --- |");
            foreach (var item in grouping)
            {
                Console.WriteLine($"| {item.MethodName} | {item.Count} |");
            }
        }
        public DependencyGraph Analyze(string projectPath, string framework = null)
        {
            if (string.IsNullOrWhiteSpace(projectPath))
            {
                throw new ArgumentException(nameof(projectPath));
            }

            if (!File.Exists(projectPath))
            {
                throw new ArgumentException("Project path does not exist.", nameof(projectPath));
            }

            var analyzerManager = new AnalyzerManager(new AnalyzerManagerOptions
            {
                LoggerFactory = _loggerFactory
            });
            var projectAnalyzer = analyzerManager.GetProject(projectPath);

            var analyzeResults = string.IsNullOrEmpty(framework) ?
                                 projectAnalyzer.Build() : projectAnalyzer.Build(framework);

            var analyzerResult = string.IsNullOrEmpty(framework) ?
                                 analyzeResults.FirstOrDefault() : analyzeResults[framework];

            if (analyzerResult == null)
            {
                // Todo: Something went wrong, log and return better exception.
                throw new InvalidOperationException("Unable to load project.");
            }

            if (!analyzerResult.IsNetSdkProject())
            {
                // Todo: Support "legacy" projects in the future.
                throw new InvalidOperationException("Unable to load project.");
            }

            var projectAssetsFilePath = analyzerResult.GetProjectAssetsFilePath();

            if (!File.Exists(projectAssetsFilePath))
            {
                // Todo: Make sure this exists in future
                throw new InvalidOperationException($"{projectAssetsFilePath} not found. Please run 'dotnet restore'");
            }

            var lockFile = new LockFileFormat().Read(projectAssetsFilePath);

            var targetFramework = analyzerResult.GetTargetFramework();

            var libraries = lockFile.Targets.Single(x => x.TargetFramework == targetFramework)
                            .Libraries.Where(x => x.IsPackage()).ToList();

            var projectNode = new ProjectReferenceNode(projectPath);
            var builder     = new DependencyGraph.Builder(projectNode);

            var libraryNodes = new Dictionary <string, PackageReferenceNode>(StringComparer.OrdinalIgnoreCase);

            foreach (var library in libraries)
            {
                var libraryNode = library.ToNode();
                builder.WithNode(libraryNode);
                libraryNodes.Add(libraryNode.PackageId, libraryNode);

                if (library.FrameworkAssemblies.Count > 0)
                {
                    var assemblyNodes = library.FrameworkAssemblies
                                        .Select(x => new AssemblyReferenceNode($"{x}.dll"));
                    builder.WithNodes(assemblyNodes);
                    builder.WithEdges(assemblyNodes
                                      .Select(x => new Edge(libraryNode, x)));
                }

                if (library.RuntimeAssemblies.Count > 0)
                {
                    var assemblyNodes = library.RuntimeAssemblies
                                        .Select(x => new AssemblyReferenceNode(Path.GetFileName(x.Path)))
                                        .Where(x => x.Id != "_._");

                    if (assemblyNodes.Any())
                    {
                        builder.WithNodes(assemblyNodes);
                        builder.WithEdges(assemblyNodes
                                          .Select(x => new Edge(libraryNode, x)));
                    }
                }

                //if (library.CompileTimeAssemblies.Count > 0)
                //{
                //    var assemblyNodes = library.CompileTimeAssemblies
                //        .Select(x => new AssemblyReferenceNode(Path.GetFileName(x.Path)));
                //    builder.WithNodes(assemblyNodes);
                //    builder.WithEdges(assemblyNodes
                //        .Select(x => new Edge(libraryNode, x)));
                //}
            }

            foreach (var library in libraries)
            {
                var libraryNode = library.ToNode();

                if (library.Dependencies.Count > 0)
                {
                    builder.WithEdges(library.Dependencies
                                      .Select(x => new Edge(libraryNode, libraryNodes[x.Id], x.VersionRange.ToString())));
                }
            }

            builder.WithEdges(analyzerResult.GetItems("PackageReference")
                              .Select(x => new Edge(projectNode, libraryNodes[x.ItemSpec], x.Metadata["Version"])));

            var references = analyzerResult.References//GetItems("Reference")
                             .Select(x => new AssemblyReferenceNode(Path.GetFileName(x)));

            builder.WithNodes(references);
            builder.WithEdges(references.Select(x => new Edge(projectNode, x)));

            return(builder.Build());
        }
Exemple #22
0
        public void Build()
        {
            /* Uncomment the below code to debug issues with msbuild */

            /*var writer = new StreamWriter(Console.OpenStandardOutput());
             * writer.AutoFlush = true;
             *
             * Console.SetOut(writer);
             * Console.SetError(writer);*/

            if (IsSolutionFile())
            {
                Logger.LogInformation("Loading the Workspace (Solution): " + WorkspacePath);

                AnalyzerManager analyzerManager = new AnalyzerManager(WorkspacePath,
                                                                      new AnalyzerManagerOptions
                {
                    LogWriter = _writer
                });

                Logger.LogInformation("Loading the Solution Done: " + WorkspacePath);

                // AnalyzerManager builds the projects based on their dependencies
                // After this, code does not depend on Buildalyzer
                BuildSolution(analyzerManager);
            }
            else
            {
                AnalyzerManager analyzerManager = new AnalyzerManager(new AnalyzerManagerOptions
                {
                    LogWriter = _writer
                });

                var dict = new Dictionary <Guid, IAnalyzerResult>();
                using (AdhocWorkspace workspace = new AdhocWorkspace())
                {
                    Queue <string> queue    = new Queue <string>();
                    ISet <string>  existing = new HashSet <string>();

                    queue.Enqueue(WorkspacePath);
                    existing.Add(WorkspacePath);

                    /*
                     * We need to resolve all the project dependencies to avoid compilation errors.
                     * If we have compilation errors, we might miss some of the semantic values.
                     */
                    while (queue.Count > 0)
                    {
                        var path = queue.Dequeue();
                        Logger.LogInformation("Building: " + path);

                        IProjectAnalyzer projectAnalyzer = analyzerManager.GetProject(path);

                        if (!TryGetRequiresNetFramework(projectAnalyzer.ProjectFile, out bool requiresNetFramework))
                        {
                            continue;
                        }

                        IAnalyzerResults analyzerResults = projectAnalyzer.Build(GetEnvironmentOptions(requiresNetFramework, projectAnalyzer.ProjectFile.ToolsVersion));
                        IAnalyzerResult  analyzerResult  = analyzerResults.First();

                        if (analyzerResult == null)
                        {
                            FailedProjects.Add(new ProjectAnalysisResult()
                            {
                                ProjectAnalyzer = projectAnalyzer
                            });
                        }

                        dict[analyzerResult.ProjectGuid] = analyzerResult;
                        analyzerResult.AddToWorkspace(workspace);

                        foreach (var pref in analyzerResult.ProjectReferences)
                        {
                            if (!existing.Contains(pref))
                            {
                                existing.Add(pref);
                                queue.Enqueue(pref);
                            }
                        }
                    }

                    foreach (var project in workspace.CurrentSolution.Projects)
                    {
                        try
                        {
                            var result = dict[project.Id.Id];

                            var projectAnalyzer = analyzerManager.Projects.Values.FirstOrDefault(p =>
                                                                                                 p.ProjectGuid.Equals(project.Id.Id));

                            Projects.Add(new ProjectAnalysisResult()
                            {
                                Project         = project,
                                AnalyzerResult  = result,
                                ProjectAnalyzer = projectAnalyzer
                            });
                        }
                        catch (Exception ex)
                        {
                            Logger.LogDebug(ex.StackTrace);
                        }
                    }
                }
            }

            Logger.LogDebug(_sb.ToString());
            _writer.Flush();
            _writer.Close();
            ProcessLog(_writer.ToString());
        }
Exemple #23
0
        public List <ClassFileInfo> Deep()
        {
            List <ClassFileInfo> result = new List <ClassFileInfo>();

            var solutionFilePath = BuildWorkspaceHelper.GetRelativeWorkspacePath("Syinpo.Model\\Syinpo.Model.csproj");

            {
                //using( var work = MSBuildWorkspace.Create() ) {
                //    var project = work.OpenProjectAsync( solutionFilePath ).Result;
                //    var documents = project.Documents.Where( w => w.Name.EndsWith( ".cs" ) ).ToList();
                //}
            }

            AnalyzerManager manager   = new AnalyzerManager();
            var             analyzer  = manager.GetProject(solutionFilePath);
            AdhocWorkspace  workspace = analyzer.GetWorkspace();
            var             project   = workspace.CurrentSolution.Projects.First();
            var             documents = project.Documents.Where(w => w.Name.EndsWith(".cs")).ToList();

            foreach (var document in documents)
            {
                string fileName = document.Name;
                string filePath = document.FilePath;

                var classes  = document.GetSyntaxRootAsync().Result.DescendantNodes().OfType <ClassDeclarationSyntax>();
                var classes2 = document.GetSyntaxRootAsync().Result.DescendantNodes().ToList().OfType <EnumDeclarationSyntax>();

                if (classes.Any())
                {
                    foreach (var cl in classes)
                    {
                        NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;
                        if (!SyntaxNodeHelper.TryGetParentSyntax(cl, out namespaceDeclarationSyntax))
                        {
                            continue;
                        }

                        var namespaceName = namespaceDeclarationSyntax.Name.ToString();
                        var fullClassName = namespaceName + "." + cl.Identifier.ToString();

                        var keys = document.Folders.ToList();
                        keys.Add(fileName);
                        result.Add(new ClassFileInfo {
                            FileName      = fileName,
                            FilePath      = filePath,
                            ClassName     = cl.Identifier.ToString(),
                            FullClassName = fullClassName,
                            Key           = string.Join(@"/", keys.ToArray())
                        });
                    }
                }

                if (classes2.Any())
                {
                    foreach (var cl in classes2)
                    {
                        NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;
                        if (!SyntaxNodeHelper.TryGetParentSyntax(cl, out namespaceDeclarationSyntax))
                        {
                            continue;
                        }

                        var namespaceName = namespaceDeclarationSyntax.Name.ToString();
                        var fullClassName = namespaceName + "." + cl.Identifier.ToString();

                        var keys = document.Folders.ToList();
                        keys.Add(fileName);
                        result.Add(new ClassFileInfo {
                            FileName      = fileName,
                            FilePath      = filePath,
                            ClassName     = cl.Identifier.ToString(),
                            FullClassName = fullClassName,
                            Key           = string.Join(@"/", keys.ToArray())
                        });
                    }
                }

                #region Old
                if (false)
                {
                    SourceText text = document.GetTextAsync().Result;
                    var        span = TextSpan.FromBounds(0, text.Length);
                    IEnumerable <ClassifiedSpan> classifiedSpans = null;
                    try {
                        classifiedSpans = Classifier.GetClassifiedSpansAsync(document, span).Result;

                        IEnumerable <Range> ranges = classifiedSpans.Select(classifiedSpan => new Range(classifiedSpan, text.GetSubText(classifiedSpan.TextSpan).ToString()));

                        // var classes = ranges.Where(w => w.ClassificationType == "class name").ToList();
                    }
                    catch (Exception ex) {
                        throw new Exception("Exception during Classification of document: " + document.FilePath);
                    }
                }
                #endregion
            }


            return(result);
        }
Exemple #24
0
        private static Project Create(AnalyzerManager manager, Options options, string projectFile)
        {
            var analyzer       = manager.GetProject(projectFile);
            var msBuildProject = analyzer.Load();

            var assemblyFile = msBuildProject.GetItems("IntermediateAssembly").FirstOrDefault()?.EvaluatedInclude;

            if (assemblyFile == null)
            {
                // Not all projects may produce an assembly
                return(null);
            }

            var projectDirectory     = Path.GetDirectoryName(projectFile);
            var assemblyFileFullPath = Path.GetFullPath(Path.Combine(projectDirectory, assemblyFile));

            if (!File.Exists(assemblyFileFullPath))
            {
                // Can't analyze this project since it hasn't been built
                Console.WriteLine($"Assembly did not exist. Ensure you've previously built it. Assembly: {assemblyFileFullPath}");
                return(null);
            }

            var assembly = LoadAssembly(assemblyFileFullPath);

            if (assembly == null)
            {
                // Can't analyze this project since we couldn't load its assembly
                Console.WriteLine($"Assembly could not be loaded. Assembly: {assemblyFileFullPath}");
                return(null);
            }

            var assemblyReferences = assembly
                                     .GetReferencedAssemblies()
                                     .Select(name => name.Name)
                                     .ToHashSet(StringComparer.OrdinalIgnoreCase);

            var references = msBuildProject
                             .GetItems("Reference")
                             .Select(reference => reference.EvaluatedInclude)
                             .ToList();

            var projectReferences = msBuildProject
                                    .GetItems("ProjectReference")
                                    .Select(reference => reference.EvaluatedInclude)
                                    .Select(projectReference => GetProject(manager, options, Path.GetFullPath(Path.Combine(projectDirectory, projectReference))))
                                    .Where(dependency => dependency != null)
                                    .ToList();

            var packageReferences = msBuildProject
                                    .GetItems("PackageReference")
                                    .Select(reference => reference.EvaluatedInclude)
                                    .ToList();

            // Certain project types may require references simply to copy them to the output folder to satisfy transitive dependencies.
            if (NeedsTransitiveAssemblyReferences(msBuildProject))
            {
                projectReferences.ForEach(projectReference => assemblyReferences.UnionWith(projectReference.AssemblyReferences));
            }

            // Only bother doing a design-time build if there is a reason to
            var packageAssemblies = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);

            if (packageReferences.Count > 0)
            {
                if (options.MsBuildBinlog)
                {
                    analyzer.WithBinaryLog();
                }

                var msBuildCompiledProject = analyzer.Compile();

                var packageParents = msBuildCompiledProject.GetItems("_ActiveTFMPackageDependencies")
                                     .Where(package => !string.IsNullOrEmpty(package.GetMetadataValue("ParentPackage")))
                                     .GroupBy(
                    package =>
                {
                    var packageIdentity = package.EvaluatedInclude;
                    return(packageIdentity.Substring(0, packageIdentity.IndexOf('/')));
                },
                    package =>
                {
                    var parentPackageIdentity = package.GetMetadataValue("ParentPackage");
                    return(parentPackageIdentity.Substring(0, parentPackageIdentity.IndexOf('/')));
                },
                    StringComparer.OrdinalIgnoreCase)
                                     .ToDictionary(group => group.Key, group => group.ToList());

                var resolvedPackageReferences = msBuildCompiledProject.GetItems("Reference")
                                                .Where(reference => reference.GetMetadataValue("NuGetSourceType").Equals("Package", StringComparison.OrdinalIgnoreCase));
                foreach (var resolvedPackageReference in resolvedPackageReferences)
                {
                    var assemblyName = Path.GetFileNameWithoutExtension(resolvedPackageReference.EvaluatedInclude);

                    // Add the assembly to the containing package and all parent packages.
                    var seenParents = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                    var queue       = new Queue <string>();
                    queue.Enqueue(resolvedPackageReference.GetMetadataValue("NuGetPackageId"));
                    while (queue.Count > 0)
                    {
                        var packageId = queue.Dequeue();

                        if (!packageAssemblies.TryGetValue(packageId, out var assemblies))
                        {
                            assemblies = new List <string>();
                            packageAssemblies.Add(packageId, assemblies);
                        }

                        assemblies.Add(assemblyName);

                        if (packageParents.TryGetValue(packageId, out var parents))
                        {
                            foreach (var parent in parents)
                            {
                                if (seenParents.Add(parent))
                                {
                                    queue.Enqueue(parent);
                                }
                            }
                        }
                    }
                }
            }

            return(new Project
            {
                AssemblyName = assembly.GetName().Name,
                AssemblyReferences = assemblyReferences,
                References = references,
                ProjectReferences = projectReferences,
                PackageReferences = packageReferences,
                PackageAssemblies = packageAssemblies,
            });
        }
Exemple #25
0
        public void AddProject(string projectPath)
        {
            var projectAnalyzer = AnalyzerManager.GetProject(projectPath);

            projectAnalyzer.AddToWorkspace(Workspace, addProjectReferences: true);
        }
        public Task <int> OnExecuteAsync(CommandLineApplication app, CancellationToken cancellationToken)
        {
            bool isMSBuildFile;

            var path = ProjectPath;

            if (path == null)
            {
                path = Directory.GetCurrentDirectory();

                var projectFiles = Directory.EnumerateFiles(path, "*", SearchOption.TopDirectoryOnly)
                                   .Where(p => s_projectExtensionFilter.Contains(Path.GetExtension(p)))
                                   .Take(2)
                                   .ToArray();

                if (projectFiles.Length == 1)
                {
                    path          = projectFiles[0];
                    isMSBuildFile = true;
                }
                else
                {
                    isMSBuildFile = false;
                }
            }
            else
            {
                path          = Path.GetFullPath(path);
                isMSBuildFile = !Directory.Exists(path);
            }

            IEnumerable <string> filePaths;

            if (isMSBuildFile)
            {
                var originalWorkingDirectory = Environment.CurrentDirectory;
                Environment.CurrentDirectory = Path.GetDirectoryName(path) !;
                try
                {
                    // https://daveaglick.com/posts/running-a-design-time-build-with-msbuild-apis
                    var analyzerManager = new AnalyzerManager();
                    var project         = analyzerManager.GetProject(path);

                    var environmentOptions = new EnvironmentOptions();

                    if (Configuration != null)
                    {
                        environmentOptions.GlobalProperties["Configuration"] = Configuration;
                    }

                    Array.ForEach(RemainingArguments, arg => environmentOptions.Arguments.Add(arg));

                    IAnalyzerResult?analyzerResult;
                    if (TargetFramework != null)
                    {
                        var buildEnvironment = project.EnvironmentFactory.GetBuildEnvironment(TargetFramework, environmentOptions);
                        var analyzerResults  = project.Build(buildEnvironment);
                        analyzerResult = analyzerResults?.FirstOrDefault(result => result.TargetFramework == TargetFramework);
                        if (analyzerResult == null)
                        {
                            throw new CommandException($"Unable to load MSBuild file \"{path}\" using target framework '{TargetFramework}'.");
                        }
                    }
                    else
                    {
                        var buildEnvironment = project.EnvironmentFactory.GetBuildEnvironment(environmentOptions);
                        var analyzerResults  = project.Build(buildEnvironment);
                        analyzerResult = analyzerResults?.FirstOrDefault();
                        if (analyzerResult == null)
                        {
                            throw new CommandException($"Unable to load MSBuild file \"{path}\".");
                        }
                    }

                    var basePath = Path.GetDirectoryName(path) !;

                    if (!analyzerResult.Items.TryGetValue("Compile", out var compileItems))
                    {
                        compileItems = Array.Empty <ProjectItem>();
                    }

                    if (!analyzerResult.Items.TryGetValue("Content", out var contentItems))
                    {
                        contentItems = Array.Empty <ProjectItem>();
                    }

                    var projectItems = compileItems.Where(projectItem => s_compileExtensionFilter.Contains(Path.GetExtension(projectItem.ItemSpec)))
                                       .Concat(contentItems.Where(projectItem => s_contentExtensionFilter.Contains(Path.GetExtension(projectItem.ItemSpec))));

                    if (!IncludeLinks)
                    {
                        projectItems = projectItems.Where(projectItem => !projectItem.Metadata.Keys.Contains("Link"));
                    }

                    filePaths = projectItems
                                .Select(projectItem => Path.GetFullPath(Path.Combine(basePath, projectItem.ItemSpec)));
                }
                finally
                {
                    Environment.CurrentDirectory = originalWorkingDirectory;
                }
            }
            else
            {
                filePaths = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
                            .Where(p => s_extensionFilter.Contains(Path.GetExtension(p)));
            }

            foreach (var filePath in filePaths)
            {
                _context.Console.WriteLine(filePath);
            }

            return(Task.FromResult(0));
        }
Exemple #27
0
        public static async Task <Compilation> GetCompilationFromProject(string csprojPath, int verbosityLevel,
                                                                         Dictionary <string, string> additionalProperties,
                                                                         IEnumerable <string> conditionalSymbols)
        {
            conditionalSymbols = conditionalSymbols != null?
                                 conditionalSymbols.Where(x => !string.IsNullOrEmpty(x)).ToArray()
                                     :
                                     Enumerable.Empty <string>();

            // f*****g workaround of resolve reference...
            var externalReferences = new List <PortableExecutableReference>();

            {
                var locations = new List <string>();
                locations.Add(typeof(object).Assembly.Location);                 // mscorlib
                locations.Add(typeof(System.Linq.Enumerable).Assembly.Location); // core

                var xElem = XElement.Load(csprojPath);
                var ns    = xElem.Name.Namespace;

                var csProjRoot   = Path.GetDirectoryName(csprojPath);
                var framworkRoot = Path.GetDirectoryName(typeof(object).Assembly.Location);

                foreach (var item in xElem.Descendants(ns + "Reference"))
                {
                    var hintPath = item.Element(ns + "HintPath")?.Value;
                    if (hintPath == null)
                    {
                        var path = Path.Combine(framworkRoot, item.Attribute("Include").Value + ".dll");
                        locations.Add(path);
                    }
                    else
                    {
                        locations.Add(Path.Combine(csProjRoot, hintPath));
                    }
                }

                foreach (var item in locations.Distinct())
                {
                    if (File.Exists(item))
                    {
                        externalReferences.Add(MetadataReference.CreateFromFile(item));
                    }
                }
            }

            EnvironmentHelper.Setup();
            var analyzerOptions = new AnalyzerManagerOptions();

            if (verbosityLevel > 0)
            {
                analyzerOptions.LogWriter = Console.Out;
            }
            var manager         = new AnalyzerManager(analyzerOptions);
            var projectAnalyzer = manager.GetProject(csprojPath);

            projectAnalyzer.AddBuildLogger(new Microsoft.Build.Logging.ConsoleLogger(verbosityLevel.ToLoggerVerbosity()));
            var buildopts = new EnvironmentOptions();

            if (additionalProperties != null)
            {
                foreach (var kv in additionalProperties)
                {
                    buildopts.GlobalProperties[kv.Key] = kv.Value;
                    projectAnalyzer.SetGlobalProperty(kv.Key, kv.Value);
                }
            }
            if (conditionalSymbols.Any())
            {
                buildopts.GlobalProperties["DefineConstants"] = string.Join("%3b", conditionalSymbols);
            }
            var analyzerResults = projectAnalyzer.Build(buildopts);
            var analyzerResult  = analyzerResults.FirstOrDefault(x => x.Succeeded);

            if (analyzerResult == null)
            {
                throw new Exception("no succeeded analyzer result found");
            }
            var ws        = new AdhocWorkspace();
            var project   = analyzerResult.AddToWorkspace(ws);
            var parseopts = project.ParseOptions as CSharpParseOptions;

            if (parseopts != null)
            {
                var symbols = analyzerResult.Properties.ContainsKey("DefineConstants") ?
                              conditionalSymbols.Concat(
                    analyzerResult.Properties["DefineConstants"].Split(';')
                    ).OrderBy(x => x).Distinct()
                    :
                              conditionalSymbols
                ;
                project = project.WithParseOptions(parseopts.WithPreprocessorSymbols(symbols));
            }
            var compilation = await project.GetCompilationAsync().ConfigureAwait(false);

            return(compilation);
        }