Exemplo n.º 1
0
        public void BuildTargetFrameworkGetsSourceFiles()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log);

            // When
            IReadOnlyList <string> sourceFiles = analyzer.Build("net462").GetSourceFiles();

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            sourceFiles.Select(x => Path.GetFileName(x).Split('.').Reverse().Take(2).Reverse().First()).ShouldBe(new[]
            {
                "Class1",
                "AssemblyAttributes",
                "AssemblyInfo"
            }, true, log.ToString());

            // When
            log.GetStringBuilder().Clear();
            sourceFiles = analyzer.Build("netstandard2.0").GetSourceFiles();

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            sourceFiles.Select(x => Path.GetFileName(x).Split('.').Reverse().Take(2).Reverse().First()).ShouldBe(new[]
            {
                "Class2",
                "AssemblyAttributes",
                "AssemblyInfo"
            }, true, log.ToString());
        }
        public void CompilesProject(EnvironmentPreference preference, string solutionPath, string projectPath)
        {
            // Given
            StringWriter    log     = new StringWriter();
            AnalyzerManager manager = new AnalyzerManager(solutionPath, new AnalyzerManagerOptions
            {
                LogWriter = log
            });
            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;

#pragma warning disable 0162
            if (BinaryLog)
            {
                analyzer.AddBinaryLogger($@"E:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog");
            }
#pragma warning restore 0162

#if Is_Windows
            AnalyzerResults results = analyzer.Build(options);
#else
            // On non-Windows platforms we have to remove the .NET Framework target frameworks and only build .NET Core target frameworks
            // See https://github.com/dotnet/sdk/issues/826
            string[] excludedTargetFrameworks = new[] { "net2", "net3", "net4", "portable" };
            string[] targetFrameworks         = analyzer.ProjectFile.TargetFrameworks.Where(x => !excludedTargetFrameworks.Any(y => x.StartsWith(y))).ToArray();
            if (targetFrameworks.Length == 0)
            {
                Assert.Ignore();
            }
            AnalyzerResults results = analyzer.Build(targetFrameworks, options);
#endif

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.OverallSuccess.ShouldBeTrue(log.ToString());
            results.ShouldAllBe(x => x.Succeeded, log.ToString());
        }
