示例#1
0
        private static int AnalyzeSubversion()
        {
            var fileMap = SaveCommittedFilesToTemp();

            // Run StyleCop

            var styleCop = new StyleCopConsole(_options.Settings, false, null, null, true);

            var rootPath = GetRootPath(fileMap.Keys.ToList());
            var project  = new CodeProject(0, rootPath, new Configuration(null));

            foreach (var file in fileMap.Keys.ToList())
            {
                styleCop.Core.Environment.AddSourceCode(project, file, null);
            }

            styleCop.OutputGenerated += OnOutputGenerated;

            var violationCount = 0;

            styleCop.ViolationEncountered += (sender, e) =>
            {
                Console.Error.WriteLine("{0}({1}): {2} {3}",
                                        fileMap[e.SourceCode.Path], e.LineNumber, e.Violation.Rule.CheckId, e.Message);

                violationCount += 1;
            };

            styleCop.Start(new[] { project }, true);

            Console.Error.WriteLine("");
            Console.Error.WriteLine("{0} Violations found", violationCount);

            return(violationCount > 0 ? 2 : 0);
        }
示例#2
0
        private static int ProcessFolder(string settings, string projectPath, SearchOption searchOption)
        {
            Log($"Using Stylecop settings located at '{settings}'");
            Log($"Checking folder: {new FileInfo(projectPath).FullName}");
            var console = new StyleCopConsole(settings, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            var files = Directory.EnumerateFiles(projectPath, "*.cs", searchOption).ToList();

            files = GetCSharpFiles(files);
            Log($"Checking {files.Count} files");


            foreach (var file in files)
            {
                console.Core.Environment.AddSourceCode(project, file, null);
            }

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            if (_encounteredViolations > 0)
            {
                Log($"Finished with {_encounteredViolations} errors");
                return((int)ExitCode.Failed);
            }

            Log("Success");
            return((int)ExitCode.Passed);
        }
        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));
            }
        }
示例#4
0
 public void Destroy()
 {
     _project = null;
     _scConsole.ViolationEncountered -= scConsole_ViolationEncontered;
     _scConsole.OutputGenerated      -= scConsole_OutputGenerated;
     _scConsole = null;
 }
示例#5
0
        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));
            }
        }
示例#6
0
        private static int ProcessFileOrFolder(string settings, string path, string outputFile, SearchOption searchOption)
        {
            var console = new StyleCopConsole(settings, false, outputFile, null, true);
            var project = new CodeProject(0, path, new Configuration(null));

            if (Path.GetExtension(path) == ".cs")
            {
                console.Core.Environment.AddSourceCode(project, path, null);
            }
            else
            {
                foreach (var file in Directory.EnumerateFiles(path, "*.cs", searchOption))
                {
                    //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                    if (file.Contains("\\packages\\"))
                    {
                        continue;
                    }

                    console.Core.Environment.AddSourceCode(project, file, null);
                }
            }

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            return(_encounteredViolations > 0 ? (int)ExitCode.Failed : (int)ExitCode.Passed);
        }
示例#7
0
        /// <summary>
        /// Initialize StyleCop console with command-line argument values.
        /// </summary>
        static void InitializeConsole()
        {
            string settingsFile = Parser.GetValue(SwitchNames.SettingsFile);
            string outputFile   = Parser.GetValue(SwitchNames.OutputFile);

            s_console = new StyleCopConsole(settingsFile, true, 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;
            }
        }
示例#8
0
        /// <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 Initialize()
 {
     scConsole     = new StyleCopConsole(null, true, null, null, true, null);
     violationList = new List <Violation>();
     scConsole.ViolationEncountered += scConsole_ViolationEncountered;
     scConsole.OutputGenerated      += scConsole_OutputGenerated;
 }
