コード例 #1
0
        static int Main(string[] args)
        {
            //formatter engine option defaults
            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
                {
                    KeywordStandardization = true,
                    IndentString = "\t",
                    SpacesPerTab = 4,
                    MaxLineWidth = 999,
                    TrailingCommas = false,
                    SpaceAfterExpandedComma = false,
                    ExpandBetweenConditions = true,
                    ExpandBooleanExpressions = true,
                    ExpandCaseStatements = true,
                    ExpandCommaLists = true,
                    BreakJoinOnSections = false,
                    UppercaseKeywords = true
                };

            //bulk formatter options
            bool allowParsingErrors = false;
            List<string> extensions = new List<string>();
            bool backups = true;
            bool recursiveSearch = false;
            string outputFileOrFolder = null;
            string uiLangCode = null;

            //flow/tracking switches
            bool showUsageFriendly = false;
            bool showUsageError = false;

            OptionSet p = new OptionSet()
              .Add("is|indentString=", delegate(string v) { options.IndentString = v; })
              .Add("st|spacesPerTab=", delegate(string v) { options.SpacesPerTab = int.Parse(v); })
              .Add("mw|maxLineWidth=", delegate(string v) { options.MaxLineWidth = int.Parse(v); })
              .Add("tc|trailingCommas", delegate(string v) { options.TrailingCommas = v != null; })
              .Add("sac|spaceAfterExpandedComma", delegate(string v) { options.SpaceAfterExpandedComma = v != null; })
              .Add("ebc|expandBetweenConditions", delegate(string v) { options.ExpandBetweenConditions = v != null; })
              .Add("ebe|expandBooleanExpressions", delegate(string v) { options.ExpandBooleanExpressions = v != null; })
              .Add("ecs|expandCaseStatements", delegate(string v) { options.ExpandCaseStatements = v != null; })
              .Add("ecl|expandCommaLists", delegate(string v) { options.ExpandCommaLists = v != null; })
              .Add("bjo|breakJoinOnSections", delegate(string v) { options.BreakJoinOnSections = v != null; })
              .Add("uk|uppercaseKeywords", delegate(string v) { options.UppercaseKeywords = v != null; })
              .Add("sk|standardizeKeywords", delegate(string v) { options.KeywordStandardization = v != null; })

              .Add("ae|allowParsingErrors", delegate(string v) { allowParsingErrors = v != null; })
              .Add("e|extensions=", delegate(string v) { extensions.Add((v.StartsWith(".") ? "" : ".") + v); })
              .Add("r|recursive", delegate(string v) { recursiveSearch = v != null; })
              .Add("b|backups", delegate(string v) { backups = v != null; })
              .Add("o|outputFileOrFolder=", delegate(string v) { outputFileOrFolder = v; })
              .Add("l|languageCode=", delegate(string v) { uiLangCode = v; })
              .Add("h|?|help", delegate(string v) { showUsageFriendly = v != null; })
                  ;

            //first parse the args
            List<string> remainingArgs = p.Parse(args);

            //then switch language if necessary
            if (uiLangCode != null)
            {
                uiLangCode = uiLangCode.ToUpperInvariant();
                if (!uiLangCode.Equals(UILANGUAGE_EN)
                    && !uiLangCode.Equals(UILANGUAGE_FR)
                    && !uiLangCode.Equals(UILANGUAGE_ES)
                    )
                {
                    showUsageError = true;
                    //get the resource manager with default language, before displaying error.
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedLanguageErrorMessage"));
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uiLangCode);
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    //get the resource manager AFTER setting language as requested.
                }
            }
            else
            {
                _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
            }

            //nasty trick to figure out whether we're in a pipeline or not
            bool throwAwayValue;
            string stdInput = null;
            try
            {
                throwAwayValue = System.Console.KeyAvailable;
            }
            catch (InvalidOperationException)
            {
                Console.InputEncoding = Encoding.UTF8;
                stdInput = System.Console.In.ReadToEnd();
            }

            //then complain about missing input or unrecognized args
            if (string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 0)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("NoInputErrorMessage"));
            }
            else if ((!string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 1) || remainingArgs.Count > 1)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedArgumentsErrorMessage"));
            }

            if (extensions.Count == 0)
                extensions.Add(".sql");

            if (showUsageFriendly || showUsageError)
            {
                TextWriter outStream = showUsageFriendly ? Console.Out : Console.Error;
                outStream.WriteLine(_generalResourceManager.GetString("ProgramSummary"));
                outStream.WriteLine("v" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                outStream.WriteLine(_generalResourceManager.GetString("ProgramUsageNotes"));
                return 1;
            }

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(options);
            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            bool warningEncountered = false;
            if (!string.IsNullOrEmpty(stdInput))
            {
                string formattedOutput = null;
                bool parsingError = false;
                Exception parseException = null;
                try
                {
                    formattedOutput = formattingManager.Format(stdInput, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors) parsingError = false;
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), "STDIN"));
                    if (parseException != null)
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    warningEncountered = true;
                }
                else
                {
                    if (!string.IsNullOrEmpty(outputFileOrFolder))
                    {
                        WriteResultFile(outputFileOrFolder, null, null, ref warningEncountered, formattedOutput);
                    }
                    else
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                        Console.Out.WriteLine(formattedOutput);
                    }
                }

            }
            else
            {
                System.IO.DirectoryInfo baseDirectory = null;
                string searchPattern = Path.GetFileName(remainingArgs[0]);
                string baseDirectoryName = Path.GetDirectoryName(remainingArgs[0]);
                if (baseDirectoryName.Length == 0)
                {
                    baseDirectoryName = ".";
                    if (searchPattern.Equals("."))
                        searchPattern = "";
                }
                System.IO.FileSystemInfo[] matchingObjects = null;
                try
                {
                    baseDirectory = new System.IO.DirectoryInfo(baseDirectoryName);
                    if (searchPattern.Length > 0)
                    {
                        if (recursiveSearch)
                            matchingObjects = baseDirectory.GetFileSystemInfos(searchPattern);
                        else
                            matchingObjects = baseDirectory.GetFiles(searchPattern);
                    }
                    else
                    {
                        if (recursiveSearch)
                            matchingObjects = baseDirectory.GetFileSystemInfos();
                        else
                            matchingObjects = new FileSystemInfo[0];
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("PathPatternErrorMessage"), e.Message));
                    return 2;
                }

                System.IO.StreamWriter singleFileWriter = null;
                string replaceFromFolderPath = null;
                string replaceToFolderPath = null;
                if (!string.IsNullOrEmpty(outputFileOrFolder))
                {
                    //ignore the backups setting - wouldn't make sense to back up the source files if we're
                    // writing to another file anyway...
                    backups = false;

                    if (Directory.Exists(outputFileOrFolder)
                        && (File.GetAttributes(outputFileOrFolder) & FileAttributes.Directory) == FileAttributes.Directory
                        )
                    {
                        replaceFromFolderPath = baseDirectory.FullName;
                        replaceToFolderPath = new DirectoryInfo(outputFileOrFolder).FullName;
                    }
                    else
                    {
                        try
                        {
                            //let's not worry too hard about releasing this resource - this is a command-line program,
                            // when it ends or dies all will be released anyway.
                            singleFileWriter = new StreamWriter(outputFileOrFolder);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("OutputFileCreationErrorMessage"), e.Message));
                            return 3;
                        }
                    }
                }

                if (!ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, matchingObjects, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("NoFilesFoundWarningMessage"), remainingArgs[0], string.Join(",", extensions.ToArray())));
                    return 4;
                }

                if (singleFileWriter != null)
                {
                    singleFileWriter.Flush();
                    singleFileWriter.Close();
                    singleFileWriter.Dispose();
                }
            }

            if (warningEncountered)
                return 5; //general "there were warnings" return code
            else
                return 0; //we got there, did something, and received no (handled) errors!
        }
