예제 #1
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);
            }
        }
예제 #2
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");
            }
        }
예제 #3
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.SourceCode.Project.ViolationsAsErrors ? LintSeverity.ERROR : LintSeverity.WARNING
                };
                results.Issues.Add(new LintIssue
                {
                    Index = index,
                    LineNumber = e.LineNumber,
                    Column = 0
                });
            };

            // Assign event handlers.
            console.OutputGenerated += outputGenerated;
            console.ViolationEncountered += violationEncountered;

            // Run StyleCop.
            console.Start(projects, false);

            // Finalise.
            console.OutputGenerated -= outputGenerated;
            console.ViolationEncountered -= violationEncountered;
        }
예제 #4
0
        public ConsoleRunner(string settingsPath, string outputPath)
        {
            var addinPaths = new List<string>();
            this.console = new StyleCopConsole(settingsPath, false, outputPath, addinPaths, true);

            this.outputs = new List<string>();
            this.violations = new List<Violation>();
        }
예제 #5
0
        public static void Execute(ICakeContext context, FilePath solutionFile, FilePath settingsFile)
        {
            if (solutionFile == null)
            {
                throw new ArgumentNullException(nameof(solutionFile), "Solution file path is null.");
            }

            var solutionParser = new SolutionParser(context.FileSystem, context.Environment);
            var projectParser  = new ProjectParser(context.FileSystem, context.Environment);

            var stylecopSettingsFile = settingsFile == null ? null : settingsFile.ToString();

            var projectPath = Cake.Common.IO.DirectoryAliases.Directory(context, solutionFile.MakeAbsolute(context.Environment).GetDirectory().FullPath);

            Cake.Common.Diagnostics.LoggingAliases.Information(context, string.Format("Project Path: {0}", projectPath.Path.FullPath));

            var styleCopConsole = new StyleCop.StyleCopConsole(
                stylecopSettingsFile,
                false, /* Input Cache Result */
                null,  /* Output file */
                null,
                true);

            var styleCopProjects = new List <CodeProject>();

            var solution = solutionParser.Parse(solutionFile);

            foreach (var solutionProject in solution.Projects)
            {
                var project         = projectParser.Parse(solutionProject.Path);
                var styleCopProject = new CodeProject(0, solutionProject.Path.GetDirectory().ToString(), new Configuration(null));
                styleCopProjects.Add(styleCopProject);

                foreach (var projectFile in project.Files)
                {
                    if (projectFile.FilePath.GetExtension() == ".cs")
                    {
                        styleCopConsole.Core.Environment.AddSourceCode(
                            styleCopProject,
                            projectFile.FilePath.ToString(),
                            null);
                    }
                }
            }

            var handler = new StylecopHandlers(context);

            styleCopConsole.OutputGenerated      += handler.OnOutputGenerated;
            styleCopConsole.ViolationEncountered += handler.ViolationEncountered;
            styleCopConsole.Start(styleCopProjects.ToArray(), true);
            styleCopConsole.OutputGenerated      -= handler.OnOutputGenerated;
            styleCopConsole.ViolationEncountered -= handler.ViolationEncountered;

            if (handler.TotalViolations > 0)
            {
                throw new Exception(string.Format("{0} StyleCop violations encountered.", handler.TotalViolations));
            }
        }
예제 #6
0
        /// <summary>
        /// Analyzes a code project.
        /// </summary>
        /// <param name="filePath">The code project file path.</param>
        /// <returns>
        /// A <see cref="IEnumerable{T}"/> of <see cref="GitHubStyleViolation"/> containing violations found with the code.
        /// </returns>
        public IEnumerable<GitHubStyleViolation> Analyze(string filePath)
        {
            this.violations.Clear();
            var console = new StyleCopConsole(null, false, null, null, true);

            console.Core.Environment.AddSourceCode(this.project, filePath, null);
            console.ViolationEncountered += this.OnViolationEncountered;

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

            return
                this.violations.Select(
                    violation => new GitHubStyleViolation(violation.Rule.CheckId, violation.Message, violation.Line));
        }
