diff --git a/README.md b/README.md index 05e47fc..fcb9de6 100644 --- a/README.md +++ b/README.md @@ -312,7 +312,17 @@ All commands support `--help`. ## Global Flags -Every tree takes the same flags; only the defaults differ. Marks are plain ASCII without +Every tree takes the same flags; only the defaults differ. With `--json` (or `-o json`, `-o yaml`) +a command prints one document on stdout and nothing else. When a command cannot do what it was +asked, the error is on stderr and stdout is empty. Exit `1` does not always mean that, though: +`doctor`, `status` and `config validate` answer a question, and `start` and `restart` report on a +container they did create, so each still prints its document when the answer is "no" (a failed +check, an instance that is down, a file with errors, a start that never became ready). `wait` +prints nothing when it times out. Read the exit code first, then the document. + +Two commands print text whatever the format, because their output is not a document: `logs` (the +container's own output) and `completion` (a script). `env` prints shell +code in text mode and the variables as a map in JSON or YAML. Marks are plain ASCII without `--no-emoji` too whenever the output is not a terminal (a pipe, a file, CI logs) or `NO_COLOR` is set. `--json` wins when it is combined with `--output`. @@ -748,6 +758,7 @@ floci config profile list # list saved profiles: container, por floci config profile create # create a new profile with the tree's defaults floci config profile create --container --port

--persist

