Пример #1
0
        public void When_HasValueFalseNotPassed_Expect_ValueFalse(string args)
        {
            // -- arrange

            // -- act
            var result = ParserExtensions.ParseCommandArgs <TestParameters>(args.Split(" "));

            // -- assert
            Assert.False(result.Flag);
        }
Пример #2
0
        public void When_RequiredParameterNotSpecified_Expect_Throw()
        {
            // -- arrange

            // -- act
            Action action = () => ParserExtensions.ParseCommandArgs <TestParameters>(new string[] { });

            // -- assert
            Assert.Throws <MissingParameterParseException>(action);
        }
Пример #3
0
        public void When_UnknownParameter_Expect_Throw(string args)
        {
            // -- arrange

            // -- act
            Action action = () => ParserExtensions.ParseCommandArgs <TestParameters>(args.Split(" "));

            // -- assert
            Assert.Throws <UnknownParameterParseException>(action);
        }
Пример #4
0
        public void When_ValueNotSpecified_Expect_Throw(string args)
        {
            // -- arrange

            // -- act
            Action action = () => ParserExtensions.ParseCommandArgs <TestParameters>(args.Split(" "));

            // -- assert
            Assert.Throws <MissingValueParseException>(action);
        }
Пример #5
0
            protected override bool?TryExecuteInternal(object source, out double result)
            {
                if (source is string s)
                {
                    return(ParserExtensions.DoubleTryParseСurrentOrInvariant(s, out result));
                }

                result = 0;
                return(null);
            }
Пример #6
0
        public void When_RequestingStringArray_Expect_ReturnSameArray(string args)
        {
            // -- arrange
            var arr = args.Split(" ");

            // -- act
            var result = ParserExtensions.ParseCommandArgs <string[]>(arr);

            // -- assert
            Assert.Same(arr, result);
        }
Пример #7
0
        public void ToSqlQuery_CorrectTable_ReturnString()
        {
            var table = new Table(new string[] { "id", "User", "Balance", "Date", "Bool" });

            table.AddRow("1243", "Петор Петров", "100000", "2000-12-12", "false");

            var ListParams = step.TransformationTableToString(table);

            var result = ParserExtensions.ToSqlQuery(ListParams, tableName);

            result.Should().BeEquivalentTo("INSERT INTO Table (id,User,Balance,Date,Bool)" +
                                           " VALUES (1243,'Петор Петров',100000,'2000-12-12',False)");
        }
Пример #8
0
        private static object InferTypeAndConvertLiteral(string literal)
        {
            //A propertly quoted string must be...
            //  At least two characters long
            //  Start and end with the same character
            //  The character that the string starts with must be one of the supported quote kinds
            if (literal.Length < 2 || literal[0] != literal[literal.Length - 1] || !SupportedQuotes.Contains(literal[0]))
            {
                if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (string.Equals(literal, "null", StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if ((literal.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) ||
                     literal.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)) &&
                    ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out double literalDouble))
                {
                    return(literalDouble);
                }

                if (long.TryParse(literal, out long literalLong))
                {
                    return(literalLong);
                }

                if (literal.StartsWith("0x", StringComparison.OrdinalIgnoreCase) &&
                    long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out literalLong))
                {
                    return(literalLong);
                }

                return(null);
            }

            return(literal.Substring(1, literal.Length - 2));
        }
        internal static object InferTypeAndConvertLiteral(string literal)
        {
            if (literal == null)
            {
                return(null);
            }

            if (!literal.Contains("\""))
            {
                if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (string.Equals(literal, "null", StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if ((literal.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) ||
                     literal.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)) &&
                    ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out double literalDouble))
                {
                    return(literalDouble);
                }

                if (long.TryParse(literal, out long literalLong))
                {
                    return(literalLong);
                }

                if (literal.StartsWith("0x", StringComparison.OrdinalIgnoreCase) &&
                    long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out literalLong))
                {
                    return(literalLong);
                }
            }

            return(literal);
        }
Пример #10
0
        public void Process(string source)
        {
            // Remove comments
            source = source.StripComments();

            // Remove unwanted characters
            source = source.CleanUnwanted();

#if DEBUG
            System.Diagnostics.Debug.WriteLine(source);
#endif

            // Parsing tree
            _script = Sylabs.Parsing.Script.Produce(ParserExtensions.PopulateSymbols(source));
            if (_script == null)
            {
                throw new ParserException("Invalid script");
            }
        }