示例#10
0
        /// <summary>
        /// Finds StyleCop+ analyzer and removes all other analyzers.
        /// </summary>
        private static StyleCopPlusRules ExtractStyleCopPlus(StyleCopConsole console)
        {
            StyleCopPlusRules styleCopPlus = null;

            foreach (SourceParser parser in console.Core.Parsers)
            {
                List <SourceAnalyzer> analyzersToRemove = new List <SourceAnalyzer>();
                foreach (SourceAnalyzer analyzer in parser.Analyzers)
                {
                    if (typeof(StyleCopPlusRules) == analyzer.GetType())
                    {
                        styleCopPlus = (StyleCopPlusRules)analyzer;
                        break;
                    }

                    analyzersToRemove.Add(analyzer);
                }

                foreach (SourceAnalyzer analyzer in analyzersToRemove)
                {
                    parser.Analyzers.Remove(analyzer);
                }
            }

            return(styleCopPlus);
        }
示例#11
0
        /// <summary>
        /// Initialize stylecop console
        /// </summary>
        /// <param name="context">The cake context.</param>
        /// <returns>Instance of stylecop console.</returns>
        private static StyleCopConsole InitializeStyleCopConsole(
            ICakeContext context)
        {
            var settingsFile = settings.SettingsFile?.ToString();
            var outputPath   = settings.ResultsFile?.ToString();
            var addins       = settings.Addins.Count == 0 ? null : settings.Addins.Select(x => x.FullPath).ToList();

            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;
            }
            return(styleCopConsole);
        }
        public void FixtureSetup()
        {
            this.AddAddInsPath(this.StyleCopFolder);
            this.AddAddInsPath(this.AddInsFolder);

            string settings = this.Settings;
            if (!File.Exists(settings))
            {
                throw new FileNotFoundException(settings);
            }

            this.console = new StyleCopConsole(settings, false, null, this.addinPaths, false);

            this.console.ViolationEncountered += (sender, args) =>
            {
                this.violations.Add(args.Violation);
                Console.WriteLine("Rule '{0}' violated at line {1}: {2}",
                                  args.Violation.Rule.CheckId,
                                  args.LineNumber,
                                  args.Message);
            };

            this.console.OutputGenerated += (sender, args) =>
            {
                this.output.Add(args.Output);
                Console.WriteLine(args.Output);
            };
        }
示例#13
0
        private static int ProcessFolder(string settings, string projectPath, string outputFile, SearchOption searchOption, string rule)
        {
            var console = new StyleCopConsole(settings, false, outputFile, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var file in Directory.EnumerateFiles(projectPath, "*.cs", searchOption))
            {
                //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                if (file.Contains("\\packages\\"))
                {
                    continue;
                }

                console.Core.Environment.AddSourceCode(project, file, null);
            }

            var violationEncounteredFilter = new EventHandler <ViolationEventArgs>(delegate(Object sender, ViolationEventArgs args)
            {
                if (string.IsNullOrEmpty(rule) || rule.Equals(args.Violation.Rule.CheckId))
                {
                    OnViolationEncountered(sender, args);
                }
            });

            console.OutputGenerated      += OnOutputGenerated;
            console.ViolationEncountered += violationEncounteredFilter;
            console.Start(new[] { project }, true);
            console.OutputGenerated      -= OnOutputGenerated;
            console.ViolationEncountered -= violationEncounteredFilter;

            return(_encounteredViolations > 0 ? (int)ExitCode.Failed : (int)ExitCode.Passed);
        }
示例#14
0
 public void Initialaze()
 {
     _scConsole  = new StyleCopConsole(TestProjectPath, true, null, null, true, null);
     _project    = new CodeProject(1, TestProjectPath, new Configuration(new string[0]));
     _violations = new List <Violation>();
     _scConsole.ViolationEncountered += scConsole_ViolationEncontered;
     _scConsole.OutputGenerated      += scConsole_OutputGenerated;
 }