コード例 #2
0
        static int Main(string[] args)
        {
            string indentString             = "\t";
            int    spacesPerTab             = 4;
            int    maxLineWidth             = 999;
            bool   trailingCommas           = false;
            bool   spaceAfterExpandedComma  = false;
            bool   expandBetweenConditions  = true;
            bool   expandBooleanExpressions = true;
            bool   expandCaseStatements     = true;
            bool   expandCommaLists         = true;
            bool   breakJoinOnSections      = false;
            bool   uppercaseKeywords        = true;
            bool   standardizeKeywords      = true;

            bool          allowParsingErrors = false;
            bool          showUsageFriendly  = false;
            bool          showUsageError     = false;
            List <string> extensions         = new List <string>();
            bool          backups            = true;
            bool          recursiveSearch    = false;
            string        outputFileOrFolder = null;
            string        uiLangCode         = null;

            OptionSet p = new OptionSet()
                          .Add("is|indentString=", delegate(string v) { indentString = v; })
                          .Add("st|spacesPerTab=", delegate(string v) { spacesPerTab = int.Parse(v); })
                          .Add("mw|maxLineWidth=", delegate(string v) { maxLineWidth = int.Parse(v); })
                          .Add("tc|trailingCommas", delegate(string v) { trailingCommas = v != null; })
                          .Add("sac|spaceAfterExpandedComma", delegate(string v) { spaceAfterExpandedComma = v != null; })
                          .Add("ebc|expandBetweenConditions", delegate(string v) { expandBetweenConditions = v != null; })
                          .Add("ebe|expandBooleanExpressions", delegate(string v) { expandBooleanExpressions = v != null; })
                          .Add("ecs|expandCaseStatements", delegate(string v) { expandCaseStatements = v != null; })
                          .Add("ecl|expandCommaLists", delegate(string v) { expandCommaLists = v != null; })
                          .Add("bjo|breakJoinOnSections", delegate(string v) { breakJoinOnSections = v != null; })
                          .Add("uk|uppercaseKeywords", delegate(string v) { uppercaseKeywords = v != null; })
                          .Add("sk|standardizeKeywords", delegate(string v) { standardizeKeywords = v != null; })
                          .Add("ae|allowParsingErrors", delegate(string v) { allowParsingErrors = v != null; })
                          .Add("e|extensions=", delegate(string v) { extensions.Add((v.StartsWith(".") ? "" : ".") + v); })
                          .Add("r|recursive", delegate(string v) { recursiveSearch = v != null; })
                          .Add("b|backups", delegate(string v) { backups = v != null; })
                          .Add("o|outputFileOrFolder=", delegate(string v) { outputFileOrFolder = v; })
                          .Add("l|languageCode=", delegate(string v) { uiLangCode = v; })
                          .Add("h|?|help", delegate(string v) { showUsageFriendly = v != null; })
            ;

            //first parse the args
            List <string> remainingArgs = p.Parse(args);

            //then switch language if necessary
            if (uiLangCode != null)
            {
                uiLangCode = uiLangCode.ToUpperInvariant();
                if (!uiLangCode.Equals(UILANGUAGE_EN) &&
                    !uiLangCode.Equals(UILANGUAGE_FR) &&
                    !uiLangCode.Equals(UILANGUAGE_ES)
                    )
                {
                    showUsageError = true;
                    //get the resource manager with default language, before displaying error.
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedLanguageErrorMessage"));
                }
                else
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(uiLangCode);
                    _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
                    //get the resource manager AFTER setting language as requested.
                }
            }
            else
            {
                _generalResourceManager = new FrameworkClassReplacements.SingleAssemblyResourceManager("GeneralLanguageContent", Assembly.GetExecutingAssembly(), typeof(Program));
            }

            //nasty trick to figure out whether we're in a pipeline or not
            bool   throwAwayValue;
            string stdInput = null;

            try
            {
                throwAwayValue = System.Console.KeyAvailable;
            }
            catch (InvalidOperationException)
            {
                Console.InputEncoding = Encoding.UTF8;
                stdInput = System.Console.In.ReadToEnd();
            }

            //then complain about missing input or unrecognized args
            if (string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 0)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("NoInputErrorMessage"));
            }
            else if ((!string.IsNullOrEmpty(stdInput) && remainingArgs.Count == 1) || remainingArgs.Count > 1)
            {
                showUsageError = true;
                Console.Error.WriteLine(_generalResourceManager.GetString("UnrecognizedArgumentsErrorMessage"));
            }

            if (extensions.Count == 0)
            {
                extensions.Add(".sql");
            }

            if (showUsageFriendly || showUsageError)
            {
                TextWriter outStream = showUsageFriendly ? Console.Out : Console.Error;
                outStream.WriteLine(_generalResourceManager.GetString("ProgramSummary"));
                outStream.WriteLine("v" + Assembly.GetExecutingAssembly().GetName().Version.ToString());
                outStream.WriteLine(_generalResourceManager.GetString("ProgramUsageNotes"));
                return(1);
            }

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(
                indentString,
                spacesPerTab,
                maxLineWidth,
                expandCommaLists,
                trailingCommas,
                spaceAfterExpandedComma,
                expandBooleanExpressions,
                expandCaseStatements,
                expandBetweenConditions,
                breakJoinOnSections,
                uppercaseKeywords,
                false,
                standardizeKeywords
                );

            formatter.ErrorOutputPrefix = _generalResourceManager.GetString("ParseErrorWarningPrefix") + Environment.NewLine;
            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            bool warningEncountered = false;

            if (!string.IsNullOrEmpty(stdInput))
            {
                string    formattedOutput = null;
                bool      parsingError    = false;
                Exception parseException  = null;
                try
                {
                    formattedOutput = formattingManager.Format(stdInput, ref parsingError);

                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }

                if (parsingError)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ParsingErrorWarningMessage"), "STDIN"));
                    if (parseException != null)
                    {
                        Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("ErrorDetailMessageFragment"), parseException.Message));
                    }
                    warningEncountered = true;
                }
                else
                {
                    if (!string.IsNullOrEmpty(outputFileOrFolder))
                    {
                        WriteResultFile(outputFileOrFolder, null, null, ref warningEncountered, formattedOutput);
                    }
                    else
                    {
                        Console.OutputEncoding = Encoding.UTF8;
                        Console.Out.WriteLine(formattedOutput);
                    }
                }
            }
            else
            {
                System.IO.DirectoryInfo baseDirectory = null;
                string searchPattern     = Path.GetFileName(remainingArgs[0]);
                string baseDirectoryName = Path.GetDirectoryName(remainingArgs[0]);
                if (baseDirectoryName.Length == 0)
                {
                    baseDirectoryName = ".";
                    if (searchPattern.Equals("."))
                    {
                        searchPattern = "";
                    }
                }
                System.IO.FileSystemInfo[] matchingObjects = null;
                try
                {
                    baseDirectory = new System.IO.DirectoryInfo(baseDirectoryName);
                    if (searchPattern.Length > 0)
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos(searchPattern);
                        }
                        else
                        {
                            matchingObjects = baseDirectory.GetFiles(searchPattern);
                        }
                    }
                    else
                    {
                        if (recursiveSearch)
                        {
                            matchingObjects = baseDirectory.GetFileSystemInfos();
                        }
                        else
                        {
                            matchingObjects = new FileSystemInfo[0];
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("PathPatternErrorMessage"), e.Message));
                    return(2);
                }

                System.IO.StreamWriter singleFileWriter = null;
                string replaceFromFolderPath            = null;
                string replaceToFolderPath = null;
                if (!string.IsNullOrEmpty(outputFileOrFolder))
                {
                    //ignore the backups setting - wouldn't make sense to back up the source files if we're
                    // writing to another file anyway...
                    backups = false;

                    if (Directory.Exists(outputFileOrFolder) &&
                        (File.GetAttributes(outputFileOrFolder) & FileAttributes.Directory) == FileAttributes.Directory
                        )
                    {
                        replaceFromFolderPath = baseDirectory.FullName;
                        replaceToFolderPath   = new DirectoryInfo(outputFileOrFolder).FullName;
                    }
                    else
                    {
                        try
                        {
                            //let's not worry too hard about releasing this resource - this is a command-line program,
                            // when it ends or dies all will be released anyway.
                            singleFileWriter = new StreamWriter(outputFileOrFolder);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("OutputFileCreationErrorMessage"), e.Message));
                            return(3);
                        }
                    }
                }

                if (!ProcessSearchResults(extensions, backups, allowParsingErrors, formattingManager, matchingObjects, singleFileWriter, replaceFromFolderPath, replaceToFolderPath, ref warningEncountered))
                {
                    Console.Error.WriteLine(string.Format(_generalResourceManager.GetString("NoFilesFoundWarningMessage"), remainingArgs[0], string.Join(",", extensions.ToArray())));
                    return(4);
                }

                if (singleFileWriter != null)
                {
                    singleFileWriter.Flush();
                    singleFileWriter.Close();
                    singleFileWriter.Dispose();
                }
            }

            if (warningEncountered)
            {
                return(5); //general "there were warnings" return code
            }
            else
            {
                return(0); //we got there, did something, and received no (handled) errors!
            }
        }