예제 #7
0
        public static void Main(string[] args)
        {
            int foundViolatons = 0;

            string[] filePaths = File.ReadAllLines(args[0]);
            string projectPath = GetRootPath(filePaths);
            string settingsPath = Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, @"Settings.StyleCop");
            if (File.Exists(settingsPath))
            {
                settingsPath = null;
            }
            Console.Error.WriteLine("DEBUG: {0}", settingsPath);
            StyleCopConsole styleCopConsole = new StyleCopConsole(settingsPath, false, null, null, true);

            Configuration configuration = new Configuration(null);

            CodeProject project = new CodeProject(0, projectPath, configuration);

            foreach (string file in filePaths)
            {
                var loaded = styleCopConsole.Core.Environment.AddSourceCode(project, file, null);
            }

            List<Violation> violations = new List<Violation>();
            styleCopConsole.ViolationEncountered += ((sender, arguments) => violations.Add(arguments.Violation));

            List<string> output = new List<string>();
            styleCopConsole.OutputGenerated += ((sender, arguments) => output.Add(arguments.Output));

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

            foreach (string file in filePaths)
            {
                List<Violation> fileViolations = violations.FindAll(viol => viol.SourceCode.Path == file);

                if (fileViolations.Count > 0)
                {
                    foundViolatons = 1;
                    Console.Error.WriteLine("{0} - {1} violations.", fileViolations[0].SourceCode.Name, fileViolations.Count);
                    foreach (Violation violation in fileViolations)
                    {
                        Console.Error.WriteLine("      {0}: Line {1}-{2}", violation.Rule.CheckId, violation.Line, violation.Message);
                    }
                }
            }
            Environment.Exit(foundViolatons);
        }
예제 #8
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;
        }
예제 #9
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));
		}
예제 #10
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);
				}
			}
		}
예제 #11
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));
        }
예제 #12
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;
		}
예제 #13
0
        public static void Main(string[] args)
        {
            string settingsFile = null;
            string outputFile = null;
            string workingDirectory = null;
            List<string> files = new List<string> ();

            string mode = null;
            foreach (string _arg in args) {
                var arg = _arg.Trim ();
                if (arg.StartsWith ("-")) {
                    mode = arg;
                    continue;
                }

                switch (mode) {
                case "-o":
                    outputFile = arg;
                    break;
                case "-s":
                    settingsFile = arg;
                    break;
                case "-w":
                    workingDirectory = arg;
                    break;
                case "-f":
                    files.Add (arg);
                    break;
                case "-l":
                    files.AddRange (System.IO.File.ReadLines (arg));
                    break;
                }
            }

            StyleCopConsole console = new StyleCopConsole (
                settingsFile,
                false,
                outputFile,
                null,
                true);

            CodeProject project = new CodeProject (
                0,
                System.IO.Directory.GetCurrentDirectory (),
                new Configuration (null));

            files.RemoveAll (file => System.String.IsNullOrEmpty (file));

            foreach (string file in files) {
                var filepath = file.Trim ();
                if (workingDirectory != null) {
                    filepath = System.IO.Path.Combine (workingDirectory, file);
                }
                console.Core.Environment.AddSourceCode (project, filepath, null);
            }

            //			console.OutputGenerated += OnOutputGenerated;
            //			console.ViolationEncountered += OnViolationEncountered;
            console.Start (new[] { project }, true);
            //			console.OutputGenerated -= OnOutputGenerated;
            //			console.ViolationEncountered -= OnViolationEncountered;
        }
예제 #14
0
        /// <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();
        }
예제 #15
0
        public void FixtureSetup()
        {
            AddAddInsPath(StyleCopFolder);
            AddAddInsPath(AddInsFolder);

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

            _console = new StyleCopConsole(settings, false, null, _addinPaths, false);

            _console.ViolationEncountered += (sender, args) =>
            {
                // Console.WriteLine(
                //    string.Format(
                //        "Rule '{0}' violated at line {1}: {2}",
                //        args.Violation.Rule.CheckId,
                //        args.LineNumber,
                //        args.Message));
                _violations.Add(args.Violation);
            };

            _console.OutputGenerated += (sender, args) =>
            {
                // Console.WriteLine(args.Output);
                _output.Add(args.Output);
            };
        }
