/// <summary> /// Initializes a new instance of the CodeFile class. /// </summary> /// <param name="path"> /// The path to the code file. /// </param> /// <param name="project"> /// The project that contains this file. /// </param> /// <param name="parser"> /// The parser that created this file object. /// </param> /// <param name="configurations"> /// The list of configurations for the file. /// </param> public CodeFile(string path, CodeProject project, SourceParser parser, IEnumerable <Configuration> configurations) : base(project, parser, configurations) { Param.RequireNotNull(path, "path"); Param.RequireNotNull(project, "project"); Param.RequireNotNull(parser, "parser"); Param.Ignore(configurations); // If this is not a full path, then we need to add the current directory. if (!path.StartsWith(@"\\", StringComparison.Ordinal) && path.Length >= 2 && path[1] != ':') { path = System.IO.Path.GetFullPath(path); } // BugFix 6777 - Update the path field after correcting the local path variable this.path = path; this.name = System.IO.Path.GetFileName(path); this.folder = StyleCopCore.CleanPath(System.IO.Path.GetDirectoryName(path)); // Strip out the file extension. this.fileType = System.IO.Path.GetExtension(this.name).ToUpperInvariant(); if (this.fileType.Length > 0) { this.fileType = this.fileType.Substring(1); } }
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> /// Starts analyzing the source code documents contained within the given project. /// </summary> /// <param name="project">The project to analyze.</param> /// <param name="fullAnalyze">Determines whether to ignore cache files and reanalyze /// every file from scratch.</param> /// <returns>Returns false if an error occurs during analysis.</returns> public bool Start(CodeProject project, bool fullAnalyze) { Param.RequireNotNull(project, "project"); Param.Ignore(fullAnalyze); return(this.Start(new CodeProject[] { project }, fullAnalyze)); }
/// <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"); } }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project">The project containing the settings.</param> /// <param name="merge">Indicates whether to merge the settings with parent settings before returning them.</param> /// <param name="exception">Returns an exception if one occured while loading the settings.</param> /// <returns>Returns the settings.</returns> public override Settings GetProjectSettings(CodeProject project, bool merge, out Exception exception) { Param.RequireNotNull(project, "project"); Param.Ignore(merge); Param.Ignore(merge); // Create the full string to the local settings file. string path = Path.Combine(project.Location, Settings.DefaultFileName); if (!File.Exists(path)) { string deprecatedSettingsFilePath = Path.Combine(project.Location, Settings.AlternateFileName); if (File.Exists(deprecatedSettingsFilePath)) { path = deprecatedSettingsFilePath; } else { deprecatedSettingsFilePath = Path.Combine(project.Location, V40Settings.DefaultFileName); if (File.Exists(deprecatedSettingsFilePath)) { path = deprecatedSettingsFilePath; } } } return(this.GetSettings(path, merge, out exception)); }
/// <summary> /// Adds a source code document to the given project. /// </summary> /// <param name="project">The project which should contain the source code instance.</param> /// <param name="path">The path to the source code document to add.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns true if any source code documents were added to the project.</returns> public override bool AddSourceCode(CodeProject project, string path, object context) { Param.RequireNotNull(project, "project"); Param.RequireValidString(path, "path"); Param.Ignore(context); bool added = false; // Get the parsers for this file based on its extension. string extension = Path.GetExtension(path); if (extension != null && extension.Length > 0) { // Remove the leading dot and convert the extension to lower-case. extension = extension.Substring(1).ToUpperInvariant(); ICollection <SourceParser> parserList = this.GetParsersForFileType(extension); if (parserList != null) { // Create SourceCode objects representing this file, for each parser. foreach (SourceParser parser in parserList) { // Create and return a SourceCode for this file. SourceCode source = this.CreateCodeFile(path, project, parser, context); project.AddSourceCode(source); added = true; } } } return(added); }
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; }
/// <summary> /// Initializes a new instance of the VisualStudioCodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="configurations">The list of configurations for the file.</param> internal VisualStudioCodeFile(string path, CodeProject project, SourceParser parser, IEnumerable <Configuration> configurations) : base(path, project, parser, configurations) { Param.AssertNotNull(path, "path"); Param.AssertNotNull(project, "project"); Param.AssertNotNull(parser, "parser"); Param.Ignore(configurations); }
/// <summary> /// Initializes a new instance of the VisualStudioCodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="configurations">The list of configurations for the file.</param> internal VisualStudioCodeFile(string path, CodeProject project, SourceParser parser, IEnumerable<Configuration> configurations) : base(path, project, parser, configurations) { Param.AssertNotNull(path, "path"); Param.AssertNotNull(project, "project"); Param.AssertNotNull(parser, "parser"); Param.Ignore(configurations); }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project"> /// The project containing the settings. /// </param> /// <param name="merge"> /// Indicates whether to merge the settings with parent settings before returning them. /// </param> /// <returns> /// Returns the settings. /// </returns> public Settings GetProjectSettings(CodeProject project, bool merge) { Param.Ignore(project, merge); Exception exception; return(this.GetProjectSettings(project, merge, out exception)); }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project"> /// The project containing the settings. /// </param> /// <param name="merge"> /// Indicates whether to merge the settings with parent settings before returning them. /// </param> /// <param name="exception"> /// Returns an exception if one occurred while loading the settings. /// </param> /// <returns> /// Returns the settings. /// </returns> public override Settings GetProjectSettings(CodeProject project, bool merge, out Exception exception) { Param.RequireNotNull(project, "project"); Param.Ignore(merge); Param.Ignore(merge); return(this.GetSettings(project.Location, merge, out exception)); }
/// <summary> /// Initializes a new instance of the SourceCode class. /// </summary> /// <param name="project"> /// The project that contains this document. /// </param> /// <param name="parser"> /// The parser that created this document. /// </param> protected SourceCode(CodeProject project, SourceParser parser) { Param.RequireNotNull(project, "project"); Param.RequireNotNull(parser, "parser"); this.project = project; this.parser = parser; }
/// <summary> /// Retrieves a <see cref="SourceCode" /> object corresponding to the given path. /// </summary> /// <param name="path">The path to the source code object.</param> /// <param name="project">The project which contains the source code object.</param> /// <param name="parser">The parser for the source code type.</param> /// <param name="context">Optional context.</param> /// <returns>Returns the source code object.</returns> private SourceCode SourceCodeFactory(string path, CodeProject project, SourceParser parser, object context) { Param.Ignore(path, project, parser, context); int index = (int)context; Assert.IsTrue(index >= 0 && index < StaticSource.Sources.Length, "The index is out of range."); return new ObjectBasedSourceCode(project, parser, index); }
/// <summary> /// Initializes a new instance of the <see cref="ObjectBasedSourceCode"/> class. /// </summary> /// <param name="project"> /// The project. /// </param> /// <param name="parser"> /// The parser. /// </param> /// <param name="index"> /// The index. /// </param> public ObjectBasedSourceCode(CodeProject project, SourceParser parser, int index) : base(project, parser) { Param.Ignore(project); Param.Ignore(parser); Param.AssertValueBetween(index, 0, StaticSource.Sources.Length - 1, "Out of range."); this.index = index; }
public CodeText(string text, CodeProject project, SourceParser parser, IEnumerable<Configuration> configurations) : base(project, parser, configurations) { Param.RequireNotNull(text, "text"); Param.RequireNotNull(project, "project"); Param.RequireNotNull(parser, "parser"); Param.Ignore(configurations); this.text = text; }
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); }
/// <summary> /// Opens the results cache for the given code project. /// </summary> /// <param name="project"> /// The code project. /// </param> /// <param name="projectNode"> /// Returns the node from the results cache for this code project. /// </param> /// <returns> /// Returns the results cache. /// </returns> private XmlDocument OpenCacheProject(CodeProject project, out XmlNode projectNode) { Param.AssertNotNull(project, "project"); projectNode = null; XmlDocument doc = null; try { lock (this) { // Determine whether this project is already in our list. if (this.documentHash.TryGetValue(project.Location, out doc)) { // Now pull out the section for this project. projectNode = doc.DocumentElement.SelectSingleNode( string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key.ToString(CultureInfo.InvariantCulture))); } else { // Load the document if it exists and add it to the hashtable. doc = this.core.Environment.LoadResultsCache(project.Location); if (doc != null) { // Get the version and make sure it matches. XmlElement node = doc["stylecopresultscache"]["version"]; if (node.InnerText == ResultsCache.Version) { // Now pull out the section for this project. projectNode = doc.DocumentElement.SelectSingleNode( string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key.ToString(CultureInfo.InvariantCulture))); } else { // Since the version does not match, ignore this document. doc = null; } } } } } catch (XmlException) { doc = null; } catch (NullReferenceException) { doc = null; } return(doc); }
public Source(CodeProject project, SourceParser parser, string source, string sourceName) : base(project, parser) { Param.Ignore(project); Param.Ignore(parser); Param.AssertNotNull(source, "source"); Param.AssertNotNull(sourceName, "sourceName"); this.source = source; this.sourceName = sourceName; }
public IDictionary<string, List<Violation>> GetViolations(IProjectElement project, ISourceCode sourceCode) { var styleCopProject = new CodeProject( project.FullName.GetHashCode(), this.GetProjectFolder(project), this.configuration); this.violations.Clear(); this.environment.AddSourceCode(styleCopProject, sourceCode.FilePath, sourceCode); this.styleCopConsole.Start(new List<CodeProject> { styleCopProject }); return new Dictionary<string, List<Violation>>(this.violations); }
/// <summary> /// Adds a source code document to the given project. /// </summary> /// <param name="project">The project which should contain the source code instance.</param> /// <param name="path">The path to the source code document to add.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns true if any source code documents were added to the project.</returns> public bool AddSourceCode(CodeProject project, string path, object context) { Param.RequireNotNull(project, "project"); Param.RequireValidString(path, "path"); Param.Ignore(context); if (this.Environment == null) { throw new InvalidOperationException(); } return(this.Environment.AddSourceCode(project, path, context)); }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project">The project containing the settings.</param> /// <returns>Returns the settings or null if the settings could not be loaded.</returns> /// <remarks>If a settings path has been provided by the host, the project is ignored and /// the alternate settings provided by the host are loaded instead.</remarks> public Settings GetSettings(CodeProject project) { Param.AssertNotNull(project, "project"); // Create the dictionary key based on the path to the settings being loaded. int key = project.Key; if (this.settingsPath != null) { key = this.settingsPath.GetHashCode(); } Settings loadedSettings = null; // Try to load this from the cache. if (this.settings != null) { this.settings.TryGetValue(key, out loadedSettings); } // If the settings were not loaded from the cache, load them from scratch. if (loadedSettings == null) { // Check whether custom settings have been specified. if (this.settingsPath != null) { loadedSettings = this.core.Environment.GetSettings(this.settingsPath, true); } else { loadedSettings = this.core.Environment.GetProjectSettings(project, true); } // Save the settings in the cache. if (loadedSettings != null) { // Create the dictionary if needed. if (this.settings == null) { this.settings = new Dictionary <int, Settings>(); } // Add the settings to the dictionary. this.settings.Add(key, loadedSettings); } } return(loadedSettings); }
/// <summary> /// Gets the analysis status for the given project. /// </summary> /// <param name="project">The project.</param> /// <returns>Returns the analysis status for the project.</returns> public ProjectStatus GetProjectStatus(CodeProject project) { Param.AssertNotNull(project, "project"); ProjectStatus status; if (!this.projectStatus.TryGetValue(project, out status)) { // Create a new status object and add add it to the dictionary. status = new ProjectStatus(); this.projectStatus.Add(project, status); } return(status); }
/// <summary> /// Initializes a new instance of the <see cref="CodeAnalyzer"/> class. /// </summary> /// <param name="projectPath">The path of the project to analyze.</param> /// <exception cref="ArgumentException">The projectPath argument is an empty string.</exception> /// <exception cref="ArgumentNullException">The projectPath argument is an empty string.</exception> public CodeAnalyzer(string projectPath) { if (projectPath == null) { throw new ArgumentNullException("projectPath"); } if (projectPath.Length == 0) { throw new ArgumentException("Cannot be empty.", "projectPath"); } this.violations = new Queue<Violation>(); this.project = new CodeProject(0, projectPath, new Configuration(null)); }
public static CodeProject CreateCodeProject(IEnumerable<string> codeFiles, string location, StyleCopEnvironment environment) { var codeProject = new CodeProject(Guid.NewGuid().GetHashCode(), location, new Configuration(new string[0])); foreach (string codeFile in codeFiles) { if (!File.Exists(codeFile)) { throw new FileNotFoundException("File " + codeFile + " not found.", codeFile); } environment.AddSourceCode(codeProject, Path.GetFullPath(codeFile), null); } return codeProject; }
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); }
public ViolationList GetViolationsFromProject(Project project) { this.violations = new ViolationList(); var styleCopProject = new CodeProject(0, project.Path, new Configuration(null)); var console = new StyleCopConsole(project.Settings, false, null, null, true); foreach (var file in project.Files) { console.Core.Environment.AddSourceCode(styleCopProject, file, null); } console.ViolationEncountered += this.OnViolationEncountered; console.Start(new[] { styleCopProject }, true); console.ViolationEncountered -= this.OnViolationEncountered; return this.violations; }
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 }); }
public void Run(ModData modData, string[] args) { var relativePath = args[1]; var projectPath = Path.GetFullPath(relativePath); var console = new StyleCopConsole(null, false, null, null, true); var project = new CodeProject(0, projectPath, new Configuration(null)); foreach (var filePath in Directory.GetFiles(projectPath, "*.cs", SearchOption.AllDirectories)) console.Core.Environment.AddSourceCode(project, filePath, null); console.ViolationEncountered += OnViolationEncountered; console.Start(new[] { project }, true); if (violationCount > 0) Environment.Exit(1); else Console.WriteLine("No violations encountered in {0}.".F(relativePath)); }
/// <summary> /// Creates a new <see cref="CodeFile"/> instance with the given values. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns the newly created <see cref="CodeFile"/>.</returns> protected override CodeFile CreateCodeFile(string path, CodeProject project, SourceParser parser, object context) { Param.Ignore(path, project, parser, context); ProjectItem p = context as ProjectItem; if (p != null) { return new VisualStudioCodeFile(path, project, parser, p); } Document d = context as Document; if (d != null) { return new VisualStudioCodeFile(path, project, parser, d); } return new VisualStudioCodeFile(path, project, parser); }
/// <summary> /// Builds code document from specified source code. /// </summary> private static CsDocument BuildCodeDocument(string sourceCode) { string tempFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CodeHelperTest.cs"); File.WriteAllText(tempFile, sourceCode); CodeProject project = new CodeProject(0, string.Empty, new Configuration(null)); CsParser parser = new CsParser(); parser.FileTypes.Add("CS"); parser.PreParse(); CodeFile file = new CodeFile(tempFile, project, parser); CodeDocument doc = null; parser.ParseFile(file, 0, ref doc); File.Delete(tempFile); return (CsDocument)doc; }
/// <summary> /// Creates a new <see cref="CodeFile"/> instance with the given values. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns the newly created <see cref="CodeFile"/>.</returns> protected override CodeFile CreateCodeFile(string path, CodeProject project, SourceParser parser, object context) { Param.Ignore(path, project, parser, context); ProjectItem p = context as ProjectItem; if (p != null) { return(new VisualStudioCodeFile(path, project, parser, p)); } Document d = context as Document; if (d != null) { return(new VisualStudioCodeFile(path, project, parser, d)); } return(new VisualStudioCodeFile(path, project, parser)); }
private static void FixStyleCopRule(string projectFilePath, string rule, EventHandler<ViolationEventArgs> onViolationEncountered) { foreach (string filePath in GetCSharpFiles(projectFilePath)) { StyleCopConsole console = new StyleCopConsole(null, false, null, null, true); CodeProject project = new CodeProject(0, Path.GetDirectoryName(projectFilePath), new Configuration(null)); bool fileHasBeenFixed = false; List<Tuple<int, string>> sourceCode = File.ReadAllText(filePath).Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None) .Select((line, index) => new Tuple<int, string>(index + 1, line)).ToList(); if (console.Core.Environment.AddSourceCode(project, filePath, null)) { console.ViolationEncountered += onViolationEncountered; console.ViolationEncountered += (sender, e) => { if (e.Violation.Rule.CheckId == rule) { FixStyleCopViolation(sourceCode, e); Console.WriteLine("{0}({1}): {2}", rule, e.LineNumber, filePath); fileHasBeenFixed = true; } }; console.Start(new[] { project }, true); } if (fileHasBeenFixed) { //preserve text encoding System.Text.Encoding encoding; using (StreamReader reader = new StreamReader(filePath, true)) { encoding = reader.CurrentEncoding; } File.WriteAllText(filePath, string.Join(Environment.NewLine, sourceCode.Select(x => x.Item2)), encoding); } } }
void IUtilityCommand.Run(Utility utility, string[] args) { var relativePath = args[1]; var projectPath = Path.GetFullPath(relativePath); // HACK: The engine code assumes that Game.modData is set. Game.ModData = utility.ModData; var console = new StyleCopConsole(null, false, null, null, true); var project = new CodeProject(0, projectPath, new Configuration(null)); foreach (var filePath in Directory.GetFiles(projectPath, "*.cs", SearchOption.AllDirectories)) console.Core.Environment.AddSourceCode(project, filePath, null); console.ViolationEncountered += OnViolationEncountered; console.Start(new[] { project }, true); if (violationCount > 0) Environment.Exit(1); else Console.WriteLine("No violations encountered in {0}.".F(relativePath)); }
/// <summary> /// Pulls out the next source code document. /// </summary> /// <returns>Returns the source code document to analyze or null if none.</returns> private SourceCode ExtractNextSourceCodeDocument() { SourceCode sourceCode = null; while (this.projectIndex < this.projects.Count) { CodeProject project = this.projects[this.projectIndex]; ++this.sourceCodeInstanceIndex; if (this.sourceCodeInstanceIndex >= project.SourceCodeInstances.Count) { ++this.projectIndex; this.sourceCodeInstanceIndex = -1; } else { sourceCode = project.SourceCodeInstances[this.sourceCodeInstanceIndex]; break; } } return(sourceCode); }
/// <summary> /// Runs StyleCop+ for specified file. /// </summary> public void Run(string sourceFile, SpecialRunningParameters specialRunningParameters) { Violations.Clear(); Output.Length = 0; string basePath = AppDomain.CurrentDomain.BaseDirectory; StyleCopConsole console = new StyleCopConsole( null, false, null, new List<string>(new[] { basePath }), true); StyleCopPlusRules styleCopPlus = ExtractStyleCopPlus(console); if (styleCopPlus == null) { throw new InvalidOperationException("StyleCopPlus was not found."); } styleCopPlus.SpecialRunningParameters = specialRunningParameters; CodeProject project = new CodeProject( 0, basePath, new Configuration(null)); console.Core.Environment.AddSourceCode(project, sourceFile, null); console.ViolationEncountered += OnViolationEncountered; console.OutputGenerated += OnOutputGenerated; console.Start(new[] { project }, true); console.OutputGenerated -= OnOutputGenerated; console.ViolationEncountered -= OnViolationEncountered; }
/// <summary> /// Loads the given project from the cache. /// </summary> /// <param name="project"> /// The project to load. /// </param> /// <returns> /// Returns the project configuration or null if the /// project does not exist in the cache. /// </returns> public string LoadProject(CodeProject project) { Param.AssertNotNull(project, "project"); lock (this) { XmlNode item = null; XmlDocument doc = this.OpenCacheProject(project, out item); if (doc != null && item != null) { try { // Get the configuration string. XmlElement node = item["configuration"]; if (node != null) { return(node.InnerText); } } catch (XmlException) { } catch (NullReferenceException) { } if (!this.documentHash.ContainsKey(project.Location)) { this.documentHash.Add(project.Location, doc); } } return(null); } }
/// <summary> /// Initializes a new instance of the VisualStudioCodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="document">The Visual Studio IDE document mapping to this file.</param> internal VisualStudioCodeFile(string path, CodeProject project, SourceParser parser, Document document) : base(path, project, parser, null) { Param.Ignore(path, project, parser, document); this.document = document; }
/// <summary> /// Initializes a new instance of the CodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="configurations">The list of configurations for the file.</param> public CodeFile(string path, CodeProject project, SourceParser parser, IEnumerable <Configuration> configurations) : base(project, parser, configurations) { Param.RequireNotNull(path, "path"); Param.RequireNotNull(project, "project"); Param.RequireNotNull(parser, "parser"); Param.Ignore(configurations); this.path = path; // If this is not a full path, then we need to add the current directory. if (!path.StartsWith(@"\\", StringComparison.Ordinal) && path.Length >= 2 && path[1] != ':') { // Get the current directory. Remove the trailing slash if it exists. string directory = Directory.GetCurrentDirectory(); if (directory.EndsWith(@"\", StringComparison.Ordinal)) { directory = directory.Substring(0, directory.Length - 1); } // Check whether the path starts with a single slash or not. if (path.StartsWith(@"\", StringComparison.Ordinal)) { // Prepend the drive letter. string newPath = directory.Substring(0, 2) + path; path = newPath; } else { // Prepend the current directory. string newPath = directory + @"\" + path; path = newPath; } } // Strip out the name of the file. int index = path.LastIndexOf(@"\", StringComparison.Ordinal); if (-1 == index) { this.name = this.path; } else { this.name = path.Substring(index + 1, path.Length - index - 1); this.folder = path.Substring(0, index); if (this.folder != 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 path. this.folder = StyleCopCore.CleanPath(this.folder); } } // Strip out the file extension. index = this.name.LastIndexOf(".", StringComparison.Ordinal); if (-1 == index) { this.fileType = string.Empty; } else { this.fileType = this.name.Substring(index + 1, this.name.Length - index - 1).ToUpperInvariant(); } }
/// <summary> /// Initializes a new instance of the CodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> public CodeFile(string path, CodeProject project, SourceParser parser) : this(path, project, parser, null) { Param.Ignore(path, project, parser); }
/// <summary> /// Initializes a new instance of the VisualStudioCodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="projectItem">The Visual Studio IDE project item mapping to this file.</param> internal VisualStudioCodeFile(string path, CodeProject project, SourceParser parser, ProjectItem projectItem) : base(path, project, parser, null) { Param.Ignore(path, project, parser, projectItem); this.projectItem = projectItem; }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project">The project.</param> /// <returns>Returns the settings, or null if there </returns> protected virtual Settings GetSettingsForProject(CodeProject project) { Param.Ignore(project); return null; }
/// <summary> /// Adds a source code document to the given project. /// </summary> /// <param name="project">The project which should contain the source code instance.</param> /// <param name="path">The path to the source code document to add.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns true if any source code documents were added to the project.</returns> public override bool AddSourceCode(CodeProject project, string path, object context) { Param.RequireNotNull(project, "project"); Param.RequireValidString(path, "path"); Param.Ignore(context); bool added = false; // Get the parsers for this file based on its extension. string extension = Path.GetExtension(path); if (extension != null && extension.Length > 0) { // Remove the leading dot and convert the extension to lower-case. extension = extension.Substring(1).ToUpperInvariant(); ICollection<SourceParser> parserList = this.GetParsersForFileType(extension); if (parserList != null) { // Create SourceCode objects representing this file, for each parser. foreach (SourceParser parser in parserList) { // Create and return a SourceCode for this file. SourceCode source = this.CreateCodeFile(path, project, parser, context); project.AddSourceCode(source); added = true; } } } return added; }
/// <summary> /// Add given Visual C# source file to given code project. /// </summary> /// <param name="sourceFile"> /// CSharpSourceFile representing Visual C# source file to add. /// </param> /// <param name="codeProject"> /// Code project to add Visual C# source file to. /// </param> static void AddSourceFile(CSharpSourceFile sourceFile, CodeProject codeProject) { sourceFile.Load(); Analyzer.Core.Environment.AddSourceCode(codeProject, sourceFile.FilePath, null); }
/// <summary> /// Opens the results cache for the given code project. /// </summary> /// <param name="project"> /// The code project. /// </param> /// <param name="projectNode"> /// Returns the node from the results cache for this code project. /// </param> /// <returns> /// Returns the results cache. /// </returns> private XmlDocument OpenCacheProject(CodeProject project, out XmlNode projectNode) { Param.AssertNotNull(project, "project"); projectNode = null; XmlDocument doc = null; try { lock (this) { // Determine whether this project is already in our list. if (this.documentHash.TryGetValue(project.Location, out doc)) { // Now pull out the section for this project. projectNode = doc.DocumentElement.SelectSingleNode( string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key.ToString(CultureInfo.InvariantCulture))); } else { // Load the document if it exists and add it to the hashtable. doc = this.core.Environment.LoadResultsCache(project.Location); if (doc != null) { // Get the version and make sure it matches. XmlElement node = doc["stylecopresultscache"]["version"]; if (node.InnerText == ResultsCache.Version) { // Now pull out the section for this project. projectNode = doc.DocumentElement.SelectSingleNode( string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key.ToString(CultureInfo.InvariantCulture))); } else { // Since the version does not match, ignore this document. doc = null; } } } } } catch (XmlException) { doc = null; } catch (NullReferenceException) { doc = null; } return doc; }
/// <summary> /// Saves the given code project configuration into a cache document. /// </summary> /// <param name="project"> /// The project to save. /// </param> /// <returns> /// Returns true if the configuration was saved. /// </returns> public bool SaveProject(CodeProject project) { Param.AssertNotNull(project, "project"); bool success = false; lock (this) { XmlDocument xml = null; try { if (!this.documentHash.TryGetValue(project.Location, out xml)) { XmlNode temp; xml = this.OpenCacheProject(project, out temp); if (xml != null) { this.documentHash.Add(project.Location, xml); } } if (xml != null) { XmlNode remove = xml.DocumentElement.SelectSingleNode(string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key)); if (remove != null) { xml.DocumentElement.RemoveChild(remove); } } else { xml = new XmlDocument(); // Create the document node. xml.AppendChild(xml.CreateElement("stylecopresultscache")); // Add the version. XmlNode versionNode = xml.CreateElement("version"); xml.DocumentElement.AppendChild(versionNode); versionNode.InnerText = ResultsCache.Version; if (this.documentHash.ContainsKey(project.Location)) { this.documentHash.Remove(project.Location); } this.documentHash.Add(project.Location, xml); } XmlNode root = xml.CreateElement("project"); XmlAttribute key = xml.CreateAttribute("key"); key.Value = project.Key.ToString(CultureInfo.InvariantCulture); root.Attributes.Append(key); xml.DocumentElement.AppendChild(root); // Add the configuration details. StringBuilder configuration = new StringBuilder(); if (project.Configuration != null) { bool first = true; foreach (string field in project.Configuration.Flags) { if (first) { first = false; configuration.Append(field); } else { configuration.AppendFormat(";{0}", field); } } } XmlNode node = xml.CreateElement("configuration"); root.AppendChild(node); node.InnerText = configuration.ToString(); success = true; } catch (XmlException) { } return success; } }
/// <summary> /// Loads the given project from the cache. /// </summary> /// <param name="project"> /// The project to load. /// </param> /// <returns> /// Returns the project configuration or null if the /// project does not exist in the cache. /// </returns> public string LoadProject(CodeProject project) { Param.AssertNotNull(project, "project"); lock (this) { XmlNode item = null; XmlDocument doc = this.OpenCacheProject(project, out item); if (doc != null && item != null) { try { // Get the configuration string. XmlElement node = item["configuration"]; if (node != null) { return node.InnerText; } } catch (XmlException) { } catch (NullReferenceException) { } if (!this.documentHash.ContainsKey(project.Location)) { this.documentHash.Add(project.Location, doc); } } return null; } }
public abstract Settings GetProjectSettings(CodeProject project, bool merge, out Exception exception);
/// <summary> /// Initializes a new instance of the SourceCode class. /// </summary> /// <param name="project"> /// The project that contains this document. /// </param> /// <param name="parser"> /// The parser that created this document. /// </param> /// <param name="configurations"> /// The list of configurations for the document. /// </param> protected SourceCode(CodeProject project, SourceParser parser, IEnumerable <Configuration> configurations) : this(project, parser) { Param.Ignore(project, parser, configurations); this.configurations = configurations; }
/// <summary> /// Adds a source code document to the given project. /// </summary> /// <param name="project"> /// The project which should contain the source code instance. /// </param> /// <param name="path"> /// The path to the source code document to add. /// </param> /// <param name="context"> /// Optional context information. /// </param> /// <returns> /// Returns true if any source code documents were added to the project. /// </returns> public abstract bool AddSourceCode(CodeProject project, string path, object context);
/// <summary> /// Starts analyzing the source code documents contained within the given project. /// </summary> /// <param name="project">The project to analyze.</param> /// <returns>Returns false if an error occurs during analysis.</returns> public bool Start(CodeProject project) { Param.RequireNotNull(project, "project"); return this.Start(new CodeProject[] { project }); }
/// <summary> /// Initializes a new instance of the VisualStudioCodeFile class. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> internal VisualStudioCodeFile(string path, CodeProject project, SourceParser parser) : base(path, project, parser, null) { Param.Ignore(path, project, parser); }
/// <summary> /// Creates a new <see cref="CodeFile"/> instance with the given values. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns the newly created <see cref="CodeFile"/>.</returns> protected virtual CodeFile CreateCodeFile(string path, CodeProject project, SourceParser parser, object context) { Param.Ignore(path, project, parser, context); return(new CodeFile(path, project, parser)); }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project"> /// The project. /// </param> /// <returns> /// Returns the settings, or null if there /// </returns> protected virtual Settings GetSettingsForProject(CodeProject project) { Param.Ignore(project); return null; }
/// <summary> /// Gets the settings for the given project. /// </summary> /// <param name="project">The project containing the settings.</param> /// <param name="merge">Indicates whether to merge the settings with parent settings before returning them.</param> /// <param name="exception">Returns an exception if one occured while loading the settings.</param> /// <returns>Returns the settings.</returns> public override Settings GetProjectSettings(CodeProject project, bool merge, out Exception exception) { Param.RequireNotNull(project, "project"); Param.Ignore(merge); Param.Ignore(merge); // Create the full string to the local settings file. string path = Path.Combine(project.Location, Settings.DefaultFileName); if (!File.Exists(path)) { string deprecatedSettingsFilePath = Path.Combine(project.Location, Settings.AlternateFileName); if (File.Exists(deprecatedSettingsFilePath)) { path = deprecatedSettingsFilePath; } else { deprecatedSettingsFilePath = Path.Combine(project.Location, V40Settings.DefaultFileName); if (File.Exists(deprecatedSettingsFilePath)) { path = deprecatedSettingsFilePath; } } } return this.GetSettings(path, merge, out exception); }
/// <summary> /// Saves the given code project configuration into a cache document. /// </summary> /// <param name="project"> /// The project to save. /// </param> /// <returns> /// Returns true if the configuration was saved. /// </returns> public bool SaveProject(CodeProject project) { Param.AssertNotNull(project, "project"); bool success = false; lock (this) { XmlDocument xml = null; try { if (!this.documentHash.TryGetValue(project.Location, out xml)) { XmlNode temp; xml = this.OpenCacheProject(project, out temp); if (xml != null) { this.documentHash.Add(project.Location, xml); } } if (xml != null) { XmlNode remove = xml.DocumentElement.SelectSingleNode(string.Format(CultureInfo.InvariantCulture, "project[@key=\"{0}\"]", project.Key)); if (remove != null) { xml.DocumentElement.RemoveChild(remove); } } else { xml = new XmlDocument(); // Create the document node. xml.AppendChild(xml.CreateElement("stylecopresultscache")); // Add the version. XmlNode versionNode = xml.CreateElement("version"); xml.DocumentElement.AppendChild(versionNode); versionNode.InnerText = ResultsCache.Version; if (this.documentHash.ContainsKey(project.Location)) { this.documentHash.Remove(project.Location); } this.documentHash.Add(project.Location, xml); } XmlNode root = xml.CreateElement("project"); XmlAttribute key = xml.CreateAttribute("key"); key.Value = project.Key.ToString(CultureInfo.InvariantCulture); root.Attributes.Append(key); xml.DocumentElement.AppendChild(root); // Add the configuration details. StringBuilder configuration = new StringBuilder(); if (project.Configuration != null) { bool first = true; foreach (string field in project.Configuration.Flags) { if (first) { first = false; configuration.Append(field); } else { configuration.AppendFormat(";{0}", field); } } } XmlNode node = xml.CreateElement("configuration"); root.AppendChild(node); node.InnerText = configuration.ToString(); success = true; } catch (XmlException) { } return(success); } }
/// <summary> /// Creates a new <see cref="CodeFile"/> instance with the given values. /// </summary> /// <param name="path">The path to the code file.</param> /// <param name="project">The project that contains this file.</param> /// <param name="parser">The parser that created this file object.</param> /// <param name="context">Optional context information.</param> /// <returns>Returns the newly created <see cref="CodeFile"/>.</returns> protected virtual CodeFile CreateCodeFile(string path, CodeProject project, SourceParser parser, object context) { Param.Ignore(path, project, parser, context); return new CodeFile(path, project, parser); }
/// <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); }