static void Main(string[] args) { string inpath = null; string outxml = null; bool help = false; bool verbose = false; var p = new OptionSet () { { "inpath=", v => inpath = v }, { "outxml=", v => outxml = v }, { "v|verbose", v => verbose = v != null }, { "h|?|help", v => help = v != null }, }; p.Parse (args); if (inpath == null || outxml == null || help) { Console.WriteLine("StyleGendarme.exe --inpath <path> --outxml <file>"); } else { StyleCopConsole console = new StyleCopConsole(null, true, outxml, null, true); Configuration configuration = new Configuration(new string[] { "DEBUG" }); List<CodeProject> projects = new List<CodeProject>(); CodeProject project = new CodeProject(inpath.GetHashCode(), inpath, configuration); // Add each source file to this project. foreach (string sourceFilePath in Directory.GetFiles(inpath, "*.cs", SearchOption.AllDirectories)) { console.Core.Environment.AddSourceCode(project, sourceFilePath, null); } projects.Add(project); console.OutputGenerated += new EventHandler<OutputEventArgs>(OnOutputGenerated); console.ViolationEncountered += new EventHandler<ViolationEventArgs>(OnViolationEncountered); console.Start(projects, true); } }
/// <summary> /// The main entrypoint to the application. /// </summary> /// <param name="args">The arguments passed to the executable.</param> public static void Main(string[] args) { int iterations = 10; string file = null; if (args.Length > 0) { int index = 0; if (args[0].StartsWith("-n:", StringComparison.Ordinal)) { iterations = int.Parse(args[0].Substring(3, args[0].Length - 3)); ++index; } if (args.Length > index) { file = args[index]; } } if (!string.IsNullOrEmpty(file)) { if (!File.Exists(file)) { Console.WriteLine("The file " + file + " does not exist"); file = null; } } if (!string.IsNullOrEmpty(file)) { DateTime start = DateTime.Now; Console.WriteLine("Start time: " + start.ToLongTimeString()); for (int i = 0; i < iterations; ++i) { Console.WriteLine("Iteration " + (i + 1)); StyleCopConsole console = new StyleCopConsole(null, false, null, null, true, "Perf"); Configuration configuration = new Configuration(new string[] { }); CodeProject project = new CodeProject(0, Environment.CurrentDirectory, configuration); console.Core.Environment.AddSourceCode(project, file, null); console.Start(new CodeProject[] { project }, true); } DateTime end = DateTime.Now; Console.WriteLine("End time: " + end.ToLongTimeString()); Console.WriteLine(); TimeSpan elapsedTime = end - start; Console.WriteLine("Elapsed time: " + elapsedTime); } else { Console.WriteLine("Usage: StyleCopPerfHarness {-n:X} FileToTest.cs"); } }
public void Process(LintResults results) { var file = results.FileName; // Start the StyleCop console. var console = new StyleCopConsole(Environment.CurrentDirectory, true, null, null, true); // Create the StyleCop configuration. var configuration = new Configuration(new string[] { "DEBUG" }); // Add the source files. var projects = new List<CodeProject>(); foreach (var myProject in this.m_ProjectDiscovery.DiscoverProjects(file)) { var project = new CodeProject(myProject.Path.GetHashCode(), myProject.Path, configuration); // Add each source file to this project. foreach (var sourceFilePath in myProject.DiscoveredFiles) { console.Core.Environment.AddSourceCode(project, sourceFilePath.Path, null); } projects.Add(project); } // Define event handlers. EventHandler<OutputEventArgs> outputGenerated = (sender, e) => { }; EventHandler<ViolationEventArgs> violationEncountered = (sender, e) => { if (e.SourceCode.Path != Path.Combine(Environment.CurrentDirectory, file)) return; var index = new LintIssueIndex { Name = e.Violation.Rule.Name, Code = e.Violation.Rule.CheckId, Message = e.Message, Severity = e.SourceCode.Project.ViolationsAsErrors ? LintSeverity.ERROR : LintSeverity.WARNING }; results.Issues.Add(new LintIssue { Index = index, LineNumber = e.LineNumber, Column = 0 }); }; // Assign event handlers. console.OutputGenerated += outputGenerated; console.ViolationEncountered += violationEncountered; // Run StyleCop. console.Start(projects, false); // Finalise. console.OutputGenerated -= outputGenerated; console.ViolationEncountered -= violationEncountered; }
public StyleCopRunner() { this.violations = new Dictionary<string, List<Violation>>(); this.environment = new ObjectBasedEnvironment(this.SourceCodeFactory, this.SettingsFactory); this.configuration = new Configuration(new[] { "DEBUG", "TRACE" }); this.styleCopConsole = new StyleCopObjectConsole(this.environment, null, null, true); this.styleCopConsole.ViolationEncountered += this.OnViolationEncountered; }
public void Dispose() { this.styleCopConsole.ViolationEncountered -= this.OnViolationEncountered; this.styleCopConsole = null; this.environment = null; this.configuration = null; this.violations = null; }
public void Setup() { this.Violations = new List<Violation>(); this.Output = new List<string>(); var configuration = new Configuration(new string[0]); string location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings.StyleCop"); this.project = new CodeProject(Guid.NewGuid().GetHashCode(), location, configuration); }
public static CodeProject CreateProject(string sourceDirectory) { if (string.IsNullOrEmpty(sourceDirectory)) { throw new ArgumentException("sourceDirectory"); } var configuration = new Configuration(new string[] { }); return new CodeProject(sourceDirectory.GetHashCode(), sourceDirectory, configuration); }
/// <summary> /// Validates all files with StyleCop. /// </summary> /// <param name="localSourceFiles">mapping of StyleCop config file to files to be checked with that file.</param> /// <param name="settingsFileOverride">the command line -settings override (if it exists)</param> /// <returns>list of violations found in the code.</returns> private static List <Violation> ValidateCommittedFiles(Dictionary <string, List <string> > localSourceFiles, string settingsFileOverride) { string settingsFile = settingsFileOverride; if (!string.IsNullOrEmpty(settingsFile)) { if (!Path.IsPathRooted(settingsFile)) { settingsFile = GetPathInExeFolder(settingsFile); } } // If a settings file has been specified and doesn't exist, it should fall back on the default settings file if (string.IsNullOrEmpty(settingsFile) || !File.Exists(settingsFile)) { settingsFile = configSection.StyleCop.SettingsFile; if (!Path.IsPathRooted(settingsFile)) { settingsFile = GetPathInExeFolder(settingsFile); } } List <Violation> violations = new List <Violation>(); StyleCopConsole console = new StyleCopConsole(settingsFile, false, null, null, true, null); List <CodeProject> projects = new List <CodeProject>(); foreach (KeyValuePair <string, List <string> > config in localSourceFiles) { StyleCop.Configuration configuration = new StyleCop.Configuration(new string[0]); CodeProject project = new CodeProject(string.Empty.GetHashCode(), string.Empty, configuration); if (!string.IsNullOrEmpty(config.Key)) { project.Settings = console.Core.Environment.GetSettings(config.Key, true); } projects.Add(project); foreach (string s in config.Value) { console.Core.Environment.AddSourceCode(project, s, null); } } console.ViolationEncountered += (sender, e) => violations.Add(e.Violation); console.Start(projects, true); return(violations); }
public static void Main(string[] args) { int foundViolatons = 0; string[] filePaths = File.ReadAllLines(args[0]); string projectPath = GetRootPath(filePaths); string settingsPath = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"Settings.StyleCop"); if (File.Exists(settingsPath)) { settingsPath = null; } Console.Error.WriteLine("DEBUG: {0}", settingsPath); StyleCopConsole styleCopConsole = new StyleCopConsole(settingsPath, false, null, null, true); Configuration configuration = new Configuration(null); CodeProject project = new CodeProject(0, projectPath, configuration); foreach (string file in filePaths) { var loaded = styleCopConsole.Core.Environment.AddSourceCode(project, file, null); } List<Violation> violations = new List<Violation>(); styleCopConsole.ViolationEncountered += ((sender, arguments) => violations.Add(arguments.Violation)); List<string> output = new List<string>(); styleCopConsole.OutputGenerated += ((sender, arguments) => output.Add(arguments.Output)); styleCopConsole.Start(new[] { project }, true); foreach (string file in filePaths) { List<Violation> fileViolations = violations.FindAll(viol => viol.SourceCode.Path == file); if (fileViolations.Count > 0) { foundViolatons = 1; Console.Error.WriteLine("{0} - {1} violations.", fileViolations[0].SourceCode.Name, fileViolations.Count); foreach (Violation violation in fileViolations) { Console.Error.WriteLine(" {0}: Line {1}-{2}", violation.Rule.CheckId, violation.Line, violation.Message); } } } Environment.Exit(foundViolatons); }
/// <summary> /// Initializes a new instance of the CodeProject class. /// </summary> /// <param name="key">The unique key for the project.</param> /// <param name="location">The location where the project is contained.</param> /// <param name="configuration">The active configuration.</param> public CodeProject(int key, string location, Configuration configuration) { Param.Ignore(key); Param.Ignore(location); Param.RequireNotNull(configuration, "configuration"); this.key = key; this.configuration = configuration; if (location != null) { // Trim the path and convert it to lowercase characters // so that we can do string matches and find other files and // projects under the same location. this.location = StyleCopCore.CleanPath(location); } }
public void StTestObjectBasedSourceCodeWithNoSettings() { ObjectBasedEnvironment environment = new ObjectBasedEnvironment(this.SourceCodeFactory, this.ProjectSettingsFactory); StyleCopObjectConsole styleCop = new StyleCopObjectConsole(environment, null, new string[] { "%projectroot%\\test\\testbin" }, false); // Create the configuration. Configuration configuration = new Configuration(null); // Create a CodeProject. CodeProject project = new CodeProject(0, null, configuration); styleCop.Core.Environment.AddSourceCode(project, "source1.cs", 0); styleCop.Core.Environment.AddSourceCode(project, "source2.cs", 1); styleCop.Core.Environment.AddSourceCode(project, "source3.cs", 2); styleCop.Start(new CodeProject[] { project }); }
/// <summary> /// Creates a StyleCop report. /// </summary> /// <param name="outputXmlFile"> /// The fully-qualified path to write the output of the report to. /// </param> public void Create(string outputXmlFile) { // Create a StyleCop configuration specifying the configuration // symbols to use for this report. var cfg = new Configuration( this.ProcessorSymbols != null ? this.ProcessorSymbols.ToArray() : null); // Create a new StyleCop console used to do the check. var scc = new StyleCopConsole( this.StyleCopSettingsFile, true, GetViolationsFile(outputXmlFile), this.AddInDirectories, true); // Process solution files if (this.SolutionFiles != null) { foreach (var i in this.SolutionFiles) { this.AddSolutionFile(i); } } // Process project files if (this.ProjectFiles != null) { foreach (var i in this.ProjectFiles) { this.AddProjectFile(i); } } // Process directories if (this.Directories != null) { foreach (var i in this.Directories) { this.AddDirectory(i); } } // Process files if (this.Files != null) { foreach (var i in this.Files) { this.AddFile(i, null); } } // Create a list of code projects from the data set. var cps = this.Report.Projects.Select( r => new CodeProject( r.Id, r.Location, cfg)).ToList(); // Add the source code files to the style cop checker foreach (var f in this.Report.SourceFiles) { var cp = cps.Where(i => i.Key == f.ProjectId).First(); scc.Core.Environment.AddSourceCode( cp, f.Path, null); } if (this.OutputGenerated != null) { scc.OutputGenerated += this.OutputGenerated; } if (this.ViolationEncountered != null) { scc.ViolationEncountered += this.ViolationEncountered; } scc.Start( cps, true); if (this.OutputGenerated != null) { scc.OutputGenerated -= this.OutputGenerated; } if (this.ViolationEncountered != null) { scc.ViolationEncountered -= this.ViolationEncountered; } }
/// <summary> /// Creates a StyleCop report. /// </summary> /// <param name="outputXmlFile"> /// The fully-qualified path to write the output of the report to. /// </param> public void Create(string outputXmlFile) { // Create a StyleCop configuration specifying the configuration // symbols to use for this report. var cfg = new Configuration( this.ProcessorSymbols != null ? this.ProcessorSymbols.ToArray() : null); // Create a new StyleCop console used to do the check. var scc = new StyleCopConsole( this.StyleCopSettingsFile, true, GetViolationsFile(outputXmlFile), this.AddInDirectories, true); // Process solution files if (this.SolutionFiles != null) { foreach (var i in this.SolutionFiles) { this.AddSolutionFile(i); } } // Process project files if (this.ProjectFiles != null) { foreach (var i in this.ProjectFiles) { this.AddProjectFile( i, null); } } // Process directories if (this.Directories != null) { foreach (var i in this.Directories) { this.AddDirectory(i); } } // Process files if (this.Files != null) { foreach (var i in this.Files) { this.AddFile( i, null, null); } } // Create a list of code projects from the data set. var cps = this.Report.Projects.Select( r => { var projfileInfo = new FileInfo(r.Location); var settingsPath = Path.Combine(projfileInfo.Directory.FullName, "Settings.StyleCop"); Settings settings = null; if (File.Exists(settingsPath)) { settings = new Settings(scc.Core, settingsPath); } return new CodeProject(r.ID, r.Location, cfg) { Settings = settings }; }).ToList(); // Add the source code files to the style cop checker foreach (var f in this.Report.SourceCodeFiles) { // ReSharper disable AccessToModifiedClosure var cp = cps.SingleOrDefault(i => i.Key == f.CodeProjectID); scc.Core.Environment.AddSourceCode( cp, f.Path, null); // ReSharper restore AccessToModifiedClosure } if (this.OutputGenerated != null) { scc.OutputGenerated += this.OutputGenerated; } scc.ViolationEncountered += this.ViolationEncountered; scc.Start( cps, true); if (this.OutputGenerated != null) { scc.OutputGenerated -= this.OutputGenerated; } scc.ViolationEncountered -= this.ViolationEncountered; // Write the report to the output XML file. this.Report.WriteXml(outputXmlFile); if (!string.IsNullOrEmpty(this.TransformFile)) { this.Transform(outputXmlFile); } }
/// <summary> /// Create a separate CodeProject for a specified .csproj file /// </summary> /// <param name="projectFilePath">File path to a .csproj file</param> /// <param name="console">Reference to our master console</param> /// <param name="configuration">Configuration from the commandline</param> /// <returns>Newly constructed CodeProject instance</returns> private CodeProject CreateProject(string projectFilePath, StyleCopConsole console, Configuration configuration) { string directory = Path.GetDirectoryName(projectFilePath); CodeProject project = new CodeProject(projectFilePath.GetHashCode(), projectFilePath, configuration); XDocument projectFile = XDocument.Load(projectFilePath); foreach (XElement x in projectFile.Descendants().Where(x => x.Name.LocalName.Equals("Compile"))) { string file = x.Attribute("Include").Value; string filePath = Path.Combine(directory, file); console.Core.Environment.AddSourceCode(project, filePath, null); } return project; }
public void Setup() { var configuration = new Configuration(new string[0]); _project = new CodeProject(Guid.NewGuid().GetHashCode(), null, configuration); }
/// <summary> /// Compares the given configuration with the given list of flags. /// </summary> /// <param name="configuration">The configuration object.</param> /// <param name="flagList">The list of flags.</param> /// <returns>Returns true if the configuration is identical to the flag list, or /// false otherwise.</returns> private static bool CompareCachedConfiguration(Configuration configuration, string flagList) { Param.AssertNotNull(configuration, "configuration"); Param.AssertNotNull(flagList, "flagList"); // Split the flags. string[] flags = new string[0]; string trimmedList = flagList.Trim(); if (trimmedList.Length > 0) { flags = flagList.Split(';'); } // If the counts are different, the configurations are different. if (flags.Length != configuration.Flags.Count) { return false; } // Make sure each of the flags exists in the configuration. foreach (string flag in flags) { if (!configuration.Contains(flag)) { return false; } } return true; }
/// <summary> /// Executes this MSBuild task, based on the input values passed in by the MSBuild engine. /// </summary> /// <returns>Returns true if there were no errors, false otherwise.</returns> public override bool Execute() { // Clear the violation count and set the violation limit for the project. this.violationCount = 0; this.violationLimit = 0; if (this.maxViolationCount != null) { if (!int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit)) { this.violationLimit = 0; } } if (this.violationLimit == 0) { this.violationLimit = DefaultViolationLimit; } // Get settings files (if null or empty use null filename so it uses right default). string overrideSettingsFileName = null; if (this.inputOverrideSettingsFile != null && this.inputOverrideSettingsFile.ItemSpec.Length > 0) { overrideSettingsFileName = this.inputOverrideSettingsFile.ItemSpec; } // Get addin paths. List<string> addinPaths = new List<string>(); foreach (ITaskItem addinPath in this.inputAdditionalAddinPaths) { addinPaths.Add(addinPath.GetMetadata("FullPath")); } // Create the StyleCop console. using (StyleCopConsole console = new StyleCopConsole( overrideSettingsFileName, this.inputCacheResults, this.outputFile == null ? null : this.outputFile.ItemSpec, addinPaths, true)) { // Create the configuration. Configuration configuration = new Configuration(this.inputDefineConstants); string projectFullPath = null; if (this.inputProjectFullPath != null) { projectFullPath = this.inputProjectFullPath.GetMetadata("FullPath"); } if (!string.IsNullOrEmpty(projectFullPath)) { // Create a CodeProject object for these files. CodeProject project = new CodeProject( projectFullPath.GetHashCode(), projectFullPath, configuration); // Add each source file to this project. foreach (ITaskItem inputSourceFile in this.inputSourceFiles) { console.Core.Environment.AddSourceCode(project, inputSourceFile.ItemSpec, null); } try { // Subscribe to events console.OutputGenerated += this.OnOutputGenerated; console.ViolationEncountered += this.OnViolationEncountered; // Analyze the source files CodeProject[] projects = new CodeProject[] { project }; console.Start(projects, this.inputForceFullAnalysis); } finally { // Unsubscribe from events console.OutputGenerated -= this.OnOutputGenerated; console.ViolationEncountered -= this.OnViolationEncountered; } } } return this.succeeded; }
/// <summary> /// Execute StyleCop as configured by this Helper instance /// </summary> public void Execute() { StyleCopConsole console = new StyleCopConsole(SettingsFile, CacheResults, null, mAdditionalAddInPaths, true); Configuration configuration = new Configuration(DefineConstants.ToArray()); List<CodeProject> projects = new List<CodeProject>(); CodeProject defaultProject = new CodeProject(ProjectFile.GetHashCode(), ProjectFile, configuration); projects.Add(defaultProject); foreach (string s in SourceFiles) { string file = Path.GetFullPath(s); string extension = Path.GetExtension(file); if (extension.Equals(".csproj", StringComparison.InvariantCultureIgnoreCase)) { CodeProject p = CreateProject(file, console, configuration); projects.Add(p); } else { console.Core.Environment.AddSourceCode(defaultProject, s, null); } } try { console.OutputGenerated += new EventHandler<OutputEventArgs>(ConsoleOutput); console.ViolationEncountered += new EventHandler<ViolationEventArgs>(ViolationEncountered); console.Start(projects.ToArray(), true); } finally { console.OutputGenerated -= new EventHandler<OutputEventArgs>(ConsoleOutput); console.ViolationEncountered -= new EventHandler<ViolationEventArgs>(ViolationEncountered); } SaveToXml(); }
/// <summary> /// Sets up a CodeProject for use during the test. /// </summary> /// <param name="testInfo">The test information.</param> /// <param name="console">The console which will run the test.</param> /// <param name="autoFix">Indicates whether the test is running in auto-fix mode.</param> /// <param name="copy">Indicates whether to create the file copy.</param> /// <param name="simulationFrameworkVersion">The framework version to simulate.</param> /// <returns> /// Returns the CodeProject. /// </returns> private static CodeProject PrepareCodeProjectForTest(TestInfo testInfo, StyleCopConsole console, bool autoFix, bool copy, double simulationFrameworkVersion) { // Create an empty configuration. Configuration configuration = new Configuration(null); // Create a CodeProject for the test file. CodeProject project = new CodeProject( "TheProject".GetHashCode(), Path.GetDirectoryName(testInfo.StyleCopSettingsFileLocation), configuration, simulationFrameworkVersion); // Add each source file to this project. foreach (TestCodeFileInfo sourceFile in testInfo.TestCodeFiles) { if (autoFix) { string autoFixFile = testInfo.AutoFixFileName(sourceFile.CodeFile); console.Core.Environment.AddSourceCode(project, autoFixFile, null); if (copy) { Directory.CreateDirectory(Path.GetDirectoryName(autoFixFile)); File.Copy(sourceFile.CodeFile, autoFixFile); } } else { console.Core.Environment.AddSourceCode(project, sourceFile.CodeFile, null); } } return project; }
/// <summary> /// Initialize StyleCop console with command-line argument values. /// </summary> static void InitializeConsole() { string settingsFile = Parser.GetValue(SwitchNames.SettingsFile); s_outputFile = Parser.GetValue(SwitchNames.OutputFile); s_console = new StyleCopConsole(settingsFile, true, s_outputFile, null, true); s_configuration = new Configuration(null); if (Parser.IsParsed(SwitchNames.ConfigurationFlags)) { string[] flags = Parser.GetValues(SwitchNames.ConfigurationFlags); s_configuration = new Configuration(flags); } s_codeProjects = new List<CodeProject>(); s_codeProjectKey = 0; s_numberViolations = 0; AddProjectFiles(); AddSolutionFiles(); AddSourceFiles(); if (HasCodeProjects) { Analyzer.OutputGenerated += OnOutputGenerated; Analyzer.ViolationEncountered += OnViolationEncountered; } }
/// <summary> /// Processes a collection of files. /// </summary> /// <param name="settingsPath">The path to the settings file.</param> /// <param name="files">The files to process.</param> /// <param name="autoFix">Indicates whether to automatically fix violations.</param> private static void Process(string settingsPath, IEnumerable<string> files, bool autoFix) { StyleCopConsole console = null; CodeProject project = null; try { Configuration configuration = new Configuration(new string[] { "DEBUG" }); project = new CodeProject(1, "default", configuration); console = new StyleCopConsole(settingsPath, false, null, null, true, autoFix, null); foreach (string file in files) { console.Core.Environment.AddSourceCode(project, file, null); } filesCount += project.SourceCodeInstances.Count; if (!estimateMode) { if (fuzzMode) { console.ViolationEncountered += OnFuzzViolationEncountered; console.OutputGenerated += OnFuzzOutputGenerated; } else { console.ViolationEncountered += OnViolationEncountered; console.OutputGenerated += OnOutputGenerated; } } console.Start(new CodeProject[] { project }, true); } catch (Exception e) { Console.WriteLine("Unhandled exception in StyleCop.\r\n{0}", e.ToString()); if (project != null) { if (project.SourceCodeInstances.Count == 1) { Console.WriteLine(project.SourceCodeInstances[0]); } } } finally { if (console != null) { if (!estimateMode) { if (fuzzMode) { console.ViolationEncountered -= OnFuzzViolationEncountered; console.OutputGenerated -= OnFuzzOutputGenerated; } else { console.ViolationEncountered -= OnViolationEncountered; console.OutputGenerated -= OnOutputGenerated; } } console.Dispose(); } } }