예제 #16
0
        /// <summary>
        /// Executes this MSBuild task, based on the input values passed in by the MSBuild engine.
        /// </summary>
        /// <returns>Returns true if there were no errors, false otherwise.</returns>
        public override bool Execute()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violationCount = 0;
            this.violationLimit = 0;

            if (this.maxViolationCount != null)
            {
                if (!int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit))
                {
                    this.violationLimit = 0;
                }
            }

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

            // Get settings files (if null or empty use null filename so it uses right default).
            string overrideSettingsFileName = null;
            if (this.inputOverrideSettingsFile != null && this.inputOverrideSettingsFile.ItemSpec.Length > 0)
            {
                overrideSettingsFileName = this.inputOverrideSettingsFile.ItemSpec;
            }

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

            // Create the StyleCop console.
            using (StyleCopConsole console = new StyleCopConsole(
                overrideSettingsFileName,
                this.inputCacheResults,
                this.outputFile == null ? null : this.outputFile.ItemSpec,
                addinPaths,
                true))
            {
                // Create the configuration.
                Configuration configuration = new Configuration(this.inputDefineConstants);

                string projectFullPath = null;
                if (this.inputProjectFullPath != null)
                {
                    projectFullPath = this.inputProjectFullPath.GetMetadata("FullPath");
                }

                if (!string.IsNullOrEmpty(projectFullPath))
                {
                    // Create a CodeProject object for these files.
                    CodeProject project = new CodeProject(
                        projectFullPath.GetHashCode(),
                        projectFullPath,
                        configuration);

                    // Add each source file to this project.
                    foreach (ITaskItem inputSourceFile in this.inputSourceFiles)
                    {
                        console.Core.Environment.AddSourceCode(project, inputSourceFile.ItemSpec, null);
                    }

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

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

            return this.succeeded;
        }
예제 #17
0
        /// <summary>
        /// Executes this MSBuild task, based on the input values passed in by the MSBuild engine.
        /// </summary>
        /// <returns>Returns true if there were no errors, false otherwise.</returns>
        public override bool Execute()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violationCount = 0;
            this.violationLimit = 0;

            if (this.maxViolationCount != null)
            {
                if (!int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit))
                {
                    this.violationLimit = 0;
                }
            }

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

            // Get settings files (if null or empty use null filename so it uses right default).
            string overrideSettingsFileName = null;

            if (this.inputOverrideSettingsFile != null && this.inputOverrideSettingsFile.ItemSpec.Length > 0)
            {
                overrideSettingsFileName = this.inputOverrideSettingsFile.ItemSpec;
            }

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

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

            // Create the StyleCop console.
            using (StyleCopConsole console = new StyleCopConsole(
                       overrideSettingsFileName,
                       this.inputCacheResults,
                       this.outputFile == null ? null : this.outputFile.ItemSpec,
                       addinPaths,
                       true))
            {
                // Create the configuration.
                Configuration configuration = new Configuration(this.inputDefineConstants);

                string projectFullPath = null;
                if (this.inputProjectFullPath != null)
                {
                    projectFullPath = this.inputProjectFullPath.GetMetadata("FullPath");
                }

                if (!string.IsNullOrEmpty(projectFullPath))
                {
                    // Create a CodeProject object for these files.
                    CodeProject project = new CodeProject(
                        projectFullPath.GetHashCode(),
                        projectFullPath,
                        configuration);

                    // Add each source file to this project.
                    foreach (ITaskItem inputSourceFile in this.inputSourceFiles)
                    {
                        console.Core.Environment.AddSourceCode(project, inputSourceFile.ItemSpec, null);
                    }

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

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

            return(this.succeeded);
        }
        /// <summary>
        /// Sets up a StyleCopConsole to run the given test.
        /// </summary>
        /// <param name="testInfo">Information about the test to run.</param>
        /// <param name="autoFix">Indicates whether StyleCop should automatically fix the violations it finds.</param>
        /// <returns>Returns the StyleCopConsole.</returns>
        private static StyleCopConsole PrepareStyleCopConsoleForTest(TestInfo testInfo, bool autoFix)
        {
            Debug.Assert(testInfo != null, "The parameter must not be null");

            // Create a list of addin paths and add the path to the currently executing test assembly.
            List<string> addinPaths = new List<string>(1);

            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            addinPaths.Add(Path.GetDirectoryName(assemblyLocation));
            addinPaths.Add(Path.GetDirectoryName(Path.Combine(testInfo.TestOutputPath, @"..\..\")));
            
            // Create the StyleCop console.
            StyleCopConsole console = new StyleCopConsole(
                testInfo.StyleCopSettingsFileLocation,
                false,
                testInfo.StyleCopOutputLocation,
                addinPaths,
                false,
                testInfo.TestOutputPath);

            return console;
        }
예제 #19
0
        /// <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;
        }
        /// <summary>
        /// Sets up a CodeProject for use during the test.
        /// </summary>
        /// <param name="testInfo">The test information.</param>
        /// <param name="console">The console which will run the test.</param>
        /// <param name="autoFix">Indicates whether the test is running in auto-fix mode.</param>
        /// <param name="copy">Indicates whether to create the file copy.</param>
        /// <param name="simulationFrameworkVersion">The framework version to simulate.</param>
        /// <returns>
        /// Returns the CodeProject.
        /// </returns>
        private static CodeProject PrepareCodeProjectForTest(TestInfo testInfo, StyleCopConsole console, bool autoFix, bool copy, double simulationFrameworkVersion)
        {
            // Create an empty configuration.
            Configuration configuration = new Configuration(null);

            // Create a CodeProject for the test file.
            CodeProject project = new CodeProject(
                "TheProject".GetHashCode(),
                Path.GetDirectoryName(testInfo.StyleCopSettingsFileLocation),
                configuration, 
                simulationFrameworkVersion);

            // Add each source file to this project.
            foreach (TestCodeFileInfo sourceFile in testInfo.TestCodeFiles)
            {
                if (autoFix)
                {
                    string autoFixFile = testInfo.AutoFixFileName(sourceFile.CodeFile);
                    console.Core.Environment.AddSourceCode(project, autoFixFile, null);

                    if (copy)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(autoFixFile));
                        File.Copy(sourceFile.CodeFile, autoFixFile);
                    }
                }
                else
                {
                    console.Core.Environment.AddSourceCode(project, sourceFile.CodeFile, null);
                }
            }

            return project;
        }
예제 #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();
                }
            }
        }