示例#15
0
 /// <summary>
 /// Adds the source code files.
 /// </summary>
 /// <param name="files">The files.</param>
 /// <param name="console">The console.</param>
 /// <param name="project">The project.</param>
 private static void AddSourceCodeFiles(
     IEnumerable <string> files,
     StyleCopConsole console,
     CodeProject project)
 {
     foreach (var file in files)
     {
         console.Core.Environment.AddSourceCode(project, file, null);
     }
 }
        protected SourceAnalysisTest()
        {
            var settings   = Path.GetFullPath(StyleCopSettingsFilePath);
            var addinPaths = new List <string>();

            Console = new StyleCopConsole(settings, false, null, addinPaths, true);

            Console.ViolationEncountered +=
                (sender, args) => Violations.Add(args.Violation);

            Console.OutputGenerated +=
                (sender, args) => Output.Add(args.Output);
        }
示例#17
0
        /// <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);
        }
示例#18
0
        private bool RunStyleCopRules(List <string> srcFilestoCheck, TfsVariable tfsVariables, UserVariable <StyleCopSetting> usrVariables)
        {
            List <string> addInPaths = new List <string> {
                usrVariables.WorkingPath
            };
            string styleSettingFile = FindRuleFile(usrVariables);

            // Create the StyleCop console. But do not initialise the addins as this can cause modal dialogs to be shown on errors
            var console = new StyleCopConsole(styleSettingFile, false, "StyleCopXmlOutputFile.xml", null, false);

            // make sure the UI is not dispayed on error
            console.Core.DisplayUI = false;

            // declare the add-ins to load
            console.Core.Initialize(addInPaths, true);

            // Create the configuration.
            Configuration configuration = new Configuration(new string[0]);

            // Create a CodeProject object for these files. we use a time stamp for the key and the current directory for the cache location
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), @".\", configuration);

            foreach (var itmFile in srcFilestoCheck)
            {
                console.Core.Environment.AddSourceCode(project, itmFile, null);
            }

            try
            {
                // Subscribe to events
                console.OutputGenerated      += this.OnOutputGenerated;
                console.ViolationEncountered += this.OnViolationEncountered;

                // Analyze the source files
                CodeProject[] projects    = new[] { project };
                var           startResult = console.Start(projects, true);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                // Unsubscribe from events
                console.OutputGenerated      -= this.OnOutputGenerated;
                console.ViolationEncountered -= this.OnViolationEncountered;
            }

            return(violateError.Count <= usrVariables.Config.MaxErrorCount);
        }
示例#19
0
        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);
        }
示例#20
0
        /// <summary>
        /// Mains entry point.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            if (ValidateCommandLineParameters(args))
            {
                return;
            }

            string projectPath         = args[0];
            IEnumerable <string> files = GetAllFileNames(projectPath);
            var console = new StyleCopConsole(null, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            AddSourceCodeFiles(files, console, project);
            SubscribeStyleCopConsoleEvents(console);
            StartStyleCopAnalysis(console, project);
            UnsubscribeStyleCopConsoleEvents(console);
            DisposeStyleCopConsole(console);
        }
示例#21
0
        public void RuleTest(string checkId, StyleCopViolations expectedValidationResult)
        {
            // arrange
            Directory.CreateDirectory(Locations.ValidationResultDirectory);
            string validationResultPath = Path.Combine(Locations.ValidationResultDirectory, $"{checkId}.xml");

            string ruleSettingPath = Path.Combine(Locations.TestDataDirectory, checkId, $"{checkId}.StyleCop");
            string codePath        = Path.Combine(Locations.TestDataDirectory, checkId, $"{checkId}.cs");

            CodeProject project = new CodeProject(
                checkId.GetHashCode(),
                Locations.BaseDirectory,
                new Configuration(null),
                0);

            StyleCopConsole console = new StyleCopConsole(
                ruleSettingPath,
                false,
                validationResultPath,
                Locations.AddInDirectory,
                false,
                Locations.BaseDirectory);

            console.Core.Environment.AddSourceCode(project, codePath, null);

            // act
            console.Start(new CodeProject[] { project }, true);

            StyleCopViolations actualValidationResult;

            using (Stream s = new FileStream(validationResultPath, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(StyleCopViolations));
                actualValidationResult = (StyleCopViolations)serializer.Deserialize(s);
            }

            // assert
            bool testDataExist = File.Exists(ruleSettingPath) && File.Exists(codePath);

            testDataExist.Should().BeTrue();
            actualValidationResult.ViolationItems.Should().BeEquivalentTo(expectedValidationResult.ViolationItems);
        }
