Beispiel #1
0
        private void LoadControlValuesFromSettings()
        {
            PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions options = _settings.Options;

            txt_IndentString.Text                = options.IndentString.Replace("\t", "\\t").Replace(" ", "\\s");
            txt_MaxLineWidth.Text                = options.MaxLineWidth.ToString();
            txt_SpacesPerTab.Text                = options.SpacesPerTab.ToString();
            txt_StatementBreaks.Text             = options.NewStatementLineBreaks.ToString();
            txt_ClauseBreaks.Text                = options.NewClauseLineBreaks.ToString();
            chk_ExpandBetweenConditions.Checked  = options.ExpandBetweenConditions;
            chk_ExpandBooleanExpressions.Checked = options.ExpandBooleanExpressions;
            chk_ExpandCaseStatements.Checked     = options.ExpandCaseStatements;
            chk_ExpandCommaLists.Checked         = options.ExpandCommaLists;
            chk_ExpandInLists.Checked            = options.ExpandInLists;
            chk_TrailingCommas.Checked           = options.TrailingCommas;
            chk_BreakJoinOnSections.Checked      = options.BreakJoinOnSections;
            chk_UppercaseKeywords.Checked        = options.UppercaseKeywords;
            chk_SpaceAfterExpandedComma.Checked  = options.SpaceAfterExpandedComma;
            chk_StandardizeKeywords.Checked      = options.KeywordStandardization;

            if (_supportsHotkey)
            {
                txt_Hotkey.Text = (string)_settings["Hotkey"];
            }
        }
        private string LoadFromLegacySettings()
        {

            // In previous versions the Options were stored in individual setting properties.
            // So that this and future versions are backward compatible, 
            // If the settings file doesn't contain an Options element assume that the file has the old individual settings.

            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions()
            {
                ExpandCommaLists = this.ExpandCommaLists,
                TrailingCommas = this.TrailingCommas,
                ExpandBooleanExpressions = this.ExpandBooleanExpressions,
                ExpandCaseStatements = this.ExpandCaseStatements,
                ExpandBetweenConditions = this.ExpandBetweenConditions,
                UppercaseKeywords = this.UppercaseKeywords,
                IndentString = this.IndentString,
                SpaceAfterExpandedComma = this.SpaceAfterExpandedComma,
                SpacesPerTab = this.SpacesPerTab,
                MaxLineWidth = this.MaxLineWidth,
                KeywordStandardization = this.KeywordStandardization,
                BreakJoinOnSections = this.BreakJoinOnSections
            };

            return options.ToSerializedString();

        }
Beispiel #3
0
        public string FormatTSqlToString(string inputString)
        {
            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 1,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = false,
                UppercaseKeywords        = true,
                ExpandInLists            = true
            };

            PoorMansTSqlFormatterLib.Interfaces.ISqlTreeFormatter _formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(options);
            var  formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(_formatter);
            bool parsingError      = false;

            return(formattingManager.Format(inputString, ref parsingError));
        }
        /// <summary>
        /// Format a SQL string.
        /// </summary>
        /// <param name="originalString">The original SQL string.</param>
        /// <returns>Returns a formatted SQL string according to the properties which have been set up for this class.</returns>
        public string FormatString(string originalString)
        {
            var formatOptions = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions()
            {
                TrailingCommas      = true,
                BreakJoinOnSections = true,
                IndentString        = this.IndentationString,
                UppercaseKeywords   = true,
                SpacesPerTab        = 2,
            };

            var formatter = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatter(formatOptions);

            var formattingManager = new PoorMansTSqlFormatterLib.SqlFormattingManager(formatter);

            return(formattingManager.Format(originalString));
        }
        private string LoadFromLegacySettings()
        {
            // In previous versions the Options were stored in individual setting properties.
            // So that this and future versions are backward compatible,
            // If the settings file doesn't contain an Options element assume that the file has the old individual settings.

            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions()
            {
                ExpandCommaLists         = this.ExpandCommaLists,
                TrailingCommas           = this.TrailingCommas,
                ExpandBooleanExpressions = this.ExpandBooleanExpressions,
                ExpandCaseStatements     = this.ExpandCaseStatements,
                ExpandBetweenConditions  = this.ExpandBetweenConditions,
                UppercaseKeywords        = this.UppercaseKeywords,
                IndentString             = this.IndentString,
                SpaceAfterExpandedComma  = this.SpaceAfterExpandedComma,
                SpacesPerTab             = this.SpacesPerTab,
                MaxLineWidth             = this.MaxLineWidth,
                KeywordStandardization   = this.KeywordStandardization,
                BreakJoinOnSections      = this.BreakJoinOnSections
            };

            return(options.ToSerializedString());
        }
        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!
        }
Beispiel #7
0
        static int Main(string[] args)
        {
            //formatter engine option defaults
            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 2,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = false,
                UppercaseKeywords        = true,
                ExpandInLists            = 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("sb|statementBreaks=", delegate(string v) { options.NewStatementLineBreaks = int.Parse(v); })
                          .Add("cb|clauseBreaks=", delegate(string v) { options.NewClauseLineBreaks = 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("eil|expandInLists", delegate(string v) { options.ExpandInLists = 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!
            }
        }
Beispiel #8
0
        static int Main(string[] args)
        {
            bool verbose            = false;
            bool allowParsingErrors = true;

            if (verbose)
            {
                Console.WriteLine("sqlipf");
            }

            string inputSQL = "select foo from bar where car";
            //inputSQL = Clipboard.GetText();
            //Console.WriteLine("GetText:" + inputSQL);
            string afs = PoorMansTSqlFormatterLib.SqlFormattingManager.AutoFormat();

            if (verbose)
            {
                Console.WriteLine(afs);
            }
            Clipboard.SetText(afs);
            Console.WriteLine("done!");
            //Console.ReadLine();

            return(0);

            //string formattedSQL = ((new PoorMansTSqlFormatterLib.SqlFormattingManager())).Format(inputSQL);
            //Console.WriteLine(formattedSQL);
            return(0);

            var options = new PoorMansTSqlFormatterLib.Formatters.TSqlStandardFormatterOptions
            {
                KeywordStandardization   = true,
                IndentString             = "\t",
                SpacesPerTab             = 4,
                MaxLineWidth             = 999,
                NewStatementLineBreaks   = 2,
                NewClauseLineBreaks      = 1,
                TrailingCommas           = false,
                SpaceAfterExpandedComma  = false,
                ExpandBetweenConditions  = true,
                ExpandBooleanExpressions = true,
                ExpandCaseStatements     = true,
                ExpandCommaLists         = true,
                BreakJoinOnSections      = false,
                UppercaseKeywords        = true,
                ExpandInLists            = true
            };

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

            if (!string.IsNullOrEmpty(inputSQL))
            {
                string    formattedOutput = null;
                bool      parsingError    = false;
                Exception parseException  = null;
                try
                {
                    formattedOutput = formattingManager.Format(inputSQL, ref parsingError);
                    Console.WriteLine(formattedOutput);
                    //hide any handled parsing issues if they were requested to be allowed
                    if (allowParsingErrors)
                    {
                        parsingError = false;
                    }
                }
                catch (Exception ex)
                {
                    parseException = ex;
                    parsingError   = true;
                }
            }

            return(0);
        }