Exemplo n.º 3
0
        public void GetsSourceFiles(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            IReadOnlyList <string> sourceFiles = analyzer.Build(options).First().SourceFiles;

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class1",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemplo n.º 4
0
        private IEnumerable <PackageReferenceInfo> LoadPackageReferences(ProjectAnalyzer projectAnalyzer)
        {
            AnalyzerResults project = projectAnalyzer.Build();

            var packageReferenceInfo = new List <PackageReferenceInfo>();
            var packagesRootFolder   = GetPackagesRootFolder();

            foreach (var result in project.Results)
            {
                packageReferenceInfo.AddRange(result.PackageReferences.Select(packageReference =>
                {
                    var packageId         = packageReference.Key;
                    var version           = packageReference.Value.First().Value;
                    var packageFolderPath = Path.Combine(packagesRootFolder, packageId.ToLower(), version.ToLower());

                    return(new PackageReferenceInfo(
                               packageId,
                               version,
                               rootFolderPath: packageFolderPath,
                               libSubfolderPath: "lib"));
                }));
            }

            return(packageReferenceInfo);
        }
Exemplo n.º 5
0
        public static MetadataReference[] GetMetadataReferencesFromSolution(FileInfo solution)
        {
            List <MetadataReference> ret = new List <MetadataReference>();

            //We are using Buildalyzer because it is xplat
            AnalyzerManager manager = new AnalyzerManager(solution.FullName);

            foreach (KeyValuePair <string, ProjectAnalyzer> proj in manager.Projects)
            {
                ProjectAnalyzer analyzer = proj.Value;
                analyzer.IgnoreFaultyImports = true;
                if (analyzer.ProjectFile.RequiresNetFramework)
                {
                    throw new Exception(
                              ".NET Framework Solutions not supported. Please use a .NET Core Solution instead.");
                }

                AnalyzerResults results = analyzer.Build();
                foreach (string filePath in results.SelectMany(s => s.References))//TODO - are these all references? Research needed
                {
                    if (!File.Exists(filePath))
                    {
                        Log.Warn("Library {0} is missing. Did you restore the Solution libraries?");
                    }
                    ret.Add(MetadataReference.CreateFromFile(filePath));
                }
            }

            return(ret.ToArray());
        }
Exemplo n.º 6
0
        public void MultiTargetingBuildAllTargetFrameworksGetsSourceFiles()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log);

            // When
            AnalyzerResults results = analyzer.Build();

            // Then
            results.Count.ShouldBe(2);
            results.TargetFrameworks.ShouldBe(new[] { "net462", "netstandard2.0" }, true, log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class1",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(results["net462"].SourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class2",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(results["netstandard2.0"].SourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemplo n.º 7
0
        public static FileInfo[] GetSourcesFromSolution(FileInfo solution)
        {
            List <FileInfo> ret = new List <FileInfo>();

            //We are using Buildalyzer because it is xplat
            AnalyzerManager manager = new AnalyzerManager(solution.FullName);

            foreach (KeyValuePair <string, ProjectAnalyzer> proj in manager.Projects)
            {
                ProjectAnalyzer analyzer = proj.Value;
                analyzer.IgnoreFaultyImports = true;
                if (analyzer.ProjectFile.RequiresNetFramework)
                {
                    throw new Exception(
                              ".NET Framework Solutions not supported. Please use a .NET Core Solution instead.");
                }

                AnalyzerResults results = analyzer.Build();
                foreach (string filePath in results.SelectMany(s => s.SourceFiles))
                {
                    if (!File.Exists(filePath))
                    {
                        Log.Warn("Source file {0} is missing.");
                    }
                    ret.Add(new FileInfo(filePath));
                }
            }

            return(ret.ToArray());
        }
Exemplo n.º 8
0
        public void MultiTargetingBuildAllTargetFrameworksGetsSourceFiles()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log);

            // When
            AnalyzerResults results = analyzer.Build();

            // Then
            results.Count.ShouldBe(2);
            results.TargetFrameworks.ShouldBe(new[] { "net462", "netstandard2.0" }, true, log.ToString());
            results["net462"].GetSourceFiles().Select(x => Path.GetFileName(x).Split('.').Reverse().Take(2).Reverse().First()).ShouldBe(new[]
            {
                "Class1",
                "AssemblyAttributes",
                "AssemblyInfo"
            }, true, log.ToString());
            results["netstandard2.0"].GetSourceFiles().Select(x => Path.GetFileName(x).Split('.').Reverse().Take(2).Reverse().First()).ShouldBe(new[]
            {
                "Class2",
                "AssemblyAttributes",
                "AssemblyInfo"
            }, true, log.ToString());
        }
Exemplo n.º 9
0
        public IEnumerable <FileInfo> GetSources(FileInfo solution)
        {
            List <FileInfo> ret = new List <FileInfo>();

            AnalyzerManager manager = new AnalyzerManager(solution.FullName);

            foreach (KeyValuePair <string, ProjectAnalyzer> proj in manager.Projects)
            {
                ProjectAnalyzer analyzer = proj.Value;
                analyzer.IgnoreFaultyImports = true;
                if (analyzer.ProjectFile.RequiresNetFramework)
                {
                    throw new Exception(
                              ".NET Framework Solutions not supported. Please use a .NET Core Solution instead.");
                }

                AnalyzerResults results = analyzer.Build();
                foreach (string filePath in results.SelectMany(s => s.SourceFiles))
                {
                    if (!File.Exists(filePath))
                    {
                        throw new Exception($"Source file {filePath} is missing!");
                    }
                    ret.Add(new FileInfo(filePath));
                }
            }

            return(ret);
        }
