예제 #1
0
        public void ArrangeInvalidConfigurationTest()
        {
            string testConfiguration = Path.GetTempFileName();

            File.WriteAllText(testConfiguration, "<xml");

            try
            {
                TestLogger   logger       = new TestLogger();
                FileArranger fileArranger = new FileArranger(testConfiguration, logger);

                bool success = fileArranger.Arrange(_testValidSourceFile1, null);

                Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
                Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
            }
            finally
            {
                try
                {
                    File.Delete(testConfiguration);
                }
                catch
                {
                }
            }
        }
예제 #2
0
        public void ArrangeEmptyProjectTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            string emptyProjectFile = Path.Combine(
                Path.GetTempPath(),
                Guid.NewGuid().ToString().Replace('-', '_') + ".csproj");

            File.WriteAllText(emptyProjectFile, "<Project></Project>");

            try
            {
                bool success = fileArranger.Arrange(emptyProjectFile, null);

                Assert.IsTrue(success, "Expected file to be arranged succesfully.");
                Assert.IsTrue(
                    logger.HasPartialMessage(LogLevel.Warning, "does not contain any supported source files"));
            }
            finally
            {
                try
                {
                    File.Delete(emptyProjectFile);
                }
                catch
                {
                }
            }
        }
예제 #3
0
        public static void Run(DTE dte, VsError selectedError)
        {
            var logger = new ConsoleLogger {
                Trace = true
            };

            Console.WriteLine();
            Console.WriteLine(new string('_', 60));

            selectedError.Navigate();
            string formatString = Properties.StyleRepair.Default.NArrangeUseRegions
                                      ? @"{0}\NArrangeConfigWithRegions.xml"
                                      : @"{0}\NArrangeConfig.xml";

            var fileArranger = new FileArranger(
                string.Format(formatString, Path.GetDirectoryName(Assembly.GetCallingAssembly().Location)),
                Logger.Instance);

            bool success = fileArranger.Arrange(dte.ActiveDocument.FullName, dte.ActiveDocument.FullName, true);

            if (!success)
            {
                logger.LogMessage(LogLevel.Error, "Unable to NArrange {0}.", dte.ActiveDocument.FullName);
            }
        }
예제 #4
0
        /// <summary>
        /// Aranges the given file and saves changes back to the file.
        /// </summary>
        /// <param name="tempFile"></param>
        /// <returns></returns>
        private static bool Arrange(string tempFile)
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            return(fileArranger.Arrange(tempFile, null));
        }
예제 #5
0
파일: Program.cs 프로젝트: wvdvegt/narrange
        /// <summary>
        /// Runs NArrange using the specified arguments.
        /// </summary>
        /// <param name="logger">Logger for messages.</param>
        /// <param name="commandArgs">Command arguments.</param>
        /// <returns>True if succesful, otherwise false.</returns>
        public static bool Run(ILogger logger, CommandArguments commandArgs)
        {
            bool success = true;

            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            else if (commandArgs == null)
            {
                throw new ArgumentNullException("commandArgs");
            }

            if (commandArgs.Restore)
            {
                logger.LogMessage(LogLevel.Verbose, "Restoring {0}...", commandArgs.Input);
                string key = BackupUtilities.CreateFileNameKey(commandArgs.Input);
                try
                {
                    success = BackupUtilities.RestoreFiles(BackupUtilities.BackupRoot, key);
                }
                catch (Exception ex)
                {
                    logger.LogMessage(LogLevel.Warning, ex.Message);
                    success = false;
                }

                if (success)
                {
                    logger.LogMessage(LogLevel.Info, "Restored");
                }
                else
                {
                    logger.LogMessage(LogLevel.Error, "Restore failed");
                }
            }
            else
            {
                //
                // Arrange the source code file
                //
                FileArranger fileArranger = new FileArranger(commandArgs.Configuration, logger);
                success = fileArranger.Arrange(commandArgs.Input, commandArgs.Output, commandArgs.Backup);

                if (!success)
                {
                    logger.LogMessage(LogLevel.Error, "Unable to arrange {0}.", commandArgs.Input);
                }
                else
                {
                    logger.LogMessage(LogLevel.Info, "Arrange successful.");
                }
            }

            return(success);
        }
예제 #6
0
        public void ArrangeInvalidSourceFileTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            bool success = fileArranger.Arrange(_testInvalidSourceFile, null);

            Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
            Assert.IsTrue(logger.HasMessage(LogLevel.Verbose, "0 files written."));
        }
예제 #7
0
        public void ArrangeNonExistantConfigurationTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger("blahblahblahblah.xml", logger);

            bool success = fileArranger.Arrange(_testValidSourceFile1, null);

            Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
            Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
        }
