예제 #1
0
        /// <summary>
        /// Compare this ConsoleString to another ConsoleString or a plain string.
        /// </summary>
        /// <param name="obj">The ConsoleString or plain string to compare to.</param>
        /// <returns>True if equal, false otherwise</returns>
        public override bool Equals(object obj)
        {
            if (obj is string)
            {
                return(ToString().Equals(obj as string));
            }

            ConsoleString other = obj as ConsoleString;

            if (object.ReferenceEquals(other, null))
            {
                return(false);
            }
            if (other.Length != this.Length)
            {
                return(false);
            }


            for (int i = 0; i < this.Length; i++)
            {
                if (this.characters[i] != other.characters[i])
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #2
0
        /// <summary>
        /// Replaces all occurrances of the given string with the replacement value using the specified formatting.
        /// </summary>
        /// <param name="toFind">The substring to find</param>
        /// <param name="toReplace">The replacement value</param>
        /// <param name="foregroundColor">The foreground color (defaults to the console's foreground color at initialization time).</param>
        /// <param name="backgroundColor">The background color (defaults to the console's background color at initialization time).</param>
        /// <returns>A new ConsoleString with the replacements.</returns>
        public ConsoleString Replace(string toFind, string toReplace, ConsoleColor?foregroundColor = null, ConsoleColor?backgroundColor = null)
        {
            ConsoleString ret = new ConsoleString();

            ret.Append(this);

            int startIndex = 0;

            while (true)
            {
                string toString     = ret.ToString();
                int    currentIndex = toString.IndexOf(toFind, startIndex);
                if (currentIndex < 0)
                {
                    break;
                }
                for (int i = 0; i < toFind.Length; i++)
                {
                    ret.RemoveAt(currentIndex);
                }
                ret.InsertRange(currentIndex, toReplace.Select(c => new ConsoleCharacter(c, foregroundColor, backgroundColor)));
                startIndex = currentIndex + toReplace.Length;
            }

            return(ret);
        }
예제 #3
0
        /// <summary>
        /// Highights all occurrances of the given string with the desired foreground and background color.
        /// </summary>
        /// <param name="toFind">The substring to find</param>
        /// <param name="foregroundColor">The foreground color (defaults to the console's foreground color at initialization time).</param>
        /// <param name="backgroundColor">The background color (defaults to the console's background color at initialization time).</param>
        /// <param name="comparison">Specifies how characters are compared</param>
        /// <returns>A new ConsoleString with the highlights.</returns>
        public ConsoleString Highlight(string toFind, ConsoleColor?foregroundColor = null, ConsoleColor?backgroundColor = null, StringComparison comparison = StringComparison.InvariantCulture)
        {
            ConsoleString ret = new ConsoleString(this);

            if (toFind == null || toFind.Length == 0)
            {
                return(ret);
            }

            int startIndex = 0;

            while (true)
            {
                string toString     = ret.ToString();
                int    currentIndex = toString.IndexOf(toFind, startIndex, comparison);
                if (currentIndex < 0)
                {
                    break;
                }

                string replacement = "";
                for (int i = 0; i < toFind.Length; i++)
                {
                    replacement += ret.characters[currentIndex].Value;
                    ret.characters.RemoveAt(currentIndex);
                }
                ret.characters.InsertRange(currentIndex, replacement.Select(c => new ConsoleCharacter(c, foregroundColor, backgroundColor)));
                startIndex = currentIndex + replacement.Length;
            }

            return(ret);
        }
예제 #4
0
        /// <summary>
        /// Evaluates the each loop
        /// </summary>
        /// <param name="context">The context that contains information about the document being rendered</param>
        /// <returns>The rendered contents of the each loop</returns>
        public ConsoleString Evaluate(DocumentRendererContext context)
        {
            var collection = context.EvaluateExpression(this.CollectionVariableExpressionToken.Value);

            if (collection == null)
            {
                throw new DocumentRenderException("'" + this.CollectionVariableExpressionToken.Value + "' resolved to a null reference", this.CollectionVariableExpressionToken);
            }

            if (collection is IEnumerable == false)
            {
                throw new DocumentRenderException("'" + this.CollectionVariableExpressionToken.Value + "' does not resolve to a collection", this.CollectionVariableExpressionToken);
            }
            ConsoleString ret   = ConsoleString.Empty;
            int           index = 0;
            var           iterationVariableName = this.IterationVariableNameToken.Value + "-index";

            foreach (var item in (IEnumerable)collection)
            {
                context.LocalVariables.Add(this.IterationVariableNameToken, item);
                context.LocalVariables.Force(iterationVariableName, index);
                ret += context.RenderBody(this.Body);
                context.LocalVariables.Remove(this.IterationVariableNameToken);
                context.LocalVariables.ForceClear(iterationVariableName);
                index++;
            }
            return(ret);
        }
예제 #5
0
 /// <summary>
 /// Concatenates two ConsoleStrings together.
 /// </summary>
 /// <param name="other">The string to append.</param>
 public void Append(ConsoleString other)
 {
     foreach (var c in other.ToArray()) // ToArray() prevents concurrent modification when a and b refer to the same object
     {
         this.Add(c);
     }
 }
        /// <summary>
        /// Reads a line of text from the console and converts it into a string array that has accounted for escape sequences and quoted string literals.
        /// </summary>
        /// <param name="initialBuffer">Optionally seed the prompt with an initial value that the end user can modify</param>
        /// <returns>the command line that was read</returns>
        public string[] ReadCommandLine(ConsoleString initialBuffer = null)
        {
            var line = ReadLine(initialBuffer).ToString();
            var ret  = Args.Convert(line);

            return(ret);
        }
예제 #7
0
 private void FireUsageWritten(ConsoleString usage)
 {
     if (UsageWritten != null)
     {
         UsageWritten(usage);
     }
 }
예제 #8
0
        private ConsoleString ImmutableAppend(string value, ConsoleColor?foregroundColor = null, ConsoleColor?backgroundColor = null)
        {
            ConsoleString str = new ConsoleString(this);

            str.ContentSet = false;
            str.Append(value, foregroundColor, backgroundColor);
            return(str);
        }
예제 #9
0
        private ConsoleString ImmutableAppend(ConsoleString other)
        {
            ConsoleString str = new ConsoleString(this);

            str.ContentSet = false;
            str.Append(other);
            return(str);
        }
예제 #10
0
        /// <summary>
        /// Performs an auto complete of the given token.
        /// </summary>
        /// <param name="currentToken">the token to complete</param>
        /// <param name="completion">the completed token.  Note that it is not required that the completion string starts with the current token value, though it usually does.</param>
        public void CompleteCurrentToken(Token currentToken, ConsoleString completion)
        {
            var  quoteStatus = GetQuoteStatus(this.Buffer, this.BufferPosition - 1);
            bool readyToEnd  = quoteStatus != QuoteStatus.ClosedQuote;
            var  endTarget   = quoteStatus == QuoteStatus.NoQuotes ? ' ' : '"';

            int currentTokenStartIndex;

            for (currentTokenStartIndex = this.BufferPosition - 1; currentTokenStartIndex >= 0; currentTokenStartIndex--)
            {
                if (this.Buffer[currentTokenStartIndex].Value == endTarget && readyToEnd)
                {
                    if (endTarget == ' ')
                    {
                        currentTokenStartIndex++;
                    }

                    break;
                }
                else if (this.Buffer[currentTokenStartIndex].Value == endTarget)
                {
                    readyToEnd = true;
                }
            }

            if (currentTokenStartIndex == -1)
            {
                currentTokenStartIndex = 0;
            }

            var insertThreshold = currentTokenStartIndex + currentToken.Value.Length;

            List <ConsoleCharacter> newBuffer = new List <ConsoleCharacter>(this.Buffer);

            for (int completionIndex = 0; completionIndex < completion.Length; completionIndex++)
            {
                if (completionIndex + currentTokenStartIndex == newBuffer.Count)
                {
                    newBuffer.Add(completion[completionIndex]);
                }
                else if (completionIndex + currentTokenStartIndex < insertThreshold)
                {
                    newBuffer[completionIndex + currentTokenStartIndex] = completion[completionIndex];
                }
                else
                {
                    newBuffer.Insert(completionIndex + currentTokenStartIndex, completion[completionIndex]);
                }
            }


            while (newBuffer.Count > currentTokenStartIndex + completion.Length)
            {
                newBuffer.RemoveAt(currentTokenStartIndex + completion.Length);
            }

            ReplaceConsole(new ConsoleString(newBuffer));
        }
예제 #11
0
        /// <summary>
        /// Creates a search result from an object, given an optional display value.
        /// </summary>
        /// <param name="value">The object to use as a result.</param>
        /// <param name="displayText">The display text for the result.  If null, the value's ToString() method will be called</param>
        /// <returns>a search result</returns>
        public static ContextAssistSearchResult FromObject(object value, ConsoleString displayText)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value", "value cannot be null");
            }

            return(new ContextAssistSearchResult(value, displayText ?? new ConsoleString(value.ToString())));
        }