Пример #11
0
        public override async Task <bool> Execute(Message message, TelegramBotClient botClient)
        {
            switch (_typeRequest)
            {
            case TypeRequest.Start:
                _messageText = "";
                var args = ParserExtensions.Parse(new Parser(), _messageText).Tokens.Select(a => a.Value).ToList();
                if (args.Count > 1)
                {
                    _messageText = string.Join(" ", args.Skip(1).ToArray());
                }
                break;

            case TypeRequest.Resource: _messageText = message.Text; break;

            case TypeRequest.ArgParameter: ReplaceArg(message.Text); break;

            default: break;
            }

            return(await ExecuteOrChoose(message, botClient));
        }
        // For explicitly data-typed variables, attempt to convert the variable value to the specified type.
        // Data type names:
        //     - choice
        //     - bool
        //     - float
        //     - int
        //     - hex
        //     - text
        // The data type names are case insensitive.
        //
        // Returns the converted value if it can be converted, throw otherwise
        internal static object DataTypeSpecifiedConvertLiteral(IEngineEnvironmentSettings environmentSettings, ITemplateParameter param, string literal, out bool valueResolutionError)
        {
            valueResolutionError = false;

            if (string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase))
            {
                if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                else if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
                else
                {
                    bool boolVal = false;
                    // Note: if the literal is ever null, it is probably due to a problem in TemplateCreator.Instantiate()
                    // which takes care of making null bool -> true as appropriate.
                    // This else can also happen if there is a value but it can't be converted.
                    string val;
                    while (environmentSettings.Host.OnParameterError(param, null, "ParameterValueNotSpecified", out val) && !bool.TryParse(val, out boolVal))
                    {
                    }

                    valueResolutionError = !bool.TryParse(val, out boolVal);
                    return(boolVal);
                }
            }
            else if (string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase))
            {
                if (TryResolveChoiceValue(literal, param, out string match))
                {
                    return(match);
                }

                if (literal == null && param.Priority != TemplateParameterPriority.Required)
                {
                    return(param.DefaultValue);
                }

                string val;
                while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValid:" + string.Join(",", param.Choices.Keys), out val) &&
                       !TryResolveChoiceValue(literal, param, out val))
                {
                }

                valueResolutionError = val == null;
                return(val);
            }

            else if (string.Equals(param.DataType, "float", StringComparison.OrdinalIgnoreCase))
            {
                if (ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out double convertedFloat))
                {
                    return(convertedFloat);
                }
                else
                {
                    string val;
                    while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeFloat", out val) && (val == null || !ParserExtensions.DoubleTryParseСurrentOrInvariant(val, out convertedFloat)))
                    {
                    }

                    valueResolutionError = !ParserExtensions.DoubleTryParseСurrentOrInvariant(val, out convertedFloat);
                    return(convertedFloat);
                }
            }
            else if (string.Equals(param.DataType, "int", StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(param.DataType, "integer", StringComparison.OrdinalIgnoreCase))
            {
                if (long.TryParse(literal, out long convertedInt))
                {
                    return(convertedInt);
                }
                else
                {
                    string val;
                    while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeInteger", out val) && (val == null || !long.TryParse(val, out convertedInt)))
                    {
                    }

                    valueResolutionError = !long.TryParse(val, out convertedInt);
                    return(convertedInt);
                }
            }
            else if (string.Equals(param.DataType, "hex", StringComparison.OrdinalIgnoreCase))
            {
                if (long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long convertedHex))
                {
                    return(convertedHex);
                }
                else
                {
                    string val;
                    while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeHex", out val) && (val == null || val.Length < 3 || !long.TryParse(val.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex)))
                    {
                    }

                    valueResolutionError = !long.TryParse(val.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex);
                    return(convertedHex);
                }
            }
            else if (string.Equals(param.DataType, "text", StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(param.DataType, "string", StringComparison.OrdinalIgnoreCase))
            {   // "text" is a valid data type, but doesn't need any special handling.
                return(literal);
            }
            else
            {
                return(literal);
            }
        }