예제 #8
0
        public void ArrangeInvalidExtensionTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            bool success = fileArranger.Arrange(_testInvalidExtensionFile, null);

            Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
            Assert.IsTrue(logger.HasPartialMessage(LogLevel.Warning, "No assembly is registered to handle file"));
        }
예제 #9
0
        public void ArrangeSolutionTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            bool success = fileArranger.Arrange(_testSolutionFile, null);

            Assert.IsTrue(success, "Expected file to be arranged succesfully.");
            Assert.IsTrue(
                logger.HasMessage(LogLevel.Verbose, "2 files written."),
                "Expected 2 files to be written. - " + logger.ToString());
        }
예제 #10
0
        public void ArrangeUTF8EncodedSourceFileTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            bool success = fileArranger.Arrange(_testUTF8File, null);

            Assert.IsTrue(success, "Expected file to be arranged succesfully. - " + logger.ToString());
            Assert.IsTrue(
                logger.HasMessage(LogLevel.Verbose, "1 files written."),
                "Expected 1 file to be written. - " + logger.ToString());

            string originalContents = GetTestFileContents("UTF8.cs", Encoding.UTF8);

            originalContents = originalContents.Replace("#endregion", "#endregion Fields");
            Assert.AreEqual(originalContents, File.ReadAllText(_testUTF8File, Encoding.UTF8), "File contents should have been preserved.");
        }
예제 #11
0
        public void ArrangeInvalidExtensionAssemblyTest()
        {
            string xml =
                @"<CodeConfiguration xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
					<Handlers>
						<ProjectHandler Parser='NArrange.Core.MSBuildProjectParser'>
							<ProjectExtensions>
								<Extension Name='csproj'/>
							</ProjectExtensions>
						</ProjectHandler>
						<SourceHandler Assembly='NArrange.BlahBlahBlahBlah, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'>
							<SourceExtensions>
								<Extension Name='cs'/>
							</SourceExtensions>
						</SourceHandler>
					</Handlers>
				</CodeConfiguration>"                ;

            string testConfiguration = Path.GetTempFileName();

            File.WriteAllText(testConfiguration, xml);

            try
            {
                TestLogger logger = new TestLogger();

                FileArranger fileArranger = new FileArranger(testConfiguration, logger);

                bool success = fileArranger.Arrange(_testValidSourceFile1, null);

                Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
                Assert.IsTrue(logger.HasPartialMessage(LogLevel.Error, "Unable to load configuration file"));
            }
            finally
            {
                try
                {
                    File.Delete(testConfiguration);
                }
                catch
                {
                }
            }
        }
예제 #12
0
        public void ArrangeReadOnlySourceFileTest()
        {
            TestLogger   logger       = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, logger);

            File.SetAttributes(_testValidSourceFile1, FileAttributes.ReadOnly);

            try
            {
                bool success = fileArranger.Arrange(_testValidSourceFile1, null);

                Assert.IsFalse(success, "Expected file to not be arranged succesfully.");
                Assert.IsTrue(logger.HasMessage(LogLevel.Verbose, "0 files written."));
            }
            finally
            {
                File.SetAttributes(_testValidSourceFile1, FileAttributes.Normal);
            }
        }
예제 #13
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            ((Logger)logger).EmitHeader();

            //! Get Active Document Path.
            DTE dte = (DTE)ServiceProvider.GetServiceAsync(typeof(DTE))?.Result;

            if (dte == null)
            {
                logger.LogMessage(LogLevel.Error, "NArrange Could not obtain DTE.", new object[] { });

                return;
            }

            string document = dte?.ActiveDocument?.FullName;

            if (String.IsNullOrEmpty(document))
            {
                logger.LogMessage(LogLevel.Error, "NArrange Could not obtain the Path of the ActiveDocument.", new object[] { });

                return;
            }

            //! No CommandArguments (i.e. null).
            FileArranger fileArranger = new FileArranger(null, logger);

            //! Try to NArrange the Active File.
            Boolean success = fileArranger.Arrange(document, document, true);

            switch (success)
            {
            case true:
                logger.LogMessage(LogLevel.Info, "NArrange Successful.", new object[] { });
                break;

            case false:
                logger.LogMessage(LogLevel.Error, "NArrange Failure.", new object[] { });
                break;
            }
        }
