diff --git a/README.md b/README.md index 8ae4af0..4161779 100644 --- a/README.md +++ b/README.md @@ -921,9 +921,10 @@ the same three codes: | `1` | It ran and failed, or the answer to the question it asks is "no". | | `2` | The command line could not be used: an unknown flag or command, a missing argument, a value picocli cannot convert (`--port abc`), or a `--profile` that does not exist or cannot be read. | -A value the command line accepts but the command then rejects is reported by that command. Most -use `2` for it, as the table below shows; three use `1`: `config default-product `, -`update --version ` and `config profile create --port `. +A value the command line accepts but the command then rejects is exit `2` as well, in every +command: an out-of-range `--port`, an unknown `--pull` policy, a `--persist` path that cannot be +used, a `--version` that is not a release version, an unknown product or action, a missing or +invalid name. Exit `1` always means the command ran. Where a command's codes carry a specific meaning a script can rely on: @@ -933,16 +934,16 @@ Where a command's codes carry a specific meaning a script can rely on: | `wait` | ready before `--timeout` | timed out | `--timeout` is not a positive duration | | `doctor` | every check passed (warnings allowed) | at least one check failed | `--check` names no known check | | `update --check` | up to date | an update is available | the check itself failed | -| `update` | updated, or already up to date | the update failed, or `--version` is not a release version; the binary is unchanged | bad flag | -| `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed | `--port`, `--pull` or the namespace is not valid | +| `update` | updated, or already up to date | the update failed; the binary is unchanged | `--version` is not a release version | +| `start`, `restart` | started (and ready, unless `--detach`) | Docker, the image, the port or readiness failed, or the `--persist` directory cannot be created | `--port`, `--pull`, the namespace or the `--persist` path is not valid | | `stop` | stopped, or was not running | no such container, or Docker failed | bad flag or profile | | `reset` | state reset | declined, not available on this server, or no running instance to reset | no terminal to ask on and no `--yes` | | `config validate` | no errors (warnings allowed) | errors found, or the file cannot be read | bad flag | -| `config profile ...` | done | not found, already exists, cannot be read, `--port` is out of range, or (for `edit`) no editor is set, the editor failed or the file no longer parses | the profile name is not valid | -| `config default-product` | saved | not `aws`, `gcp`, `az` or `oci`, or the file cannot be written | bad flag | +| `config profile ...` | done | not found, already exists, cannot be read, or (for `edit`) no editor is set, the editor failed or the file no longer parses | unknown action, missing or invalid profile name, `--port` out of range | +| `config default-product` | saved | the file cannot be written | not `aws`, `gcp`, `az` or `oci` | | `env` | variables printed | | `--shell` is not supported | | `completion` | script printed | | the shell is not `bash` or `zsh` | -| `snapshot ...` | done | failed, or the server has no snapshot API yet | bad flag or profile | +| `snapshot ...` | done | failed, or the server has no snapshot API yet | invalid snapshot name | `docs/help/` holds the `--help` text of every command, generated from the code. A test fails when the files and the commands drift apart; regenerate them with diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index a3754e9..e7725b5 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -74,6 +74,11 @@ public class RestartCommand implements Callable { printer.error(invalid); return 2; } + String rejected = start.persistPathError(); + if (rejected != null) { + printer.error(rejected); + return ExitCode.USAGE; + } String unwritable = start.preparePersistDir(); if (unwritable != null) { printer.error(unwritable); diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index ce907ab..8b70388 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -187,8 +187,13 @@ public class StartCommand implements Callable { return preparePersistDir(docker.daemonHost()); } - /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ - public String preparePersistDir(DockerClient.DockerHost daemon) { + /** + * Why the {@code --persist} value cannot be used at all, or {@code null}. This is about the + * value, not about the file system: a path this machine cannot parse, or a relative one for + * a remote daemon. Callers report it as a usage error (exit 2); a directory that is fine as a + * value but cannot be created is {@link #preparePersistDir}'s to report (exit 1). + */ + public String persistPathError(DockerClient.DockerHost daemon) { if (persistDir == null || persistDir.isBlank()) return null; // A remote daemon reads the bind source on its own machine, where this CLI can neither // create nor check it; it is passed on untouched (bindSource), so nothing here can fail @@ -199,14 +204,29 @@ public class StartCommand implements Callable { : "With a remote Docker daemon, --persist must be an absolute path on the daemon's machine, but was '" + persistDir + "'.\nPass an absolute path, for example /srv/floci-data."; } - Path path; try { - path = Path.of(persistPath()); + Path.of(persistPath()); + return null; } catch (InvalidPathException e) { // Names persistDir as given: resolving it is what failed. return "Invalid persist directory '" + persistDir + "': " + e.getReason() + ".\nPass a --persist path that is valid on this system."; } + } + + /** {@link #persistPathError(DockerClient.DockerHost)} for the daemon docker resolved. */ + public String persistPathError() { + return persistPathError(docker.daemonHost()); + } + + /** {@link #preparePersistDir()} for a daemon reached through {@code daemon}; the test seam. */ + public String preparePersistDir(DockerClient.DockerHost daemon) { + if (persistDir == null || persistDir.isBlank()) return null; + String rejected = persistPathError(daemon); + if (rejected != null) return rejected; + // A remote daemon creates the directory on its own machine. + if (daemon.kind() == DockerClient.Kind.TCP) return null; + Path path = Path.of(persistPath()); try { Files.createDirectories(path); return null; @@ -314,6 +334,11 @@ public class StartCommand implements Callable { // whether the daemon docker will talk to is on this machine. DockerClient.DockerHost daemon = docker.daemonHost(); + String rejected = persistPathError(daemon); + if (rejected != null) { + printer.error(rejected); + return ExitCode.USAGE; + } String unwritable = preparePersistDir(daemon); if (unwritable != null) { printer.error(unwritable); diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index 5bf0e73..c9c2af4 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -101,8 +101,10 @@ public class UpdateCommand implements Callable { String current = CliVersion.CLI_VERSION; boolean pinned = to != null && !to.isBlank(); if (pinned && !Version.isValid(to.trim())) { - // It goes into the download URL; refuse anything that is not a release version. - throw new UpdateException("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + // It goes into the download URL; refuse anything that is not a release version. A + // value the command cannot accept, so the exit code of any other bad argument. + printer.error("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + return ExitCode.USAGE; } String target = pinned ? to.trim() : fetchLatestVersion(); diff --git a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java index c40c3f8..e3b8c1a 100644 --- a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java @@ -120,8 +120,9 @@ public class AzSetupCommand implements Callable { try { flociAzDir = InstanceState.dir(stateRoot, ProductProfile.AZ, cloud); } catch (IllegalArgumentException e) { + // A container name that cannot be used: the same exit code as any other bad argument. printer.error(e.getMessage()); - return 1; + return ExitCode.USAGE; } try { return reset ? reset(printer, flociAzDir, cloud) : setup(printer, flociAzDir, cloud); 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 28343d8..a9f5b2f 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -27,7 +27,7 @@ public class ConfigDefaultProductCommand implements Callable { Printer printer = global.printer(); if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product) && !"oci".equals(product)) { printer.error("Unknown product '" + product + "'.\nUse one of: aws, az, gcp, oci."); - return 1; + return ExitCode.USAGE; // a value the command cannot accept, like any other bad argument } GlobalConfigStore store = new GlobalConfigStore(); try { 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 dd8f1ea..d27bc1f 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -99,7 +99,7 @@ public class ConfigProfileCommand implements Callable { case "delete" -> deleteProfile(printer, store); default -> { printer.error("Unknown action '" + action + "'.\nUse one of: list, show, create, edit, delete."); - yield 1; + yield ExitCode.USAGE; } }; } catch (IllegalArgumentException e) { @@ -156,7 +156,7 @@ public class ConfigProfileCommand implements Callable { } private int showProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { var profile = store.get(name); if (profile.isEmpty()) { @@ -186,7 +186,7 @@ public class ConfigProfileCommand implements Callable { * not created here, since {@code create} is what writes the product's defaults into it. */ private int editProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } String prefix = this.profile.commandPrefix() + " config profile "; // Asked of the file, not of its contents: a profile that no longer parses is exactly the // one that has to be opened to be repaired. @@ -299,7 +299,7 @@ public class ConfigProfileCommand implements Callable { } private int createProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { if (store.get(name).isPresent()) { printer.error("Profile '" + name + "' already exists.\nDelete it first, or edit " + store.existingFile(name) + "."); @@ -308,7 +308,7 @@ public class ConfigProfileCommand implements Callable { if (port != null && (port < 1 || port > 65535)) { printer.error("--port must be between 1 and 65535, but was " + port + ".\n" + "Pick a free port, for example " + (profile.defaultPort() + 10000) + "."); - return 1; + return ExitCode.USAGE; } Profile p = new Profile(profile, name); // Only flags the user typed: the mixin's own values may come from FLOCI_* env vars, and @@ -388,7 +388,7 @@ public class ConfigProfileCommand implements Callable { } private int deleteProfile(Printer printer, ProfileStore store) { - if (name == null) { printer.error(nameRequired()); return 1; } + if (name == null) { printer.error(nameRequired()); return ExitCode.USAGE; } try { List removed = store.delete(name); if (removed.isEmpty()) { 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 51def60..30ac1a0 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java @@ -38,6 +38,11 @@ public class SnapshotDeleteCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); 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 93c8547..ab06b91 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java @@ -38,6 +38,11 @@ public class SnapshotLoadCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); 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 4b19c40..e55812a 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java @@ -41,6 +41,11 @@ public class SnapshotSaveCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); + String invalidName = FlociHttpClient.snapshotNameError(name); + if (invalidName != null) { + printer.error(invalidName); + return ExitCode.USAGE; + } // Resolve the endpoint from the container's port mapping, like status/services/wait do, // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index 1f3e2cb..73dd484 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -313,12 +313,22 @@ public class FlociHttpClient { } } + /** + * Why {@code name} cannot be a snapshot name, or {@code null}. Commands ask before they send + * anything, so a bad name is a usage error rather than a failed request. + */ + public static String snapshotNameError(String name) { + if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) { + return "Invalid snapshot name '" + name + "'.\n" + + "Use a name that is not '.' or '..' and has no '/'."; + } + return null; + } + /** A snapshot name as one URL path segment; names that could change the path are refused. */ static String snapshotSegment(String name) throws FlociException { - if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) { - throw new FlociException("Invalid snapshot name '" + name + "'.\n" - + "Use a name that is not '.' or '..' and has no '/'."); - } + String invalid = snapshotNameError(name); + if (invalid != null) throw new FlociException(invalid); return URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20"); } } diff --git a/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java index 1107b8b..f96986c 100644 --- a/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java +++ b/src/test/java/io/floci/cli/unit/AzSetupCommandTest.java @@ -339,7 +339,7 @@ class AzSetupCommandTest { @Test void aContainerNameThatWouldEscapeIsRefused() { - assertEquals(1, run("--container", "../x")); + assertEquals(2, run("--container", "../x"), "a rejected value is a usage error"); assertTrue(az.calls.isEmpty()); } diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index a9591df..210cccf 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -207,7 +207,7 @@ class ConfigCommandsTest { void createRefusesAPortOutOfRange() throws Exception { Run r = profileCmd(ProductProfile.AZ, "create", "bad", "--port", "70000"); - assertEquals(1, r.exit()); + assertEquals(2, r.exit(), "a rejected value is a usage error"); assertTrue(store().get("bad").isEmpty()); } diff --git a/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java b/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java index 8fd74a6..4d0c9d4 100644 --- a/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java +++ b/src/test/java/io/floci/cli/unit/ExitCodeTableTest.java @@ -39,9 +39,23 @@ class ExitCodeTableTest { "2, completion fish", "2, status --json --no-such-flag", "2, config profile show ../escape", - // Accepted by the command line, rejected by the command with 1. - "1, update --version not-a-version", - "1, config profile create demo --port 0", + // Accepted by the command line, rejected by the command: the same code. + "2, update --version not-a-version", + "2, update --check --version not-a-version", + "2, config profile create demo --port 0", + "2, config profile create demo --port 70000", + "2, config profile bogus", + "2, config profile show", + "2, config profile create", + "2, config profile edit", + "2, config profile delete", + "2, config default-product nope", + "2, snapshot save a/b", + "2, snapshot load ..", + "2, snapshot delete a/b", + "2, gcp snapshot save a/b", + "2, az setup --container ../escape", + // It ran and the answer is no. "1, config profile show no-such-profile", "1, config profile edit no-such-profile", "1, config validate -f no-such-compose-file.yml", diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 0e8fd82..90f16f5 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -171,7 +171,7 @@ class StartPreflightTest { FakeDocker refused = new FakeDocker(REMOTE); Out relative = start(refused, "--persist", "data", "--container", "floci-gcp-preflight", "--detach"); - assertEquals(1, relative.exit()); + assertEquals(2, relative.exit(), "a rejected value is a usage error"); assertTrue(relative.err().contains("must be an absolute path on the daemon's machine"), relative.err()); assertEquals(List.of(), refused.calls); }