Exemplo n.º 10
0
        private static void RunDotNetCommand(string text, StringBuilder outputBuffer, StringBuilder errorBuffer)
        {
            if (!text.StartsWith("dotnet "))
            {
                throw new ArgumentException("Unexpected dotnet command: " + text, nameof(text));
            }

            using (Process dotnet = new Process())
            {
                dotnet.StartInfo.FileName               = "dotnet";
                dotnet.StartInfo.Arguments              = text.Substring("dotnet ".Length);
                dotnet.StartInfo.UseShellExecute        = false;
                dotnet.StartInfo.CreateNoWindow         = true;
                dotnet.StartInfo.RedirectStandardOutput = true;
                dotnet.StartInfo.RedirectStandardError  = true;
                dotnet.OutputDataReceived              += (sender, args) => outputBuffer.AppendLine(args.Data);
                dotnet.ErrorDataReceived += (sender, args) => errorBuffer.AppendLine(args.Data);
                dotnet.Start();
                dotnet.BeginOutputReadLine();
                dotnet.BeginErrorReadLine();

                dotnet.WaitForExit();

                dotnet.CancelOutputRead();
                dotnet.CancelErrorRead();
            }

            AnalyzerManager manager  = new AnalyzerManager();
            ProjectAnalyzer analyzer = manager.GetProject(@"C:\Users\wafuqua\.replay\ReplaySession20190302153809\Session\Session.csproj");
            var             result   = analyzer.Build();

            ;
        }
 private IReadOnlyCollection <MetadataReference> ReadProjectReferences(string name)
 {
     return(analyzer.Build()
            .Results.Single()
            .References.Where(reference => reference.Contains(name))
            .Select(file => MetadataReference.CreateFromFile(file))
            .ToArray());
 }
Exemplo n.º 12
0
        protected internal static AnalyzerResult CompileProjectAndTrace(ProjectAnalyzer analyzer, StringWriter log)
        {
            log.GetStringBuilder().Clear();
            AnalyzerResult result = analyzer.Build();

            if (result.OverallSuccess == false)
            {
                Trace.Error($"Could not compile project at {analyzer.ProjectFile.Path}");
                Trace.Warning(log.ToString());
                return(null);
            }
            return(result);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Adds a project to an existing Roslyn workspace. Note that this will rebuild the project. Use an <see cref="AnalyzerResult"/> instead if you already have one available.
        /// </summary>
        /// <param name="analyzer">The Buildalyzer project analyzer.</param>
        /// <param name="workspace">A Roslyn workspace.</param>
        /// <param name="addProjectReferences">
        /// <c>true</c> to add projects to the workspace for project references that exist in the same <see cref="AnalyzerManager"/>.
        /// If <c>true</c> this will trigger (re)building all referenced projects. Directly add <see cref="AnalyzerResult"/> instances instead if you already have them available.
        /// </param>
        /// <returns>The newly added Roslyn project.</returns>
        public static Project AddToWorkspace(this ProjectAnalyzer analyzer, Workspace workspace, bool addProjectReferences = false)
        {
            if (analyzer == null)
            {
                throw new ArgumentNullException(nameof(analyzer));
            }
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            return(analyzer.Build().FirstOrDefault().AddToWorkspace(workspace, addProjectReferences));
        }
Exemplo n.º 14
0
        public void LegacyFrameworkProjectWithPackageReferenceGetsReferences()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"LegacyFrameworkProjectWithPackageReference\LegacyFrameworkProjectWithPackageReference.csproj", log);

            // When
            IReadOnlyList <string> references = analyzer.Build().First().GetReferences();

            // Then
            references.ShouldNotBeNull(log.ToString());
            references.ShouldContain(x => x.EndsWith("NodaTime.dll"), log.ToString());
        }
Exemplo n.º 15
0
        public void SdkProjectWithProjectReferenceGetsReferences()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkNetCoreProjectWithReference\SdkNetCoreProjectWithReference.csproj", log);

            // When
            IReadOnlyList <string> references = analyzer.Build().First().GetProjectReferences();

            // Then
            references.ShouldNotBeNull(log.ToString());
            references.ShouldContain(x => x.EndsWith("SdkNetStandardProjectWithPackageReference.csproj"), log.ToString());
            references.ShouldContain(x => x.EndsWith("SdkNetStandardProject.csproj"), log.ToString());
        }
Exemplo n.º 16
0
        public void BuildsFSharpProject()
        {
            // Given
            const string    projectFile = @"FSharpProject\FSharpProject.fsproj";
            StringWriter    log         = new StringWriter();
            ProjectAnalyzer analyzer    = GetProjectAnalyzer(projectFile, log);

            // When
            DeleteProjectDirectory(projectFile, "obj");
            DeleteProjectDirectory(projectFile, "bin");
            AnalyzerResults results = analyzer.Build();

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.OverallSuccess.ShouldBeTrue(log.ToString());
            results.ShouldAllBe(x => x.Succeeded, log.ToString());
        }