예제 #12
0
 /// <summary>
 /// Pretends to intercept a ConsoleString
 /// </summary>
 /// <param name="value">the string to intercept</param>
 public void Write(ConsoleString value)
 {
     lock (intercepted)
     {
         foreach (var c in value)
         {
             intercepted.Add(c);
         }
     }
 }
예제 #13
0
        private void InitializeClearedLine()
        {
            var buffer = new List <ConsoleCharacter>();

            for (int i = 0; i < Console.BufferWidth; i++)
            {
                buffer.Add(new ConsoleCharacter(' '));
            }
            clearedLine = new ConsoleString(buffer);
        }
예제 #14
0
        private static ConsoleString FormatAsTable(List <ConsoleString> columns, List <List <ConsoleString> > rows, string rowPrefix = "")
        {
            if (rows.Count == 0)
            {
                return(new ConsoleString());
            }

            Dictionary <int, int> maximums = new Dictionary <int, int>();

            for (int i = 0; i < columns.Count; i++)
            {
                maximums.Add(i, columns[i].Length);
            }
            for (int i = 0; i < columns.Count; i++)
            {
                foreach (var row in rows)
                {
                    maximums[i] = Math.Max(maximums[i], row[i].Length);
                }
            }

            ConsoleString ret    = new ConsoleString();
            int           buffer = 3;

            ret += rowPrefix;
            for (int i = 0; i < columns.Count; i++)
            {
                var val = columns[i];
                while (val.Length < maximums[i] + buffer)
                {
                    val += " ";
                }
                ret += val;
            }

            ret += "\n";

            foreach (var row in rows)
            {
                ret += rowPrefix;
                for (int i = 0; i < columns.Count; i++)
                {
                    var val = row[i];
                    while (val.Length < maximums[i] + buffer)
                    {
                        val += " ";
                    }

                    ret += val;
                }
                ret += "\n";
            }

            return(ret);
        }
