|
| 1 | +package io.github.easy4j.opencli.capability; |
| 2 | + |
| 3 | +import io.github.easy4j.opencli.core.OpenCliArgSupport; |
| 4 | +import io.github.easy4j.opencli.parser.OpenCliHelpSchema; |
| 5 | +import io.github.easy4j.opencli.parser.OpenCliHelpSchema.Argument; |
| 6 | +import io.github.easy4j.opencli.util.OpenCliStrings; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.Collections; |
| 9 | +import java.util.HashSet; |
| 10 | +import java.util.LinkedHashMap; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.Objects; |
| 14 | +import java.util.Set; |
| 15 | +import java.util.regex.Pattern; |
| 16 | +import lombok.RequiredArgsConstructor; |
| 17 | + |
| 18 | +/** Converts one explicitly selected help leaf into validated literal CLI arguments. */ |
| 19 | +public final class OpenCliCapabilityCommand { |
| 20 | + private static final Pattern COMMAND_TOKEN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_-]*"); |
| 21 | + private static final Pattern OPTION_TOKEN = Pattern.compile("--[A-Za-z0-9][A-Za-z0-9-]*|-[A-Za-z0-9]"); |
| 22 | + |
| 23 | + private OpenCliCapabilityCommand() { |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @param snapshot currently available structured help |
| 28 | + * @param command exact leaf display path from help, including any placeholders |
| 29 | + * @param session explicit browser session, or null for a non-browser leaf |
| 30 | + * @param positionals literal values in declared order, or null |
| 31 | + * @param options declared option spellings and values, with null values for bare flags |
| 32 | + * @return immutable literal arguments excluding the executable |
| 33 | + */ |
| 34 | + public static List<String> bind(OpenCliCapabilitySnapshot snapshot, String command, String session, |
| 35 | + List<String> positionals, Map<String, String> options) { |
| 36 | + Objects.requireNonNull(snapshot, "snapshot"); |
| 37 | + Objects.requireNonNull(command, "command"); |
| 38 | + if (snapshot.getStatus() != OpenCliCapabilitySnapshot.Status.AVAILABLE |
| 39 | + || Objects.isNull(snapshot.getHelp()) || Objects.isNull(snapshot.getHelp().getSchema())) { |
| 40 | + throw new IllegalStateException("Current structured help is unavailable"); |
| 41 | + } |
| 42 | + OpenCliHelpSchema scope = snapshot.getHelp().getSchema(); |
| 43 | + OpenCliHelpSchema leaf = locateLeaf(scope, command); |
| 44 | + String[] path = command.split(" ", -1); |
| 45 | + if (path.length < 3 || !"opencli".equals(path[0])) { |
| 46 | + throw new IllegalArgumentException("The help command path cannot be bound"); |
| 47 | + } |
| 48 | + |
| 49 | + List<String> prefixOptions = new ArrayList<>(); |
| 50 | + List<String> leafOptions = new ArrayList<>(); |
| 51 | + appendOptions(scope, leaf, options, prefixOptions, leafOptions); |
| 52 | + |
| 53 | + List<String> argv = new ArrayList<>(); |
| 54 | + argv.add(path[1]); |
| 55 | + argv.addAll(prefixOptions); |
| 56 | + boolean sessionUsed = false; |
| 57 | + for (int index = 2; index < path.length; index++) { |
| 58 | + String token = path[index]; |
| 59 | + if ("<session>".equals(token) && index == 2 && "browser".equals(path[1])) { |
| 60 | + if (OpenCliStrings.isBlank(session) || !COMMAND_TOKEN.matcher(session).matches()) { |
| 61 | + throw new IllegalArgumentException("A literal browser session identifier is required"); |
| 62 | + } |
| 63 | + argv.add(session); |
| 64 | + sessionUsed = true; |
| 65 | + } else { |
| 66 | + if (!COMMAND_TOKEN.matcher(token).matches()) { |
| 67 | + throw new IllegalArgumentException("The help command path contains an unsupported token"); |
| 68 | + } |
| 69 | + argv.add(token); |
| 70 | + } |
| 71 | + } |
| 72 | + if (!sessionUsed && Objects.nonNull(session)) { |
| 73 | + throw new IllegalArgumentException("This command has no browser session binding"); |
| 74 | + } |
| 75 | + argv.addAll(leafOptions); |
| 76 | + List<String> values = OpenCliArgSupport.merge(null, positionals); |
| 77 | + validatePositionals(leaf.getPositionals(), values); |
| 78 | + if (!values.isEmpty()) { |
| 79 | + argv.add("--"); |
| 80 | + argv.addAll(values); |
| 81 | + } |
| 82 | + return Collections.unmodifiableList(argv); |
| 83 | + } |
| 84 | + |
| 85 | + private static OpenCliHelpSchema locateLeaf(OpenCliHelpSchema scope, String command) { |
| 86 | + if (command.equals(scope.getCommand()) && scope.getCommands().isEmpty()) { |
| 87 | + return scope; |
| 88 | + } |
| 89 | + return scope.getCommands().stream() |
| 90 | + .filter(child -> command.equals(child.getCommand()) && child.getCommands().isEmpty()) |
| 91 | + .findFirst() |
| 92 | + .orElseThrow(() -> new IllegalArgumentException("The requested command is not a leaf in this help scope")); |
| 93 | + } |
| 94 | + |
| 95 | + private static void validatePositionals(List<Argument> definitions, List<String> values) { |
| 96 | + int consumed = 0; |
| 97 | + for (Argument definition : definitions) { |
| 98 | + int count = Boolean.TRUE.equals(definition.getVariadic()) ? values.size() - consumed |
| 99 | + : Math.min(1, values.size() - consumed); |
| 100 | + if (count == 0 && Boolean.TRUE.equals(definition.getRequired())) { |
| 101 | + throw invalid(definition, "is required"); |
| 102 | + } |
| 103 | + for (int index = 0; index < count; index++) { |
| 104 | + validateValue(definition, values.get(consumed++)); |
| 105 | + } |
| 106 | + } |
| 107 | + if (consumed != values.size()) { |
| 108 | + throw new IllegalArgumentException("Too many positional arguments"); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + private static void appendOptions(OpenCliHelpSchema scope, OpenCliHelpSchema leaf, Map<String, String> options, |
| 113 | + List<String> prefix, List<String> local) { |
| 114 | + Map<String, Option> definitions = new LinkedHashMap<>(); |
| 115 | + index(definitions, inherited(leaf.getGlobalOptions(), scope.getGlobalOptions()), prefix); |
| 116 | + index(definitions, inherited(leaf.getNamespaceOptions(), scope.getNamespaceOptions()), prefix); |
| 117 | + index(definitions, inherited(leaf.getCommonOptions(), scope.getCommonOptions()), local); |
| 118 | + index(definitions, leaf.getCommandOptions(), local); |
| 119 | + Set<Option> supplied = new HashSet<>(); |
| 120 | + if (Objects.nonNull(options)) { |
| 121 | + new LinkedHashMap<>(options).forEach((flag, value) -> { |
| 122 | + Option option = definitions.get(flag); |
| 123 | + if (Objects.isNull(option)) { |
| 124 | + throw new IllegalArgumentException("An option identifier was not declared by help"); |
| 125 | + } |
| 126 | + if (!supplied.add(option)) { |
| 127 | + throw invalid(option.argument, "was supplied more than once"); |
| 128 | + } |
| 129 | + option.append(flag, value); |
| 130 | + }); |
| 131 | + } |
| 132 | + for (Option option : new HashSet<>(definitions.values())) { |
| 133 | + if (Boolean.TRUE.equals(option.argument.getRequired()) && !supplied.contains(option)) { |
| 134 | + throw invalid(option.argument, "is required"); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + private static List<Argument> inherited(List<Argument> own, List<Argument> parent) { |
| 140 | + return own.isEmpty() ? parent : own; |
| 141 | + } |
| 142 | + |
| 143 | + private static void index(Map<String, Option> definitions, List<Argument> arguments, List<String> target) { |
| 144 | + for (Argument argument : arguments) { |
| 145 | + Option option = new Option(argument, target); |
| 146 | + String flags = argument.getFlags(); |
| 147 | + if (OpenCliStrings.isBlank(flags)) { |
| 148 | + flags = "--" + argument.getName(); |
| 149 | + } |
| 150 | + for (String flag : flags.split("[,\\s]+")) { |
| 151 | + if (OPTION_TOKEN.matcher(flag).matches() && Objects.nonNull(definitions.putIfAbsent(flag, option))) { |
| 152 | + throw invalid(argument, "has an ambiguous flag in this help scope"); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + private static void validateValue(Argument argument, String value) { |
| 159 | + if (value.indexOf(0) >= 0) { |
| 160 | + throw invalid(argument, "contains an invalid character"); |
| 161 | + } |
| 162 | + if (!argument.getChoices().isEmpty() && !argument.getChoices().contains(value)) { |
| 163 | + throw invalid(argument, "must be one of the declared choices"); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + private static IllegalArgumentException invalid(Argument argument, String reason) { |
| 168 | + return new IllegalArgumentException("Argument '" + argument.getName() + "' " + reason); |
| 169 | + } |
| 170 | + |
| 171 | + @RequiredArgsConstructor |
| 172 | + private static class Option { |
| 173 | + private final Argument argument; |
| 174 | + private final List<String> target; |
| 175 | + |
| 176 | + private void append(String flag, String value) { |
| 177 | + String arity = argument.getTakesValue(); |
| 178 | + String flags = argument.getFlags(); |
| 179 | + if (Objects.isNull(arity)) { |
| 180 | + if (Boolean.TRUE.equals(argument.getValueRequired()) || Boolean.TRUE.equals(argument.getRequired()) |
| 181 | + || (Objects.nonNull(flags) && flags.indexOf('<') >= 0)) { |
| 182 | + arity = "required"; |
| 183 | + } else if (OpenCliStrings.isBlank(flags) || flags.indexOf('[') >= 0) { |
| 184 | + arity = "optional"; |
| 185 | + } else { |
| 186 | + arity = "none"; |
| 187 | + } |
| 188 | + } |
| 189 | + if (flag.startsWith("--no-") || Boolean.TRUE.equals(argument.getNegate())) { |
| 190 | + arity = "none"; |
| 191 | + } |
| 192 | + switch (arity) { |
| 193 | + case "required": |
| 194 | + if (Objects.isNull(value)) { |
| 195 | + throw invalid(argument, "requires a value"); |
| 196 | + } |
| 197 | + validateValue(argument, value); |
| 198 | + OpenCliArgSupport.addOptionPair(target, flag, value); |
| 199 | + break; |
| 200 | + case "optional": |
| 201 | + if (Objects.isNull(value)) { |
| 202 | + target.add(flag); |
| 203 | + } else { |
| 204 | + validateValue(argument, value); |
| 205 | + if (flag.startsWith("--")) { |
| 206 | + OpenCliArgSupport.addOptionEquals(target, flag, value); |
| 207 | + } else if (!value.isEmpty()) { |
| 208 | + target.add(flag + value); |
| 209 | + } else { |
| 210 | + throw invalid(argument, "requires a long option spelling for an empty value"); |
| 211 | + } |
| 212 | + } |
| 213 | + break; |
| 214 | + case "none": |
| 215 | + if (Objects.nonNull(value)) { |
| 216 | + throw invalid(argument, "does not take a value"); |
| 217 | + } |
| 218 | + target.add(flag); |
| 219 | + break; |
| 220 | + default: |
| 221 | + throw invalid(argument, "has unknown value semantics"); |
| 222 | + } |
| 223 | + } |
| 224 | + } |
| 225 | +} |
0 commit comments