| 34 | * Can not use JOptSimple as that doesn't parse out the values for keys unless the spec says it has a value. |
| 35 | */ |
| 36 | class ArgumentList { |
| 37 | private static final Logger LOGGER = LogManager.getLogger(); |
| 38 | private List<Supplier<String[]>> entries = new ArrayList<>(); |
| 39 | private Map<String, EntryValue> values = new HashMap<>(); |
| 40 | |
| 41 | public static ArgumentList from(String... args) { |
| 42 | ArgumentList ret = new ArgumentList(); |
| 43 | |
| 44 | boolean ended = false; |
| 45 | for (int x = 0; x < args.length; x++) { |
| 46 | if (!ended) { |
| 47 | if ("--".equals(args[x])) { // '--' by itself means there are no more arguments |
| 48 | ended = true; |
| 49 | } else if ("-".equals(args[x])) { |
| 50 | ret.addRaw(args[x]); |
| 51 | } else if (args[x].startsWith("-")) { |
| 52 | int idx = args[x].indexOf('='); |
| 53 | String key = idx == -1 ? args[x] : args[x].substring(0, idx); |
| 54 | String value = idx == -1 ? null : idx == args[x].length() - 1 ? "" : args[x].substring(idx + 1); |
| 55 | |
| 56 | if (idx == -1 && x + 1 < args.length && !args[x+1].startsWith("-")) { //Not in --key=value, so try and grab the next argument. |
| 57 | ret.addArg(true, key, args[x+1]); //Assume that if the next value is a "argument" then don't use it as a value. |
| 58 | x++; // This isn't perfect, but the best we can do without knowing all of the spec. |
| 59 | } else { |
| 60 | ret.addArg(false, key, value); |
| 61 | } |
| 62 | } else { |
| 63 | ret.addRaw(args[x]); |
| 64 | } |
| 65 | } else { |
| 66 | ret.addRaw(args[x]); |
| 67 | } |
| 68 | } |
| 69 | return ret; |
| 70 | } |
| 71 | |
| 72 | public void addRaw(final String arg) { |
| 73 | entries.add(() -> new String[] { arg }); |
| 74 | } |
| 75 | |
| 76 | public void addArg(boolean split, String raw, String value) { |
| 77 | int idx = raw.startsWith("--") ? 2 : 1; |
| 78 | String prefix = raw.substring(0, idx); |
| 79 | String key = raw.substring(idx); |
| 80 | EntryValue entry = new EntryValue(split, prefix, key, value); |
| 81 | if (values.containsKey(key)) { |
| 82 | LOGGER.info("Duplicate entries for " + key + " Unindexable"); |
| 83 | } else { |
| 84 | values.put(key, entry); |
| 85 | } |
| 86 | entries.add(entry); |
| 87 | } |
| 88 | |
| 89 | public String[] getArguments() { |
| 90 | return entries.stream() |
| 91 | .flatMap(e -> Arrays.asList(e.get()).stream()) |
| 92 | .toArray(size -> new String[size]); |
| 93 | } |