/// <summary> /// Initializes a new instance of the <see cref="SkillsController"/> class. /// </summary> /// <param name="projectRepository">The projects repo.</param> /// <param name="skillRepository">The skills repo.</param> /// <param name="candidateRepository">The candidates repo.</param> /// <param name="analyzer">The ML analyzer.</param> public ProjectsController(IProjectRepository projectRepository, ISkillRepository skillRepository, ICandidateRepository candidateRepository, IProjectAnalyzer analyzer) { _projectRepository = projectRepository; _skillRepository = skillRepository; _candidateRepository = candidateRepository; _analyzer = analyzer; }
public async Task HappyPath() { AnalyzerManager manager = new AnalyzerManager(); IProjectAnalyzer analyzer = manager.GetProject(@"..\..\..\..\Tests.Assets.WebApi2022\Tests.Assets.WebApi2022.csproj"); AdhocWorkspace workspace = analyzer.GetWorkspace(false); var project = workspace.CurrentSolution.Projects.Where(x => x.Name == "Tests.Assets.WebApi2022").First(); var errorList = new IErrorListMock(); var fileReaderWriter = new IFileReaderWriterMock(); var output = new IOutputMock(); var solutionItemsManager = new ISolutionItemsManagerMock(); var sourceControl = new ISourceControlMock(); var status = new IStatusMock(); var cmd = new NTypewriter.Runtime.RenderTemplatesCommand(errorList, output, fileReaderWriter, sourceControl, status, solutionItemsManager, new IFileSearcherMock()); var inputTemplate = Path.Combine(Path.GetDirectoryName(project.FilePath) !, "RenderTemplatesCommand_HappyPathTemplate.nt"); var expectedOutputFile = Path.Combine(Path.GetDirectoryName(project.FilePath) !, "RenderTemplatesCommand_HappyPath.txt"); var expectedOutput = await fileReaderWriter.Read(expectedOutputFile); var input = new List <TemplateToRender>() { new TemplateToRender(inputTemplate, project.FilePath) }; await cmd.Execute(workspace.CurrentSolution, input); var outputContent = output.ToString(); //var actualOutput = fileReaderWriter.WriteResults[expectedOutputFile]; Assert.AreEqual(0, fileReaderWriter.WriteResults.Count); Assert.AreEqual(0, errorList.errors.Count); //actualOutput.ShouldBe(expectedOutput); }
public void MultiTargetingBuildAllTargetFrameworksGetsSourceFiles() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log); // When IAnalyzerResults results = analyzer.Build(); // Then results.Count.ShouldBe(2); results.TargetFrameworks.ShouldBe(new[] { "net462", "netstandard2.0" }, true, log.ToString()); new[] { // Linux and Mac builds appear to omit the AssemblyAttributes.cs file "AssemblyAttributes", "Class1", "AssemblyInfo" }.ShouldBeSubsetOf(results["net462"].SourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString()); new[] { // Linux and Mac builds appear to omit the AssemblyAttributes.cs file "AssemblyAttributes", "Class2", "AssemblyInfo" }.ShouldBeSubsetOf(results["netstandard2.0"].SourceFiles.Select(x => Path.GetFileName(x).Split('.').TakeLast(2).First()), log.ToString()); }
private ProjectAnalysisResult BuildIncremental(string WorkspacePath) { 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; } IAnalyzerResult analyzerResult = projectAnalyzer.Build(GetEnvironmentOptions(requiresNetFramework, projectAnalyzer.ProjectFile.ToolsVersion)).FirstOrDefault(); if (analyzerResult == null) { Logger.LogDebug("Building complete for {0} - {1}", path, "Fail"); return(new ProjectAnalysisResult() { ProjectAnalyzer = projectAnalyzer }); } if (!DictAnalysisResult.ContainsKey(analyzerResult.ProjectGuid)) { DictAnalysisResult[analyzerResult.ProjectGuid] = analyzerResult; projectAnalyzer.AddToWorkspace(_workspaceIncremental); foreach (var pref in analyzerResult.ProjectReferences) { if (!existing.Contains(pref)) { existing.Add(pref); queue.Enqueue(pref); } } } } Project project = _workspaceIncremental.CurrentSolution?.Projects.FirstOrDefault(x => x.FilePath.Equals(WorkspacePath)); Logger.LogDebug("Building complete for {0} - {1}", WorkspacePath, DictAnalysisResult[project.Id.Id].Succeeded ? "Success" : "Fail"); return(new ProjectAnalysisResult() { Project = project, AnalyzerResult = DictAnalysisResult[project.Id.Id], ProjectAnalyzer = _analyzerManager.Projects.Values.FirstOrDefault(p => p.ProjectGuid.Equals(project.Id.Id)) }); }
public GraphAnalyzer(ILogger logger, IProjectAnalyzer projectAnalyzer, IResultsReporter resultsReporter, bool failFast) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _projectAnalyzer = projectAnalyzer ?? throw new ArgumentNullException(nameof(projectAnalyzer)); _resultsReporter = resultsReporter ?? throw new ArgumentNullException(nameof(resultsReporter)); _failFast = failFast; }
public void GetsSourceFiles( [ValueSource(nameof(Preferences))] EnvironmentPreference preference, [ValueSource(nameof(ProjectFiles))] string projectFile) { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log); EnvironmentOptions options = new EnvironmentOptions { Preference = preference }; // When IAnalyzerResults results = analyzer.Build(options); // Then // If this is the multi-targeted project, use the net462 target IReadOnlyList <string> sourceFiles = results.Count == 1 ? results.First().SourceFiles : results["net462"].SourceFiles; 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()); }
public void Dispose() { Compilation = null; AnalyzerResult = null; ProjectAnalyzer = null; Project = null; Logger = null; }
/// <summary> /// Initializes a new instance of the <see cref="ProjectController" /> class. /// </summary> /// <param name="analyzer">The analyzer.</param> /// <param name="linkGenerator">The link generator.</param> /// <param name="httpContextAccessor">The HTTP context accessor.</param> public ProjectController(IProjectAnalyzer analyzer, LinkGenerator linkGenerator, IHttpContextAccessor httpContextAccessor) { _analyzer = analyzer; _linkGenerator = linkGenerator; _httpContextAccessor = httpContextAccessor; }
public void SolutionDirShouldEndWithDirectorySeparator() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkMultiTargetingProject\SdkMultiTargetingProject.csproj", log); analyzer.SolutionDirectory.ShouldEndWith(Path.DirectorySeparatorChar.ToString()); }
public ProjectFileParser(string path) { _analyzerManager = new AnalyzerManager(); _path = path; _projectAnalyzer = _analyzerManager.GetProject(_path); _packageConfigFile = Path.Combine(Path.GetDirectoryName(_path), PackageReferenceFile); _document = XDocument.Load(_path); _projectElement = _document.GetDescendants("Project").FirstOrDefault(); }
/// <summary> /// Gets a Roslyn workspace for the analyzed project. 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="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>A Roslyn workspace.</returns> public static AdhocWorkspace GetWorkspace(this IProjectAnalyzer analyzer, bool addProjectReferences = false) { if (analyzer == null) { throw new ArgumentNullException(nameof(analyzer)); } AdhocWorkspace workspace = new AdhocWorkspace(); AddToWorkspace(analyzer, workspace, addProjectReferences); return(workspace); }
public void LoadsWorkspace() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\SdkNetStandardProject\SdkNetStandardProject.csproj", log); // When Workspace workspace = analyzer.GetWorkspace(); // Then workspace.CurrentSolution.Projects.First().Documents.ShouldContain(x => x.Name == "Class1.cs", log.ToString()); }
public void AddsTransitiveProjectReferences(bool addProjectReferences, int totalProjects) { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\TransitiveProjectReference\TransitiveProjectReference.csproj", log); // When Workspace workspace = analyzer.GetWorkspace(addProjectReferences); // Then workspace.CurrentSolution.Projects.Count().ShouldBe(totalProjects, 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 }); IProjectAnalyzer analyzer = manager.GetProject(projectPath); EnvironmentOptions options = new EnvironmentOptions { Preference = preference }; // Set some environment 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($@"C:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog"); } #pragma warning restore 0162 #if Is_Windows IAnalyzerResults 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(); } IAnalyzerResults 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()); }
public void LegacyFrameworkProjectWithPackageReferenceGetsPackageReferences() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer 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()); }
public void SupportsAnalyzers() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\SdkNetCoreProjectWithAnalyzer\SdkNetCoreProjectWithAnalyzer.csproj", log); // When Workspace workspace = analyzer.GetWorkspace(); Project project = workspace.CurrentSolution.Projects.First(); // Then project.AnalyzerReferences.ShouldContain(reference => reference.Display == "Microsoft.CodeQuality.Analyzers"); }
public void SupportsCompilation() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\SdkNetStandardProject\SdkNetStandardProject.csproj", log); // When Workspace workspace = analyzer.GetWorkspace(); Compilation compilation = workspace.CurrentSolution.Projects.First().GetCompilationAsync().Result; // Then compilation.GetSymbolsWithName(x => x == "Class1").ShouldNotBeEmpty(log.ToString()); }
public void CreatesCompilationOptions() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\SdkNetStandardProject\SdkNetStandardProject.csproj", log); // When Workspace workspace = analyzer.GetWorkspace(); CompilationOptions compilationOptions = workspace.CurrentSolution.Projects.First().CompilationOptions; // Then compilationOptions.OutputKind.ShouldBe(OutputKind.DynamicallyLinkedLibrary, log.ToString()); }
/// <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 IProjectAnalyzer 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)); }
public void LegacyFrameworkProjectWithPackageReferenceGetsReferences() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"LegacyFrameworkProjectWithPackageReference\LegacyFrameworkProjectWithPackageReference.csproj", log); // When IReadOnlyList <string> references = analyzer.Build().First().References; // Then references.ShouldNotBeNull(log.ToString()); references.ShouldContain(x => x.EndsWith("NodaTime.dll"), log.ToString()); }
public void HandlesWpfCustomControlLibrary() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\WpfCustomControlLibrary1\WpfCustomControlLibrary1.csproj", log); // When AdhocWorkspace workspace = analyzer.GetWorkspace(); Project project = workspace.CurrentSolution.Projects.First(); // Then Assert.NotNull(project); Assert.IsNotEmpty(project.Documents); }
public void SdkProjectWithProjectReferenceGetsReferences() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"SdkNetCore2ProjectWithReference\SdkNetCore2ProjectWithReference.csproj", log); // When IEnumerable <string> references = analyzer.Build().First().ProjectReferences; // Then references.ShouldNotBeNull(log.ToString()); references.ShouldContain(x => x.EndsWith("SdkNetStandardProjectWithPackageReference.csproj"), log.ToString()); references.ShouldContain(x => x.EndsWith("SdkNetStandardProject.csproj"), log.ToString()); }
public void AddsProjectReferences(bool addProjectReferences, int totalProjects) { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\LegacyFrameworkProjectWithReference\LegacyFrameworkProjectWithReference.csproj", log); GetProjectAnalyzer(@"projects\LegacyFrameworkProject\LegacyFrameworkProject.csproj", log, analyzer.Manager); // When Workspace workspace = analyzer.GetWorkspace(addProjectReferences); // Then workspace.CurrentSolution.Projects.Count().ShouldBe(totalProjects, log.ToString()); }
public void GetsSourceFilesFromVersion9BinLog() { // Given StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer( @"SdkNetCore31Project\SdkNetCore31Project.csproj", log); string binLogPath = Path.ChangeExtension(Path.GetTempFileName(), ".binlog"); EnvironmentOptions options = new EnvironmentOptions(); options.Arguments.Add("/bl:" + binLogPath); // Tell MSBuild to produce the binlog so we use the latest internal logger try { // When analyzer.Build(options); using (Stream stream = File.OpenRead(binLogPath)) { using (GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress)) { using (BinaryReader reader = new BinaryReader(gzip)) { // Verify this produced a version 9 binlog reader.ReadInt32().ShouldBe(9); } } } 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); } } }
static async Task Main(string[] args) { // 1) Load project AnalyzerManager manager = new AnalyzerManager(); IProjectAnalyzer analyzer = manager.GetProject(@"..\..\..\..\NTypewriter\NTypewriter.csproj"); AdhocWorkspace workspace = analyzer.GetWorkspace(false); var project = workspace.CurrentSolution.Projects.Where(x => x.Name == "NTypewriter").First(); // 2) Add xml documentation project = AddXmlDocumentation(project, typeof(ICodeModel)); project = AddXmlDocumentation(project, typeof(ActionFunctions)); project = AddXmlDocumentation(project, typeof(Scriban.Functions.StringFunctions)); // 3) Compile var compilation = await project.GetCompilationAsync(); // 4) Create CodeModel var codeModelConfiguration = new CodeModelConfiguration() { OmitSymbolsFromReferencedAssemblies = false }; var codeModel = new CodeModel(compilation, codeModelConfiguration); // 5) Load template string template = File.ReadAllText(@"..\..\..\CodeModel.nt"); // 6) Add custom functions var ntypewriterConfig = new Configuration(); ntypewriterConfig.AddCustomFunctions(typeof(NTEConfig)); // 7) Render var result = await NTypeWriter.Render(template, codeModel, ntypewriterConfig); if (!result.HasErrors) { var renderedItem = result.Items.First(); var path = Path.Combine(@"..\..\..\", renderedItem.Name); File.WriteAllText(path, renderedItem.Content); } else { foreach (var msg in result.Messages) { Console.WriteLine(msg.Message); } } }
public async Task LoadConfigurationForGivenProjectShouldReturnDefinedConfig() { AnalyzerManager manager = new AnalyzerManager(); IProjectAnalyzer analyzer = manager.GetProject(@"..\..\..\..\Tests.Assets.WebApi2022\Tests.Assets.WebApi2022.csproj"); AdhocWorkspace workspace = analyzer.GetWorkspace(false); var project = workspace.CurrentSolution.Projects.Where(x => x.Name == "Tests.Assets.WebApi2022").First(); var output = new IOutputMock(); var loader = new UserCodeLoader(output, new IFileSearcherMock()); var userCode = await loader.LoadUserCodeForGivenProject(workspace.CurrentSolution, project.FilePath); var config = userCode.Config; Assert.AreEqual(false, config.AddGeneratedFilesToVSProject); config.ProjectsToBeSearched.ShouldBe(new[] { "Tests.Assets.WebApi2022" }); }
public void BuildsFSharpProject() { // Given const string projectFile = @"FSharpProject\FSharpProject.fsproj"; StringWriter log = new StringWriter(); IProjectAnalyzer analyzer = GetProjectAnalyzer(projectFile, log); // When DeleteProjectDirectory(projectFile, "obj"); DeleteProjectDirectory(projectFile, "bin"); IAnalyzerResults results = analyzer.Build(); // Then results.Count.ShouldBeGreaterThan(0, log.ToString()); results.OverallSuccess.ShouldBeTrue(log.ToString()); results.ShouldAllBe(x => x.Succeeded, log.ToString()); }
private IAnalyzerResult BuildProject(IProjectAnalyzer projectAnalyzer) { try { return(projectAnalyzer.Build(GetEnvironmentOptions(projectAnalyzer.ProjectFile)).FirstOrDefault()); } catch (Exception e) { Logger.LogDebug("Exception : " + projectAnalyzer.ProjectFile.Path); Logger.LogDebug(e.StackTrace); // TODO Handle errors // Ignore errors from vbproj until a fix from Buildalyzer if (!projectAnalyzer.ProjectFile.Path.EndsWith("vbproj")) { throw; } } return(null); }
public void GetsSourceFilesFromBinaryLog( [ValueSource(nameof(Preferences))] EnvironmentPreference preference, [ValueSource(nameof(ProjectFiles))] string projectFile) { // Given StringWriter log = new StringWriter(); IProjectAnalyzer 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); IAnalyzerResults results = analyzer.Manager.Analyze(binLogPath); // Then // If this is the multi-targeted project, use the net462 target IReadOnlyList <string> sourceFiles = results.Count == 1 ? results.First().SourceFiles : results["net462"].SourceFiles; 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); } } }
public void GetsProjectGuidFromSolution([ValueSource(nameof(Preferences))] EnvironmentPreference preference) { // Given AnalyzerManager manager = new AnalyzerManager( GetProjectPath("TestProjects.sln")); IProjectAnalyzer 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"); IAnalyzerResults results = analyzer.Build(options); // Then results.First().ProjectGuid.ToString().ShouldBe("016713d9-b665-4272-9980-148801a9b88f"); }