Class for arranging source code files.
        /// <summary>
        /// Lancia NArrange su una stringa.
        /// </summary>
        /// <param name="oldText">
        /// La stringa di partenza.
        /// </param>
        /// <returns>
        /// Il nuovo testo corretto.
        /// </returns>
        public string GoNArrange(string oldText)
        {
            var myTempFileWrite = new StreamWriter(this.tempFilePath, false);

            myTempFileWrite.Write(oldText);
            myTempFileWrite.Close();

            FileArranger fileArranger = new FileArranger(string.Format(@"{0}\NArrangeConfig.xml", (new Utility()).GetSetupDir()), null);

            // FileArranger fileArranger = new FileArranger(string.Format(@"{0}\DefaultConfig.xml", (new Utility()).GetSetupDir()), null);
            bool success = fileArranger.Arrange(this.tempFilePath, this.tempFilePath, false);

            var myTempFileRead = new StreamReader(this.tempFilePath);
            var ret = myTempFileRead.ReadToEnd();
            myTempFileRead.Close();
            File.Delete(this.tempFilePath);
            return ret;

            // return oldText;
        }
        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);
            }
        }
        public void CodeWithMultilinePropertyShouldNotBeFormatted()
        {
            var tmp = GetTempCSharpFile();
            try
            {
                File.WriteAllText(tmp, GetTestFileContents(_implementedPropertyResourceName));
                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(_implementedPropertyResourceName);
                Assert.AreEqual(originalContents, File.ReadAllText(tmp), "File contents should have been preserved.");
            }
            finally
            {
                File.Delete(tmp);
            }
        }
Exemple #4
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());
        }
        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
                {
                }
            }
        }
        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.");
        }
        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());
        }
        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);
            }
        }
        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"));
        }
        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."));
        }
        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"));
        }
        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
                {
                }
            }
        }
        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
                {
                }
            }
        }
        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
                {
                }
            }
        }
        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
                {
                }
            }
        }
Exemple #16
0
        /// <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;
        }
        /// <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);
        }