CommandLineInput DebugSource () { Whitespace (); if (ParseString ("DebugSource") == null) return null; Whitespace (); var expectMsg = "character offset in parentheses, e.g. DebugSource(5)"; if (Expect (String ("("), expectMsg) == null) return null; Whitespace (); int? characterOffset = ParseInt (); if (characterOffset == null) { Error (expectMsg); return null; } Whitespace (); Expect (String (")"), "closing parenthesis"); var inputStruct = new CommandLineInput (); inputStruct.debugSource = characterOffset; return inputStruct; }
// Valid returned objects: // - "help" // - int: for choice number // - Parsed.Divert // - Variable declaration/assignment // - Epression // - Lookup debug source for character offset // - Lookup debug source for runtime path public CommandLineInput CommandLineUserInput() { CommandLineInput result = new CommandLineInput(); Whitespace(); if (ParseString("help") != null) { result.isHelp = true; return(result); } if (ParseString("exit") != null || ParseString("quit") != null) { result.isExit = true; return(result); } return((CommandLineInput)OneOf( DebugSource, DebugPathLookup, UserChoiceNumber, UserImmediateModeStatement )); }
/// <summary> /// Control flow begins here. /// </summary> /// <param name="args">Command-line arguments. See <see cref="CommandLineInput.ShowUsage"/> /// for usage.</param>. /// <returns>0 on success, -1 on bad input, 1 on runtime error. See also <see cref="Result"/> /// enum.</returns> public static int Main(string[] args) { var input = new CommandLineInput(args); Feature?feature = input.Parse(); if (feature == null) { return(CommandLineInput.ShowUsage()); } // hijack Console.Out so it writes to a text file RedirectOutput(input.OutputFilename); // load configurable properties from a properties file ConfiguredProperties properties = ConfiguredProperties.Load(input.PropertiesFilename); // map the feature and configurable properties to a Program instance Program p = GetProgramInstance(feature.Value, properties); if (p == null) { return(Result.Invalid); } return(TryToExecute(p, DateTime.Now)); }
/// <summary> /// Runs the application with specified command line arguments and environment variables, and returns the exit code. /// </summary> public async ValueTask <int> RunAsync( IReadOnlyList <string> commandLineArguments, IReadOnlyDictionary <string, string> environmentVariables) { try { var applicationSchema = ApplicationSchema.Resolve(_configuration.CommandTypes); var commandLineInput = CommandLineInput.Parse(commandLineArguments); return (await HandleDebugDirectiveAsync(commandLineInput) ?? HandlePreviewDirective(applicationSchema, commandLineInput) ?? HandleVersionOption(commandLineInput) ?? HandleHelpOption(applicationSchema, commandLineInput) ?? await HandleCommandExecutionAsync(applicationSchema, commandLineInput, environmentVariables)); } catch (CliFxException cfe) { // We want to catch exceptions in order to print errors and return correct exit codes. // Doing this also gets rid of the annoying Windows troubleshooting dialog that shows up on unhandled exceptions. var exitCode = HandleCliFxException(commandLineArguments, cfe); return(exitCode); } catch (Exception ex) { // For all other errors, we just write the entire thing to stderr. _console.WithForegroundColor(ConsoleColor.Red, () => _console.Error.WriteLine(ex.ToString())); return(ex.HResult); } }
/// <summary> /// Runs the application with specified command line arguments and environment variables, and returns the exit code. /// </summary> public async ValueTask <int> RunAsync( IReadOnlyList <string> commandLineArguments, IReadOnlyDictionary <string, string> environmentVariables) { try { var applicationSchema = ApplicationSchema.Resolve(_configuration.CommandTypes); var commandLineInput = CommandLineInput.Parse(commandLineArguments); return (await HandleDebugDirectiveAsync(commandLineInput) ?? HandlePreviewDirective(applicationSchema, commandLineInput) ?? HandleVersionOption(commandLineInput) ?? HandleHelpOption(applicationSchema, commandLineInput) ?? await HandleCommandExecutionAsync(applicationSchema, commandLineInput, environmentVariables)); } catch (Exception ex) { // We want to catch exceptions in order to print errors and return correct exit codes. // Doing this also gets rid of the annoying Windows troubleshooting dialog that shows up on unhandled exceptions. // Prefer showing message without stack trace on exceptions coming from CliFx or on CommandException var errorMessage = !string.IsNullOrWhiteSpace(ex.Message) && (ex is CliFxException || ex is CommandException) ? ex.Message : ex.ToString(); _console.WithForegroundColor(ConsoleColor.Red, () => _console.Error.WriteLine(errorMessage)); return(ex is CommandException commandException ? commandException.ExitCode : ex.HResult); } }
internal void Any_remaining_arguments_are_treated_as_unbound_arguments(string[] arguments, CommandLineInput expectedInput) { // Act var input = CommandLineInput.Parse(arguments); // Assert input.Should().BeEquivalentTo(expectedInput); }
internal void Directive_can_be_enabled_by_specifying_its_name_in_square_brackets(string[] arguments, CommandLineInput expectedInput) { // Act var input = CommandLineInput.Parse(arguments); // Assert input.Should().BeEquivalentTo(expectedInput); }
public void Parse_Test(IReadOnlyList <string> commandLineArguments, CommandLineInput expectedResult) { // Act var result = CommandLineInput.Parse(commandLineArguments); // Assert result.Should().BeEquivalentTo(expectedResult); }
internal void Option_can_be_set_by_specifying_its_short_name_after_a_single_dash(string[] arguments, CommandLineInput expectedInput) { // Act var input = CommandLineInput.Parse(arguments); // Assert input.Should().BeEquivalentTo(expectedInput); }
CommandLineInput UserImmediateModeStatement() { var statement = OneOf(SingleDivert, TempDeclarationOrAssignment, Expression); var inputStruct = new CommandLineInput(); inputStruct.userImmediateModeStatement = statement; return(inputStruct); }
public void Input_is_empty_if_no_arguments_are_provided() { // Arrange var args = Array.Empty <string>(); // Act var input = CommandLineInput.Parse(args); // Assert input.Should().BeEquivalentTo(CommandLineInput.Empty); }
private async ValueTask <int> HandleCommandExecutionAsync( ApplicationSchema applicationSchema, CommandLineInput commandLineInput, IReadOnlyDictionary <string, string> environmentVariables) { await applicationSchema .InitializeEntryPoint(commandLineInput, environmentVariables, _typeActivator) .ExecuteAsync(_console); return(0); }
private int?HandleVersionOption(CommandLineInput commandLineInput) { // Version option is available only on the default command (i.e. when arguments are not specified) var shouldRenderVersion = !commandLineInput.Arguments.Any() && commandLineInput.IsVersionOptionSpecified; if (!shouldRenderVersion) { return(null); } _console.Output.WriteLine(_metadata.VersionText); return(0); }
public GetParsedInputDataResponse GetParsedInputData(Request request) { var response = new GetParsedInputDataResponse(); var processInputArgumentsRequest = request as ProcessInputArgumentsRequest; if (processInputArgumentsRequest == null) { response.AddErrorMessage(string.Format("{0}: request type should be {1}", ErrorStatus.InvalidRequest, nameof(ProcessInputArgumentsRequest))); return(response); } var args = processInputArgumentsRequest.args; int index = 0; var input = new CommandLineInput(); if (args.Count() < 2) { response.AddErrorMessage(string.Format("{0}: Please provide valid command line arguments", ErrorStatus.InvalidArgument) + "\n--file <path> full path to the input file" + "\n--sortByStartDate sort results by column \"Start date\" in ascending order" + "\n--project <project id> filter results by column \"Project\""); return(response); } if (!args.Contains(Options.File)) { response.AddErrorMessage(string.Format("{0}: --file <path> is mandatory", ErrorStatus.InvalidCommand)); return(response); } foreach (var arg in args) { if (arg == Options.File) { input.FilePath = args[index + 1]; } if (arg == Options.SortedByDate) { input.IsSortByStartDate = true; } if (arg == Options.Project) { input.ProjectId = args[index + 1]; } index += 1; } response.Data = input; return(response); }
private int?HandlePreviewDirective(ApplicationSchema applicationSchema, CommandLineInput commandLineInput) { var isPreviewMode = _configuration.IsPreviewModeAllowed && commandLineInput.IsPreviewDirectiveSpecified; if (!isPreviewMode) { return(null); } var commandSchema = applicationSchema.TryFindCommand(commandLineInput, out var argumentOffset); _console.Output.WriteLine("Parser preview:"); // Command name if (commandSchema != null && argumentOffset > 0) { _console.WithForegroundColor(ConsoleColor.Cyan, () => _console.Output.Write(commandSchema.Name)); _console.Output.Write(' '); } // Parameters foreach (var parameter in commandLineInput.Arguments.Skip(argumentOffset)) { _console.Output.Write('<'); _console.WithForegroundColor(ConsoleColor.White, () => _console.Output.Write(parameter)); _console.Output.Write('>'); _console.Output.Write(' '); } // Options foreach (var option in commandLineInput.Options) { _console.Output.Write('['); _console.WithForegroundColor(ConsoleColor.White, () => _console.Output.Write(option)); _console.Output.Write(']'); _console.Output.Write(' '); } _console.Output.WriteLine(); return(0); }
// Valid returned objects: // - "help" // - int: for choice number // - Parsed.Divert // - Variable declaration/assignment // - Epression public CommandLineInput CommandLineUserInput() { CommandLineInput result = new CommandLineInput (); Whitespace (); if (ParseString ("help") != null) { result.isHelp = true; return result; } if (ParseString ("exit") != null || ParseString ("quit") != null) { result.isExit = true; return result; } return (CommandLineInput) OneOf (DebugSource, UserChoiceNumber, UserImmediateModeStatement); }
/// <summary> /// The command Prompt for Pisces /// </summary> public void PiscesPrompt() { var input = new CommandLineInput(m_interval); do { Console.Write("pisces>"); var s = Console.ReadLine(); if (s.Trim() == "") continue; input.Read(s); if (input.Parameters.Length == 0 && input.SiteList.Length ==1) // get all parameters in database input.Parameters = GetAllParametersForSiteID(input.SiteList[0],m_interval); if (!input.Valid) { Console.WriteLine("Error: Invalid Input"); continue; } if (input.Command == Command.Exit) break; if (input.Command == Command.Help) { Help(); } if (input.Command == Command.Get) { if (input.SiteList.Length == 0) { Console.WriteLine("site is required"); continue; } Print(input,m_interval); } //Console.WriteLine("cmd = " + input.Command); //Console.WriteLine("sites = " + String.Join(",", input.SiteList)); //Console.WriteLine("parameters = " + String.Join(",", input.Parameters)); } while (true); }
CommandLineInput UserChoiceNumber() { Whitespace (); int? number = ParseInt (); if (number == null) { return null; } Whitespace (); if (Parse(EndOfLine) == null) { return null; } var inputStruct = new CommandLineInput (); inputStruct.choiceInput = number; return inputStruct; }
private async ValueTask <int?> HandleDebugDirectiveAsync(CommandLineInput commandLineInput) { var isDebugMode = _configuration.IsDebugModeAllowed && commandLineInput.IsDebugDirectiveSpecified; if (!isDebugMode) { return(null); } _console.WithForegroundColor(ConsoleColor.Green, () => _console.Output.WriteLine($"Attach debugger to PID {Process.GetCurrentProcess().Id} to continue.")); while (!Debugger.IsAttached) { await Task.Delay(100); } return(null); }
/// <summary> /// Handle <see cref="CommandException"/>s differently from the rest because we want to /// display it different based on whether we are showing the help text or not. /// </summary> private int HandleCliFxException(IReadOnlyList <string> commandLineArguments, CliFxException cfe) { var showHelp = cfe.ShowHelp; var errorMessage = cfe.HasMessage ? cfe.Message : cfe.ToString(); _console.WithForegroundColor(ConsoleColor.Red, () => _console.Error.WriteLine(errorMessage)); if (showHelp) { var applicationSchema = ApplicationSchema.Resolve(_configuration.CommandTypes); var commandLineInput = CommandLineInput.Parse(commandLineArguments); var commandSchema = applicationSchema.TryFindCommand(commandLineInput) ?? CommandSchema.StubDefaultCommand; _helpTextWriter.Write(applicationSchema, commandSchema); } return(cfe.ExitCode); }
private int?HandleHelpOption(ApplicationSchema applicationSchema, CommandLineInput commandLineInput) { // Help is rendered either when it's requested or when the user provides no arguments and there is no default command var shouldRenderHelp = commandLineInput.IsHelpOptionSpecified || !applicationSchema.Commands.Any(c => c.IsDefault) && !commandLineInput.Arguments.Any() && !commandLineInput.Options.Any(); if (!shouldRenderHelp) { return(null); } // Get the command schema that matches the input or use a dummy default command as a fallback var commandSchema = applicationSchema.TryFindCommand(commandLineInput) ?? CommandSchema.StubDefaultCommand; RenderHelp(applicationSchema, commandSchema); return(0); }
CommandLineInput DebugPathLookup() { Whitespace(); if (ParseString("DebugPath") == null) { return(null); } if (Whitespace() == null) { return(null); } var pathStr = Expect(RuntimePath, "path") as string; var inputStruct = new CommandLineInput(); inputStruct.debugPathLookup = pathStr; return(inputStruct); }
CommandLineInput UserChoiceNumber() { Whitespace(); int?number = ParseInt(); if (number == null) { return(null); } Whitespace(); if (Parse(EndOfLine) == null) { return(null); } var inputStruct = new CommandLineInput(); inputStruct.choiceInput = number; return(inputStruct); }
CommandLineInput DebugSource() { Whitespace(); if (ParseString("DebugSource") == null) { return(null); } Whitespace(); var expectMsg = "character offset in parentheses, e.g. DebugSource(5)"; if (Expect(String("("), expectMsg) == null) { return(null); } Whitespace(); int?characterOffset = ParseInt(); if (characterOffset == null) { Error(expectMsg); return(null); } Whitespace(); Expect(String(")"), "closing parenthesis"); var inputStruct = new CommandLineInput(); inputStruct.debugSource = characterOffset; return(inputStruct); }
/// <summary> /// Create a Series List /// </summary> /// <param name="input"></param> input from the command line /// <param name="interval"></param> time interval /// <returns></returns> private SeriesList CreateSeriesList(CommandLineInput input, TimeInterval interval) { List<TimeSeriesName> names = new List<TimeSeriesName>(); foreach (var cbtt in input.SiteList) { foreach (var pcode in input.Parameters) { string sInterval = TimeSeriesName.GetTimeIntervalForTableName(interval); TimeSeriesName tn = new TimeSeriesName(cbtt + "_" + pcode,sInterval); names.Add(tn); } } var tableNames = (from n in names select n.GetTableName()).ToArray(); var sc = m_db.GetSeriesCatalog("tablename in ('" + String.Join("','", tableNames) + "')"); SeriesList sList = new SeriesList(); foreach (var tn in names) { Series s = new Series(); s.TimeInterval = interval; if (sc.Select("tablename = '" + tn.GetTableName() + "'").Length == 1) { s = m_db.GetSeriesFromTableName(tn.GetTableName()); } s.Table.TableName = tn.GetTableName(); sList.Add(s); } return sList; }
/// <summary> /// /// </summary> /// <param name="input"></param> command line input /// <param name="interval"></param> time interval private void Print(CommandLineInput input, TimeInterval interval) { var list = CreateSeriesList(input, interval); //SeriesListDataTable sTable = new SeriesListDataTable(list, interval); //int counter = 0; list.Read(input.T1, input.T2);// example for read input if (interval == TimeInterval.Daily) { PrintDaily(list); } else { PrintInstant(list); } }
CommandLineInput UserImmediateModeStatement() { var statement = OneOf (SingleDivert, TempDeclarationOrAssignment, Expression); var inputStruct = new CommandLineInput (); inputStruct.userImmediateModeStatement = statement; return inputStruct; }