From 94fdf7762c975cb330abf3aec36b8196ff5e8ad0 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 4 Nov 2026 01:00:26 -0600 Subject: [PATCH 1/4] docs(skill): wire Python Secret Manager to the emulator explicitly (#71) The Python client ignores SECRET_MANAGER_EMULATOR_HOST and still targets secretmanager.googleapis.com, so the skill's claim that client libraries skip credentials when these variables are set was wrong for it. Add a recipe with the REST transport, an explicit endpoint and anonymous credentials, and link it from the README and the Docker reference. Signed-off-by: Hector Ventura --- README.md | 4 ++++ plugin.json | 2 +- skills/floci/assets/compose/gcp.yml | 4 +++- skills/floci/references/docker.md | 4 +++- skills/floci/references/gcp.md | 25 ++++++++++++++++++++++++- 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index be64838..38335a4 100644 --- a/README.md +++ b/README.md @@ -549,6 +549,10 @@ Variables exported (per enabled service): | `SECRET_MANAGER_EMULATOR_HOST` | Secret Manager | | `IAM_EMULATOR_HOST` | IAM | +SDK support for these variables varies by service and language. Python Secret Manager ignores +`SECRET_MANAGER_EMULATOR_HOST`; set an explicit emulator endpoint and anonymous credentials. +See the [Python Secret Manager recipe](skills/floci/references/gcp.md#python-secret-manager). + ### `floci az env` Prints Azure connection variables for the running Floci Azure instance. diff --git a/plugin.json b/plugin.json index 3df93ea..01636cc 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "floci", - "version": "1.0.0", + "version": "1.0.1", "description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.", "author": { "name": "Floci", diff --git a/skills/floci/assets/compose/gcp.yml b/skills/floci/assets/compose/gcp.yml index 886d641..a3a280e 100644 --- a/skills/floci/assets/compose/gcp.yml +++ b/skills/floci/assets/compose/gcp.yml @@ -35,11 +35,13 @@ services: app: build: . environment: - # Client libraries skip credentials when these are set. Storage needs the scheme. + # SDK support varies by service. Storage needs the scheme. STORAGE_EMULATOR_HOST: http://floci-gcp:4588 PUBSUB_EMULATOR_HOST: floci-gcp:4588 FIRESTORE_EMULATOR_HOST: floci-gcp:4588 DATASTORE_EMULATOR_HOST: floci-gcp:4588 + # Python Secret Manager needs explicit endpoint + anonymous credentials; see gcp.md. + # This variable alone does not configure that SDK. SECRET_MANAGER_EMULATOR_HOST: floci-gcp:4588 GOOGLE_CLOUD_PROJECT: floci-local depends_on: diff --git a/skills/floci/references/docker.md b/skills/floci/references/docker.md index 3ee829f..1cb17c8 100644 --- a/skills/floci/references/docker.md +++ b/skills/floci/references/docker.md @@ -143,7 +143,9 @@ Ask before running `docker compose down -v`: `-v` deletes the data volume. Plain - **GCP**: `STORAGE_EMULATOR_HOST=http://floci-gcp:4588` (with scheme) and `PUBSUB_EMULATOR_HOST`, `FIRESTORE_EMULATOR_HOST`, `DATASTORE_EMULATOR_HOST`, `SECRET_MANAGER_EMULATOR_HOST` set to `floci-gcp:4588` (no scheme). Set both - `FLOCI_GCP_HOSTNAME` and `FLOCI_GCP_BASE_URL` on the emulator. + `FLOCI_GCP_HOSTNAME` and `FLOCI_GCP_BASE_URL` on the emulator. SDK support varies: + Python Secret Manager ignores its emulator variable; use the explicit REST endpoint + `http://floci-gcp:4588` with anonymous credentials (see [gcp.md](gcp.md)). - **Azure**: a connection string with the service name in each endpoint (see `azure.yml`). The control plane (`az`, ARM, Terraform) needs TLS on and the CA trusted: from the host run `floci az setup --container `; inside another container, read diff --git a/skills/floci/references/gcp.md b/skills/floci/references/gcp.md index 85f01ca..8c3d6ec 100644 --- a/skills/floci/references/gcp.md +++ b/skills/floci/references/gcp.md @@ -19,7 +19,9 @@ silently, so check the output): | `SECRET_MANAGER_EMULATOR_HOST` | Secret Manager | | `IAM_EMULATOR_HOST` | IAM | -Client libraries skip credentials when these are set. +Emulator-variable support depends on the service and SDK. Do not assume an exported +variable redirects a client or disables credential lookup. Python Secret Manager ignores +`SECRET_MANAGER_EMULATOR_HOST`: configure its endpoint and credentials explicitly, as below. Pass `project="floci-local"` (or any id) explicitly to clients. Firebase Auth uses `FIREBASE_AUTH_EMULATOR_HOST=localhost:4588`, which `floci gcp env` does not export: set it yourself when the app uses the Firebase Admin SDK. @@ -29,6 +31,27 @@ etc.) need the endpoint set on the client: `http://localhost:4588` for REST, `lo plaintext for gRPC, with no credentials (`NoCredentialsProvider` in Java, `AnonymousCredentials` in Python, `ClientOptions(api_endpoint=...)`). +### Python Secret Manager + +Use the REST transport with an explicit endpoint and anonymous credentials. On the host, +use `http://localhost:4588`; from the Compose app service use `http://floci-gcp:4588`. +Setting `SECRET_MANAGER_EMULATOR_HOST` alone does not configure this client. + +```python +from google.auth.credentials import AnonymousCredentials +from google.cloud import secretmanager_v1 + +client = secretmanager_v1.SecretManagerServiceClient( + transport="rest", + credentials=AnonymousCredentials(), + client_options={"api_endpoint": "http://localhost:4588"}, +) +``` + +Before making requests, check `client.transport._host` in a local test. It must be your +emulator endpoint. For gRPC, provide an explicit plaintext channel instead of the default +TLS channel. See the [Python client source](https://github.com/googleapis/google-cloud-python/blob/main/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py). + ## Wiring for gcloud (important) **gcloud does not honor `*_EMULATOR_HOST`.** Without the overrides below, `gcloud` commands go From 763bb2d854a8012f1486b6eac588dc9f62f81e29 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 4 Nov 2026 01:00:30 -0600 Subject: [PATCH 2/4] ci: expand native smoke coverage for CLI commands and output (#72) Run completion, Compose validation with YAML anchors and merge keys, profile editing, JSON and YAML output, and the snapshot and reset input guards through the native binary. None of it needs an emulator or a Docker daemon. --no-emoji is only checked to parse, because piped output is already plain. Profile editing is skipped on Windows: it has not been proven there, and the script runs on Windows only while a release is being cut. Signed-off-by: Hector Ventura --- .github/scripts/smoke.sh | 87 +++++++++++++++++++++++++++++++++++++++- CONTRIBUTING.md | 5 +++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/.github/scripts/smoke.sh b/.github/scripts/smoke.sh index a827a99..8683ab2 100755 --- a/.github/scripts/smoke.sh +++ b/.github/scripts/smoke.sh @@ -11,6 +11,69 @@ expected="${2:-}" "$bin" version +work=$(mktemp -d) +profile="floci-smoke-$$" +cleanup() { + "$bin" config profile delete "$profile" > /dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT + +expect_exit() { + local expected_code="$1" + shift + local actual_code=0 + "$@" > "$work/out" 2> "$work/err" || actual_code=$? + if [ "$actual_code" -ne "$expected_code" ]; then + cat "$work/out" "$work/err" + echo "::error::command exited $actual_code, expected $expected_code: $*" + exit 1 + fi +} + +# A bare grep or test would stop the script under set -e with nothing in the CI log saying why. +require_output() { + local pattern="$1" file="$2" what="$3" + if ! grep -q "$pattern" "$file"; then + cat "$file" + echo "::error::$what: expected output matching '$pattern'" + exit 1 + fi +} + +# The shorthand and the plain-marks flag parse in the shipped binary. What --no-emoji does cannot +# be seen here: piped output is already plain. ErgonomicsTest covers that. +reported=$("$bin" version --json --no-emoji | tr -d ' \r\n') +case "$reported" in + *'"cli":'*) ;; + *) echo "::error::version --json did not return a version object: $reported"; exit 1 ;; +esac + +"$bin" completion bash > "$work/completion" +[ -s "$work/completion" ] || { echo "::error::completion bash printed nothing"; exit 1; } +expect_exit 2 "$bin" completion fish +require_output 'Use bash or zsh' "$work/err" "completion fish" + +# SnakeYAML aliases/merge keys must also work in a native image, not just the JVM. +cat > "$work/compose.yml" <<'YAML' +x-emulator: &emulator + image: floci/floci:latest + ports: ["14566:4566"] + volumes: ["/var/run/docker.sock:/var/run/docker.sock"] +services: + floci: + <<: *emulator +YAML +validated=$("$bin" aws config validate --file "$work/compose.yml" --json | tr -d ' \r\n') +case "$validated" in + *'"valid":true'*'"errors":[]'*) ;; + *) echo "::error::native Compose validation failed: $validated"; exit 1 ;; +esac + +# A rejected snapshot name and a declined reset must finish without contacting Docker/server. +expect_exit 2 "$bin" snapshot save bad/name +expect_exit 2 "$bin" reset --endpoint http://127.0.0.1:1 < /dev/null + if [ -n "$expected" ]; then reported=$("$bin" version -o json | tr -d ' \r\n') case "$reported" in @@ -25,8 +88,6 @@ done # A profile round trip: Jackson writes it and reads it back. Listing alone proves little on a # fresh runner, where there is nothing to read. The name is unique and the profile is deleted. -profile="floci-smoke-$$" -trap '"$bin" config profile delete "$profile" > /dev/null 2>&1 || true' EXIT "$bin" config profile create "$profile" --container floci-smoke --port 14566 > /dev/null shown=$("$bin" config show --profile "$profile" -o json | tr -d ' \r\n') case "$shown" in @@ -36,6 +97,28 @@ esac "$bin" config profile list -o json | grep -q "$profile" \ || { echo "::error::profile $profile is missing from 'config profile list'"; exit 1; } +# Edit through a real child process, then read its new value via Jackson in the binary. Not on +# Windows: launching 'sh' with a Git Bash path from a native exe has not been proven there, and +# this script runs on Windows only while a release is being cut, so a false failure would stop it. +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) echo "skipping profile edit on Windows" ;; + *) + cat > "$work/editor.sh" <<'SH' +printf 'container: floci-smoke\nport: 14566\nnamespace: smoke-native\n' > "$1" +SH + edited=$(VISUAL="sh \"$work/editor.sh\"" EDITOR="sh \"$work/editor.sh\"" \ + "$bin" config profile edit "$profile" --json | tr -d ' \r\n') + case "$edited" in + *'"action":"edited"'*) ;; + *) echo "::error::profile edit did not report success: $edited"; exit 1 ;; + esac + "$bin" config profile show "$profile" --json > "$work/profile.json" + require_output 'smoke-native' "$work/profile.json" "profile show after edit" + ;; +esac +"$bin" config show --profile "$profile" -o yaml > "$work/config.yaml" +require_output 'container: "\{0,1\}floci-smoke' "$work/config.yaml" "config show -o yaml" + # An unknown profile is a usage error: exit 2, not a crash. set +e "$bin" start --profile floci-smoke-no-such-profile > /dev/null 2>&1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3346f2d..ff71f35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,6 +38,11 @@ mvn package # fat JAR → target/floci.jar mvn package -Pnative -DskipTests # native binary → target/floci (requires GraalVM) ``` +The native CI and release jobs run `.github/scripts/smoke.sh ./target/floci`. It checks +completion, rejected input, JSON and YAML output, profile create/edit/read/delete, reset's +confirmation guard and Compose validation with YAML anchors and merge keys. It needs no +emulator or Docker daemon. It skips profile edit on Windows. Run it after building the native binary when changing these paths. + ### Try it against a real emulator ```bash From a319e2d242c7b9466bd8b47d18e0faab14c9b0e7 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 4 Nov 2026 01:05:50 -0600 Subject: [PATCH 3/4] fix(restart): show how to recover after startup fails (#73) When restart has removed the old container and the new one does not come up, it now prints a start command with the same port, image, persist dir, services and namespace. When the new container is running but did not become ready, it says to check logs and run wait instead, because start refuses a running container. The commands name their tree, because a bare floci follows the configured default product. They keep a typed --endpoint, and --persist prints the directory a local daemon would mount, so a retry from another directory finds the same state. Signed-off-by: Hector Ventura --- README.md | 6 + plugin.json | 2 +- skills/floci/SKILL.md | 4 +- src/main/java/io/floci/cli/GlobalOptions.java | 2 +- .../java/io/floci/cli/ProductProfile.java | 5 + .../io/floci/cli/commands/RestartCommand.java | 36 +++- .../io/floci/cli/commands/StartCommand.java | 37 +++- .../io/floci/cli/unit/ProductProfileTest.java | 4 + .../floci/cli/unit/RestartRecoveryTest.java | 173 ++++++++++++++++++ 9 files changed, 262 insertions(+), 7 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/RestartRecoveryTest.java diff --git a/README.md b/README.md index 38335a4..f11deb3 100644 --- a/README.md +++ b/README.md @@ -489,6 +489,12 @@ stdout: the progress lines are left out and docker's pull progress goes to stder `restart` report `container`, `id`, `image`, `endpoint`, `state` and `ready` (`ready` is absent with `--detach`). `logs` prints the container's own output and stays plain text. +If `restart` fails after removing the old container, stderr includes a `start` command with +the resolved container, port, image, endpoint, persistence, services and namespace settings. +It also appears with structured output. Review the failure, then run that command to retry. If +the new container is running but did not become ready, stderr instead says to check `logs` and +run `wait`, because `start` refuses a running container. + ### `floci status` / `floci gcp status` / `floci az status` / `floci oci status` ```sh diff --git a/plugin.json b/plugin.json index 01636cc..a0d9d0e 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "floci", - "version": "1.0.1", + "version": "1.0.2", "description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.", "author": { "name": "Floci", diff --git a/skills/floci/SKILL.md b/skills/floci/SKILL.md index 097373e..0490509 100644 --- a/skills/floci/SKILL.md +++ b/skills/floci/SKILL.md @@ -81,7 +81,9 @@ clouds the user works with; suggest installing them, do not install them unasked and create a new one: `restart` keeps the settings (port, image, services, persist dir, namespace) but not in-memory state, and on Azure the new container has a new certificate, so `floci az setup` must be run again. `start` on a running container fails. Say so before - recreating anything. + recreating anything. If restart fails after removal, follow stderr: a start command that + retries with the same settings, or `logs` and `wait` when the new container is up but not + ready. Neither restores in-memory state. 7. **Never add `-q` to `env`**: it suppresses the exports themselves. 8. **Do not guess what an emulator supports.** Check `floci services -o json` and the published docs ([references/docs.md](references/docs.md)) instead of answering from memory. diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index 50826a4..d1f45f4 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -125,7 +125,7 @@ public class GlobalOptions { } // POSIX single quotes: the hints are shell command lines like the CLI's other 'Run ...' hints. - private static String shellWord(String value) { + public static String shellWord(String value) { if (PLAIN_WORD.matcher(value).matches()) return value; return "'" + value.replace("'", "'\\''") + "'"; } diff --git a/src/main/java/io/floci/cli/ProductProfile.java b/src/main/java/io/floci/cli/ProductProfile.java index 9071412..bb18ceb 100644 --- a/src/main/java/io/floci/cli/ProductProfile.java +++ b/src/main/java/io/floci/cli/ProductProfile.java @@ -36,6 +36,11 @@ public record ProductProfile( return "aws".equals(name) ? "floci" : "floci " + name; } + /** Always names the tree: a bare {@code floci} goes to whatever default product is configured. */ + public String explicitCommandPrefix() { + return "floci " + name; + } + /** * The Docker resource namespace an instance in {@code container} gets when none is set: none * for the default container, so its child containers keep their names; otherwise the container diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index e7725b5..9d7550b 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -96,7 +96,14 @@ public class RestartCommand implements Callable { int stopResult = buildStopCommand().call(); if (stopResult != 0) return stopResult; - return start.call(); + // Capture before start mutates its endpoint while waiting. This command stands alone, + // even if the profile is edited or deleted after the failed restart. + String recovery = start.recoveryCommand(); + int result = start.call(); + if (result != 0) { + printer.error(recoveryMessage(recovery)); + } + return result; } /** @@ -125,7 +132,7 @@ public class RestartCommand implements Callable { public StartCommand buildStartCommand() throws DockerException { // The outer parse's provider: its memoized profile is the snapshot the globals below were // resolved from, so the start settings cannot come from a newer version of the file. - StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile); + StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile, docker); // The real invocation's globals win: they already carry the profile plus any flag the // user passed, resolved once by the outer parse. @@ -153,6 +160,31 @@ public class RestartCommand implements Callable { }); } + // A new container that is up but has not answered yet cannot be started again: start refuses a + // running container. So the retry command is only for a container that did not come up. + private String recoveryMessage(String recovery) { + boolean running; + try { + running = docker.inspectContainer(global.container) + .filter(info -> "running".equals(info.state())).isPresent(); + } catch (DockerException e) { + running = false; + } + if (running) { + String prefix = profile.explicitCommandPrefix(); + String selector = global.instanceSelector(); + // By now this is the endpoint start waited on, with the port it bound. + String wait = global.typed("--endpoint") && !selector.contains(" --endpoint ") + ? selector + " --endpoint " + GlobalOptions.shellWord(global.endpoint) + : selector; + return "The new container is running but did not become ready.\n" + + "Check it with '" + prefix + " logs" + selector + "', then run '" + + prefix + " wait" + wait + "' to wait again."; + } + return "Restart did not finish after the old container was removed.\n" + + "To retry with the same settings, run:\n" + recovery; + } + private boolean containerExists() { try { return docker.inspectContainer(global.container).isPresent(); diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index e9893e8..d529b89 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -99,7 +99,14 @@ public class StartCommand implements Callable { public static StartCommand resolvedFor(ProductProfile product, ProfileDefaultValueProvider provider, String profileName) { - StartCommand start = new StartCommand(product); + return resolvedFor(product, provider, profileName, new DockerClient()); + } + + /** Reuse the caller's Docker client when a restart starts the resolved instance. */ + public static StartCommand resolvedFor(ProductProfile product, + ProfileDefaultValueProvider provider, + String profileName, DockerClient docker) { + StartCommand start = new StartCommand(product, docker); if (profileName != null) { new CommandLine(start) .setCaseInsensitiveEnumValuesAllowed(true) @@ -109,6 +116,25 @@ public class StartCommand implements Callable { return start; } + /** A self-contained POSIX command that recovers the resolved settings after a failed restart. */ + public String recoveryCommand() { + StringBuilder command = new StringBuilder(profile.explicitCommandPrefix()).append(" start"); + command.append(" --container ").append(GlobalOptions.shellWord(global.container)); + command.append(" --port ").append(port); + command.append(" --image ").append(GlobalOptions.shellWord(image)); + // --port already moves the default endpoint, so only a different one is worth naming. + if (!profile.defaultEndpoint().equals(global.endpoint)) { + command.append(" --endpoint ").append(GlobalOptions.shellWord(global.endpoint)); + } + // Resolved, so the retry mounts the same directory from wherever it is run. + if (persistDir != null && !persistDir.isBlank()) { + command.append(" --persist ").append(GlobalOptions.shellWord(bindSource(docker.daemonHost()))); + } + if (services != null) command.append(" --services ").append(GlobalOptions.shellWord(services)); + if (namespace != null) command.append(" --namespace ").append(GlobalOptions.shellWord(namespace)); + return command.toString(); + } + /** What a profile-resolved instance would start with. Read by {@code config show}. */ public String image() { return image; } @@ -433,9 +459,16 @@ public class StartCommand implements Callable { return exit; } + private String readinessTimeout = "30s"; + /** How long start waits for the emulator to answer. A seam: tests do not wait half a minute. */ protected String readinessTimeout() { - return "30s"; + return readinessTimeout; + } + + /** Test seam for a start built by {@code restart}, which cannot be subclassed from outside. */ + public void readinessTimeout(String timeout) { + this.readinessTimeout = timeout; } // What -o json/yaml reports for a start: 'ready' is left out when --detach did not wait for it. diff --git a/src/test/java/io/floci/cli/unit/ProductProfileTest.java b/src/test/java/io/floci/cli/unit/ProductProfileTest.java index 55758d1..04d3fa0 100644 --- a/src/test/java/io/floci/cli/unit/ProductProfileTest.java +++ b/src/test/java/io/floci/cli/unit/ProductProfileTest.java @@ -22,6 +22,7 @@ class ProductProfileTest { assertEquals("FLOCI_ENDPOINT", ProductProfile.AWS.envVar("ENDPOINT")); assertEquals("/_floci", ProductProfile.AWS.controlPrefix()); assertEquals("floci", ProductProfile.AWS.commandPrefix()); + assertEquals("floci aws", ProductProfile.AWS.explicitCommandPrefix()); assertEquals(Map.of(), ProductProfile.AWS.startEnv()); } @@ -35,6 +36,7 @@ class ProductProfileTest { assertEquals("FLOCI_GCP_CONTAINER", ProductProfile.GCP.envVar("CONTAINER")); assertEquals("/_floci-gcp", ProductProfile.GCP.controlPrefix()); assertEquals("floci gcp", ProductProfile.GCP.commandPrefix()); + assertEquals("floci gcp", ProductProfile.GCP.explicitCommandPrefix()); assertEquals(Map.of(), ProductProfile.GCP.startEnv()); } @@ -49,6 +51,7 @@ class ProductProfileTest { // The floci-az server exposes /_floci/* (same as AWS), NOT /_floci-az. assertEquals("/_floci", ProductProfile.AZ.controlPrefix()); assertEquals("floci az", ProductProfile.AZ.commandPrefix()); + assertEquals("floci az", ProductProfile.AZ.explicitCommandPrefix()); assertEquals(Map.of("TLS_ENABLED", "true"), ProductProfile.AZ.startEnv()); } @@ -62,6 +65,7 @@ class ProductProfileTest { assertEquals("FLOCI_OCI_ENDPOINT", ProductProfile.OCI.envVar("ENDPOINT")); assertEquals("/_floci-oci", ProductProfile.OCI.controlPrefix()); assertEquals("floci oci", ProductProfile.OCI.commandPrefix()); + assertEquals("floci oci", ProductProfile.OCI.explicitCommandPrefix()); assertEquals(Map.of(), ProductProfile.OCI.startEnv()); } diff --git a/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java b/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java new file mode 100644 index 0000000..99506e3 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/RestartRecoveryTest.java @@ -0,0 +1,173 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.RestartCommand; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class RestartRecoveryTest { + @TempDir Path profiles; + + static class FailedStart extends DockerClient { + String state = "running"; + boolean failStop; + final List actions = new ArrayList<>(); + @Override public DockerHost daemonHost() { return new DockerHost(Kind.TCP, null, "tcp://host:2375"); } + @Override public Optional inspectContainer(String name) { + return state == null ? Optional.empty() : Optional.of(new ContainerInfo("id", name, "floci/floci-gcp:0.9", state, "14588->4588/tcp")); + } + @Override public Optional inspectRunSettings(String name, int port) { + return Optional.of(new RunSettings("floci/floci-gcp:0.9", 14588, "/data/team's state", + Map.of("FLOCI_GCP_SERVICES", "storage,pubsub", "FLOCI_GCP_DOCKER_RESOURCE_NAMESPACE", "team"))); + } + @Override public void stopContainer(String name, int timeout) throws DockerException { + if (failStop) throw new DockerException("stop failed"); + actions.add("stop"); state = "exited"; + } + @Override public void removeContainer(String name) { actions.add("remove"); state = null; } + @Override public void pull(String image, String policy) { } + @Override public void pull(String image, String policy, PrintStream stream) { } + @Override public String startContainer(List args) throws DockerException { + actions.add("run"); throw new DockerException("run failed"); + } + } + + @Test + void failedStartReportsACopyableSnapshotInTextAndJson() throws Exception { + for (String format : List.of("text", "json")) { + FailedStart docker = new FailedStart(); + var restart = new RestartCommand(ProductProfile.GCP, docker); + CommandLine command = new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(profiles))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream captured = new ByteArrayOutputStream(), stdout = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(captured)); System.setOut(new PrintStream(stdout)); + assertEquals(1, command.execute("--container", "floci-gcp-team", "-o", format)); + } finally { System.setErr(err); System.setOut(out); } + assertEquals(List.of("stop", "remove", "run"), docker.actions); + String line = captured.toString().lines().filter(s -> s.startsWith("floci gcp start")).findFirst().orElseThrow(); + assertTrue(line.contains("--port 14588"), line); + assertTrue(line.contains("--image floci/floci-gcp:0.9"), line); + assertTrue(line.contains("--persist '/data/team'\\''s state'"), line); + assertTrue(line.contains("--services storage,pubsub --namespace team"), line); + assertTrue(line.contains("--container floci-gcp-team"), line); + assertFalse(line.contains("--endpoint"), line); + if (format.equals("json")) assertEquals("", stdout.toString()); + } + } + + @Test + void aRunningContainerThatIsNotReadyGetsLogsAndWaitNotARefusedStart() throws Exception { + FailedStart docker = new FailedStart() { + @Override public String startContainer(List args) { + actions.add("run"); state = "running"; return "new-id"; + } + }; + var restart = new RestartCommand(ProductProfile.GCP, docker) { + @Override public StartCommand buildStartCommand() throws DockerException { + StartCommand start = super.buildStartCommand(); + start.readinessTimeout("1ms"); + return start; + } + }; + CommandLine command = new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(profiles))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(stderr)); System.setOut(new PrintStream(new ByteArrayOutputStream())); + assertEquals(1, command.execute("--container", "floci-gcp-team")); + } finally { System.setErr(err); System.setOut(out); } + String text = stderr.toString(); + assertTrue(text.contains("running but did not become ready"), text); + assertTrue(text.contains("floci gcp logs --container floci-gcp-team"), text); + assertTrue(text.contains("floci gcp wait --container floci-gcp-team"), text); + assertFalse(text.contains("floci gcp start --container"), text); + } + + private String restartStderr(ProductProfile product, FailedStart docker, String... args) throws Exception { + var restart = new RestartCommand(product, docker) { + @Override public StartCommand buildStartCommand() throws DockerException { + StartCommand start = super.buildStartCommand(); + start.readinessTimeout("1ms"); + return start; + } + }; + CommandLine command = new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(profiles))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream stderr = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(stderr)); System.setOut(new PrintStream(new ByteArrayOutputStream())); + assertEquals(1, command.execute(args)); + } finally { System.setErr(err); System.setOut(out); } + return stderr.toString(); + } + + private static FailedStart comesUpRunning() { + return new FailedStart() { + @Override public String startContainer(List args) { + actions.add("run"); state = "running"; return "new-id"; + } + }; + } + + @Test + void awsRecoveryNamesItsTreeBecauseABareCommandFollowsTheDefaultProduct() throws Exception { + String refused = restartStderr(ProductProfile.AWS, new FailedStart(), "--container", "other"); + assertTrue(refused.contains("floci aws start --container other"), refused); + String unready = restartStderr(ProductProfile.AWS, comesUpRunning(), "--container", "other"); + assertTrue(unready.contains("floci aws logs --container other"), unready); + assertTrue(unready.contains("floci aws wait --container other"), unready); + } + + @Test + void theSuggestedWaitChecksTheEndpointStartWaitedOn() throws Exception { + String text = restartStderr(ProductProfile.GCP, comesUpRunning(), + "--container", "floci-gcp-team", "--endpoint", "http://build-host:4588"); + assertTrue(text.contains("floci gcp wait --container floci-gcp-team --endpoint http://build-host:14588"), text); + } + + @Test + void theRecoveryCommandPrintsTheDirectoryALocalDaemonWouldMount() { + FailedStart local = new FailedStart() { + @Override public DockerHost daemonHost() { return new DockerHost(Kind.UNIX, null, "unix:///var/run/docker.sock"); } + }; + StartCommand onLocal = new StartCommand(ProductProfile.GCP, local); + new CommandLine(onLocal).parseArgs("--persist", "rel/data"); + assertTrue(onLocal.recoveryCommand().contains("--persist " + Path.of("rel/data").toAbsolutePath()), onLocal.recoveryCommand()); + + StartCommand onRemote = new StartCommand(ProductProfile.GCP, new FailedStart()); + new CommandLine(onRemote).parseArgs("--persist", "/srv/data"); + assertTrue(onRemote.recoveryCommand().contains("--persist /srv/data"), onRemote.recoveryCommand()); + } + + @Test + void failedStopDoesNotClaimTheOldContainerWasRemoved() { + FailedStart docker = new FailedStart(); docker.failStop = true; + PrintStream err = System.err; ByteArrayOutputStream captured = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(captured)); + assertEquals(1, new CommandLine(new RestartCommand(ProductProfile.GCP, docker)).execute()); + } finally { System.setErr(err); } + assertFalse(captured.toString().contains("old container was removed")); + assertTrue(docker.actions.isEmpty()); + } +} From 882c0ea7be23ad03ef289eed262f94f87dc2184b Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Wed, 4 Nov 2026 01:48:30 -0600 Subject: [PATCH 4/4] fix(cli): keep the selected instance in the commands that hints suggest (#74) Commands printed by errors, env and doctor now carry --profile, --container and an explicit --endpoint, so pasting one acts on the same instance. After a failed pull, the suggested start also keeps the --port, --image, --persist, --services and --namespace you typed. The env load hint adds -o text after a profile, which may set output: json, and quotes values for the shell it is for. A value containing a line break prints as a placeholder, because the hint is a comment in the output people feed to eval. Signed-off-by: Hector Ventura --- README.md | 3 +- plugin.json | 2 +- skills/floci/SKILL.md | 3 +- src/main/java/io/floci/cli/GlobalOptions.java | 37 +++- .../io/floci/cli/commands/DoctorCommand.java | 8 +- .../io/floci/cli/commands/EnvCommand.java | 12 +- .../io/floci/cli/commands/LogsCommand.java | 10 +- .../floci/cli/commands/ServicesCommand.java | 11 +- .../io/floci/cli/commands/StartCommand.java | 20 +- .../io/floci/cli/commands/StatusCommand.java | 2 +- .../io/floci/cli/commands/StopCommand.java | 2 +- .../io/floci/cli/commands/WaitCommand.java | 2 +- .../floci/cli/commands/az/AzEnvCommand.java | 12 +- .../floci/cli/commands/az/AzSetupCommand.java | 18 +- .../floci/cli/commands/gcp/GcpEnvCommand.java | 10 +- .../floci/cli/commands/oci/OciEnvCommand.java | 10 +- src/main/java/io/floci/cli/doctor/Check.java | 5 + .../doctor/checks/ContainerRunningCheck.java | 7 + .../doctor/checks/EndpointReachableCheck.java | 8 +- .../cli/doctor/checks/ImagePresentCheck.java | 6 + .../cli/doctor/checks/ImageVersionCheck.java | 6 + .../cli/doctor/checks/PortAvailableCheck.java | 6 + .../java/io/floci/cli/output/ShellExport.java | 24 +++ .../io/floci/cli/unit/InstanceHintsTest.java | 172 ++++++++++++++++++ .../io/floci/cli/unit/StartPreflightTest.java | 2 +- 25 files changed, 355 insertions(+), 43 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/InstanceHintsTest.java diff --git a/README.md b/README.md index f11deb3..d4c7d48 100644 --- a/README.md +++ b/README.md @@ -854,7 +854,8 @@ expect. An instance is a profile. Its **container name** is its identity, its **port** is the only thing that must differ from the other instances, and its **persist dir** keeps its state across -container recreation. Every command (`status`, `logs`, `env`, `doctor`, `stop`, ...) finds the +container recreation. Hints for follow-up CLI commands preserve the selected profile, container +and explicit endpoint, and a retried `start` keeps the flags you typed. Every command (`status`, `logs`, `env`, `doctor`, `stop`, ...) finds the instance through its container, so passing the same `--profile` is all it takes. Any local state the CLI keeps about an instance lives in `~/.floci///`. diff --git a/plugin.json b/plugin.json index a0d9d0e..8170423 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "floci", - "version": "1.0.2", + "version": "1.0.3", "description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.", "author": { "name": "Floci", diff --git a/skills/floci/SKILL.md b/skills/floci/SKILL.md index 0490509..506e802 100644 --- a/skills/floci/SKILL.md +++ b/skills/floci/SKILL.md @@ -84,7 +84,8 @@ clouds the user works with; suggest installing them, do not install them unasked recreating anything. If restart fails after removal, follow stderr: a start command that retries with the same settings, or `logs` and `wait` when the new container is up but not ready. Neither restores in-memory state. -7. **Never add `-q` to `env`**: it suppresses the exports themselves. +7. **Never add `-q` to `env`**: it suppresses the exports themselves. Follow-up command hints + keep the instance's flags; keep them when retrying. 8. **Do not guess what an emulator supports.** Check `floci services -o json` and the published docs ([references/docs.md](references/docs.md)) instead of answering from memory. 9. **With a profile, start and wait before `env`.** Until the profile's container is running, diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java index d1f45f4..191fba9 100644 --- a/src/main/java/io/floci/cli/GlobalOptions.java +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -5,6 +5,7 @@ import io.floci.cli.output.Ansi; import io.floci.cli.output.Glyphs; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; +import io.floci.cli.output.ShellExport; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Option; import picocli.CommandLine.Spec; @@ -105,12 +106,40 @@ public class GlobalOptions { * empty. Values are shell-quoted, because hints are meant to be pasted. */ public String instanceSelector() { + return selector(GlobalOptions::shellWord); + } + + /** + * The flags for a hint that loads {@code env} in {@code shell}: the selector, quoted for that + * shell, and {@code -o text} after a profile, which may set {@code output: json} that no shell + * can load. + * + *

This hint is a comment in the output people feed to {@code eval}, so a line break in a + * value would end the comment and run the rest as code. No quoting survives that: such a value + * becomes a placeholder. PLAIN_WORD is a POSIX rule ({@code @team} is a splat in PowerShell), + * so other shells always get quotes. + */ + public String envLoadFlags(String shell) { + String selector = selector(value -> { + if (ShellExport.breaksLine(value)) return ""; + return ShellExport.isPosix(shell) && PLAIN_WORD.matcher(value).matches() + ? value : ShellExport.quoted(shell, value); + }); + return profile != null ? selector + " -o text" : selector; + } + + private String selector(UnaryOperator quote) { + String selector = ""; if (profile != null) { - String selector = " --profile " + shellWord(profile); - return typed("--container") ? selector + " --container " + shellWord(container) : selector; + selector = " --profile " + quote.apply(profile); + if (typed("--container")) selector += " --container " + quote.apply(container); + } else if (!product.defaultContainer().equals(container)) { + selector = " --container " + quote.apply(container); } - if (!product.defaultContainer().equals(container)) return " --container " + shellWord(container); - return ""; + if (typed("--endpoint") || (profile == null && !product.defaultEndpoint().equals(endpoint))) { + selector += " --endpoint " + quote.apply(endpoint); + } + return selector; } /** Whether {@code option} was given on the command line, as opposed to coming from a profile, the environment or the default. */ diff --git a/src/main/java/io/floci/cli/commands/DoctorCommand.java b/src/main/java/io/floci/cli/commands/DoctorCommand.java index ebb6014..752b83f 100644 --- a/src/main/java/io/floci/cli/commands/DoctorCommand.java +++ b/src/main/java/io/floci/cli/commands/DoctorCommand.java @@ -125,7 +125,7 @@ public class DoctorCommand implements Callable { List selected = selected(); if (selected.isEmpty()) { printer.error("Unknown check '" + checkName + "'.\nRun '" + profile.commandPrefix() - + " doctor' to see every check, or pass one of: " + String.join(", ", knownNames()) + "."); + + " doctor" + global.instanceSelector() + "' to see every check, or pass one of: " + String.join(", ", knownNames()) + "."); return ExitCode.USAGE; } @@ -143,7 +143,7 @@ public class DoctorCommand implements Callable { // concurrently; results are still printed in list order as each one becomes available. try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { List> pending = selected.stream() - .map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container))) + .map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container, global.instanceSelector()))) .toList(); for (int i = 0; i < selected.size(); i++) { CheckResult result = await(selected.get(i), pending.get(i)); @@ -200,9 +200,9 @@ public class DoctorCommand implements Callable { } // One failing check must not abort the run: report it and keep going. - private static CheckResult runSafely(Check check, String endpoint, String container) { + private static CheckResult runSafely(Check check, String endpoint, String container, String selector) { try { - return check.run(endpoint, container); + return check.run(endpoint, container, selector); } catch (RuntimeException e) { return failed(check, e); } diff --git a/src/main/java/io/floci/cli/commands/EnvCommand.java b/src/main/java/io/floci/cli/commands/EnvCommand.java index a98566e..4dee195 100644 --- a/src/main/java/io/floci/cli/commands/EnvCommand.java +++ b/src/main/java/io/floci/cli/commands/EnvCommand.java @@ -21,7 +21,7 @@ import java.util.concurrent.Callable; public class EnvCommand implements Callable { @Mixin - GlobalOptions global; + GlobalOptions global = new GlobalOptions(); @Option(names = {"--host"}, description = "Hostname for the AWS endpoint URL (default: localhost.floci.io)", @@ -41,6 +41,12 @@ public class EnvCommand implements Callable { paramLabel = "") String shell; + private final DockerClient docker; + + public EnvCommand() { this(new DockerClient()); } + + public EnvCommand(DockerClient docker) { this.docker = docker; } + @Override public Integer call() { Printer printer = global.printer(); @@ -48,7 +54,7 @@ public class EnvCommand implements Callable { printer.error(ShellExport.unsupported(shell)); return 2; } - String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + String effectiveEndpoint = global.resolvedEndpoint(docker); int port = extractPort(effectiveEndpoint); String endpointUrl = "http://" + host + ":" + port; @@ -67,7 +73,7 @@ public class EnvCommand implements Callable { printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue())); } printer.println(""); - printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci env"))); + printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci env" + global.envLoadFlags(shell)))); return 0; } diff --git a/src/main/java/io/floci/cli/commands/LogsCommand.java b/src/main/java/io/floci/cli/commands/LogsCommand.java index af0f752..3dba302 100644 --- a/src/main/java/io/floci/cli/commands/LogsCommand.java +++ b/src/main/java/io/floci/cli/commands/LogsCommand.java @@ -27,6 +27,11 @@ public class LogsCommand implements Callable { } protected LogsCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + public LogsCommand(ProductProfile profile, DockerClient docker) { + this.docker = docker; this.profile = profile; this.global = new GlobalOptions(profile); } @@ -43,15 +48,16 @@ public class LogsCommand implements Callable { @Option(names = {"--service"}, description = "Filter to a specific service (not yet supported; requires server-side filtering)", paramLabel = "") String service; + private final DockerClient docker; + @Override public Integer call() { Printer printer = global.printer(); - DockerClient docker = new DockerClient(); try { var info = docker.inspectContainer(global.container); if (info.isEmpty()) { - printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start' to launch one."); + printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch one."); return 1; } } catch (DockerException e) { diff --git a/src/main/java/io/floci/cli/commands/ServicesCommand.java b/src/main/java/io/floci/cli/commands/ServicesCommand.java index 6d28cdc..a40a272 100644 --- a/src/main/java/io/floci/cli/commands/ServicesCommand.java +++ b/src/main/java/io/floci/cli/commands/ServicesCommand.java @@ -32,16 +32,23 @@ public class ServicesCommand implements Callable { } protected ServicesCommand(ProductProfile profile) { + this(profile, new DockerClient()); + } + + public ServicesCommand(ProductProfile profile, DockerClient docker) { + this.docker = docker; this.profile = profile; this.global = new GlobalOptions(profile); } + private final DockerClient docker; + @Override public Integer call() { Printer printer = global.printer(); // Resolve the endpoint from the container's port mapping, like status/wait/env do, // so a container started with --port is still found without --endpoint. - String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + String effectiveEndpoint = global.resolvedEndpoint(docker); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile); List services; @@ -50,7 +57,7 @@ public class ServicesCommand implements Callable { services = Arrays.asList(health.services()); } catch (Exception e) { printer.error("Could not reach " + profile.displayName() + " at " + effectiveEndpoint - + ".\nIs " + profile.displayName() + " running? Try '" + profile.commandPrefix() + " start'."); + + ".\nIs " + profile.displayName() + " running? Try '" + profile.commandPrefix() + " start" + global.instanceSelector() + "'."); return 1; } diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index d529b89..713f330 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -116,6 +116,18 @@ public class StartCommand implements Callable { return start; } + // The rest of what was typed, so a retried start is the same start. Empty for a start built by + // restart, which was never parsed. + private String typedStartFlags() { + StringBuilder flags = new StringBuilder(); + if (global.typed("--port")) flags.append(" --port ").append(port); + if (global.typed("--image")) flags.append(" --image ").append(GlobalOptions.shellWord(image)); + if (global.typed("--persist")) flags.append(" --persist ").append(GlobalOptions.shellWord(persistDir)); + if (global.typed("--services")) flags.append(" --services ").append(GlobalOptions.shellWord(services)); + if (global.typed("--namespace")) flags.append(" --namespace ").append(GlobalOptions.shellWord(namespace)); + return flags.toString(); + } + /** A self-contained POSIX command that recovers the resolved settings after a failed restart. */ public String recoveryCommand() { StringBuilder command = new StringBuilder(profile.explicitCommandPrefix()).append(" start"); @@ -378,7 +390,7 @@ public class StartCommand implements Callable { if (existing.isPresent()) { String state = existing.get().state(); if ("running".equals(state)) { - printer.error("Container '" + global.container + "' is already running.\nRun '" + profile.commandPrefix() + " stop' first or pass --container to use a different name."); + printer.error("Container '" + global.container + "' is already running.\nRun '" + profile.commandPrefix() + " stop" + global.instanceSelector() + "' first or pass --container to use a different name."); return 1; } // Remove stopped container so we can start fresh @@ -416,7 +428,7 @@ public class StartCommand implements Callable { docker.pull(image, pull); } } catch (DockerException e) { - printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never' to skip pulling."); + printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never" + global.instanceSelector() + typedStartFlags() + "' to skip pulling."); return 1; } @@ -431,7 +443,7 @@ public class StartCommand implements Callable { // withNextStep, not the two-argument error: docker's own output is often several // lines, which must not be taken for a next step. printer.error("Failed to start container: " + e.withNextStep( - "Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port.")); + "Run '" + profile.commandPrefix() + " doctor" + global.instanceSelector() + "' to check Docker, the image and the port.")); return 1; } @@ -440,7 +452,7 @@ public class StartCommand implements Callable { String endpoint = withPort(global.endpoint, port); if (detach) { - progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness.")); + progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait" + global.instanceSelector() + "' to poll for readiness.")); if (structured) printer.structured(result(id, endpoint, null)); return 0; } diff --git a/src/main/java/io/floci/cli/commands/StatusCommand.java b/src/main/java/io/floci/cli/commands/StatusCommand.java index 34b24cd..f620e8b 100644 --- a/src/main/java/io/floci/cli/commands/StatusCommand.java +++ b/src/main/java/io/floci/cli/commands/StatusCommand.java @@ -115,7 +115,7 @@ public class StatusCommand implements Callable { if (!reachable && !"running".equals(containerState)) { printer.println(""); - printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start' to launch " + profile.displayName() + ".")); + printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch " + profile.displayName() + ".")); } return exit; diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java index 2d75e6e..a4861e1 100644 --- a/src/main/java/io/floci/cli/commands/StopCommand.java +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -64,7 +64,7 @@ public class StopCommand implements Callable { try { var info = docker.inspectContainer(global.container); if (info.isEmpty()) { - printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start' to launch one."); + printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch one."); return 1; } if (!"running".equals(info.get().state())) { diff --git a/src/main/java/io/floci/cli/commands/WaitCommand.java b/src/main/java/io/floci/cli/commands/WaitCommand.java index 030db5a..012de23 100644 --- a/src/main/java/io/floci/cli/commands/WaitCommand.java +++ b/src/main/java/io/floci/cli/commands/WaitCommand.java @@ -123,7 +123,7 @@ public class WaitCommand implements Callable { if (spinner) clearSpinner(printer); printer.error("Timed out waiting for " + profile.displayName() + " after " + timeout - + ".\nIs the container running? Try '" + profile.commandPrefix() + " status'."); + + ".\nIs the container running? Try '" + profile.commandPrefix() + " status" + global.instanceSelector() + "'."); return 1; } diff --git a/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java index 537ec3b..ecf9a95 100644 --- a/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java @@ -68,6 +68,7 @@ public class AzEnvCommand implements Callable { paramLabel = "") String shell; + private final DockerClient docker; private final Path stateRoot; private final AzSetupCommand.CertSource certSource; @@ -81,6 +82,11 @@ public class AzEnvCommand implements Callable { * each instance's config dir and CA; {@code certSource} reads the running server's CA. */ public AzEnvCommand(Path stateRoot, AzSetupCommand.CertSource certSource) { + this(stateRoot, certSource, new DockerClient()); + } + + public AzEnvCommand(Path stateRoot, AzSetupCommand.CertSource certSource, DockerClient docker) { + this.docker = docker; this.stateRoot = stateRoot; this.certSource = certSource; } @@ -92,7 +98,7 @@ public class AzEnvCommand implements Callable { printer.error(ShellExport.unsupported(shell)); return 2; } - String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + String effectiveEndpoint = global.resolvedEndpoint(docker); int port = extractPort(effectiveEndpoint); boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null; @@ -121,7 +127,7 @@ public class AzEnvCommand implements Callable { printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_CONNECTION_STRING", connStr)); printAzCliVars(printer, azCliVars); printer.println(""); - printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env"))); + printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env" + global.envLoadFlags(shell)))); } else { printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_ACCOUNT", account)); printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_KEY", DEV_KEY)); @@ -130,7 +136,7 @@ public class AzEnvCommand implements Callable { } printAzCliVars(printer, azCliVars); printer.println(""); - printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env --format sdk-vars"))); + printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env --format sdk-vars" + global.envLoadFlags(shell)))); } return 0; 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 e3b8c1a..44340c4 100644 --- a/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java +++ b/src/main/java/io/floci/cli/commands/az/AzSetupCommand.java @@ -128,11 +128,11 @@ public class AzSetupCommand implements Callable { return reset ? reset(printer, flociAzDir, cloud) : setup(printer, flociAzDir, cloud); } catch (AzCliNotFoundException e) { printer.error("az CLI not found in PATH.\n" - + "Install it from https://learn.microsoft.com/cli/azure/install-azure-cli, then re-run 'floci az setup'."); + + "Install it from https://learn.microsoft.com/cli/azure/install-azure-cli, then re-run 'floci az setup" + global.instanceSelector() + "'."); return 1; } catch (StepFailedException e) { printer.error(e.getMessage() - + "\nFix the error above and re-run 'floci az setup', or run 'floci az setup --reset' to start over."); + + "\nFix the error above and re-run 'floci az setup" + global.instanceSelector() + "', or run 'floci az setup --reset" + global.instanceSelector() + "' to start over."); return 1; } } @@ -149,12 +149,12 @@ public class AzSetupCommand implements Callable { caPem = fetchWithRetry(certSource, httpEndpoint, CERT_ATTEMPTS, certRetryDelay); } catch (TlsUnavailableException e) { printer.error(e.notYet() - ? "Floci Azure is still generating its TLS certificate.\nWait a few seconds and re-run 'floci az setup'." + ? "Floci Azure is still generating its TLS certificate.\nWait a few seconds and re-run 'floci az setup" + global.instanceSelector() + "'." : "Floci Azure is running without TLS, which the az CLI needs to log in.\n" - + "Run 'floci az restart' to enable it, then re-run 'floci az setup'."); + + "Run 'floci az restart" + global.instanceSelector() + "' to enable it, then re-run 'floci az setup" + global.instanceSelector() + "'."); return 1; } catch (FlociException e) { - printer.error(e.getMessage() + "\nRun 'floci az start', then re-run 'floci az setup'."); + printer.error(e.getMessage() + "\nRun 'floci az start" + global.instanceSelector() + "', then re-run 'floci az setup" + global.instanceSelector() + "'."); return 1; } @@ -169,7 +169,7 @@ public class AzSetupCommand implements Callable { } } catch (Exception e) { printer.error("Could not write the az configuration: " + e.getMessage() - + "\nCheck that " + flociAzDir + " is writable and re-run 'floci az setup'."); + + "\nCheck that " + flociAzDir + " is writable and re-run 'floci az setup" + global.instanceSelector() + "'."); return 1; } @@ -195,7 +195,7 @@ public class AzSetupCommand implements Callable { boolean subscriptionSet = az.run(List.of("account", "set", "--subscription", subscription), env).ok(); // This instance now uses the default az config. An isolated config left by an earlier - // setup would otherwise keep 'floci az env' selecting its old login. + // setup would otherwise keep the old login selected by env. boolean isolatedRemoved = false; if (globalConfig && Files.isDirectory(configDir)) { try { @@ -203,7 +203,7 @@ public class AzSetupCommand implements Callable { isolatedRemoved = true; } catch (IOException e) { printer.warn("Could not remove the old isolated az config " + configDir.toAbsolutePath() + ": " - + e.getMessage() + "\nDelete it by hand, or 'floci az env' keeps selecting it."); + + e.getMessage() + "\nDelete it by hand, or 'floci az env" + global.instanceSelector() + "' keeps selecting it."); } } @@ -279,7 +279,7 @@ public class AzSetupCommand implements Callable { deleteIfEmpty(flociAzDir); } catch (IOException e) { printer.error("Could not remove " + flociAzDir + ": " + e.getMessage() - + "\nDelete it by hand, then re-run 'floci az setup' if you need it again."); + + "\nDelete it by hand, then re-run 'floci az setup" + global.instanceSelector() + "' if you need it again."); return 1; } out.put("reset", existed); diff --git a/src/main/java/io/floci/cli/commands/gcp/GcpEnvCommand.java b/src/main/java/io/floci/cli/commands/gcp/GcpEnvCommand.java index 6b8ded6..0288ea9 100644 --- a/src/main/java/io/floci/cli/commands/gcp/GcpEnvCommand.java +++ b/src/main/java/io/floci/cli/commands/gcp/GcpEnvCommand.java @@ -41,6 +41,12 @@ public class GcpEnvCommand implements Callable { paramLabel = "") String shell; + private final DockerClient docker; + + public GcpEnvCommand() { this(new DockerClient()); } + + public GcpEnvCommand(DockerClient docker) { this.docker = docker; } + @Override public Integer call() { Printer printer = global.printer(); @@ -48,7 +54,7 @@ public class GcpEnvCommand implements Callable { printer.error(ShellExport.unsupported(shell)); return 2; } - String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + String effectiveEndpoint = global.resolvedEndpoint(docker); String host = extractHost(effectiveEndpoint); int port = extractPort(effectiveEndpoint); String hostPort = host + ":" + port; @@ -71,7 +77,7 @@ public class GcpEnvCommand implements Callable { printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue())); } printer.println(""); - printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci gcp env"))); + printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci gcp env" + global.envLoadFlags(shell)))); return 0; } diff --git a/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java b/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java index 16f6b5a..0babaf1 100644 --- a/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java +++ b/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java @@ -30,6 +30,12 @@ public class OciEnvCommand implements Callable { paramLabel = "") String shell; + private final DockerClient docker; + + public OciEnvCommand() { this(new DockerClient()); } + + public OciEnvCommand(DockerClient docker) { this.docker = docker; } + @Override public Integer call() { Printer printer = global.printer(); @@ -37,7 +43,7 @@ public class OciEnvCommand implements Callable { printer.error(ShellExport.unsupported(shell)); return 2; } - String endpoint = global.resolvedEndpoint(new DockerClient()); + String endpoint = global.resolvedEndpoint(docker); Map vars = new LinkedHashMap<>(); // OCI SDKs and CLI take one endpoint for every service; ocilocal reads FLOCI_OCI_ENDPOINT. @@ -67,7 +73,7 @@ public class OciEnvCommand implements Callable { printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue())); } printer.println(""); - printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci oci env"))); + printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci oci env" + global.envLoadFlags(shell)))); return 0; } } diff --git a/src/main/java/io/floci/cli/doctor/Check.java b/src/main/java/io/floci/cli/doctor/Check.java index 891bf39..0994cac 100644 --- a/src/main/java/io/floci/cli/doctor/Check.java +++ b/src/main/java/io/floci/cli/doctor/Check.java @@ -4,6 +4,11 @@ package io.floci.cli.doctor; public interface Check { CheckResult run(String endpoint, String container); + /** Instance-aware entry point; checks without CLI hints keep the original contract. */ + default CheckResult run(String endpoint, String container, String selector) { + return run(endpoint, container); + } + /** * The name this check reports under ({@code docker.installed}, ...), so {@code doctor --check} * can select it without running every other check first. {@code null} means unknown until diff --git a/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java index b613250..1b49239 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java @@ -36,6 +36,13 @@ public class ContainerRunningCheck implements Check { @Override public CheckResult run(String endpoint, String container) { + return run(endpoint, container, ""); + } + + @Override + public CheckResult run(String endpoint, String container, String selector) { + String start = this.start + selector; + String stop = this.stop + selector; try { var info = docker.inspectContainer(container); if (info.isEmpty()) { diff --git a/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java index 6fc72b3..2aea257 100644 --- a/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java @@ -37,6 +37,12 @@ public class EndpointReachableCheck implements Check { @Override public CheckResult run(String endpoint, String container) { + return run(endpoint, container, ""); + } + + @Override + public CheckResult run(String endpoint, String container, String selector) { + FlociHttpClient client = new FlociHttpClient(endpoint, controlPrefix); try { var health = client.health(Duration.ofSeconds(3)); @@ -51,6 +57,6 @@ public class EndpointReachableCheck implements Check { } return CheckResult.fail("endpoint.reachable", "GET " + controlPrefix + "/health at " + endpoint + " did not return 200", - "Is Floci running? Try '" + commandPrefix + " start'."); + "Is Floci running? Try '" + commandPrefix + " start" + selector + "'."); } } diff --git a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java index 3375a14..91932f2 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java @@ -44,6 +44,12 @@ public class ImagePresentCheck implements Check { @Override public CheckResult run(String endpoint, String container) { + return run(endpoint, container, ""); + } + + @Override + public CheckResult run(String endpoint, String container, String selector) { + String pullHint = this.pullHint + selector; try { if (docker.isImagePresent(image)) { return CheckResult.ok("image.present", image + " image present locally"); diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java index f267a41..500e73c 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -46,6 +46,12 @@ public class ImageVersionCheck implements Check { @Override public CheckResult run(String endpoint, String container) { + return run(endpoint, container, ""); + } + + @Override + public CheckResult run(String endpoint, String container, String selector) { + String pullHint = this.pullHint + selector; try { if (!docker.isImagePresent(image)) { return CheckResult.warn("image.version", image + " not present — version cannot be checked", diff --git a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java index b6464cb..95fd261 100644 --- a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java @@ -45,6 +45,12 @@ public class PortAvailableCheck implements Check { @Override public CheckResult run(String endpoint, String container) { + return run(endpoint, container, ""); + } + + @Override + public CheckResult run(String endpoint, String container, String selector) { + String startCommand = this.startCommand + selector; int port = extractPort(endpoint, defaultPort); // If a Floci container is already listening on the port, that's fine try { diff --git a/src/main/java/io/floci/cli/output/ShellExport.java b/src/main/java/io/floci/cli/output/ShellExport.java index 04a2188..d732250 100644 --- a/src/main/java/io/floci/cli/output/ShellExport.java +++ b/src/main/java/io/floci/cli/output/ShellExport.java @@ -39,6 +39,30 @@ public final class ShellExport { }; } + /** Whether {@code shell} is one of the POSIX family, as opposed to fish or PowerShell. */ + public static boolean isPosix(String shell) { + return switch (shell.toLowerCase()) { + case "fish", "powershell", "pwsh", "ps1" -> false; + default -> true; + }; + } + + /** Whether {@code value} could end the comment line it is printed in, in any shell. */ + public static boolean breaksLine(String value) { + return value.chars().anyMatch(c -> Character.isISOControl(c) + || Character.getType(c) == Character.LINE_SEPARATOR + || Character.getType(c) == Character.PARAGRAPH_SEPARATOR); + } + + /** {@code value} as one single-quoted argument in the given shell. */ + public static String quoted(String shell, String value) { + return switch (shell.toLowerCase()) { + case "fish" -> "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"; + case "powershell", "pwsh", "ps1" -> "'" + value.replace("'", "''") + "'"; + default -> "'" + value.replace("'", "'\\''") + "'"; + }; + } + /** Renders one export line for the given shell ({@code bash}, {@code fish}, {@code powershell}). */ public static String formatExport(String shell, String key, String value) { return switch (shell.toLowerCase()) { diff --git a/src/test/java/io/floci/cli/unit/InstanceHintsTest.java b/src/test/java/io/floci/cli/unit/InstanceHintsTest.java new file mode 100644 index 0000000..b1a3bb9 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/InstanceHintsTest.java @@ -0,0 +1,172 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.DoctorCommand; +import io.floci.cli.commands.EnvCommand; +import io.floci.cli.commands.LogsCommand; +import io.floci.cli.commands.ServicesCommand; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.commands.StatusCommand; +import io.floci.cli.commands.StopCommand; +import io.floci.cli.commands.WaitCommand; +import io.floci.cli.commands.az.AzEnvCommand; +import io.floci.cli.commands.gcp.GcpEnvCommand; +import io.floci.cli.commands.oci.OciEnvCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.checks.ContainerRunningCheck; +import io.floci.cli.doctor.checks.ImagePresentCheck; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; + +import static org.junit.jupiter.api.Assertions.*; + +class InstanceHintsTest { + @TempDir Path temp; + private static final List PRODUCTS = List.of(ProductProfile.AWS, ProductProfile.GCP, ProductProfile.AZ, ProductProfile.OCI); + static class FakeDocker extends DockerClient { + boolean running; + @Override public DockerHost daemonHost() { return new DockerHost(Kind.TCP, null, "tcp://host:2375"); } + @Override public Optional inspectContainer(String name) { + return running ? Optional.of(new ContainerInfo("id", name, "image", "running", "")) : Optional.empty(); + } + @Override public boolean isImagePresent(String image) { return false; } + } + private record Run(int exit, String out, String err) { } + private Run run(Callable command, String... args) throws Exception { + Files.writeString(temp.resolve("team alpha.yaml"), "container: other\nendpoint: http://127.0.0.1:1\n"); + CommandLine cli = new CommandLine(command).setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(temp))); + PrintStream out = System.out, err = System.err; + ByteArrayOutputStream stdout = new ByteArrayOutputStream(), stderr = new ByteArrayOutputStream(); + try { + System.setOut(new PrintStream(stdout)); System.setErr(new PrintStream(stderr)); + int exit = cli.execute(args); + return new Run(exit, stdout.toString(), stderr.toString()); + } finally { System.setOut(out); System.setErr(err); } + } + @Test + void lifecycleFailureHintsSelectTheSameProfileAndContainerInEveryTree() throws Exception { + for (ProductProfile product : PRODUCTS) { + FakeDocker docker = new FakeDocker(); + for (Callable command : List.>of(new StopCommand(product, docker), new LogsCommand(product, docker), + new ServicesCommand(product, docker), new WaitCommand(product, docker))) { + String[] args = command instanceof WaitCommand + ? new String[]{"--profile", "team alpha", "--container", "override", "--timeout", "1ms"} + : new String[]{"--profile", "team alpha", "--container", "override"}; + Run result = run(command, args); + assertEquals(1, result.exit()); + assertTrue(result.err().contains("--profile 'team alpha' --container override"), result.err()); + } + docker.running = true; + Run start = run(new StartCommand(product, docker), "--profile", "team alpha", "--container", "override"); + assertTrue(start.err().contains(product.commandPrefix() + " stop --profile 'team alpha' --container override"), start.err()); + docker.running = false; + Run status = run(new StatusCommand(product, docker), "--profile", "team alpha"); + assertTrue(status.out().contains("start --profile 'team alpha'"), status.out()); + } + } + @Test + void aFailedPullKeepsTheWholeStartInvocation() throws Exception { + FakeDocker docker = new FakeDocker() { + @Override public void pull(String image, String policy) throws DockerException { throw new DockerException("no such image"); } + @Override public void pull(String image, String policy, PrintStream stream) throws DockerException { throw new DockerException("no such image"); } + }; + Run start = run(new StartCommand(ProductProfile.AWS, docker), "--container", "other", "--port", "14566", + "--image", "my image:1", "--pull", "always"); + assertEquals(1, start.exit()); + assertTrue(start.err().contains("floci start --pull never --container other --port 14566 --image 'my image:1'"), start.err()); + } + @Test + void envLoadHintsPreserveTheProfileInAllFourTrees() throws Exception { + FakeDocker docker = new FakeDocker(); + for (Callable env : List.>of(new EnvCommand(docker), new GcpEnvCommand(docker), + new OciEnvCommand(docker), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, docker))) { + Run result = run(env, "--profile", "team alpha"); + assertEquals(0, result.exit(), result.err()); + assertTrue(result.out().contains("env --profile 'team alpha' -o text"), result.out()); + } + } + @Test + void envLoadHintsQuoteForTheShellTheyAreFor() throws Exception { + Files.writeString(temp.resolve("team's.yaml"), "container: other\nendpoint: http://127.0.0.1:1\n"); + for (Callable env : List.>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()), + new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) { + assertTrue(run(env, "--profile", "team's").out().contains("--profile 'team'\\''s' -o text)\"")); + } + for (Callable env : List.>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()), + new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) { + String out = run(env, "--profile", "team's", "--shell", "powershell").out(); + assertTrue(out.contains("--profile 'team''s' -o text --shell powershell | Invoke-Expression"), out); + } + for (Callable env : List.>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()), + new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) { + String out = run(env, "--profile", "team's", "--shell", "fish").out(); + assertTrue(out.contains("--profile 'team\\'s' -o text --shell fish | source"), out); + } + } + private List> allEnvCommands() { + return List.of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()), new OciEnvCommand(new FakeDocker()), + new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker())); + } + @Test + void aValueWithALineBreakCannotEscapeTheHintComment() throws Exception { + for (String breaker : List.of("\n", "\r", "\u0085", "\u2028", "\u2029")) { + for (String shell : List.of("bash", "fish", "powershell")) { + for (Callable env : allEnvCommands()) { + Run result = run(env, "--container", "x" + breaker + "touch injected" + breaker + "#", + "--endpoint", "http://localhost:1", "--shell", shell); + assertEquals(0, result.exit(), result.err()); + assertFalse(result.out().contains("touch injected"), result.out()); + assertTrue(result.out().contains("--container "), result.out()); + } + } + } + } + @Test + void nonPosixShellsQuoteEvenAPlainValue() throws Exception { + for (Callable env : allEnvCommands()) { + String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1", "--shell", "powershell").out(); + assertTrue(out.contains("--container '@team'"), out); + } + for (Callable env : allEnvCommands()) { + String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1", "--shell", "fish").out(); + assertTrue(out.contains("--container '@team'"), out); + } + for (Callable env : allEnvCommands()) { + String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1").out(); + assertTrue(out.contains("--container @team"), out); + } + } + @Test + void aProfileThatAsksForJsonStillGetsALoadableHint() throws Exception { + Files.writeString(temp.resolve("json.yaml"), "container: other\nendpoint: http://127.0.0.1:1\noutput: json\n"); + String out = run(new EnvCommand(new FakeDocker()), "--profile", "json", "-o", "text").out(); + assertTrue(out.contains("eval \"$(floci env --profile json -o text)\""), out); + } + @Test + void aLoadHintWithoutAProfileStaysBare() throws Exception { + assertTrue(run(new EnvCommand(new FakeDocker())).out().contains("eval \"$(floci env)\"")); + } + @Test + void doctorPassesTheSelectorToCheckFixesInStructuredOutput() throws Exception { + for (ProductProfile product : PRODUCTS) { + FakeDocker docker = new FakeDocker(); + DoctorCommand doctor = new DoctorCommand(product, docker, List.of(new ContainerRunningCheck(docker, product), new ImagePresentCheck(product, docker))); + Run result = run(doctor, "--profile", "team alpha", "--container", "override", "--json"); + assertEquals(1, result.exit()); + assertEquals(2, result.out().split("--profile 'team alpha' --container override", -1).length - 1, result.out()); + } + } +} diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 5582df3..b3038ab 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -294,7 +294,7 @@ class StartPreflightTest { assertEquals(1, r.exit()); assertTrue(r.err().contains("Failed to start container: docker: Error response from daemon"), r.err()); - assertTrue(r.err().strip().endsWith("Run 'floci gcp doctor' to check Docker, the image and the port."), r.err()); + assertTrue(r.err().strip().endsWith("Run 'floci gcp doctor --container floci-gcp-preflight' to check Docker, the image and the port."), r.err()); } /** A context selected with DOCKER_CONTEXT or 'docker context use' is not in the environment: docker is asked. */