Пример #13
0
        internal static object?DataTypeSpecifiedConvertLiteral(IEngineEnvironmentSettings environmentSettings, ITemplateParameter param, string literal, out bool valueResolutionError)
        {
            valueResolutionError = false;

            if (string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase))
            {
                if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                else if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
                else
                {
                    bool boolVal = false;
                    // Note: if the literal is ever null, it is probably due to a problem in TemplateCreator.Instantiate()
                    // which takes care of making null bool -> true as appropriate.
                    // This else can also happen if there is a value but it can't be converted.
                    string?val;
#pragma warning disable CS0618 // Type or member is obsolete - for backward compatibility
                    while (environmentSettings.Host.OnParameterError(param, string.Empty, "ParameterValueNotSpecified", out val) && !bool.TryParse(val, out boolVal))
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                    }

                    valueResolutionError = !bool.TryParse(val, out boolVal);
                    return(boolVal);
                }
            }
            else if (param.IsChoice())
            {
                if (param.AllowMultipleValues)
                {
                    List <string> val =
                        literal
                        .TokenizeMultiValueParameter()
                        .Select(t => ResolveChoice(environmentSettings, t, param))
                        .Where(r => !string.IsNullOrEmpty(r))
                        .Select(r => r !)
                        .ToList();
                    if (val.Count <= 1)
                    {
                        return(val.Count == 0 ? string.Empty : val[0]);
                    }

                    return(new MultiValueParameter(val));
                }
                else
                {
                    string?val = ResolveChoice(environmentSettings, literal, param);
                    valueResolutionError = val == null;
                    return(val);
                }
            }
            else if (string.Equals(param.DataType, "float", StringComparison.OrdinalIgnoreCase))
            {
                if (ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out double convertedFloat))
                {
                    return(convertedFloat);
                }
                else
                {
                    string?val;
#pragma warning disable CS0618 // Type or member is obsolete - for backward compatibility
                    while (environmentSettings.Host.OnParameterError(param, string.Empty, "ValueNotValidMustBeFloat", out val) && (val == null || !ParserExtensions.DoubleTryParseСurrentOrInvariant(val, out convertedFloat)))
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                    }

                    valueResolutionError = !ParserExtensions.DoubleTryParseСurrentOrInvariant(val, out convertedFloat);
                    return(convertedFloat);
                }
            }
            else if (string.Equals(param.DataType, "int", StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(param.DataType, "integer", StringComparison.OrdinalIgnoreCase))
            {
                if (long.TryParse(literal, out long convertedInt))
                {
                    return(convertedInt);
                }
                else
                {
                    string?val;
#pragma warning disable CS0618 // Type or member is obsolete - for backward compatibility
                    while (environmentSettings.Host.OnParameterError(param, string.Empty, "ValueNotValidMustBeInteger", out val) && (val == null || !long.TryParse(val, out convertedInt)))
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                    }

                    valueResolutionError = !long.TryParse(val, out convertedInt);
                    return(convertedInt);
                }
            }
            else if (string.Equals(param.DataType, "hex", StringComparison.OrdinalIgnoreCase))
            {
                if (long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long convertedHex))
                {
                    return(convertedHex);
                }
                else
                {
                    string?val;
#pragma warning disable CS0618 // Type or member is obsolete - for backward compatibility
                    while (environmentSettings.Host.OnParameterError(param, string.Empty, "ValueNotValidMustBeHex", out val) && (val == null || val.Length < 3 || !long.TryParse(val.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex)))
#pragma warning restore CS0618 // Type or member is obsolete
                    {
                    }

                    valueResolutionError = !long.TryParse(val?.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex);
                    return(convertedHex);
                }
            }
            else if (string.Equals(param.DataType, "text", StringComparison.OrdinalIgnoreCase) ||
                     string.Equals(param.DataType, "string", StringComparison.OrdinalIgnoreCase))
            {
                // "text" is a valid data type, but doesn't need any special handling.
                return(literal);
            }
            else
            {
                return(literal);
            }
        }