示例#22
0
        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);
                }
            }
        }
示例#23
0
        /// <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);
        }
示例#24
0
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: OpenRA.StyleCheck.exe DIRECTORY");
                Console.WriteLine("Check the *.cs source code files in a directory for code style violations.");
                return;
            }

            var projectPath = Path.GetFullPath(args[0]);
            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);
            }

            var violationCount = 0;

            console.ViolationEncountered += (object sender, ViolationEventArgs e) => {
                violationCount++;
                var path = e.SourceCode.Path.Replace(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar, "");
                Console.WriteLine("{0}:L{1}: [{2}] {3}", path, e.LineNumber, e.Violation.Rule.CheckId, e.Message);
            };

            console.Start(new[] { project }, true);

            if (violationCount > 0)
            {
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("No violations encountered in {0}.", args[0]);
            }
        }
示例#25
0
        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);
            }
        }
示例#26
0
        /// <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;
        }
示例#27
0
        private static int ProcessFolder(string settings, string projectPath, SearchOption searchOption)
        {
            var console = new StyleCopConsole(settings, false, null, null, true);
            var project = new CodeProject(0, projectPath, new Configuration(null));

            foreach (var file in Directory.EnumerateFiles(projectPath, "*.cs", SearchOption.AllDirectories))
            {
                //TODO: This is pretty hacky. Have to figure out a better way to exclude packages and/or make this configurable.
                if (file.Contains("\\packages\\"))
                {
                    continue;
                }

                console.Core.Environment.AddSourceCode(project, file, null);
            }

            console.OutputGenerated += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] {project}, true);
            console.OutputGenerated -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;

            return _encounteredViolations > 0 ? (int) ExitCode.Failed : (int) ExitCode.Passed;
        }
        /// <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.");
            }
        }
        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)
            {
                int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit);
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            Log.LogMessage(MessageImportance.Low, "ViolationLimit: '{0}'", this.violationLimit);

            // 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;
            }

            Log.LogMessage(MessageImportance.Low, "OverrideSettingsFile: '{0}'", overrideSettingsFileName ?? "(none)");

            Log.LogMessage(MessageImportance.Low, "CacheResults: '{0}'", CacheResults);

            var outputFile = OutputFile == null ? null : OutputFile.ItemSpec;

            Log.LogMessage(MessageImportance.Low, "OutputFile: '{0}'", outputFile ?? "(none)");

            // Get addin paths.
            List <string> addinPaths = new List <string>();

            foreach (ITaskItem addinPath in this.inputAdditionalAddinPaths)
            {
                addinPaths.Add(addinPath.GetMetadata("FullPath"));
            }

            if (addinPaths.Count > 0)
            {
                Log.LogMessage(MessageImportance.Low, "AdditionalAddins:");
                foreach (var addinPath in addinPaths)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", addinPath);
                }
            }

            if (this.IgnoreVoluntaryRules)
            {
                Log.LogMessage(MessageImportance.Low, "IgnoreVoluntaryRules: True");
            }

            if (this.AlwaysIgnoredRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "AlwaysIgnoredRuleIds:");
                foreach (var ruleId in this.AlwaysIgnoredRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            if (this.MandatoryRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "MandatoryRuleIds:");
                foreach (var ruleId in this.MandatoryRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            // Create the StyleCop console.
            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);

            Log.LogMessage(MessageImportance.Low, "ProjectFullPath: '{0}'", ProjectFullPath == null ? "(null)" : ProjectFullPath.ItemSpec ?? "(none)");

            if (this.inputProjectFullPath != null && this.inputProjectFullPath.ItemSpec != null)
            {
                // Add each source file to this project.
                if (SourceFiles != null && SourceFiles.Length > 0)
                {
                    Log.LogMessage(MessageImportance.Low, "SourceFiles:");
                    foreach (var sourceFile in SourceFiles)
                    {
                        Log.LogMessage(
                            MessageImportance.Low,
                            "\t'{0}'",
                            sourceFile == null ? "(null)" : sourceFile.ItemSpec ?? "(none)");
                    }
                }

                Log.LogMessage(MessageImportance.Low, "ForceFullAnalysis: '{0}'", ForceFullAnalysis);

                // Create a CodeProject object for these files.
                CodeProject project = new CodeProject(
                    this.inputProjectFullPath.ItemSpec.GetHashCode(),
                    this.inputProjectFullPath.ItemSpec,
                    configuration);

                // Add each source file to this project.
                if (SourceFiles != null)
                {
                    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);
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format("{0}", exception.Message));

                    if (ThrowOnError)
                    {
                        throw;
                    }

                    return(false);
                }
                finally
                {
                    // Unsubscribe from events
                    console.OutputGenerated      -= this.OnOutputGenerated;
                    console.ViolationEncountered -= this.OnViolationEncountered;
                }
            }

            return(this.succeeded);
        }
