public void RightEnumName()
        {
            var project = new CodeProject(1, @".\TestData", new Configuration(new string[] { "DEBUG" }));

            scConsole.Core.Environment.AddSourceCode(project, @".\TestData\Enum_Right.cs", null);

            scConsole.Start(new List <CodeProject>()
            {
                project
            }, true);

            Assert.AreEqual(0, violationList.Count);
        }
Exemple #2
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);
        }
Exemple #3
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");
            }
        }
Exemple #4
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));
            }
        }
Exemple #5
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);
        }
Exemple #6
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);
        }
        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));
            }
        }
Exemple #8
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);
        }
Exemple #9
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);
        }
Exemple #10
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);
        }
        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);
        }
Exemple #12
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);
        }
Exemple #13
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);
                }
            }
        }
Exemple #14
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;
        }
Exemple #15
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);
            }
        }
Exemple #16
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]);
            }
        }
Exemple #17
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;
        }
        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);
        }
Exemple #19
0
        private static int AnalyzeLocal()
        {
            // Collect file list

            var files        = new List <string>();
            var searchOption = _options.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

            foreach (var input in _options.Inputs)
            {
                var isPattern = input.Contains("*") || input.Contains("?");
                if (isPattern)
                {
                    var pathPart = Path.GetDirectoryName(input);
                    var filePart = Path.GetFileName(input);
                    files.AddRange(Directory.GetFiles(string.IsNullOrEmpty(pathPart) ? "." : pathPart, filePart, searchOption).Select(Path.GetFullPath));
                }
                else
                {
                    try
                    {
                        var fileAttr    = File.GetAttributes(input);
                        var isDirectory = (fileAttr & FileAttributes.Directory) == FileAttributes.Directory;
                        if (isDirectory)
                        {
                            files.AddRange(Directory.GetFiles(input, "*", searchOption).Select(Path.GetFullPath));
                        }
                        else
                        {
                            files.Add(Path.GetFullPath(input));
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Path not found: {0}", input);
                        return(1);
                    }
                }
            }

            files = files.Where(CheckFileFilter).ToList();

            // Run StyleCop

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

            var rootPath = GetRootPath(files);
            var project  = new CodeProject(0, rootPath, new Configuration(null));

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

            styleCop.OutputGenerated += OnOutputGenerated;

            var violationCount = 0;

            styleCop.ViolationEncountered += (sender, e) =>
            {
                Console.Error.WriteLine("{0}({1}): {2} {3}",
                                        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);
        }
        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.");
            // }
        }
Exemple #21
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;
        }
Exemple #23
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);

                // get the associatedChangesets
                IList <Changeset> associatedChangesets = this.ActivityContext.GetValue(this.BuildAssociatedChangesets);

                // workspace for build instance
                var workspace = this.ActivityContext.GetValue(this.Workspace);

                // make sure we have associated changesets
                if (associatedChangesets != null)
                {
                    // loop through changesets to get all the associated files
                    foreach (Changeset changeset in associatedChangesets)
                    {
                        List <Change> files = GetFilesAssociatedWithBuild(changeset.VersionControlServer, changeset.ChangesetId);

                        // loop through files in changeset
                        foreach (Change file in files)
                        {
                            // try catch for ItemNotMappedException. If an item is not the local workspace, continue on after posting
                            // a log message that the local file was not mapped to the workspace.
                            try
                            {
                                if (this.ShowOutput.Get(this.ActivityContext))
                                {
                                    LogBuildMessage(
                                        string.Format(CultureInfo.CurrentCulture, "Adding file to check [{0}", file) +
                                        "]",
                                        BuildMessageImportance.Low);
                                    LogBuildMessage(
                                        string.Format(
                                            CultureInfo.CurrentCulture,
                                            "ServerItem converted to local item [{0}",
                                            workspace.GetLocalItemForServerItem(file.Item.ServerItem)) + "]",
                                        BuildMessageImportance.Low);
                                }

                                console.Core.Environment.AddSourceCode(
                                    project, workspace.GetLocalItemForServerItem(file.Item.ServerItem), null);
                            }
                            catch (ItemNotMappedException itemNotMappedException)
                            {
                                LogBuildMessage(
                                    string.Format(CultureInfo.CurrentCulture, "ItemNotMappedException [{0}", file) +
                                    "]",
                                    BuildMessageImportance.Low);
                            }
                        }
                    }
                }
                else
                {
                    LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "Associated changesets is NULL", BuildMessageImportance.Low));
                }

                if (this.FullStyleCopCompliance.Get(this.ActivityContext))
                {
                    // 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))
                                {
                                    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))
                                    {
                                        LogBuildMessage(
                                            string.Format(
                                                CultureInfo.CurrentCulture, "Adding file to check [{0}", fileInDirectory) +
                                            "]",
                                            BuildMessageImportance.Low);
                                    }

                                    console.Core.Environment.AddSourceCode(project, fileInDirectory, null);
                                }
                            }
                            else
                            {
                                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);
        }
        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;
        }