Пример #14
0
        private async Task <bool> ExecuteOrChoose(Message message, TelegramBotClient botClient)
        {
            var endCommand = false;
            var cmdArgs    = ParserExtensions.Parse(new Parser(), _messageText).Tokens.Select(a => a.Value).ToList();

            if (cmdArgs.Count == 0)
            {
                //request resource
                _typeRequest = TypeRequest.Resource;
                await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, DEFAULT_MSG);
            }
            else
            {
                var resource = cmdArgs[0];
                if (!resource.StartsWith("/"))
                {
                    resource = "/" + resource;
                }
                var requestArgs    = StringHelper.GetArgumentTags(resource);
                var parameters     = cmdArgs.Skip(1).ToArray();
                var parametersArgs = parameters.SelectMany(a => StringHelper.GetArgumentTags(a)).ToList();

                if (requestArgs.Count() > 0)
                {
                    //fix request
                    resource = resource.Substring(0, resource.IndexOf(StringHelper.CreateArgumentTag(requestArgs[0])) - 1);

                    var pveClient = PveHelper.GetClient();
                    var(Values, Error) = ApiExplorer.ListValues(pveClient, PveHelper.GetClassApiRoot(pveClient), resource);
                    if (!string.IsNullOrWhiteSpace(Error))
                    {
                        //return error
                        await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id, Error);

                        endCommand = true;
                    }
                    else
                    {
                        _typeRequest = TypeRequest.ArgResource;

                        await botClient.ChooseInlineKeyboard(message.Chat.Id,
                                                             $"Choose {requestArgs[0]}",
                                                             Values.Select(a => ("", a.Value, a.Value)));
                    }
                }
                else if (parametersArgs.Count() > 0)
                {
                    //request parameter value
                    _typeRequest = TypeRequest.ArgParameter;

                    await botClient.SendTextMessageAsyncNoKeyboard(message.Chat.Id,
                                                                   $"Insert value for parmater <b>{parametersArgs[0]}</b>");
                }
                else if (requestArgs.Count() == 0)
                {
                    var pveClient = PveHelper.GetClient();
                    //execute request
                    var(ResultCode, ResultText) = ApiExplorer.Execute(pveClient,
                                                                      PveHelper.GetClassApiRoot(pveClient),
                                                                      resource,
                                                                      MethodType,
                                                                      ApiExplorer.CreateParameterResource(parameters),
                                                                      false,
                                                                      ApiExplorer.OutputType.Html);

                    if (ResultCode != 200)
                    {
                        await botClient.SendTextMessageAsync(message.Chat.Id, $"Error: {ResultText}");
                    }
                    else
                    {
                        var filename = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(resource).Replace("/", "");
                        await botClient.SendDocumentAsyncFromText(message.Chat.Id, ResultText, $"{filename}.html");
                    }

                    endCommand = true;
                }
            }

            if (endCommand)
            {
                _messageText = "";
            }

            return(await Task.FromResult(endCommand));
        }
Пример #15
0
        private static bool ParseLine(TextWriter output,
                                      string input,
                                      PveClient client,
                                      ClassApi classApiRoot,
                                      AliasManager aliasManager,
                                      bool onlyResult)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return(false);
            }
            input = input.Trim();

            //comment
            if (input.StartsWith("#"))
            {
                return(false);
            }

            using var app = new CommandLineApplication();
            var exit = false;

            app.Name        = "";
            app.Description = "Corsinvest Interactive Shell API for Proxmox VE";
            app.DebugOption();
            app.DryRunOption();
            app.UsePagerForHelpText = false;
            app.HelpOption(true);

            ShellCommands.ApiCommands(app, client, classApiRoot);

            //fix help text
            foreach (var command in app.Commands)
            {
                command.FullName            = app.Description;
                command.ExtendedHelpText    = "";
                command.UsePagerForHelpText = false;
            }

            //create command from alias
            CreateCommandFromAlias(output,
                                   app,
                                   client,
                                   classApiRoot,
                                   aliasManager,
                                   onlyResult);

            #region Commands base
            app.Command("quit", cmd =>
            {
                cmd.AddName("exit");
                cmd.Description          = "Close application";
                cmd.OnExecute(() => exit = true);
            });

            app.Command("clear", cmd =>
            {
                cmd.AddName("cls");
                cmd.Description = "Clear screen";
                cmd.OnExecute(() => Console.Clear());
            });

            app.Command("help", cmd =>
            {
                cmd.Description = "Show help information";
                cmd.OnExecute(() => app.ShowHelp());
            });

            CmdAlias(output, app, aliasManager);
            CmdHistory(output, app, onlyResult);
            #endregion

            app.OnExecute(() => app.ShowHint());

            //execute command
            try { app.Execute(ParserExtensions.Parse(new Parser(), input).Tokens.Select(a => a.Value).ToArray()); }
            catch (CommandParsingException ex) { output.WriteLine(ex.Message); }
            //     catch (Exception ex) { output.WriteLine(ex.Message); }

            return(exit);
        }