示例#30
0
        static void Main(string[] args)
        {
            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 = "./StyleCop.Runner.csproj";
            //var settingsFile = args[1];
            var outputPath = "Results.xml";
            //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;

            styleCopConsole = new StyleCopConsole(
                null,
                false,
                /* Input Cache Result */
                outputPath,
                /* Output file */
                null,
                false);

            var styleCopProjects = new List <CodeProject>();

            var styleCopProject = new CodeProject(0, args[0], new Configuration(null));

            styleCopProjects.Add(styleCopProject);
            styleCopConsole.Core.Environment.AddSourceCode(styleCopProject, args[1], 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(), true);
            //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.");
            // }
        }
示例#31
0
        /// <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();
                }
            }
        }
        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)
            {
                int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit);
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            Log.LogMessage(MessageImportance.Low, "ViolationLimit: '{0}'", this.violationLimit);

            // 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;
            }

            Log.LogMessage(MessageImportance.Low, "OverrideSettingsFile: '{0}'", overrideSettingsFileName ?? "(none)");

            Log.LogMessage(MessageImportance.Low, "CacheResults: '{0}'", CacheResults);

            var outputFile = OutputFile == null ? null : OutputFile.ItemSpec;
            Log.LogMessage(MessageImportance.Low, "OutputFile: '{0}'", outputFile ?? "(none)");

            // Get addin paths.
            List<string> addinPaths = new List<string>();
            foreach (ITaskItem addinPath in this.inputAdditionalAddinPaths)
            {
                addinPaths.Add(addinPath.GetMetadata("FullPath"));
            }

            if (addinPaths.Count > 0)
            {
                Log.LogMessage(MessageImportance.Low, "AdditionalAddins:");
                foreach (var addinPath in addinPaths)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", addinPath);
                }
            }

            if (this.IgnoreVoluntaryRules)
            {
                Log.LogMessage(MessageImportance.Low, "IgnoreVoluntaryRules: True");
            }

            if (this.AlwaysIgnoredRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "AlwaysIgnoredRuleIds:");
                foreach (var ruleId in this.AlwaysIgnoredRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            if (this.MandatoryRuleIds != null)
            {
                Log.LogMessage(MessageImportance.Low, "MandatoryRuleIds:");
                foreach (var ruleId in this.MandatoryRuleIds)
                {
                    Log.LogMessage(MessageImportance.Low, "\t'{0}'", ruleId);
                }
            }

            // Create the StyleCop console.
            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);

            Log.LogMessage(MessageImportance.Low, "ProjectFullPath: '{0}'", ProjectFullPath == null ? "(null)" : ProjectFullPath.ItemSpec ?? "(none)");

            if (this.inputProjectFullPath != null && this.inputProjectFullPath.ItemSpec != null)
            {
                // Add each source file to this project.
                if (SourceFiles != null && SourceFiles.Length > 0)
                {
                    Log.LogMessage(MessageImportance.Low, "SourceFiles:");
                    foreach (var sourceFile in SourceFiles)
                    {
                        Log.LogMessage(
                            MessageImportance.Low,
                            "\t'{0}'",
                            sourceFile == null ? "(null)" : sourceFile.ItemSpec ?? "(none)");
                    }
                }

                Log.LogMessage(MessageImportance.Low, "ForceFullAnalysis: '{0}'", ForceFullAnalysis);

                // Create a CodeProject object for these files.
                CodeProject project = new CodeProject(
                    this.inputProjectFullPath.ItemSpec.GetHashCode(),
                    this.inputProjectFullPath.ItemSpec,
                    configuration);

                // Add each source file to this project.
                if (SourceFiles != null)
                {
                    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);
                }
                catch (Exception exception)
                {
                    Log.LogError(string.Format("{0}", exception.Message));

                    if (ThrowOnError) throw;

                    return false;
                }
                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>
        /// 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;
        }
        private void Scan()
        {
            this.LogTaskMessage("Performing StyleCop scan...");
            if (File.Exists(this.SettingsFile.GetMetadata("FullPath")) == false)
            {
                Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Settings file was not found: {0}", this.SettingsFile.GetMetadata("FullPath")));
                return;
            }

            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "SourceFiles count is: {0}", this.SourceFiles.Length));
            List<string> addinPaths = new List<string>();
            StyleCopConsole console = new StyleCopConsole(this.SettingsFile.GetMetadata("FullPath"), this.CacheResults, this.OutputFile == null ? null : this.OutputFile.GetMetadata("FullPath"), addinPaths, true);
            
            Configuration configuration = new Configuration(new string[0]);
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), null, configuration);
            foreach (ITaskItem item2 in this.SourceFiles)
            {
                if (this.ShowOutput)
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding file: {0}", item2.ItemSpec));
                }

                if (!console.Core.Environment.AddSourceCode(project, item2.ItemSpec, null))
                {
                    Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to add file: {0}", item2.ItemSpec));
                    return;
                }
            }

            try
            {
                if (this.ShowOutput)
                {
                    console.OutputGenerated += this.OnOutputGenerated;
                }

                console.ViolationEncountered += this.OnViolationEncountered;
                CodeProject[] projects = new[] { project };
                console.Start(projects, this.ForceFullAnalysis);
            }
            finally
            {
                if (this.ShowOutput)
                {
                    console.OutputGenerated -= this.OnOutputGenerated;
                }

                console.ViolationEncountered -= this.OnViolationEncountered;
            }

            // log the results to disk if there have been failures AND LogFile is specified
            if (this.LogFile != null && this.Succeeded == false)
            {
                using (StreamWriter streamWriter = new StreamWriter(this.LogFile.GetMetadata("FullPath"), false, Encoding.UTF8))
                {
                    foreach (ITaskItem i in this.FailedFiles)
                    {
                        string checkid = i.GetMetadata("CheckId") ?? "NoCheckIdFound";
                        string message = i.GetMetadata("Message") ?? "NoMessageFound";
                        string linenumber = i.GetMetadata("LineNumber") ?? "NoLineNumberFound";
                        streamWriter.WriteLine(i.ItemSpec + " (" + checkid + ": " + message + " Line: " + linenumber + ")");
                    }
                }
            }

            // set the ViolationCount
            this.ViolationCount = this.failedFiles.Count;
        }