Exemple #25
0
        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.Warning ? LintSeverity.WARNING : LintSeverity.ERROR
                };
                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>
 /// Starts the style cop analysis.
 /// </summary>
 /// <param name="console">The console.</param>
 /// <param name="project">The project.</param>
 private static void StartStyleCopAnalysis(StyleCopConsole console, CodeProject project)
 {
     console.Start(new[] { project }, true);
 }
Exemple #27
0
        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;
        }
        /// <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();
        }
Exemple #29
0
        /// <summary>
        /// Creates a StyleCop report.
        /// </summary>
        /// <param name="outputXmlFile">
        /// The fully-qualified path to write the output of the report to.
        /// </param>
        public void Create(string outputXmlFile)
        {
            // Create a StyleCop configuration specifying the configuration
            // symbols to use for this report.
            var cfg = new Configuration(
                this.ProcessorSymbols != null
                    ?
                this.ProcessorSymbols.ToArray()
                    :
                null);

            // Create a new StyleCop console used to do the check.
            var scc = new StyleCopConsole(
                this.StyleCopSettingsFile,
                true,
                GetViolationsFile(outputXmlFile),
                this.AddInDirectories,
                true);

            // Process solution files
            if (this.SolutionFiles != null)
            {
                foreach (var i in this.SolutionFiles)
                {
                    this.AddSolutionFile(i);
                }
            }

            // Process project files
            if (this.ProjectFiles != null)
            {
                foreach (var i in this.ProjectFiles)
                {
                    this.AddProjectFile(
                        i,
                        null);
                }
            }

            // Process directories
            if (this.Directories != null)
            {
                foreach (var i in this.Directories)
                {
                    this.AddDirectory(i);
                }
            }

            // Process files
            if (this.Files != null)
            {
                foreach (var i in this.Files)
                {
                    this.AddFile(
                        i,
                        null,
                        null);
                }
            }

            // Create a list of code projects from the data set.
            var cps = this.Report.Projects.Select(
                r => new CodeProject(
                    r.ID,
                    r.Location,
                    cfg)).ToList();

            // Add the source code files to the style cop checker
            foreach (var f in this.Report.SourceCodeFiles)
            {
                // ReSharper disable AccessToModifiedClosure
                var cp = cps.SingleOrDefault(i => i.Key == f.CodeProjectID);
                scc.Core.Environment.AddSourceCode(
                    cp,
                    f.Path,
                    null);

                // ReSharper restore AccessToModifiedClosure
            }

            if (this.OutputGenerated != null)
            {
                scc.OutputGenerated += this.OutputGenerated;
            }

            scc.ViolationEncountered += this.ViolationEncountered;

            scc.Start(
                cps,
                true);

            if (this.OutputGenerated != null)
            {
                scc.OutputGenerated -= this.OutputGenerated;
            }

            scc.ViolationEncountered -= this.ViolationEncountered;


            // Write the report to the output XML file.
            this.Report.WriteXml(outputXmlFile);

            if (!string.IsNullOrEmpty(this.TransformFile))
            {
                this.Transform(outputXmlFile);
            }
        }
        /// <summary>
        /// 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.");
            }
        }
Exemple #31
0
        public 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 != 0)
            {
                this.violationLimit = this.MaximumViolationCount;
            }

            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) == false)
            {
                settingsFileName = this.SettingsFile;
            }

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

            if (this.AdditionalAddInPaths != null)
            {
                addinPaths.AddRange(this.AdditionalAddInPaths);
            }

            // 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, this.XmlOutputFile, 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 == null)
            {
                throw new ArgumentException("The list of source files must be specified");
            }
            else
            {
                foreach (var inputSourceLocation in this.SourceFiles)
                {
                    // could be a path or a file
                    if (System.IO.File.Exists(inputSourceLocation))
                    {
                        if (this.ShowOutput)
                        {
                            Debug.WriteLine("Adding file to check [{0}]", inputSourceLocation);
                            Console.WriteLine("Adding file to check [{0}]", inputSourceLocation);
                        }

                        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)
                            {
                                Debug.WriteLine("Adding file to check [{0}]", fileInDirectory);
                                Console.WriteLine("Adding file to check [{0}]", fileInDirectory);
                            }

                            console.Core.Environment.AddSourceCode(project, fileInDirectory, null);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Cannot add file to check [{0}]", inputSourceLocation);
                    }
                }

                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);
                }
                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) == false && this.exitCode == false)
            {
                using (StreamWriter streamWriter = new StreamWriter(this.LogFile, false, Encoding.UTF8))
                {
                    foreach (string i in this.violations)
                    {
                        streamWriter.WriteLine(i);
                    }
                }
            }

            this.Succeeded      = this.exitCode;
            this.ViolationCount = this.violations.Count;
        }
        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);
        }
Exemple #33
0
        public void RightEntityTest()
        {
            _scConsole.Core.Environment.AddSourceCode(_project, TestEntitiesPath + @"\RightEntity.cs", null);
            _scConsole.Start(new List <CodeProject> {
                _project
            }, true);

            Assert.AreEqual(0, _violations.Count);
        }