예제 #15
0
        /// <summary>
        /// Get a substring of this ConsoleString starting at the given index and with the given length.
        /// </summary>
        /// <param name="start">the start index.</param>
        /// <param name="length">the number of characters to return</param>
        /// <returns>A new ConsoleString representing the substring requested.</returns>
        public ConsoleString Substring(int start, int length)
        {
            ConsoleString ret = new ConsoleString();

            for (int i = start; i < start + length; i++)
            {
                ret.characters.Add(this.characters[i]);
            }

            return(ret);
        }
예제 #16
0
        /// <summary>
        /// Prompts the user for a line of input with the given message
        /// </summary>
        /// <param name="message">the prompt message</param>
        /// <returns>the input that the user entered</returns>
        public string PromptForLine(string message)
        {
            if (message.EndsWith(": ") == false)
            {
                message += ": ";
            }
            ConsoleString.Write(message, ConsoleColor.Yellow);
            var input = Reader.ReadLine().ToString();

            return(input);
        }
예제 #17
0
        private ConsoleString Evaluate(List <IDocumentExpression> expressions, DocumentRendererContext context)
        {
            ConsoleString ret = new ConsoleString();

            foreach (var expression in expressions)
            {
                var eval = expression.Evaluate(context);
                ret += eval;
            }

            return(ret);
        }