示例#36
0
        private void Scan()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violations = new List<string>();
            this.violationLimit = 0;

            if (this.MaximumViolationCount.Get(this.ActivityContext) != 0)
            {
                this.violationLimit = this.MaximumViolationCount.Get(this.ActivityContext);
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            // Get settings files (if null or empty use null filename so it uses default).
            string settingsFileName = string.Empty;
            if (string.IsNullOrEmpty(this.SettingsFile.Get(this.ActivityContext)) == false)
            {
                settingsFileName = this.SettingsFile.Get(this.ActivityContext);
            }

            // Get addin paths.
            List<string> addinPaths = new List<string>();
            if (this.AdditionalAddInPaths.Get(this.ActivityContext) != null)
            {
                addinPaths.AddRange(this.AdditionalAddInPaths.Get(this.ActivityContext));
            }

            // Create the StyleCop console. But do not initialise the addins as this can cause modal dialogs to be shown on errors
            var console = new StyleCopConsole(settingsFileName, this.CacheResults.Get(this.ActivityContext), this.XmlOutputFile.Get(this.ActivityContext), null, false);

            // make sure the UI is not dispayed on error
            console.Core.DisplayUI = false;

            // declare the add-ins to load
            console.Core.Initialize(addinPaths, true);

            // Create the configuration.
            Configuration configuration = new Configuration(new string[0]);

            // Create a CodeProject object for these files. we use a time stamp for the key and the current directory for the cache location
            CodeProject project = new CodeProject(DateTime.Now.ToLongTimeString().GetHashCode(), @".\", configuration);

            // Add each source file to this project.
            if (this.SourceFiles.Get(this.ActivityContext) != null)
            {
                foreach (var inputSourceLocation in this.SourceFiles.Get(this.ActivityContext))
                {
                    // could be a path or a file
                    if (System.IO.File.Exists(inputSourceLocation))
                    {
                        if (this.ShowOutput.Get(this.ActivityContext))
                        {
                            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Adding file to check [{0}", inputSourceLocation) + "]", BuildMessageImportance.Low);
                        }

                        console.Core.Environment.AddSourceCode(project, inputSourceLocation, null);
                    }
                    else if (System.IO.Directory.Exists(inputSourceLocation))
                    {
                        foreach (var fileInDirectory in System.IO.Directory.GetFiles(inputSourceLocation, "*.cs", SearchOption.AllDirectories))
                        {
                            if (this.ShowOutput.Get(this.ActivityContext))
                            {
                                this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Adding file to check [{0}", fileInDirectory) + "]", BuildMessageImportance.Low);
                            }

                            console.Core.Environment.AddSourceCode(project, fileInDirectory, null);
                        }
                    }
                    else
                    {
                        this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Cannot add file to check [{0}", inputSourceLocation) + "]", BuildMessageImportance.Low);
                    }
                }

                try
                {
                    // Subscribe to events
                    console.OutputGenerated += this.OnOutputGenerated;
                    console.ViolationEncountered += this.OnViolationEncountered;

                    // Analyze the source files
                    CodeProject[] projects = new[] { project };
                    console.Start(projects, this.ForceFullAnalysis.Get(this.ActivityContext));
                }
                finally
                {
                    // Unsubscribe from events
                    console.OutputGenerated -= this.OnOutputGenerated;
                    console.ViolationEncountered -= this.OnViolationEncountered;
                }
            }

            // log the results to disk as a simple list if there have been failures AND LogFile is specified
            if (string.IsNullOrEmpty(this.LogFile.Get(this.ActivityContext)) == false && this.exitCode == false)
            {
                using (StreamWriter streamWriter = new StreamWriter(this.LogFile.Get(this.ActivityContext), false, Encoding.UTF8))
                {
                    foreach (string i in this.violations)
                    {
                        streamWriter.WriteLine(i);
                    }
                }
            }

            this.Succeeded.Set(this.ActivityContext, this.exitCode);
            this.ViolationCount.Set(this.ActivityContext, this.violations.Count);
        }