예제 #14
0
        public void ArrangeProjectFilteredTest()
        {
            CodeConfiguration filterProjectConfig = CodeConfiguration.Default.Clone() as CodeConfiguration;

            // Set up the filter
            FilterBy filter = new FilterBy();

            filter.Condition = "!($(File.Path) : '.Filtered.')";
            ((ProjectHandlerConfiguration)filterProjectConfig.Handlers[0]).ProjectExtensions[0].FilterBy = filter;

            string filterProjectConfigFile = Path.Combine(Path.GetTempPath(), "FilterProjectConfig.xml");

            try
            {
                filterProjectConfig.Save(filterProjectConfigFile);

                TestLogger   logger       = new TestLogger();
                FileArranger fileArranger = new FileArranger(filterProjectConfigFile, logger);

                bool success = fileArranger.Arrange(_testFilteredProjectFile, null);

                Assert.IsTrue(success, "Expected file to be arranged succesfully.");
                Assert.IsTrue(
                    logger.HasMessage(LogLevel.Verbose, "0 files written."),
                    "Expected 0 files to be written - " + logger.ToString());
            }
            finally
            {
                try
                {
                    File.Delete(filterProjectConfigFile);
                }
                catch
                {
                }
            }
        }
        public void PrettyCodeShouldNotBeModified()
        {
            var tmp = GetTempCSharpFile();

            try
            {
                File.WriteAllText(tmp, GetTestFileContents(_prettyCodeResourceName));
                TestLogger   logger       = new TestLogger();
                FileArranger fileArranger = new FileArranger(null, logger);

                bool success = fileArranger.Arrange(tmp, null);

                Assert.IsTrue(success, "Expected file to be arranged succesfully. - " + logger);
                Assert.IsTrue(
                    logger.HasMessage(LogLevel.Verbose, "0 files written."), "Expected no file to be written. - " + logger);

                string originalContents = GetTestFileContents(_prettyCodeResourceName);
                Assert.AreEqual(originalContents, File.ReadAllText(tmp), "File contents should have been preserved.");
            }
            finally
            {
                File.Delete(tmp);
            }
        }
        public void CodeWithMultilineAutoPropertyShouldBeFormatted()
        {
            var tmp = GetTempCSharpFile();

            try
            {
                File.WriteAllText(tmp, GetTestFileContents(_uglyCodeResourceName));
                TestLogger   logger       = new TestLogger();
                FileArranger fileArranger = new FileArranger(null, logger);

                bool success = fileArranger.Arrange(tmp, null);

                Assert.IsTrue(success, "Expected file to be arranged succesfully. - " + logger);
                Assert.IsTrue(
                    logger.HasMessage(LogLevel.Verbose, "1 files written."), "Expected 1 file to be written. - " + logger);

                string originalContents = GetTestFileContents(_prettyCodeResourceName);
                Assert.AreEqual(originalContents, File.ReadAllText(tmp), "File should have been formatted to look like the pretty code file.");
            }
            finally
            {
                File.Delete(tmp);
            }
        }
