public static List <string> Parse(string[] args, IList <BeeOpts> opts, OnUnknownOption OnUnknown) { List <string> parsedArgs = new List <string>(); int argIdx = 0; while (argIdx < args.Length) { string curr = args[argIdx]; if (curr.StartsWith("--")) { if (curr.Length > 2) { ParseLong(args, opts, ref argIdx, OnUnknown); } else { parsedArgs.AddRange(args.Skip(argIdx + 1)); break; } } else if (curr.StartsWith("-")) { if (curr.Length > 1) { ParseShort(args, opts, ref argIdx, OnUnknown); } else { throw new Exception($"bad option [{curr}]"); } } else { parsedArgs.Add(args[argIdx]); } ++argIdx; } return(parsedArgs); }
private static void ParseShort(string[] args, IList <BeeOpts> opts, ref int currArgIdx, OnUnknownOption OnUnknown) { string currArg = args[currArgIdx]; int shotOptIdx = 1; // skip beginning "-" while (shotOptIdx < currArg.Length) { char curr = currArg[shotOptIdx]; BeeOpts foundOpt = opts.FirstOrDefault(o => o.opt == curr); if (foundOpt == null) { OnUnknown(curr.ToString()); ++shotOptIdx; } else { if (foundOpt.type == OPTTYPE.BOOL) { foundOpt.OnOptionCallback(null); ++shotOptIdx; } else if (foundOpt.type == OPTTYPE.VALUE) { if (shotOptIdx < currArg.Length - 1) { foundOpt.OnOptionCallback(currArg.Substring(shotOptIdx + 1)); // rest is the value } else { string value = ReadNextAsArg(args, ref currArgIdx); foundOpt.OnOptionCallback(value); } break; } } } }
private static void ParseLong(string[] args, IList <BeeOpts> opts, ref int currArgIdx, OnUnknownOption OnUnknown) { string longOpt = args[currArgIdx].Substring(2); string[] optWithValue = longOpt.Split('='); string optname; if (optWithValue.Length == 1 || optWithValue.Length == 2) { optname = optWithValue[0]; } else { throw new Exception($"bad option [{longOpt}]"); } BeeOpts foundOpt = opts.FirstOrDefault(o => o.optLong.Equals(optname)); if (foundOpt == null) { OnUnknown?.Invoke(optname); } else { if (foundOpt.type == OPTTYPE.BOOL) { foundOpt.OnOptionCallback(null); } else if (foundOpt.type == OPTTYPE.VALUE) { if (optWithValue.Length == 2) { foundOpt.OnOptionCallback(optWithValue[1]); } else { string value = ReadNextAsArg(args, ref currArgIdx); foundOpt.OnOptionCallback(value); } } } }