Exemplo n.º 17
0
        public void MultiTargetingBuildCoreTargetFrameworkGetsSourceFiles()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log);

            // When
            IReadOnlyList <string> sourceFiles = analyzer.Build("netstandard2.0").First().SourceFiles;

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            new[]
            {
                "Class2",
                "AssemblyAttributes",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemplo n.º 18
0
        public void GetsProjectGuidFromSolution([ValueSource(nameof(Preferences))] EnvironmentPreference preference)
        {
            // Given
            AnalyzerManager manager = new AnalyzerManager(
                GetProjectPath("TestProjects.sln"));
            ProjectAnalyzer    analyzer = manager.Projects.First(x => x.Key.EndsWith("SdkNetStandardProject.csproj")).Value;
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj");
            DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin");
            AnalyzerResults results = analyzer.Build(options);

            // Then
            results.First().ProjectGuid.ToString().ShouldBe("016713d9-b665-4272-9980-148801a9b88f");
        }
Exemplo n.º 19
0
        protected internal static AnalyzerResult CompileProjectAndTrace(ProjectAnalyzer analyzer, StringWriter log)
        {
            log.GetStringBuilder().Clear();
            Common.Tracing.Trace.Verbose($"Building project {analyzer.ProjectFile.Path}");
            Stopwatch sw = new Stopwatch();

            sw.Start();
            AnalyzerResult result = analyzer.Build().FirstOrDefault();

            sw.Stop();
            Common.Tracing.Trace.Verbose($"Project {analyzer.ProjectFile.Path} built in {sw.ElapsedMilliseconds} ms");
            if (result == null || !result.Succeeded)
            {
                Common.Tracing.Trace.Error($"Could not compile project at {analyzer.ProjectFile.Path}");
                Common.Tracing.Trace.Warning(log.ToString());
                return(null);
            }
            return(result);
        }
        protected internal static AnalyzerResult CompileProject(IExecutionContext context, ProjectAnalyzer analyzer, StringWriter log)
        {
            log.GetStringBuilder().Clear();
            context.LogDebug($"Building project {analyzer.ProjectFile.Path}");
            Stopwatch sw = new Stopwatch();

            sw.Start();
            AnalyzerResult result = analyzer.Build().FirstOrDefault();

            sw.Stop();
            context.LogDebug($"Project {analyzer.ProjectFile.Path} built in {sw.ElapsedMilliseconds} ms");
            if (result?.Succeeded != true)
            {
                context.LogError($"Could not compile project at {analyzer.ProjectFile.Path}");
                context.LogWarning(log.ToString());
                return(null);
            }
            return(result);
        }
Exemplo n.º 21
0
        public void GetsSourceFilesFromBinaryLog(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };
            string binLogPath = Path.ChangeExtension(Path.GetTempFileName(), ".binlog");

            analyzer.AddBinaryLogger(binLogPath);

            try
            {
                // When
                analyzer.Build(options);
                IReadOnlyList <string> sourceFiles = analyzer.Manager.Analyze(binLogPath).First().SourceFiles;

                // Then
                sourceFiles.ShouldNotBeNull(log.ToString());
                new[]
                {
#if Is_Windows
                    // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                    "AssemblyAttributes",
#endif
                    "Class1",
                    "AssemblyInfo"
                }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
            }
            finally
            {
                if (File.Exists(binLogPath))
                {
                    File.Delete(binLogPath);
                }
            }
        }
Exemplo n.º 22
0
        public void DesignTimeBuildsProject(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            DeleteProjectDirectory(projectFile, "obj");
            DeleteProjectDirectory(projectFile, "bin");
            AnalyzerResults results = analyzer.Build(options);

            // Then
            results.Count.ShouldBeGreaterThan(0, log.ToString());
            results.ShouldAllBe(x => x.OverallSuccess, log.ToString());
        }