--services --image --namespace floci config profile show # show a profile +floci config profile show --json # the same keys as one row of `config profile list --json` floci config profile edit # open the profile in $VISUAL or $EDITOR, then check it still reads floci config profile delete # delete a profile floci config validate -f docker-compose.yml # validate a Compose file diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java index 57c6a66..1ab40b8 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -3,11 +3,14 @@ package io.floci.cli.commands.config; import io.floci.cli.GlobalOptions; import io.floci.cli.config.GlobalConfigStore; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import io.floci.cli.util.Causes; import picocli.CommandLine.*; import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; @Command( @@ -20,6 +23,17 @@ public class ConfigDefaultProductCommand implements Callable { @Mixin GlobalOptions global; + private final GlobalConfigStore store; + + public ConfigDefaultProductCommand() { + this(new GlobalConfigStore()); + } + + /** Test seam: a store pointed at a temporary config file. */ + public ConfigDefaultProductCommand(GlobalConfigStore store) { + this.store = store; + } + @Parameters(index = "0", description = "Product to use by default: aws, az, gcp, oci", paramLabel = "aws|az|gcp|oci") String product; @@ -30,9 +44,15 @@ public class ConfigDefaultProductCommand implements Callable { printer.error("Unknown product '" + product + "'.\nUse one of: aws, az, gcp, oci."); return ExitCode.USAGE; // a value the command cannot accept, like any other bad argument } - GlobalConfigStore store = new GlobalConfigStore(); try { store.setDefaultProduct(product); + if (printer.format() != OutputFormat.text) { + Map result = new LinkedHashMap<>(); + result.put("defaultProduct", product); + result.put("file", store.configFilePath().toString()); + printer.structured(result); + return 0; + } printer.println(Ansi.green("Default product set to: ") + Ansi.bold(product)); printer.println(Ansi.gray("'floci start' will now run: floci " + product + " start")); printer.println(Ansi.gray("Config saved to: " + store.configFilePath())); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index 31c8ccd..15ecf9a 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -120,16 +120,7 @@ public class ConfigProfileCommand implements Callable { if (printer.format() != OutputFormat.text) { List> out = new ArrayList<>(); for (Profile p : profiles) { - Map row = new LinkedHashMap<>(); - row.put("name", p.name); - row.put("container", p.container); - row.put("port", p.port); - row.put("endpoint", p.endpoint); - row.put("image", p.image); - row.put("persistDir", p.persistDir); - row.put("services", p.services); - row.put("namespace", p.namespace); - out.add(row); + out.add(row(p)); } printer.structured(out); return 0; @@ -156,6 +147,30 @@ public class ConfigProfileCommand implements Callable { } } + // One profile as structured output: the same keys from list and show, null where unset. + private static Map row(Profile p) { + Map row = new LinkedHashMap<>(); + row.put("name", p.name); + row.put("container", p.container); + row.put("port", p.port); + row.put("endpoint", p.endpoint); + row.put("image", p.image); + row.put("persistDir", p.persistDir); + row.put("services", p.services); + row.put("namespace", p.namespace); + return row; + } + + // What create, edit and delete report in structured output: the profile, what was done to it + // and the file or files involved. + private static Map done(String name, String action, List files) { + Map result = new LinkedHashMap<>(); + result.put("name", name); + result.put("action", action); + result.put("files", files.stream().map(Path::toString).toList()); + return result; + } + private int showProfile(Printer printer, ProfileStore store) { if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { @@ -166,6 +181,10 @@ public class ConfigProfileCommand implements Callable { } Profile p = profile.get(); ProfileDefaultValueProvider.warnAboutUnknownKeys(store, name, p); + if (printer.format() != OutputFormat.text) { + printer.structured(row(p)); + return 0; + } printer.println(Ansi.bold("Profile: ") + p.name); if (p.endpoint != null) printer.println(" endpoint: " + p.endpoint); if (p.container != null) printer.println(" container: " + p.container); @@ -207,7 +226,7 @@ public class ConfigProfileCommand implements Callable { command.add(file.toString()); int exit; try { - exit = new ProcessBuilder(command).inheritIO().start().waitFor(); + exit = editorProcess(command, printer.format() != OutputFormat.text).start().waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); printer.error("Interrupted while " + editor.get(0) + " was open.\nRe-run '" + prefix + "edit " + name + "'."); @@ -236,10 +255,32 @@ public class ConfigProfileCommand implements Callable { + "Re-run '" + prefix + "edit " + name + "' to fix it."); return 1; } + if (printer.format() != OutputFormat.text) { + printer.structured(done(name, "edited", List.of(file))); + return 0; + } printer.println("Profile '" + name + "' saved " + Ansi.gray("(" + file + ")")); return 0; } + /** + * How the editor is started. It shares this command's terminal, so an interactive editor + * works. With structured output its stdout goes to stderr instead: stdout carries the one + * result document, and anything an editor or its wrapper prints there would break it. + */ + public static ProcessBuilder editorProcess(List command, boolean structured) { + ProcessBuilder editor = new ProcessBuilder(command).inheritIO(); + if (structured) { + // /dev/stderr is this process's own stderr, still the terminal when only stdout is + // captured. Where there is no such file (Windows), the editor's output is dropped. + Path stderr = Path.of("/dev/stderr"); + editor.redirectOutput(Files.isWritable(stderr) + ? ProcessBuilder.Redirect.appendTo(stderr.toFile()) + : ProcessBuilder.Redirect.DISCARD); + } + return editor; + } + /** * The editor to run, as a command and its arguments: {@code VISUAL} first, then * {@code EDITOR}, as other tools do. Empty when neither is set. @@ -325,6 +366,10 @@ public class ConfigProfileCommand implements Callable { printer.warn(warning); } store.save(p); + if (printer.format() != OutputFormat.text) { + printer.structured(done(name, "created", List.of(store.profileFile(name)))); + return 0; + } printer.println(Ansi.green("Created") + " profile '" + name + "' at " + store.profileFile(name)); printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name)); return 0; @@ -398,6 +443,10 @@ public class ConfigProfileCommand implements Callable { String files = removed.size() > 1 ? " (" + removed.get(0).getFileName() + " and " + removed.get(1).getFileName() + ")" : ""; + if (printer.format() != OutputFormat.text) { + printer.structured(done(name, "deleted", removed)); + return 0; + } printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files); return 0; } catch (IOException e) { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java index 30ac1a0..b54a4e3 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java @@ -6,9 +6,12 @@ import io.floci.cli.docker.DockerClient; import io.floci.cli.http.FlociException; import io.floci.cli.http.FlociHttpClient; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; @Command( @@ -49,6 +52,14 @@ public class SnapshotDeleteCommand implements Callable { FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile); try { client.deleteSnapshot(name); + if (printer.format() != OutputFormat.text) { + Map result = new LinkedHashMap<>(); + result.put("snapshot", name); + result.put("action", "deleted"); + result.put("endpoint", effectiveEndpoint); + printer.structured(result); + return 0; + } printer.println(Ansi.green("Snapshot deleted:") + " " + name); return 0; } catch (FlociException e) { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java index ab06b91..22bfca3 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java @@ -6,9 +6,12 @@ import io.floci.cli.docker.DockerClient; import io.floci.cli.http.FlociException; import io.floci.cli.http.FlociHttpClient; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; @Command( @@ -49,6 +52,14 @@ public class SnapshotLoadCommand implements Callable { FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile); try { client.loadSnapshot(name); + if (printer.format() != OutputFormat.text) { + Map result = new LinkedHashMap<>(); + result.put("snapshot", name); + result.put("action", "loaded"); + result.put("endpoint", effectiveEndpoint); + printer.structured(result); + return 0; + } printer.println(Ansi.green("Snapshot loaded:") + " " + name); return 0; } catch (FlociException e) { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java index e55812a..5a41a94 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java @@ -6,9 +6,12 @@ import io.floci.cli.docker.DockerClient; import io.floci.cli.http.FlociException; import io.floci.cli.http.FlociHttpClient; import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.concurrent.Callable; @Command( @@ -56,6 +59,14 @@ public class SnapshotSaveCommand implements Callable { } try { client.postSnapshot(name); + if (printer.format() != OutputFormat.text) { + Map result = new LinkedHashMap<>(); + result.put("snapshot", name); + result.put("action", "saved"); + result.put("endpoint", effectiveEndpoint); + printer.structured(result); + return 0; + } printer.println(Ansi.green("Snapshot saved:") + " " + name); return 0; } catch (FlociException e) { diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index a801900..94a0a1d 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -1,10 +1,14 @@ package io.floci.cli.unit; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.cli.FlociCli; import io.floci.cli.ProductProfile; +import io.floci.cli.commands.config.ConfigDefaultProductCommand; import io.floci.cli.commands.config.ConfigProfileCommand; import io.floci.cli.commands.config.ConfigShowCommand; +import io.floci.cli.config.GlobalConfigStore; import io.floci.cli.config.Profile; import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileStore; @@ -402,6 +406,100 @@ class ConfigCommandsTest { assertEquals(partial, jsonKeys(runShow(ProductProfile.AWS, "--profile", "partial", "-o", "json"))); } + // ---- BL-091: --json and -o json reach the profile commands ------------------------------------- + + private static final ObjectMapper STRICT_JSON = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + @Test + void showPrintsTheProfileAsOneJsonDocument() throws Exception { + writeProfile("dev", "container: floci-dev\nport: 14566\nservices: s3,sqs\n"); + + Run r = profileCmd(ProductProfile.AWS, "show", "dev", "--json"); + + assertEquals(0, r.exit(), r.err()); + JsonNode json = STRICT_JSON.readTree(r.out()); + assertEquals("dev", json.path("name").asText()); + assertEquals("floci-dev", json.path("container").asText()); + assertEquals(14566, json.path("port").asInt()); + assertEquals("s3,sqs", json.path("services").asText()); + assertTrue(json.path("image").isNull(), "an unset field is null, as in list: " + r.out()); + assertFalse(r.out().contains("Profile:"), r.out()); + } + + /** show and list describe a profile with the same keys. */ + @Test + void showAndListAgreeOnTheShape() throws Exception { + writeProfile("dev", "container: floci-dev\nport: 14566\n"); + + JsonNode shown = STRICT_JSON.readTree(profileCmd(ProductProfile.AWS, "show", "dev", "-o", "json").out()); + JsonNode listed = STRICT_JSON.readTree(profileCmd(ProductProfile.AWS, "list", "-o", "json").out()); + + assertEquals(1, listed.size()); + assertEquals(listed.get(0), shown); + } + + @Test + void createAndDeleteReportWhatTheyDid() throws Exception { + Run created = profileCmd(ProductProfile.GCP, "create", "ci", "--port", "14588", "--json"); + + assertEquals(0, created.exit(), created.err()); + JsonNode create = STRICT_JSON.readTree(created.out()); + assertEquals("ci", create.path("name").asText()); + assertEquals("created", create.path("action").asText()); + assertEquals(store().profileFile("ci").toString(), create.path("files").get(0).asText()); + assertEquals(14588, store().get("ci").orElseThrow().port); + + Run deleted = profileCmd(ProductProfile.GCP, "delete", "ci", "-o", "json"); + + assertEquals(0, deleted.exit(), deleted.err()); + JsonNode delete = STRICT_JSON.readTree(deleted.out()); + assertEquals("deleted", delete.path("action").asText()); + assertEquals(1, delete.path("files").size()); + assertTrue(store().get("ci").isEmpty()); + } + + @Test + void yamlWorksToo() throws Exception { + writeProfile("dev", "port: 14566\n"); + + Run r = profileCmd(ProductProfile.AWS, "show", "dev", "-o", "yaml"); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("name: \"dev\""), r.out()); + assertTrue(r.out().contains("port: 14566"), r.out()); + } + + /** A failure still goes to stderr and leaves stdout empty, so a script never parses half a result. */ + @Test + void aFailedShowLeavesStdoutEmptyInJson() { + Run r = profileCmd(ProductProfile.AWS, "show", "nope", "--json"); + + assertEquals(1, r.exit()); + assertEquals("", r.out()); + assertTrue(r.err().contains("Profile 'nope' not found."), r.err()); + } + + @Test + void defaultProductReportsWhatItSaved() throws Exception { + Path config = tempDir.resolve("config.yaml"); + ConfigDefaultProductCommand command = new ConfigDefaultProductCommand(new GlobalConfigStore(config)); + PrintStream out = System.out; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + int exit; + try { + exit = new CommandLine(command).execute("oci", "--json"); + } finally { + System.setOut(out); + } + + assertEquals(0, exit); + JsonNode json = STRICT_JSON.readTree(outBuf.toString()); + assertEquals("oci", json.path("defaultProduct").asText()); + assertEquals(config.toString(), json.path("file").asText()); + assertEquals("oci", new GlobalConfigStore(config).getDefaultProduct()); + } + /** * BL-096: a profile that does not parse is reported in one line of cause, followed by the next * step. The parser's "at [Source: ...]" line used to stand in for it. diff --git a/src/test/java/io/floci/cli/unit/ErgonomicsTest.java b/src/test/java/io/floci/cli/unit/ErgonomicsTest.java index 66b4da7..db3f789 100644 --- a/src/test/java/io/floci/cli/unit/ErgonomicsTest.java +++ b/src/test/java/io/floci/cli/unit/ErgonomicsTest.java @@ -161,6 +161,57 @@ class ErgonomicsTest { assertTrue(r.out().contains("Profile 'dev' saved"), r.out()); } + @Test + @DisabledOnOs(OS.WINDOWS) + void editReportsItselfAsJsonWhenAsked() throws Exception { + store().save(new Profile(ProductProfile.AWS, "dev")); + Path editor = editorThat("echo 'port: 14566' >> \"$1\""); + ConfigProfileCommand command = new ConfigProfileCommand(ProductProfile.AWS, store(), Map.of("EDITOR", editor.toString())::get); + + Run r = capture(() -> new CommandLine(command).execute("edit", "dev", "--json")); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().strip().startsWith("{") && r.out().strip().endsWith("}"), r.out()); + assertTrue(r.out().contains("\"action\" : \"edited\""), r.out()); + assertFalse(r.out().contains("saved ("), r.out()); + } + + /** + * With structured output the editor's stdout must not be this command's stdout, or whatever + * the editor prints lands in front of the result. A real child process shows it: its stdout is + * captured in a file here, as a shell redirect would. + */ + @Test + @DisabledOnOs(OS.WINDOWS) + void anEditorsOutputStaysOffStdoutInStructuredMode() throws Exception { + Path noisy = editorThat("echo 'Waiting for your editor to close the file...'"); + Path captured = tempDir.resolve("stdout.txt"); + Path errors = tempDir.resolve("stderr.txt"); + + ProcessBuilder structured = ConfigProfileCommand.editorProcess(List.of(noisy.toString(), "file"), true); + assertNotEquals(ProcessBuilder.Redirect.INHERIT, structured.redirectOutput()); + assertEquals(ProcessBuilder.Redirect.INHERIT, structured.redirectInput(), "the editor still reads the terminal"); + + // The same decision, observed from outside: a shell runs the editor the way the command + // would, with fd 1 and fd 2 captured separately. + String redirect = structured.redirectOutput().file() == null ? "/dev/null" : structured.redirectOutput().file().toString(); + Process shell = new ProcessBuilder("sh", "-c", "'" + noisy + "' file >> " + redirect) + .redirectOutput(captured.toFile()).redirectError(errors.toFile()).start(); + assertEquals(0, shell.waitFor()); + + assertEquals("", Files.readString(captured), "nothing from the editor on stdout"); + assertTrue(Files.readString(errors).contains("Waiting for your editor"), "it went to stderr instead"); + } + + @Test + void inTextModeTheEditorSharesTheTerminal() { + ProcessBuilder text = ConfigProfileCommand.editorProcess(List.of("vi", "file"), false); + + assertEquals(ProcessBuilder.Redirect.INHERIT, text.redirectOutput()); + assertEquals(ProcessBuilder.Redirect.INHERIT, text.redirectInput()); + assertEquals(ProcessBuilder.Redirect.INHERIT, text.redirectError()); + } + /** VISUAL wins over EDITOR, and a value with arguments is a command line. */ @Test @DisabledOnOs(OS.WINDOWS) diff --git a/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java b/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java index e8190c0..1065cef 100644 --- a/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java @@ -1,5 +1,8 @@ package io.floci.cli.unit; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.net.httpserver.HttpServer; import io.floci.cli.FlociCli; import io.floci.cli.config.ProfileStore; @@ -115,4 +118,29 @@ class SnapshotCommandsTest { assertEquals("1", r[0]); assertTrue(r[2].contains("floci status --container floci-snapshot-test-none"), r[2]); } + + /** BL-091: with --json a snapshot action prints one document saying what it did and where. */ + @ParameterizedTest + @CsvSource({"save, saved", "load, loaded", "delete, deleted"}) + void aSnapshotActionReportsItselfAsJson(String command, String action) throws Exception { + status = 200; + + String[] r = run("snapshot", command, "nightly", "--json"); + + assertEquals("0", r[0], r[2]); + JsonNode json = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(r[1]); + assertEquals("nightly", json.path("snapshot").asText()); + assertEquals(action, json.path("action").asText()); + assertEquals("http://127.0.0.1:" + server.getAddress().getPort(), json.path("endpoint").asText()); + } + + @Test + void aSnapshotActionInTextIsUnchanged() { + status = 200; + + String[] r = run("snapshot", "save", "nightly"); + + assertEquals("0", r[0], r[2]); + assertTrue(r[1].contains("Snapshot saved: nightly"), r[1]); + } }