/// <summary> /// Attempts to parses command line args and returns command type. /// </summary> /// <param name="args">Args to parse</param> /// <param name="commandType">Parsed command type</param> /// <param name="fileArg">Parsed filename (optional arg)</param> /// <returns>true if parse is valid</returns> public static bool TryParseArgs(string[] args, out CommandLineArgType commandType, out string fileArg) { // First arg is command commandType = GetArgType(args.ElementAtOrDefault(0) ?? ""); // Optional filename arg string?filename = args.ElementAtOrDefault(1); // Check for value, and not a rogue command if (!string.IsNullOrEmpty(filename) && !filename.StartsWith('-')) { fileArg = filename; } else { // Method responsible for initializing to something fileArg = ""; } // Validate parse return(commandType switch { CommandLineArgType.CreateConfig or CommandLineArgType.ExecuteBackup => args.Length == 2 && !string.IsNullOrEmpty(fileArg), CommandLineArgType.Help or CommandLineArgType.Version => args.Length == 1, _ => false, });
public void TestTryParseArgs(string argsAsString, bool parseValid, CommandLineArgType correctType, string correctFileArg) { string[] args = argsAsString.Split(' '); bool parsed = CommandLineArgs.TryParseArgs(args, out CommandLineArgType type, out string fileArg); Assert.AreEqual(parseValid, parsed); Assert.AreEqual(correctType, type); Assert.AreEqual(correctFileArg, fileArg); }
/// <summary> /// Determines whether the command requires a filename arg. /// </summary> public static bool RequiresFilename(this CommandLineArgType type) { return(type == CommandLineArgType.CreateConfig || type == CommandLineArgType.ExecuteBackup); }
public void TestGetArgType(string arg, CommandLineArgType correctType) { Assert.AreEqual(correctType, CommandLineArgs.GetArgType(arg)); }