Exemplo n.º 23
0
        public void MultiTargetingBuildFrameworkTargetFrameworkGetsSourceFiles()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log);

            // When
            IReadOnlyList <string> sourceFiles = analyzer.Build("net462").First().SourceFiles;

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            new[]
            {
#if Is_Windows
                // Linux and Mac builds appear to omit the AssemblyAttributes.cs file
                "AssemblyAttributes",
#endif
                "Class1",
                "AssemblyInfo"
            }.ShouldBeSubsetOf(sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString());
        }
Exemplo n.º 24
0
        public void GetsReferences(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            IReadOnlyList <string> references = analyzer.Build(options).First().GetReferences();

            // Then
            references.ShouldNotBeNull(log.ToString());
            references.ShouldContain(x => x.EndsWith("mscorlib.dll"), log.ToString());
            if (projectFile.Contains("PackageReference"))
            {
                references.ShouldContain(x => x.EndsWith("NodaTime.dll"), log.ToString());
            }
        }
        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());
        }
Exemplo n.º 26
0
        public void GetsSourceFiles(
            [ValueSource(nameof(Preferences))] EnvironmentPreference preference,
            [ValueSource(nameof(ProjectFiles))] string projectFile)
        {
            // Given
            StringWriter       log      = new StringWriter();
            ProjectAnalyzer    analyzer = GetProjectAnalyzer(projectFile, log);
            EnvironmentOptions options  = new EnvironmentOptions
            {
                Preference = preference
            };

            // When
            IReadOnlyList <string> sourceFiles = analyzer.Build(options).First().GetSourceFiles();

            // Then
            sourceFiles.ShouldNotBeNull(log.ToString());
            sourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()).ShouldBe(new[]
            {
                "Class1",
                "AssemblyAttributes",
                "AssemblyInfo"
            }, true, log.ToString());
        }
Exemplo n.º 27
0
        private DependencyGraph.Builder CreateBuilder(ProjectAnalyzer projectAnalyzer, string projectPath, DependencyGraph.Builder builder = null, string framework = null)
        {
            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.");
            }
            var projectNode = new ProjectReferenceNode(projectPath);

            if (builder == null)
            {
                builder = new DependencyGraph.Builder(projectNode);
            }
            else
            {
                builder.WithNode(projectNode);
                builder.WithEdge(new Edge(builder.Root, projectNode));
            }

            var projectAssetsFilePath = analyzerResult.GetProjectAssetsFilePath();

            if (!File.Exists(projectAssetsFilePath))
            {
                if (analyzerResult.IsNetSdkProject())
                {
                    // a new project doesn't have an asset file
                    throw new InvalidOperationException($"{projectAssetsFilePath} not found. Please run 'dotnet restore'");
                }

                // Old csproj

                var oldStylePackageReferences = analyzerResult.GetItems("Reference").Where(x => x.ItemSpec.Contains("Version"));
                foreach (var reference in oldStylePackageReferences)
                {
                    var split   = reference.ItemSpec.Split(',');
                    var version = split.Single(s => s.Contains("Version"))?.Split('=')[1];
                    var name    = reference.ItemSpec.Split(',')[0];
                    var node    = new PackageReferenceNode(name, version);
                    builder.WithNode(node);
                    builder.WithEdge(new Edge(projectNode, node, version));
                }
            }
            else
            {
                // New csproj

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

                var targetFramework   = analyzerResult.GetTargetFramework();
                var runtimeIdentifier = analyzerResult.GetRuntimeIdentifier();

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

                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())));
                    }
                }

                // Ignore unversioned references like implicit SDK packages
                builder.WithEdges(analyzerResult.GetItems("PackageReference")
                                  .Where(x => x.Metadata.ContainsKey("Version"))
                                  .Select(x => new Edge(projectNode, libraryNodes[x.ItemSpec], x.Metadata["Version"])));
            }

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

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

            return(builder);
        }
Exemplo n.º 28
0
        public void LegacyFrameworkProjectWithPackageReferenceGetsPackageReferences()
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"LegacyFrameworkProjectWithPackageReference\LegacyFrameworkProjectWithPackageReference.csproj", log);

            // When
            IReadOnlyDictionary <string, IReadOnlyDictionary <string, string> > packageReferences = analyzer.Build().First().PackageReferences;

            // Then
            packageReferences.ShouldNotBeNull(log.ToString());
            packageReferences.Keys.ShouldContain("NodaTime", log.ToString());
        }