public void EmptyDirectoryShouldNotCheckAnyDlls() { var projects = parser.Parse(@"C:\"); Assert.AreEqual(0, parser.AssembliesChecked); Assert.AreEqual(0, parser.AssembliesMatching); Assert.AreEqual(0, projects.Count); }
public IEnumerable<ProjectInfo> ParseSolutionFile(SolutionInfo solutionInfo) { var solutionParserResult = solutionParser.Parse((FilePath)solutionInfo.SolutionPath); foreach (var project in solutionParserResult.Projects) { ProjectParserResult parserResult = null; if (File.Exists(project.Path.FullPath)) { parserResult = projectParser.Parse(project.Path); } yield return new ProjectInfo(solutionInfo, project.Path, project, parserResult); } }
public Processor( CommandLineService commandLineService, ProjectParser projectParser, ProcessRunner processRunner, ILogger <Processor> logger) { AppDomain.CurrentDomain.UnhandledException += (s, e) => logger.LogCritical("发生了灾难性故障。请联系开发者反馈错误。\n" + ((e.ExceptionObject as Exception)?.Message ?? string.Empty)); try { switch (commandLineService.Options) { case ProcessOptions: processRunner.Run(projectParser.Parse()); break; default: throw new IndexOutOfRangeException("不支持的命令类型。"); } } catch (Exception e) { logger.LogCritical(e, "处理命令时出现错误。"); Environment.Exit(1); } logger.LogInformation("完成了所有的操作。"); }
private void ParseProjects(TokenWalker tokenWalker, Solution solution) { while (tokenWalker.NextIs <BeginProjectToken>()) { _projectParser.Parse(tokenWalker, solution); } }
public static void Execute(ICakeContext context, FilePath solutionFile, FilePath settingsFile) { if (solutionFile == null) { throw new ArgumentNullException(nameof(solutionFile), "Solution file path is null."); } var solutionParser = new SolutionParser(context.FileSystem, context.Environment); var projectParser = new ProjectParser(context.FileSystem, context.Environment); var stylecopSettingsFile = settingsFile == null ? null : settingsFile.ToString(); var projectPath = Cake.Common.IO.DirectoryAliases.Directory(context, solutionFile.MakeAbsolute(context.Environment).GetDirectory().FullPath); Cake.Common.Diagnostics.LoggingAliases.Information(context, string.Format("Project Path: {0}", projectPath.Path.FullPath)); var styleCopConsole = new StyleCop.StyleCopConsole( stylecopSettingsFile, false, /* Input Cache Result */ null, /* Output file */ null, true); var styleCopProjects = new List <CodeProject>(); var solution = solutionParser.Parse(solutionFile); foreach (var solutionProject in solution.Projects) { var project = projectParser.Parse(solutionProject.Path); var styleCopProject = new CodeProject(0, solutionProject.Path.GetDirectory().ToString(), new Configuration(null)); styleCopProjects.Add(styleCopProject); foreach (var projectFile in project.Files) { if (projectFile.FilePath.GetExtension() == ".cs") { styleCopConsole.Core.Environment.AddSourceCode( styleCopProject, projectFile.FilePath.ToString(), null); } } } var handler = new StylecopHandlers(context); styleCopConsole.OutputGenerated += handler.OnOutputGenerated; styleCopConsole.ViolationEncountered += handler.ViolationEncountered; styleCopConsole.Start(styleCopProjects.ToArray(), true); styleCopConsole.OutputGenerated -= handler.OnOutputGenerated; styleCopConsole.ViolationEncountered -= handler.ViolationEncountered; if (handler.TotalViolations > 0) { throw new Exception(string.Format("{0} StyleCop violations encountered.", handler.TotalViolations)); } }
/// <summary> /// Orchestrate the work of loading the file and reading it into a ConfigModel. /// </summary> private ProjectModel DoRead(string path) { using (var stream = File.OpenRead(path)) { var xml = XDocument.Load(stream); var parser = new ProjectParser(xml); return(parser.Parse()); } }
public void Parse_InvalidProjectFilename_ArgumentExceptionThrown() { // Arrange const string filename = "myFileName"; // Act ArgumentException exception = Assert.Throws <ArgumentException>(() => ProjectParser.Parse(filename, Guid.NewGuid().ToString())); // Assert Assert.Equal($"Cannot find project {filename}", exception.Message); }
public void Parse_ValidProjectFilename_ExpectedPackageCount(string packageFilename, int expectedCount) { // Arrange string basePath = Path.Combine(AppContext.BaseDirectory, "TestData", "ProjectParser"); string folderName = Path.GetFileNameWithoutExtension(packageFilename); string extractedFolderPath = Path.Combine(basePath, folderName); ZipFile.ExtractToDirectory(Path.Combine(basePath, packageFilename), basePath, true); // Act ProjectItem project = ProjectParser.Parse( Path.Combine(extractedFolderPath, $"{folderName}.csproj"), Guid.NewGuid().ToString()); // Assert Assert.Equal(expectedCount, project.PackageReferences.Count); }
public IReadOnlyList <ProjectInformation> FindExamples() { var result = new List <ProjectInformation>(); var folders = GetExampleFolders(); var examples = folders.Select(FindProjects).Aggregate((acc, xs) => acc.Concat(xs)); foreach (var example in examples) { result.Add(_parser.Parse(example)); } return(result .Where(x => x.Visible && !_skip.Contains(x.Name, StringComparer.OrdinalIgnoreCase)) .OrderBy(x => x.Order) .ToList()); }
/// <summary> /// Initialize project to analyze. /// </summary> /// <param name="context">The cake context.</param> /// <param name="projectPath">The path to a project to analyze.</param> /// <param name="projectParser">The project parser.</param> /// <param name="styleCopConsole">The style cop console.</param> /// <returns>Prepared project to analyze.</returns> private static CodeProject InitializeProject( ICakeContext context, FilePath projectPath, ProjectParser projectParser, StyleCopConsole styleCopConsole) { context.Log.Information($"Stylecop: Found project {projectPath}"); var project = projectParser.Parse(projectPath); var styleCopProject = new CodeProject(0, projectPath.GetDirectory().ToString(), new Configuration(null)); foreach (var projectFile in project.Files) { if (projectFile.FilePath.GetExtension() != ".cs") { continue; } context.Log.Debug($"Stylecop: Found file {projectFile.FilePath}"); styleCopConsole.Core.Environment.AddSourceCode(styleCopProject, projectFile.FilePath.ToString(), null); } return(styleCopProject); }
public ProjectParserResult Parse() { var parser = new ProjectParser(FileSystem, Environment); return(parser.Parse(ProjFilePath)); }
public void TestParse1() { var path = TestPath.Get(@"Build.Test/Parser/Build.Test.csproj"); var project = _parser.Parse(path); project.Should().NotBeNull(); project.Filename.Should().Be(path); project.Properties.Should().NotBeNull(); project.Properties.Count.Should().Be(3); var group = project.Properties[0]; group.Should().NotBeNull(); group.Condition.Should().BeNull(); group.Count.Should().Be(9); group[0].Should().Be(new Property(Properties.Configuration, "Debug", " '$(Configuration)' == '' ")); group[1].Should().Be(new Property(Properties.Platform, "AnyCPU", " '$(Platform)' == '' ")); group[2].Should().Be(new Property(Properties.ProjectGuid, "{34B3464E-CBE5-4410-9052-3AB2E720BACF}")); group[3].Should().Be(new Property(Properties.OutputType, "Library")); group[4].Should().Be(new Property(Properties.AppDesignerFolder, "Properties")); group[5].Should().Be(new Property(Properties.RootNamespace, "Build.Test")); group[6].Should().Be(new Property(Properties.AssemblyName, "Build.Test")); group[7].Should().Be(new Property(Properties.TargetFrameworkVersion, "v4.5")); group[8].Should().Be(new Property(Properties.FileAlignment, "512")); group = project.Properties[1]; group.Should().NotBeNull(); group.Condition.Should().Be(" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "); group.Count.Should().Be(7); group[0].Should().Be(new Property(Properties.DebugSymbols, "true")); group[1].Should().Be(new Property(Properties.DebugType, "full")); group[2].Should().Be(new Property(Properties.Optimize, "false")); group[3].Should().Be(new Property(Properties.OutputPath, @"bin\Debug\")); group[4].Should().Be(new Property(Properties.DefineConstants, "DEBUG;TRACE")); group[5].Should().Be(new Property(Properties.ErrorReport, "prompt")); group[6].Should().Be(new Property(Properties.WarningLevel, "4")); group = project.Properties[2]; group.Should().NotBeNull(); group.Condition.Should().Be(" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "); group.Count.Should().Be(6); group[0].Should().Be(new Property(Properties.DebugType, "pdbonly")); group[1].Should().Be(new Property(Properties.Optimize, "true")); group[2].Should().Be(new Property(Properties.OutputPath, @"bin\Release\")); group[3].Should().Be(new Property(Properties.DefineConstants, "TRACE")); group[4].Should().Be(new Property(Properties.ErrorReport, "prompt")); group[5].Should().Be(new Property(Properties.WarningLevel, "4")); var itemGroups = project.ItemGroups; itemGroups.Should().NotBeNull(); itemGroups.Count.Should().Be(4); var items = itemGroups[0]; items.Should().NotBeNull(); items.Condition.Should().BeNull(); items.Count.Should().Be(10); items[0].Should() .Be(new ProjectItem(Items.Reference, "FluentAssertions", metadata: new List <Metadata> { new Metadata(Metadatas.HintPath, @"..\packages\FluentAssertions.4.0.0\lib\net45\FluentAssertions.dll") })); items[1].Should().Be(new ProjectItem(Items.Reference, "FluentAssertions.Core", metadata: new List <Metadata> { new Metadata(Metadatas.HintPath, @"..\packages\FluentAssertions.4.0.0\lib\net45\FluentAssertions.Core.dll") })); items[2].Should().Be(new ProjectItem(Items.Reference, "nunit.framework", metadata: new List <Metadata> { new Metadata(Metadatas.HintPath, @"..\packages\NUnit.2.6.4\lib\nunit.framework.dll") })); items[3].Should().Be(new ProjectItem(Items.Reference, "System")); items[4].Should().Be(new ProjectItem(Items.Reference, "System.Core")); items[5].Should().Be(new ProjectItem(Items.Reference, "System.Xml.Linq")); items[6].Should().Be(new ProjectItem(Items.Reference, "System.Data.DataSetExtensions")); items[7].Should().Be(new ProjectItem(Items.Reference, "Microsoft.CSharp")); items[8].Should().Be(new ProjectItem(Items.Reference, "System.Data")); items[9].Should().Be(new ProjectItem(Items.Reference, "System.Xml")); items = itemGroups[1]; items.Should().NotBeNull(); items.Condition.Should().BeNull(); items.Count.Should().Be(8); items[0].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\ExpressionEngine\BinaryExpressionTest.cs")); items[1].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\ExpressionEngine\ExpressionEngineParsingTest.cs")); items[2].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\ExpressionEngine\ExpressionEngineEvaluationTest.cs")); items[3].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\ExpressionEngine\TokenizerTest.cs")); items[4].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\ExpressionEngine\UnaryExpressionTest.cs")); items[5].Should().Be(new ProjectItem(Items.Compile, @"BusinessLogic\PathTest.cs")); items[6].Should().Be(new ProjectItem(Items.Compile, @"Class1.cs")); items[7].Should().Be(new ProjectItem(Items.Compile, @"Properties\AssemblyInfo.cs")); items = itemGroups[2]; items.Should().NotBeNull(); items.Condition.Should().BeNull(); items.Count.Should().Be(2); items[0].Should().Be(new ProjectItem(Items.Folder, @"BusinessLogic\BuildEngine\")); items[1].Should().Be(new ProjectItem(Items.Folder, @"BusinessLogic\Parser\")); items = itemGroups[3]; items.Should().NotBeNull(); items.Condition.Should().BeNull(); items.Count.Should().Be(1); items[0].Should().Be(new ProjectItem(Items.ProjectReference, @"..\Build\Build.csproj", metadata: new List <Metadata> { new Metadata("Project", "{63F3A0B5-909C-43C5-8B79-CEA032DFE4F1}"), new Metadata("Name", "Build") })); }
public bool CollectProjectData(ProjectInfo project) { var parser = new ProjectParser(false); try { using (var stream = File.OpenRead(project.FileName)) { using (var reader = new BinaryReader(stream)) { parser.Parse(reader); } } // add only non-empty project paths if (!string.IsNullOrWhiteSpace(parser.project.ProjectPath)) { project.ProjectPath = parser.project.ProjectPath; } } catch (Exception ex) { // it has read error, so it may have invalid tracks project.HasLoadErrors = true; // if there is project path were parsed, it's correct if (!string.IsNullOrWhiteSpace(parser.project.ProjectPath)) { project.ProjectPath = parser.project.ProjectPath; } } // skip project where is no project path set if (string.IsNullOrWhiteSpace(project.ProjectPath)) { return(false); } // try to fix project data path, if hard drives were mysteriously changed if (!Directory.Exists(project.ProjectPath)) { var projectLocation = Helpers.NormalizePath(Path.GetDirectoryName(project.FileName)); var projectDataLocation = Helpers.NormalizePath(project.ProjectPath); // remove drive letter if (string.Compare(projectDataLocation.Substring(1), projectLocation.Substring(1), StringComparison.InvariantCultureIgnoreCase) == 0) { project.ProjectPath = projectLocation; } else { // ask user if he want to use the project location as project data folder var pathErrMsg = string.Format("Project folder '{0}' was not found for project {1}\n\nTry to use path {2} for it?", project.ProjectPath, project.FileName, projectLocation); var dlgResult = (DialogResult)_parent.Invoke((Func <DialogResult>)(() => MessageBox.Show(_parent, pathErrMsg, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question))); if (dlgResult == DialogResult.Yes) { project.ProjectPath = projectLocation; } else { project.PathError = true; } } } // fix project path project.ProjectPath = Helpers.NormalizePath(project.ProjectPath); // second we try search for WAV files in project folder CollectWAVFilesRecursively(project); // third we check WAV files usage CollectWAVFilesUsage(parser, project); return(true); }
public void Should_mark_found_project_as_read() { var document = _parser.Parse(getCSharpProject(), null); document.IsReadFromFile.ShouldBeTrue(); }
public void Should_mark_found_project_as_read() { _config.Stub(x => x.ProjectsToIgnore).Return(new string[] {}); var document = _parser.Parse(getCSharpProject(), null); document.IsReadFromFile.ShouldBeTrue(); }
public ProjectParserResult ParseIncomplete() { var parser = new ProjectParser(FileSystem, Environment); return(parser.Parse("/Working/Cake.Incomplete.csproj")); }
/// <summary> /// Starts an analysis run. /// </summary> /// <param name="context">The cake context.</param> /// <param name="settingsDelegate">The stylecop setting to use during the analysis.</param> public static void Execute(ICakeContext context, SettingsDelegate settingsDelegate) { settings = settingsDelegate(new StyleCopSettings()); // need to get pwd for stylecop.dll for stylesheet var assemblyDirectory = AssemblyDirectory(Assembly.GetAssembly(typeof(StyleCopSettings))); var toolPath = context.File(assemblyDirectory).Path.GetDirectory(); var defaultStyleSheet = context.File(toolPath + "/StyleCopStyleSheet.xslt"); context.Log.Information($"Stylecop: Default stylesheet {context.MakeAbsolute(defaultStyleSheet)}"); var solutionFile = settings.SolutionFile; var settingsFile = settings.SettingsFile?.ToString(); var outputPath = settings.ResultsFile?.ToString(); var addins = settings.Addins.Count == 0 ? null : settings.Addins.Select(x => x.FullPath).ToList(); var solutionParser = new SolutionParser(context.FileSystem, context.Environment); var projectParser = new ProjectParser(context.FileSystem, context.Environment); var projectPath = solutionFile.MakeAbsolute(context.Environment).GetDirectory(); context.Log.Information($"Stylecop: Found solution {projectPath.FullPath}"); StyleCopConsole styleCopConsole = null; try { styleCopConsole = new StyleCopConsole( settingsFile, settings.WriteResultsCache, /* Input Cache Result */ outputPath, /* Output file */ addins, settings.LoadFromDefaultPath); } catch (TypeLoadException typeLoadException) { context.Log.Error($"Error: Stylecop was unable to load an Addin .dll. {typeLoadException.Message}"); throw; } var styleCopProjects = new List <CodeProject>(); var solution = solutionParser.Parse(solutionFile); foreach (var solutionProject in solution.Projects.Where(p => p.Type != FOLDER_PROJECT_TYPE_GUID)) { context.Log.Information($"Stylecop: Found project {solutionProject.Path}"); var project = projectParser.Parse(solutionProject.Path); var styleCopProject = new CodeProject(0, solutionProject.Path.GetDirectory().ToString(), new Configuration(null)); styleCopProjects.Add(styleCopProject); foreach (var projectFile in project.Files) { if (projectFile.FilePath.GetExtension() != ".cs") { continue; } context.Log.Debug($"Stylecop: Found file {projectFile.FilePath}"); styleCopConsole.Core.Environment.AddSourceCode(styleCopProject, projectFile.FilePath.ToString(), null); } } var handler = new StylecopHandlers(context, settings); styleCopConsole.OutputGenerated += handler.OnOutputGenerated; styleCopConsole.ViolationEncountered += handler.ViolationEncountered; context.Log.Information($"Stylecop: Starting analysis"); styleCopConsole.Start(styleCopProjects.ToArray(), settings.FullAnalyze); context.Log.Information($"Stylecop: Finished analysis"); styleCopConsole.OutputGenerated -= handler.OnOutputGenerated; styleCopConsole.ViolationEncountered -= handler.ViolationEncountered; if (settings.HtmlReportFile != null) { settings.HtmlReportFile = settings.HtmlReportFile.MakeAbsolute(context.Environment); // copy default resources to output folder context.CopyDirectory(context.Directory(toolPath + "/resources"), settings.HtmlReportFile.GetDirectory() + "/resources"); context.Log.Information($"Stylecop: Creating html report {settings.HtmlReportFile.FullPath}"); Transform(context, settings.HtmlReportFile, settings.ResultsFile.MakeAbsolute(context.Environment), settings.StyleSheet ?? context.MakeAbsolute(defaultStyleSheet)); } if (handler.TotalViolations > 0 && settings.FailTask) { throw new Exception($"{handler.TotalViolations} StyleCop violations encountered."); } }
// 進捗画面側で実行してもらう処理 private async Task DoWorkAsync() { // ソースコードをRoslynに渡す、ソースコードをDBに入れる await Task.Run(async() => { var slnParser = new SolutionParser(); var prjParser = new ProjectParser(); // ソリューションファイル var slnInfo = slnParser.Parse(SolutionFile); if (AppEnv.SolutionInfos.Any(x => x.SolutionFile == SolutionFile)) { return; } AppEnv.SolutionInfos.Add(slnInfo); foreach (var prjRefInfo in slnInfo.ProjectFiles) { // プロジェクトファイル var prjInfo = prjParser.Parse(SolutionFile, prjRefInfo.ProjectFile); if (AppEnv.ProjectInfos.Any(x => x.SolutionFile == prjInfo.SolutionFile && x.ProjectFile == prjInfo.ProjectFile)) { continue; } AppEnv.ProjectInfos.Add(prjInfo); // Roslyn 解析に必要なデータ系 //Microsoft.CodeAnalysis.ProjectInfo と DotBarg.Libraries.Parsers.ProjectInfo が同じクラス名のため、こちらはフルパスで書く var dllItems = new List <Microsoft.CodeAnalysis.MetadataReference>(); var mscorlib = Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location); dllItems.Add(mscorlib); var csSrcItems = new List <Microsoft.CodeAnalysis.SyntaxTree>(); var vbSrcItems = new List <Microsoft.CodeAnalysis.SyntaxTree>(); // ソースファイル var srcInfos = prjInfo.SourceFiles; foreach (var srcInfo in srcInfos) { var contents = await Util.ReadToEndAsync(srcInfo.SourceFile); switch (prjInfo.Languages) { case Languages.CSharp: var csTree = CSharpSyntaxTree.ParseText(text: contents, path: srcInfo.SourceFile); var csWalker = new CSharpSourceSyntaxWalker(); csWalker.Parse(srcInfo.SourceFile, contents, prjInfo.RootNamespace); if (csWalker.UserDefinitions.Any()) { AppEnv.UserDefinitions.AddRange(csWalker.UserDefinitions.ToList()); } csSrcItems.Add(csTree); if (srcInfo.HasDesignerFile) { contents = await Util.ReadToEndAsync(srcInfo.DesignerFile); csTree = CSharpSyntaxTree.ParseText(text: contents, path: srcInfo.DesignerFile); csWalker = new CSharpSourceSyntaxWalker(); csWalker.Parse(srcInfo.DesignerFile, contents, prjInfo.RootNamespace); if (csWalker.UserDefinitions.Any()) { AppEnv.UserDefinitions.AddRange(csWalker.UserDefinitions.ToList()); } csSrcItems.Add(csTree); } break; case Languages.VBNet: var vbTree = VisualBasicSyntaxTree.ParseText(text: contents, path: srcInfo.SourceFile); var vbWalker = new VBNetSourceSyntaxWalker(); vbWalker.Parse(srcInfo.SourceFile, contents, prjInfo.RootNamespace); if (vbWalker.UserDefinitions.Any()) { AppEnv.UserDefinitions.AddRange(vbWalker.UserDefinitions.ToList()); } vbSrcItems.Add(vbTree); if (srcInfo.HasDesignerFile) { contents = await Util.ReadToEndAsync(srcInfo.DesignerFile); vbTree = VisualBasicSyntaxTree.ParseText(text: contents, path: srcInfo.DesignerFile); vbWalker = new VBNetSourceSyntaxWalker(); vbWalker.Parse(srcInfo.DesignerFile, contents, prjInfo.RootNamespace); if (vbWalker.UserDefinitions.Any()) { AppEnv.UserDefinitions.AddRange(vbWalker.UserDefinitions.ToList()); } vbSrcItems.Add(vbTree); } break; } } if (csSrcItems.Any()) { var comp = CSharpCompilation.Create(prjInfo.AssemblyName, csSrcItems, dllItems); AppEnv.CSharpCompilations.Add(comp); AppEnv.CSharpSyntaxTrees.AddRange(csSrcItems); } if (vbSrcItems.Any()) { var kinds = Path.GetExtension(prjInfo.AssemblyFile).ToLower() == ".exe" ? Microsoft.CodeAnalysis.OutputKind.ConsoleApplication : Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary; var options = new VisualBasicCompilationOptions(outputKind: kinds, rootNamespace: prjInfo.RootNamespace); var comp = VisualBasicCompilation.Create(prjInfo.AssemblyName, vbSrcItems, dllItems, options); AppEnv.VisualBasicCompilations.Add(comp); AppEnv.VisualBasicSyntaxTrees.AddRange(vbSrcItems); } } }); // 上記で登録したDB内容をもとに、継承元クラス、インターフェースの定義元を名前解決する // ツリーノードのモデルを作成する await Task.Run(() => { var containers = AppEnv.UserDefinitions.Where(x => x.BaseTypeInfos.Any()); if (containers.Any()) { FindDefinitionInfo(containers); } var model = CreateTreeData(SolutionFile); Items.Add(model); }); }