예제 #18
0
        /// <summary>
        /// Replaces all matches of the given regular expression with the replacement value using the specified formatting.
        /// </summary>
        /// <param name="regex">The regular expression to find.</param>
        /// <param name="toReplace">The replacement value</param>
        /// <param name="foregroundColor">The foreground color (defaults to the console's foreground color at initialization time).</param>
        /// <param name="backgroundColor">The background color (defaults to the console's background color at initialization time).</param>
        /// <returns></returns>
        public ConsoleString ReplaceRegex(string regex, string toReplace, ConsoleColor?foregroundColor = null, ConsoleColor?backgroundColor = null)
        {
            ConsoleString   ret     = new ConsoleString(this);
            MatchCollection matches = Regex.Matches(this.ToString(), regex);

            foreach (Match match in matches)
            {
                ret = ret.Replace(match.Value, toReplace ?? match.Value, foregroundColor, backgroundColor);
            }

            return(ret);
        }
예제 #19
0
        /// <summary>
        /// Writes the given string to the console, followed by a newline
        /// </summary>
        /// <param name="consoleString">the string to write</param>
        public void WriteLine(ConsoleString consoleString)
        {
            var existing = ConsoleString.ConsoleProvider;

            try
            {
                ConsoleString.ConsoleProvider = this;
                consoleString.WriteLine();
            }
            finally
            {
                ConsoleString.ConsoleProvider = existing;
            }
        }
        /// <summary>
        /// Reads a line of text from the console.  Any interactions you've configured before calling this method will be in effect.
        /// </summary>
        /// <param name="initialBuffer">Optionally seed the prompt with an initial value that the end user can modify</param>
        /// <returns>a line of text from the console</returns>
        public ConsoleString ReadLine(ConsoleString initialBuffer = null)
        {
            RichCommandLineContext context = new RichCommandLineContext(this.HistoryManager);

            context.Console          = this.Console;
            context.ConsoleStartTop  = this.Console.CursorTop;
            context.ConsoleStartLeft = this.Console.CursorLeft;

            if (initialBuffer != null)
            {
                context.ReplaceConsole(initialBuffer);
            }

            while (true)
            {
                context.Reset();
                context.KeyPressed       = this.Console.ReadKey(true);
                context.CharacterToWrite = new ConsoleCharacter(context.KeyPressed.KeyChar);
                context.BufferPosition   = this.Console.CursorLeft - context.ConsoleStartLeft + (this.Console.CursorTop - context.ConsoleStartTop) * this.Console.BufferWidth;

                IKeyHandler handler = null;

                if (KeyHandlers.TryGetValue(context.KeyPressed.Key, out handler) == false && context.CharacterToWrite.Value != '\u0000')
                {
                    context.WriteCharacterForPressedKey();
                    DoSyntaxHighlighting(context);
                }
                else if (handler != null)
                {
                    handler.Handle(context);

                    if (context.Intercept == false && context.CharacterToWrite.Value != '\u0000')
                    {
                        this.Console.Write(context.CharacterToWrite);
                    }

                    DoSyntaxHighlighting(context);

                    if (context.IsFinished)
                    {
                        this.Console.WriteLine();
                        break;
                    }
                }
            }

            return(new ConsoleString(context.Buffer));
        }