예제 #17
0
        /// <summary>
        /// Tests the files.
        /// </summary>
        /// <param name="inputDir">The input dir.</param>
        /// <param name="logger">The logger.</param>
        private static void TestFiles(string inputDir, ILogger logger)
        {
            if (!Directory.Exists(inputDir))
            {
                logger.LogMessage(LogLevel.Error, "Test directory {0} does not exist", inputDir);
                Environment.Exit(Fail);
            }

            string arrangedDir = Path.Combine(inputDir, "Arranged");

            if (Directory.Exists(arrangedDir))
            {
                Directory.Delete(arrangedDir, true);
            }
            Directory.CreateDirectory(arrangedDir);

            FileInfo[] allSourceFiles = GetSourceFileNames(inputDir);
            logger.LogMessage(LogLevel.Info, "Testing with {0} source files...", allSourceFiles.Length);

            int preprocessorCount = 0;
            int uncompiledCount   = 0;
            int successCount      = 0;
            int failedCount       = 0;

            TestLogger   testLogger   = new TestLogger();
            FileArranger fileArranger = new FileArranger(null, testLogger);

            foreach (FileInfo sourceFile in allSourceFiles)
            {
                string initialSource = File.ReadAllText(sourceFile.FullName, Encoding.Default);

                CompilerResults initialResults = CompileSourceFile(sourceFile, initialSource);

                CompilerError error = TestUtilities.GetCompilerError(initialResults);
                if (error == null)
                {
                    logger.LogMessage(LogLevel.Trace, "Succesfully compiled {0}", sourceFile.FullName);

                    //
                    // Arrange the source code file
                    //
                    testLogger.Clear();
                    string outputFile = Path.Combine(arrangedDir, sourceFile.Name);
                    bool   success    = false;
                    try
                    {
                        success = fileArranger.Arrange(sourceFile.FullName, outputFile);
                    }
                    catch (Exception ex)
                    {
                        logger.LogMessage(
                            LogLevel.Error,
                            "Unable to arrange {0}.  {1}",
                            sourceFile.Name,
                            ex.Message);
                        failedCount++;
                    }

                    if (success)
                    {
                        logger.LogMessage(LogLevel.Info, "Arrange successful.");
                    }
                    else if (testLogger.HasPartialMessage(LogLevel.Warning, "preprocessor"))
                    {
                        logger.LogMessage(LogLevel.Trace, "File is unhandled.");
                        preprocessorCount++;
                    }
                    else
                    {
                        foreach (TestLogger.TestLogEvent logEvent in testLogger.Events)
                        {
                            logger.LogMessage(logEvent.Level, logEvent.Message);
                        }

                        logger.LogMessage(LogLevel.Error, "Unable to arrange {0}.", sourceFile.Name);
                        failedCount++;
                    }

                    if (success)
                    {
                        string          arrangedSource  = File.ReadAllText(outputFile, Encoding.Default);
                        CompilerResults arrangedResults = CompileSourceFile(
                            new FileInfo(outputFile), arrangedSource);

                        CompilerError arrangedError = TestUtilities.GetCompilerError(arrangedResults);
                        if (arrangedError == null)
                        {
                            logger.LogMessage(LogLevel.Trace, "Succesfully compiled arranged file {0}", outputFile);
                            try
                            {
                                bool assembliesMatch = CompareAssemblies(
                                    initialResults.CompiledAssembly, arrangedResults.CompiledAssembly, logger);
                                if (assembliesMatch)
                                {
                                    successCount++;
                                }
                                else
                                {
                                    logger.LogMessage(LogLevel.Error, "Arranged assembly differs.");
                                    failedCount++;
                                }
                            }
                            catch (ReflectionTypeLoadException ex)
                            {
                                logger.LogMessage(
                                    LogLevel.Error,
                                    "Failed to load one or more types. {0}, {1}",
                                    outputFile,
                                    ex.ToString());
                                failedCount++;
                            }
                        }
                        else
                        {
                            logger.LogMessage(
                                LogLevel.Error,
                                "Failed to compile arranged file {0}, {1}",
                                outputFile,
                                arrangedError.ToString());
                            failedCount++;
                        }
                    }
                }
                else
                {
                    logger.LogMessage(LogLevel.Error, "Failed to compile {0}", sourceFile.FullName);
                    uncompiledCount++;
                }
            }

            logger.LogMessage(LogLevel.Info, "Unsupported - preprocessor: " + preprocessorCount.ToString());
            logger.LogMessage(LogLevel.Info, "Uncompiled: " + uncompiledCount.ToString());
            logger.LogMessage(LogLevel.Info, "Success: " + successCount.ToString());
            logger.LogMessage(LogLevel.Info, "Failed: " + failedCount.ToString());
        }
예제 #18
0
        public void ArrangeDirectoryTest()
        {
            string testSourceParentDirectory = Path.Combine(Path.GetTempPath(), "TestSource");
            string testSourceChildDirectory  = Path.Combine(testSourceParentDirectory, "Child");

            try
            {
                try
                {
                    Directory.CreateDirectory(testSourceParentDirectory);
                }
                catch
                {
                }

                try
                {
                    Directory.CreateDirectory(testSourceChildDirectory);
                }
                catch
                {
                }

                File.Copy(
                    _testValidSourceFile1,
                    Path.Combine(testSourceParentDirectory, Path.GetFileName(_testValidSourceFile1)),
                    true);

                File.Copy(
                    _testValidSourceFile2,
                    Path.Combine(testSourceParentDirectory, Path.GetFileName(_testValidSourceFile2)),
                    true);

                File.Copy(
                    _testValidSourceFile1,
                    Path.Combine(testSourceChildDirectory, Path.GetFileName(_testValidSourceFile1)),
                    true);

                File.Copy(
                    _testValidSourceFile2,
                    Path.Combine(testSourceChildDirectory, Path.GetFileName(_testValidSourceFile2)),
                    true);

                TestLogger   logger       = new TestLogger();
                FileArranger fileArranger = new FileArranger(null, logger);

                bool success = fileArranger.Arrange(testSourceParentDirectory, null);

                string log = logger.ToString();
                Assert.IsTrue(success, "Expected directory to be arranged succesfully - " + log);
                Assert.IsTrue(
                    logger.HasMessage(LogLevel.Verbose, "4 files written."),
                    "Expected 4 files to be written - " + log);
            }
            finally
            {
                try
                {
                    Directory.Delete(testSourceParentDirectory, true);
                }
                catch
                {
                }
            }
        }