예제 #22
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);
                }
            }

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

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

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

            // Add the source code files to the style cop checker
            foreach (var f in this.Report.SourceFiles)
            {
                var cp = cps.Where(i => i.Key == f.ProjectId).First();
                scc.Core.Environment.AddSourceCode(
                    cp,
                    f.Path,
                    null);
            }

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

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

            scc.Start(
                cps,
                true);

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

            if (this.ViolationEncountered != null)
            {
                scc.ViolationEncountered -= this.ViolationEncountered;
            }
        }
예제 #23
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;
		}
예제 #24
0
        /// <summary>
        /// Lancia syileCop su un progetto. le violazioni verranno corrette in maniera mirata.
        /// </summary>
        /// <param name="projectPath">
        /// Il percorso del progetto.
        /// </param>
        /// <param name="filePath">
        /// Il percorso del documento da correggere.
        /// </param>
        public void RunStyleCop(string projectPath, string filePath)
        {
            // Debug.Assert(sfWorkingLines.Count > 0);
            violationContent = new StringBuilder();
            if (!Violations.ContainsKey(filePath))
            {
                violations.Add(filePath, new List<Violation>());
            }

            violations[filePath] = new List<Violation>();       // reset violation list
            StyleCopConsole console = new StyleCopConsole(null, false, null, null, true);
            CodeProject project = new CodeProject(0, projectPath, new Configuration(null));
            console.Core.Environment.AddSourceCode(project, filePath, null);
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(new[] { project }, true);
            console.ViolationEncountered -= OnViolationEncountered;

            // console.Dispose();
        }
예제 #25
0
        /// <summary>
        /// Initialize StyleCop console with command-line argument values.
        /// </summary>
        static void InitializeConsole()
        {
            string settingsFile = Parser.GetValue(SwitchNames.SettingsFile);
            s_outputFile = Parser.GetValue(SwitchNames.OutputFile);

            s_console = new StyleCopConsole(settingsFile, true, s_outputFile, null, true);

            s_configuration = new Configuration(null);

            if (Parser.IsParsed(SwitchNames.ConfigurationFlags))
            {
                string[] flags = Parser.GetValues(SwitchNames.ConfigurationFlags);

                s_configuration = new Configuration(flags);
            }

            s_codeProjects = new List<CodeProject>();

            s_codeProjectKey = 0;
            s_numberViolations = 0;

            AddProjectFiles();
            AddSolutionFiles();
            AddSourceFiles();

            if (HasCodeProjects)
            {
                Analyzer.OutputGenerated += OnOutputGenerated;
                Analyzer.ViolationEncountered += OnViolationEncountered;
            }
        }
예제 #26
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 =>
                    {
                        var projfileInfo = new FileInfo(r.Location);
                        var settingsPath = Path.Combine(projfileInfo.Directory.FullName, "Settings.StyleCop");
                        Settings settings = null;
                        if (File.Exists(settingsPath))
                        {
                            settings = new Settings(scc.Core, settingsPath);
                        }

                        return new CodeProject(r.ID, r.Location, cfg) { Settings = settings };
                    }).ToList();

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

                // ReSharper restore AccessToModifiedClosure
            }

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

            scc.ViolationEncountered += this.ViolationEncountered;

            scc.Start(
                cps,
                true);

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

            scc.ViolationEncountered -= this.ViolationEncountered;

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

            if (!string.IsNullOrEmpty(this.TransformFile))
            {
                this.Transform(outputXmlFile);
            }
        }