private static async Task RunFormatItemAsync(IFormattingEngine engine, string item, string language, CancellationToken cancellationToken)
        {
            Console.WriteLine(Path.GetFileName(item));
            string extension = Path.GetExtension(item);

            if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".rsp"))
            {
                using (var workspace = ResponseFileWorkspace.Create())
                {
                    Project project = workspace.OpenCommandLineProject(item, language);
                    await engine.FormatProjectAsync(project, cancellationToken);
                }
            }
            else if (StringComparer.OrdinalIgnoreCase.Equals(extension, ".sln"))
            {
                AnalyzerManager manager = new AnalyzerManager(item);
                using (var workspace = manager.GetWorkspace())
                {
                    var solution = workspace.CurrentSolution;
                    await engine.FormatSolutionAsync(solution, cancellationToken);
                }
            }
            else
            {
                AnalyzerManager manager  = new AnalyzerManager();
                ProjectAnalyzer analyzer = manager.GetProject(item);

                using (var workspace = analyzer.GetWorkspace())
                {
                    var project = workspace.CurrentSolution.Projects.FirstOrDefault();
                    await engine.FormatProjectAsync(project, cancellationToken);
                }
            }
        }
Exemple #2
0
        public static TaskRunnerResult Execute(string assemblyPath, string projectPath)
        {
            var assembly = Assembly.LoadFrom(assemblyPath);

            Dictionary <Type, IPostCompileTask> tasks =
                (from type in assembly.GetTypes()
                 where typeof(IPostCompileTask).IsAssignableFrom(type)
                 where !type.IsAbstract
                 where type.HasDefaultConstructor()
                 select type).ToDictionary(x => x, x => (IPostCompileTask)Activator.CreateInstance(x));

            CheckTaskDependencies(tasks);

            List <IPostCompileTask> sortedTaskInstances = tasks.Values.TopologicalSort(x => x.DependsOn.Select(y => tasks[y])).ToList();

            AnalyzerManager manager   = new AnalyzerManager();
            ProjectAnalyzer analyzer  = manager.GetProject(projectPath);
            AdhocWorkspace  workspace = analyzer.GetWorkspace();

            Solution solution = workspace.CurrentSolution;
            var      log      = new ConcreteLog(solution, Console.Out);

            foreach (var taskInstance in sortedTaskInstances)
            {
                taskInstance.Log = log;
                taskInstance.RunAsync().Wait();
            }

            // Return task types that need to be removed
            return(new TaskRunnerResult
            {
                TaskTypes = tasks.Select(x => x.Key.FullName).ToList()
            });
        }
Exemple #3
0
        public SyntaxNode Format(SyntaxNode tree)
        {
            AnalyzerManager manager   = new AnalyzerManager();
            ProjectAnalyzer analyzer  = manager.GetProject(projectFile);
            var             workspace = analyzer.GetWorkspace();

            return(Formatter.Format(tree, workspace));
        }
        public RoslynExtensionsTests()
        {
            AnalyzerManager manager   = new AnalyzerManager();
            ProjectAnalyzer analyzer  = manager.GetProject(@"..\..\..\PostCompile.Tests.csproj");
            AdhocWorkspace  workspace = analyzer.GetWorkspace();

            _solution               = workspace.CurrentSolution;
            _testProject            = _solution.Projects.First(x => x.Name == "PostCompile.Tests");
            _testProjectCompilation = _testProject.GetCompilationAsync().Result;
        }
Exemple #5
0
        /// <inheritdoc />
        protected override IEnumerable <Project> GetProjects(IFile file)
        {
            StringWriter    log      = new StringWriter();
            AnalyzerManager manager  = new AnalyzerManager(log);
            ProjectAnalyzer analyzer = manager.GetProject(file.Path.FullPath);

            CompileProjectAndTrace(analyzer, log);
            AdhocWorkspace workspace = analyzer.GetWorkspace();

            return(workspace.CurrentSolution.Projects);
        }
        public void LoadsWorkspace()
        {
            // Given
            StringBuilder   log      = new StringBuilder();
            ProjectAnalyzer analyzer = GetProjectAnalyzer(@"projects\SdkNetStandardProject\SdkNetStandardProject.csproj", log);

            // When
            Workspace workspace = analyzer.GetWorkspace();

            // Then
            workspace.CurrentSolution.Projects.First().Documents.ShouldContain(x => x.Name == "Class1.cs");
        }
        public void CreatesCompilationOptions()
        {
            // Given
            StringBuilder   log      = new StringBuilder();
            ProjectAnalyzer 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);
        }
        public void SupportsCompilation()
        {
            // Given
            StringBuilder   log      = new StringBuilder();
            ProjectAnalyzer 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();
        }
        private async Task <ProjectModel> GetProjects(ProjectAnalyzer project)
        {
            var p             = new ProjectModel();
            var workspace     = project.GetWorkspace();
            var csharpProject = workspace.CurrentSolution.Projects.First();
            var controllers   = await GetControllers(csharpProject);

            logger.LogInformation($"Inspecting Project:{project.ProjectFile.Path} for Controllers");
            p.Controllers  = controllers.ToList();
            p.ProjectPath  = project.ProjectFile.Path;
            p.SolutionPath = workspace.CurrentSolution.FilePath;
            return(p);
        }
        public void AddsProjectReferences(bool addProjectReferences, int totalProjects)
        {
            // Given
            StringWriter    log      = new StringWriter();
            ProjectAnalyzer 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 async Task <SemanticModel> LoadSemanticModelAsync(string filePath)
        {
            AnalyzerManager manager     = new AnalyzerManager();
            var             projectPath = _pathGenerator.FindProjectFile(filePath);

            ProjectAnalyzer analyzer  = manager.GetProject(projectPath);
            AdhocWorkspace  workspace = analyzer.GetWorkspace();

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

            var doc = project.Documents.FirstOrDefault(_ => _.FilePath == filePath);

            return(await doc.GetSemanticModelAsync());
        }
Exemple #12
0
        /// <inheritdoc />
        protected override IEnumerable <Project> GetProjects(IExecutionContext context, IFile file)
        {
            StringWriter    log     = new StringWriter();
            AnalyzerManager manager = new AnalyzerManager(new AnalyzerManagerOptions
            {
                LogWriter = log
            });
            ProjectAnalyzer analyzer = manager.GetProject(file.Path.FullPath);

            if (context.Bool(CodeAnalysisKeys.OutputBuildLog))
            {
                analyzer.WithBinaryLog();
            }
            CompileProjectAndTrace(analyzer, log);
            AdhocWorkspace workspace = analyzer.GetWorkspace();

            return(workspace.CurrentSolution.Projects);
        }
Exemple #13
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 #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);
        }