예제 #21
0
        /// <summary>
        /// Asks the user if they are sure about performing some operation and returns true if they indicate yes and
        /// false if they indicate no.
        /// </summary>
        /// <param name="about">The message to display.  'Are you sure?' will be apended.</param>
        /// <returns>true if they indicate yes and false if they indicate no.</returns>
        public bool IsUserSure(ConsoleString about)
        {
            if (about.EndsWith("."))
            {
                about = about.Substring(0, about.Length - 1);
            }

            var response = Prompt(about + ".  Are you sure?", "y", "n");

            if (response.Equals("y", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #22
0
        /// <summary>
        /// Prompts the user to select a value from a set of options.
        /// </summary>
        /// <param name="message">the prompt message</param>
        /// <param name="options">the options to choose from</param>
        /// <returns>The selected value</returns>
        public string Prompt(ConsoleString message, params string[] options)
        {
            var optionsString = new ConsoleString("(" + string.Join("/", options) + ")", ConsoleColor.Cyan);
            var prompt        = message + new ConsoleString(" ") + optionsString + ": ";

            prompt.Write();

            var option = Reader.ReadLine().ToString();

            if (options.Contains(option, StringComparer.InvariantCultureIgnoreCase) == false)
            {
                Console.WriteLine("Unrecognized option: " + option);
                return(Prompt(message, options));
            }
            else
            {
                return(option);
            }
        }
예제 #23
0
        /// <summary>
        /// Rewrites the console using the latest values in the Buffer and moves the cursor to the end of the line.
        /// </summary>
        /// <param name="newBuffer">The new line of text that will replace the current buffer.</param>
        public void ReplaceConsole(ConsoleString newBuffer)
        {
            this.Console.CursorLeft = this.ConsoleStartLeft;
            this.Console.CursorTop  = this.ConsoleStartTop;
            for (int i = 0; i < newBuffer.Length; i++)
            {
                this.Console.Write(newBuffer[i]);
            }

            var newLeft = this.Console.CursorLeft;
            var newTop  = this.Console.CursorTop;

            for (int i = 0; i < this.Buffer.Count - newBuffer.Length; i++)
            {
                this.Console.Write(" ");
            }

            this.Console.CursorTop  = newTop;
            this.Console.CursorLeft = newLeft;
            this.Buffer             = newBuffer.ToList();;
        }
예제 #24
0
        private void RedrawSearchResults()
        {
            using (var snapshot = this.console.TakeSnapshot())
            {
                resultsWiper.Wipe();
                resultsWiper.SetBottomToTop();
                menuWiper.Bottom = resultsWiper.Bottom;

                this.console.CursorTop  = resultsWiper.Top;
                this.console.CursorLeft = 0;


                for (int i = 0; i < latestResults.Count; i++)
                {
                    ConsoleString searchResult = latestResults[i].RichDisplayText;

                    if (i == selectedIndex)
                    {
                        searchResult = searchResult.HighlightSubstring(0, searchResult.Length, ConsoleColor.Yellow, null);
                    }

                    if (searchResult.Length > this.console.BufferWidth - 1)
                    {
                        searchResult = searchResult.Substring(0, this.console.BufferWidth - 4) + "...";
                    }

                    if (latestResultsSearchString.Length > 0)
                    {
                        searchResult = searchResult.Highlight(latestResultsSearchString, ConsoleColor.Black, ConsoleColor.Yellow, StringComparison.InvariantCultureIgnoreCase);
                    }

                    this.console.WriteLine(searchResult);
                    resultsWiper.IncrementBottom();
                    menuWiper.IncrementBottom();
                }
            }
        }
        /// <summary>
        /// Renders the tokens in the expression, using the ambient foreground and background colors if they are set.
        /// </summary>
        /// <param name="context">The data context to use for evaluation</param>
        /// <returns>The rendered plain text</returns>
        public ConsoleString Evaluate(DocumentRendererContext context)
        {
            var ret = new ConsoleString();

            ConsoleColor fg = new ConsoleCharacter('a').ForegroundColor;
            ConsoleColor bg = new ConsoleCharacter('a').BackgroundColor;

            if (context.LocalVariables.IsDefined("ConsoleForegroundColor"))
            {
                fg = (ConsoleColor)context.LocalVariables["ConsoleForegroundColor"];
            }

            if (context.LocalVariables.IsDefined("ConsoleBackgroundColor"))
            {
                bg = (ConsoleColor)context.LocalVariables["ConsoleBackgroundColor"];
            }

            foreach (var token in this.tokens)
            {
                ret += new ConsoleString(token.Value, fg, bg);
            }

            return(ret);
        }
예제 #26
0
        /// <summary>
        /// Creates a result that replaces the current token with the given selection.
        /// </summary>
        /// <param name="context">Context from the parent reader</param>
        /// <param name="selection">The selection string to insert</param>
        /// <returns>a result that replaces the current token with the given selection</returns>
        public static ContextAssistResult CreateInsertResult(RichCommandLineContext context, ConsoleString selection)
        {
            context.RefreshTokenInfo();
            var ret = new ContextAssistResult();

            bool hasInserted = false;
            var  newBuffer   = new List <ConsoleCharacter>();

            foreach (var token in context.Tokens)
            {
                if (context.IsCursorOnToken(token))
                {
                    if (string.IsNullOrWhiteSpace(token.Value))
                    {
                        newBuffer.AddRange(context.GetBufferSubstringFromToken(token));
                        ret.ConsoleRefreshLeftOffset = selection.Length;
                    }
                    else
                    {
                        var tokenOffset = context.BufferPosition - token.StartIndex;
                        ret.ConsoleRefreshLeftOffset = selection.Length - tokenOffset;
                    }

                    if (hasInserted == false)
                    {
                        hasInserted = true;
                        // cursor is on the current token
                        newBuffer.AddRange(selection);
                    }
                }
                else
                {
                    // this token not be modified
                    newBuffer.AddRange(context.GetBufferSubstringFromToken(token));
                }
            }

            if (hasInserted == false)
            {
                hasInserted = true;
                // cursor is on the current token
                newBuffer.AddRange(selection);
                ret.ConsoleRefreshLeftOffset = selection.Length;
            }

            ret.StatusCode = ContextAssistResultStatusCode.Success;
            ret.NewBuffer  = newBuffer;
            return(ret);
        }
예제 #27
0
        /// <summary>
        /// Renders the table given a data context
        /// </summary>
        /// <param name="context">the data context</param>
        /// <returns>the console friendly table, as a ConsoleString</returns>
        public ConsoleString Evaluate(DocumentRendererContext context)
        {
            var eval = context.EvaluateExpression(this.EvalToken.Value);

            if (eval == null)
            {
                throw new DocumentRenderException("NullReference for '" + this.EvalToken.Value + "'", this.EvalToken);
            }
            else if (eval is IEnumerable == false)
            {
                throw new DocumentRenderException("'" + this.EvalToken.Value + "' is not enumerable", this.EvalToken);
            }

            IEnumerable collection = (IEnumerable)eval;

            List <ConsoleString>          headers   = new List <ConsoleString>();
            List <List <ConsoleString> >  rows      = new List <List <ConsoleString> >();
            List <ColumnOverflowBehavior> overflows = new List <ColumnOverflowBehavior>();

            for (int colIndex = 0; colIndex < Columns.Count; colIndex++)
            {
                var col      = Columns[colIndex];
                var colValue = col.Value;

                if (colValue.EndsWith("+"))
                {
                    colValue = colValue.Substring(0, colValue.Length - 1);
                    overflows.Add(new SmartWrapOverflowBehavior());
                    if (colIndex != Columns.Count - 1)
                    {
                        throw new DocumentRenderException("The auto expand indicator '+' can only be used on the last column", col);
                    }
                }
                else
                {
                    overflows.Add(new GrowUnboundedOverflowBehavior());
                }

                if (colValue.Contains(">"))
                {
                    var newColName = colValue.Split('>')[1];
                    headers.Add(new ConsoleString(newColName, ConsoleColor.Yellow));
                }
                else
                {
                    headers.Add(new ConsoleString(colValue, ConsoleColor.Yellow));
                }
            }

            foreach (var element in collection)
            {
                if (element is CommandLineArgument && ((CommandLineArgument)element).OmitFromUsage)
                {
                    continue;
                }

                var row = new List <ConsoleString>();
                foreach (var col in Columns)
                {
                    string propName;
                    if (col.Value.Contains(">"))
                    {
                        propName = col.Value.Split('>')[0];
                    }
                    else
                    {
                        propName = col.Value;
                    }

                    if (propName.EndsWith("+"))
                    {
                        propName = propName.Substring(0, propName.Length - 1);
                    }

                    var propToGet = element.GetType().GetProperty(propName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                    if (propToGet == null)
                    {
                        throw new DocumentRenderException("'" + propName + "' is not a valid property for type '" + element.GetType().FullName + "'", col);
                    }
                    var value = propToGet.GetValue(element, null);

                    ConsoleString valueString;

                    if (value != null)
                    {
                        valueString = new ConsoleString(value.ToString());
                        if (ShowDefaultValuesForArguments && element is CommandLineArgument && propToGet.Name == "Description" && ((CommandLineArgument)element).DefaultValue != null)
                        {
                            valueString += new ConsoleString(" [Default='" + ((CommandLineArgument)element).DefaultValue.ToString() + "'] ", ConsoleColor.DarkGreen);
                        }
                    }
                    else
                    {
                        valueString = ConsoleString.Empty;
                    }
                    row.Add(valueString);
                }
                rows.Add(row);

                if (ShowPossibleValuesForArguments && element is CommandLineArgument && ((CommandLineArgument)element).ArgumentType.IsEnum)
                {
                    foreach (var val in ((CommandLineArgument)element).EnumValuesAndDescriptions)
                    {
                        List <ConsoleString> possibilitiesRow = new List <ConsoleString>();
                        for (int i = 0; i < Columns.Count - 1; i++)
                        {
                            possibilitiesRow.Add(ConsoleString.Empty);
                        }
                        possibilitiesRow.Add(new ConsoleString(val, ConsoleColor.DarkGreen));
                        rows.Add(possibilitiesRow);
                    }
                }
            }

            string rowPrefix = "";

            for (int i = 0; i < indent; i++)
            {
                rowPrefix += " ";
            }

            ConsoleTableBuilder builder = new ConsoleTableBuilder();
            var tableText = builder.FormatAsTable(headers, rows, rowPrefix: rowPrefix, columnOverflowBehaviors: overflows);

            // remove the prefix from the first row
            tableText = tableText.Substring(indent);
            var tableTextStr = tableText.ToString();

            return(tableText);
        }
예제 #28
0
 public void WriteLine(ConsoleString consoleString)
 {
     throw new NotImplementedException();
 }
예제 #29
0
 public void Write(ConsoleString consoleString)
 {
     state.CursorPosition += consoleString.Length;
 }
예제 #30
0
        private static ConsoleString GetOptionsUsage(IEnumerable <CommandLineArgument> opts, bool ignoreActionProperties, ArgUsageOptions options)
        {
            if (opts.Count() == 0)
            {
                return(new ConsoleString("There are no options\n"));
            }

            var usageInfos = opts.Select(o => new ArgumentUsageInfo(o));

            var hasPositionalArgs = usageInfos.Where(i => i.Position >= 0).Count() > 0;

            List <ConsoleString> columnHeaders = new List <ConsoleString>()
            {
                new ConsoleString("OPTION", ConsoleColor.Yellow),
                new ConsoleString("DESCRIPTION", ConsoleColor.Yellow),
            };

            bool hasTypeCol = false, hasPosCol = false;

            int insertPosition = 1;

            if (options.ShowType)
            {
                columnHeaders.Insert(insertPosition++, new ConsoleString("TYPE", ConsoleColor.Yellow));
                hasTypeCol = true;
            }

            if (hasPositionalArgs && options.ShowPosition)
            {
                columnHeaders.Insert(insertPosition, new ConsoleString("POSITION", ConsoleColor.Yellow));
                hasPosCol = true;
            }

            List <List <ConsoleString> > rows = new List <List <ConsoleString> >();

            foreach (ArgumentUsageInfo usageInfo in usageInfos.OrderBy(i => i.Position >= 0 ? i.Position : 1000))
            {
                var hooks = new List <UsageHook>();
                if (usageInfo.Property != null && ArgUsage.ExplicitPropertyHooks.ContainsKey(usageInfo.Property))
                {
                    hooks.AddRange(ArgUsage.ExplicitPropertyHooks[usageInfo.Property]);
                }

                hooks.AddRange(ArgUsage.GlobalUsageHooks);

                hooks.AddRange(usageInfo.Argument.UsageHooks);

                foreach (var hook in hooks)
                {
                    hook.BeforeGenerateUsage(usageInfo);
                }


                if (usageInfo.Ignore)
                {
                    continue;
                }
                if (usageInfo.IsAction && ignoreActionProperties)
                {
                    continue;
                }

                var positionString    = new ConsoleString(usageInfo.Position >= 0 ? usageInfo.Position + "" : "NA");
                var requiredString    = new ConsoleString(usageInfo.IsRequired ? "*" : "", ConsoleColor.Red);
                var descriptionString = new ConsoleString(usageInfo.Description);
                if (options.AppendDefaultValueToDescription && usageInfo.DefaultValue != null)
                {
                    descriptionString += new ConsoleString(" [default=" + usageInfo.DefaultValue.ToString() + "]", ConsoleColor.DarkGreen);
                }

                var typeString = new ConsoleString(usageInfo.Type);

                var    aliases = usageInfo.Aliases.OrderBy(a => a.Length).ToList();
                var    maxInlineAliasLength = 8;
                string inlineAliasInfo      = "";

                int aliasIndex;
                for (aliasIndex = 0; aliasIndex < aliases.Count; aliasIndex++)
                {
                    var proposedInlineAliases = inlineAliasInfo == string.Empty ? aliases[aliasIndex] : inlineAliasInfo + ", " + aliases[aliasIndex];
                    if (proposedInlineAliases.Length <= maxInlineAliasLength)
                    {
                        inlineAliasInfo = proposedInlineAliases;
                    }
                    else
                    {
                        break;
                    }
                }

                if (inlineAliasInfo != string.Empty)
                {
                    inlineAliasInfo = " (" + inlineAliasInfo + ")";
                }

                rows.Add(new List <ConsoleString>()
                {
                    new ConsoleString("") + (usageInfo.Name + inlineAliasInfo),
                    descriptionString,
                });

                insertPosition = 1;
                if (options.ShowType)
                {
                    rows.Last().Insert(insertPosition++, typeString + requiredString);
                }

                if (hasPositionalArgs && options.ShowPosition)
                {
                    rows.Last().Insert(insertPosition, positionString);
                }

                for (int i = aliasIndex; i < aliases.Count; i++)
                {
                    rows.Add(new List <ConsoleString>()
                    {
                        new ConsoleString("  " + aliases[i]),
                        ConsoleString.Empty,
                    });

                    if (hasTypeCol)
                    {
                        rows.Last().Add(ConsoleString.Empty);
                    }
                    if (hasPosCol)
                    {
                        rows.Last().Add(ConsoleString.Empty);
                    }
                }

                if (options.ShowPossibleValues)
                {
                    foreach (var possibleValue in usageInfo.PossibleValues)
                    {
                        rows.Add(new List <ConsoleString>()
                        {
                            ConsoleString.Empty,
                            new ConsoleString("  " + possibleValue),
                        });

                        if (hasTypeCol)
                        {
                            rows.Last().Insert(rows.Last().Count - 1, ConsoleString.Empty);
                        }
                        if (hasPosCol)
                        {
                            rows.Last().Insert(rows.Last().Count - 1, ConsoleString.Empty);
                        }
                    }
                }
            }

            return(FormatAsTable(columnHeaders, rows, "   "));
        }