8000 Client API v2 CLI client: make discriminator subcommand optional by michalvavrik · Pull Request #48018 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,15 @@ static void addCommands(CommandLine cli, KcAdmV2CommandDescriptor descriptor) {
}

private static CommandLine buildSubcommand(CommandDescriptor cmd) {
List<VariantDescriptor> variants = cmd.getVariants();
if (variants != null && !variants.isEmpty()) {
if (cmd.hasVariants()) {
return buildVariantParentCommand(cmd);
}

return buildLeafCommand(cmd, cmd.getOptions(), null);
}

private static CommandLine buildVariantParentCommand(CommandDescriptor cmd) {
GroupCommand groupCommand = new GroupCommand(cmd.getName());
CommandSpec parentSpec = CommandSpec.wrapWithoutInspection(groupCommand);
parentSpec.name(cmd.getName());
parentSpec.usageMessage().description(cmd.getDescription());
addHelpOption(parentSpec);

CommandLine parentCli = new CommandLine(parentSpec);
groupCommand.setSpec(parentSpec);
CommandLine parentCli = buildLeafCommand(cmd, null, null);

for (VariantDescriptor variant : cmd.getVariants()) {
parentCli.addSubcommand(variant.getName(),
Expand All @@ -72,6 +64,8 @@ private static CommandLine buildVariantParentCommand(CommandDescriptor cmd) {

private static CommandLine buildLeafCommand(CommandDescriptor cmd,
List<OptionDescriptor> options, VariantDescriptor variant) {
boolean isVariantParent = variant == null && cmd.hasVariants();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
boolean isVariantParent = variant == null
&& cmd.getVariants() != null && !cmd.getVariants().isEmpty();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, thanks

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I did bit refactoring, but essentially it is your suggestion in there)

KcAdmV2RequestExecutor executor = new KcAdmV2RequestExecutor(cmd, variant);
CommandSpec spec = CommandSpec.forAnnotatedObject(executor);
spec.name(variant != null ? variant.getName() : cmd.getName());
Expand All @@ -87,7 +81,7 @@ private static CommandLine buildLeafCommand(CommandDescriptor cmd,
addOutputGroup(spec);
}

if (cmd.isRequiresId()) {
if (!isVariantParent && cmd.isRequiresId()) {
spec.addPositional(PositionalParamSpec.builder()
.index("0")
.paramLabel("<id>")
Expand All @@ -97,21 +91,20 @@ private static CommandLine buildLeafCommand(CommandDescriptor cmd,
.build());
}

if (options != null && !options.isEmpty()) {
boolean hasFieldOptions = options != null && !options.isEmpty();
if (hasFieldOptions || isVariantParent) {
ArgGroupSpec.Builder fieldGroup = ArgGroupSpec.builder()
.heading("%nOptions:%n")
.exclusive(false)
.validate(false)
.order(1);

fieldGroup.addArg(OptionSpec.builder(OPT_FILE, "--file")
.type(String.class)
.paramLabel("<file>")
.description("JSON file with request body (mutually exclusive with field options)")
.build());
fieldGroup.addArg(buildFileOption(hasFieldOptions));

for (OptionDescriptor opt : options) {
fieldGroup.addArg(buildOption(opt));
if (hasFieldOptions) {
for (OptionDescriptor opt : options) {
fieldGroup.addArg(buildOption(opt));
}
}

spec.addArgGroup(fieldGroup.build());
Expand Down Expand Up @@ -143,6 +136,17 @@ private static OptionSpec buildOption(OptionDescriptor opt) {
return builder.build();
}

private static OptionSpec buildFileOption(boolean hasFieldOptions) {
String description = hasFieldOptions
? "JSON file with request body (mutually exclusive with field options)"
: "JSON file with request body";
return OptionSpec.builder(OPT_FILE, "--file")
.type(String.class)
.paramLabel("<file>")
.description(description)
.build();
}

private static void addOutputGroup(CommandSpec spec) {
spec.addArgGroup(ArgGroupSpec.builder()
.heading("%nOutput options:%n")
Expand Down
4 changes: 4 additions & 0 deletions < 10000 span class="Truncate"> ...li/admin-cli/src/main/java/org/keycloak/client/admin/cli/v2/KcAdmV2CommandDescriptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ public List<VariantDescriptor> getVariants() {
return variants;
}

public boolean hasVariants() {
return variants != null && !variants.isEmpty();
}

public void setVariants(List<VariantDescriptor> variants) {
this.variants = variants;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ class KcAdmV2RequestExecutor extends AbstractTargetAuthOptionsCmd {
static final String API_VERSION = "v2";
static final String DEFAULT_REALM = "master";

// Maps resource name to the JSON field that holds its ID, used to extract
// the path parameter from --file content when no positional <id> is given
private static final Map<String, String> RESOURCE_ID_FIELDS = Map.of(
"client", "clientId"
);

@Spec CommandSpec spec;
private final CommandDescriptor descriptor;
private final VariantDescriptor variant;
Expand All @@ -59,6 +65,10 @@ class KcAdmV2RequestExecutor extends AbstractTargetAuthOptionsCmd {
this.variant = variant;
}

private boolean isVariantParent() {
return variant == null && descriptor.hasVariants();
}

@Override
protected String help() {
return "";
Expand Down Expand Up @@ -145,8 +155,12 @@ public void run() {
}
configData.setRealm(requestRealm);

String url = buildUrl(configData);
String body = buildRequestBody();
if (body == null && isVariantParent()) {
throw new RuntimeException(
"No file specified. Use -f/--file to provide a request body.");
}
String url = buildUrl(configData, body);

Headers headers = new Headers();
if (token != null) {
Expand Down Expand Up @@ -184,25 +198,45 @@ public void run() {
}
}

private String buildUrl(ConfigData configData) {
private String buildUrl(ConfigData configData, String body) {
String path = descriptor.getPath()
.replace("{realmName}", HttpUtil.urlencode(configData.getRealm()))
.replace("{version}", API_VERSION);

if (descriptor.isRequiresId()) {
var positional = spec.commandLine().getParseResult().matchedPositional(0);
if (positional == null) {
throw new RuntimeException("Missing required ID argument");
final String id;
if (positional != null) {
id = positional.getValue();
} else {
id = extractIdFromBody(body);
}
path = path.replace(KcAdmV2DescriptorBuilder.ID_PATH_PARAM, HttpUtil.urlencode(positional.getValue()));
path = path.replace(KcAdmV2DescriptorBuilder.ID_PATH_PARAM, HttpUtil.urlencode(id));
}

return configData.getServerUrl() + path;
}

private String extractIdFromBody(String body) {
String idField = RESOURCE_ID_FIELDS.get(descriptor.getResourceName());
if (idField == null) {
throw new RuntimeException("Cannot extract '" + descriptor.getResourceName()
+ "' resource ID from file. Use a subcommand that accepts <id> instead.");
}
try {
JsonNode node = JsonSerialization.readValue(body, JsonNode.class);
JsonNode idNode = node.get(idField);
if (idNode == null || idNode.isNull() || idNode.asText().isBlank()) {
throw new RuntimeException("File does not contain required '" + idField + "' field");
}
return idNode.asText();
} catch (IOException e) {
throw new RuntimeException("Cannot parse JSON to extract ID: " + e.getMessage(), e);
}
}

private String buildRequestBody() throws IOException {
String file = spec.commandLine().getParseResult()
.matchedOptionValue(KcAdmV2CommandBuilder.OPT_FILE, null);
String file = resolveFileOption();

List<OptionDescriptor> options = variant != null
? variant.getOptions() : descriptor.getOptions();
Expand Down Expand Up @@ -275,6 +309,20 @@ private boolean hasAnyFieldOptionSet(List<OptionDescriptor> options) {
return false;
}

private String resolveFileOption() {
String file = spec.commandLine().getParseResult().matchedOptionValue(KcAdmV2CommandBuilder.OPT_FILE, null);
CommandLine parent = spec.commandLine().getParent();
String parentFile = parent != null
? parent.getParseResult().matchedOptionValue(KcAdmV2CommandBuilder.OPT_FILE, null)
: null;

if (file != null && parentFile != null) {
throw new RuntimeException(
"Option -f/--file specified twice. Use it either before or after the subcommand, not both.");
}
return file != null ? file : parentFile;
}

private String formatOutput(String json) {
try {
var parseResult = spec.commandLine().getParseResult();
Expand Down
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ public void testSamlOptionsInAutocompleteForCreateSaml() {
assertFalse("Should not suggest '--login-flows'", candidates.contains("--login-flows"));
}

@Test
public void testFileOptionInAutocompleteForCreateParent() {
List<String> candidates = complete("client", "create", "-");
assertTrue("Should suggest '-f' at parent level", candidates.contains("-f"));
}

@Test
public void testFieldOptionsNotInAutocompleteForCreateParent() {
List<String> candidates = complete("client", "create", "--");
assertFalse("Should not suggest '--client-id' at parent level", candidates.contains("--client-id"));
assertFalse("Should not suggest '--login-flows' at parent level", candidates.contains("--login-flows"));
}

@Test
public void testFileOptionNotInAutocompleteForList() {
List<String> candidates = complete("client", "list", "-");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,44 @@ public void testHelpFlagOnGroupCommand() {
assertTrue("should show subcommands", out.toString().contains("list"));
}

@Test
public void testVariantParentShowsFileOptionForCreate() {
String help = getVariantParentHelp("create");
assertTrue("create parent should show -f option: " + help, help.contains("-f"));
assertTrue("create parent should show --file option: " + help, help.contains("--file"));
}

@Test
public void testVariantParentShowsFileOptionForUpdate() {
String help = getVariantParentHelp("update");
assertTrue("update parent should show -f option: " + help, help.contains("-f"));
assertTrue("update parent should show --file option: " + help, help.contains("--file"));
assertFalse("update parent should not show <id>: " + help, help.contains("<id>"));
}

@Test
public void testVariantParentShowsFileOptionForPatch() {
String help = getVariantParentHelp("patch");
assertTrue("patch parent should show -f option: " + help, help.contains("-f"));
assertTrue("patch parent should show --file option: " + help, help.contains("--file"));
assertFalse("patch parent should not show <id>: " + help, help.contains("<id>"));
}

@Test
public void testVariantParentDoesNotShowFieldOptions() {
String help = getVariantParentHelp("create");
assertFalse("create parent should not show --client-id: " + help, help.contains("--client-id"));
assertFalse("create parent should not show --login-flows: " + help, help.contains("--login-flows"));
assertFalse("create parent should not show --sign-documents: " + help, help.contains("--sign-documents"));
}

@Test
public void testVariantParentShowsConnectionOptions() {
String help = getVariantParentHelp("create");
assertTrue("create parent should show --config: " + help, help.contains("--config"));
assertTrue("create parent should show --server: " + help, help.contains("--server"));
}

@Test
public void testHelpFlagOnVariantParent() {
CommandLine cli = createCli();
Expand Down Expand Up @@ -415,6 +453,16 @@ public void testConfigCredentialsHelpShowsOpenApiUrl() {
assertTrue("should show --v2 in command: " + help, help.contains("--v2"));
}

private String getVariantParentHelp(String command) {
CommandLine cli = createCli();
StringWriter out = new StringWriter();
cli.setOut(new PrintWriter(out));
cli.setErr(new PrintWriter(new StringWriter()));
int exitCode = cli.execute("client", command, "--help");
assertEquals("--help should exit with 0", 0, exitCode);
return out.toString();
}

private String getVariantHelp(String command, String variant) {
CommandLine cli = createCli();
return cli.getSubcommands().get("client").getSubcommands().get(command)
Expand Down
Loading
Loading
0