diff --git a/plugin.json b/plugin.json index 780db64..1a45c22 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.1.1", + "version": "1.1.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, lookups in the published docs, and the Floci MCP server for agent tools.", "author": { "name": "Floci", diff --git a/skills/floci/scripts/ensure-running.sh b/skills/floci/scripts/ensure-running.sh index b72f41d..388d5dc 100755 --- a/skills/floci/scripts/ensure-running.sh +++ b/skills/floci/scripts/ensure-running.sh @@ -47,7 +47,7 @@ case "$state" in "not found") start ;; - "") + ""|error:*) echo "could not read the state of floci $tree${profile:+ ($profile)}; run 'floci $tree doctor'" >&2 exit 1 ;; diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index c9c2af4..38eed3b 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -106,7 +106,7 @@ public class UpdateCommand implements Callable { printer.error("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); return ExitCode.USAGE; } - String target = pinned ? to.trim() : fetchLatestVersion(); + String target = pinned ? Version.normalize(to.trim()) : fetchLatestVersion(); // Unpinned updates are semantic, not string-equal: a pre-release/snapshot build // (0.1.9-rc.1) must not be silently downgraded to the latest stable (0.1.8). diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java index d8ffe49..4fc4536 100644 --- a/src/main/java/io/floci/cli/docker/DockerClient.java +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -14,6 +14,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -180,7 +181,8 @@ public class DockerClient { try { out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name); } catch (DockerException e) { - if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) { + String message = e.getMessage() == null ? "" : e.getMessage().toLowerCase(Locale.ROOT); + if (message.contains("no such container") || message.contains("no such object")) { return Optional.empty(); } throw e; diff --git a/src/main/java/io/floci/cli/update/Version.java b/src/main/java/io/floci/cli/update/Version.java index 94b0944..b4f2afd 100644 --- a/src/main/java/io/floci/cli/update/Version.java +++ b/src/main/java/io/floci/cli/update/Version.java @@ -16,6 +16,11 @@ public final class Version { return s != null && SHAPE.matcher(s).matches(); } + /** Canonical spelling of a validated version, without its optional leading "v". */ + public static String normalize(String version) { + return version.startsWith("v") ? version.substring(1) : version; + } + /** Numeric compare of the x.y.z core; a pre-release suffix on equal cores sorts older. */ public static boolean isNewer(String candidate, String current) { if (!isValid(candidate) || !isValid(current)) { @@ -33,8 +38,7 @@ public final class Version { } private static int[] core(String v) { - String stripped = v.startsWith("v") ? v.substring(1) : v; - String[] parts = stripped.split("[-+]", 2)[0].split("\\."); + String[] parts = normalize(v).split("[-+]", 2)[0].split("\\."); return new int[]{Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2])}; } diff --git a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java index 343640b..308e287 100644 --- a/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java +++ b/src/test/java/io/floci/cli/unit/DockerClientProcessTest.java @@ -370,15 +370,40 @@ class DockerClientProcessTest { assertEquals("", DockerClient.publishedPorts(new ObjectMapper().readTree("{}"))); } + @ParameterizedTest + @ValueSource(strings = { + "Error response from daemon: No such container: floci", + "Error: inspecting object: no such container \"floci\"", + "Error: No such object: floci" + }) + @DisabledOnOs(OS.WINDOWS) + void aMissingContainerIsEmpty(String diagnostic) throws Exception { + DockerClient docker = new DockerClient(fakeDocker("echo '" + diagnostic + "' >&2\nexit 1\n")); + + assertTrue(docker.inspectContainer("floci").isEmpty()); + assertTrue(docker.inspectRunSettings("floci", 4566).isEmpty()); + } + + @ParameterizedTest + @ValueSource(strings = { + "error during connect: dial unix /var/run/docker.sock: connect: no such file or directory", + "error during connect: dial tcp: lookup docker.example: no such host", + "permission denied while trying to connect to the Docker daemon socket", + "error during connect: dial tcp 127.0.0.1:2375: connect: connection refused" + }) + @DisabledOnOs(OS.WINDOWS) + void aFailedInspectionIsNotAMissingContainer(String diagnostic) throws Exception { + DockerClient docker = new DockerClient(fakeDocker("echo '" + diagnostic + "' >&2\nexit 1\n")); + + DockerException containerError = assertThrows(DockerException.class, () -> docker.inspectContainer("floci")); + assertEquals(diagnostic, containerError.getMessage()); + DockerException settingsError = assertThrows(DockerException.class, () -> docker.inspectRunSettings("floci", 4566)); + assertEquals(diagnostic, settingsError.getMessage()); + } + @Test @DisabledOnOs(OS.WINDOWS) - void aMissingContainerIsEmptyAndGarbageIsReportedWithANextStep() throws Exception { - Path missing = Files.createTempFile(tempDir, "docker", ""); - Files.writeString(missing, "#!/bin/sh\necho 'Error response from daemon: No such container: floci' >&2\nexit 1\n"); - assertTrue(missing.toFile().setExecutable(true)); - - assertTrue(new DockerClient(missing.toString()).inspectContainer("floci").isEmpty()); - + void garbageIsReportedWithANextStep() throws Exception { DockerException e = assertThrows(DockerException.class, () -> dockerPrinting("not json").inspectContainer("floci")); assertTrue(e.getMessage().contains("Could not read the details of container 'floci'"), e.getMessage()); assertTrue(e.getMessage().contains("docker info"), e.getMessage()); diff --git a/src/test/java/io/floci/cli/unit/EnsureRunningScriptTest.java b/src/test/java/io/floci/cli/unit/EnsureRunningScriptTest.java new file mode 100644 index 0000000..6f9f631 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/EnsureRunningScriptTest.java @@ -0,0 +1,86 @@ +package io.floci.cli.unit; + +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +/** The skill must not offer to replace a container whose state Docker could not read. */ +@DisabledOnOs(OS.WINDOWS) +class EnsureRunningScriptTest { + + @TempDir + Path tempDir; + + @ParameterizedTest + @CsvSource({ + "aws, error: cannot connect to Docker, false, 1, false", + "aws, error: cannot connect to Docker, true, 1, false", + "gcp, error: cannot connect to Docker, false, 1, false", + "gcp, error: cannot connect to Docker, true, 1, false", + "az, error: cannot connect to Docker, false, 1, false", + "az, error: cannot connect to Docker, true, 1, false", + "oci, error: cannot connect to Docker, false, 1, false", + "oci, error: cannot connect to Docker, true, 1, false", + "aws, '', false, 1, false", + "aws, '', true, 1, false", + "aws, running, false, 0, false", + "aws, not found, false, 0, true", + "aws, exited, false, 3, false", + "aws, exited, true, 0, true" + }) + void handlesContainerStateWithoutReplacingAnUnknownContainer( + String tree, String state, boolean replace, int expectedExit, boolean expectedStart) throws Exception { + Path bin = Files.createDirectory(tempDir.resolve("bin")); + Path floci = bin.resolve("floci"); + Files.writeString(floci, """ + #!/usr/bin/env bash + case "$2" in + status) + printf '{"state":"%s"}\n' "$TEST_STATE" + [[ "$TEST_STATE" == running ]] && exit 0 + exit 1 + ;; + start) touch "$TEST_STARTED" ;; + wait) exit 0 ;; + env) echo "export AWS_ENDPOINT_URL='http://localhost:4566'" ;; + *) exit 99 ;; + esac + """); + assertTrue(floci.toFile().setExecutable(true)); + Path started = tempDir.resolve("started"); + Path stdout = tempDir.resolve("stdout"); + Path stderr = tempDir.resolve("stderr"); + ProcessBuilder builder = new ProcessBuilder("bash", + Path.of("skills/floci/scripts/ensure-running.sh").toAbsolutePath().toString(), tree); + var env = builder.environment(); + env.keySet().removeIf(name -> name.startsWith("FLOCI_")); + env.put("PATH", bin + File.pathSeparator + env.get("PATH")); + env.put("TEST_STATE", state); + env.put("TEST_STARTED", started.toString()); + if (replace) env.put("FLOCI_REPLACE_STOPPED", "1"); + Process process = builder.redirectOutput(stdout.toFile()).redirectError(stderr.toFile()).start(); + try { + assertTrue(process.waitFor(10, TimeUnit.SECONDS), "ensure-running.sh did not finish"); + String err = Files.readString(stderr); + assertEquals(expectedExit, process.exitValue(), err); + assertEquals(expectedStart, Files.exists(started), "whether a container was started"); + assertEquals(expectedExit == 0 ? "export AWS_ENDPOINT_URL='http://localhost:4566'\n" : "", + Files.readString(stdout)); + if (state.isEmpty() || state.startsWith("error:")) { + assertTrue(err.contains("floci " + tree + " doctor"), err); + assertFalse(err.contains("FLOCI_REPLACE_STOPPED"), err); + } + } finally { + process.destroyForcibly(); + } + } +} diff --git a/src/test/java/io/floci/cli/unit/UpdateCommandTest.java b/src/test/java/io/floci/cli/unit/UpdateCommandTest.java index b174019..db508b3 100644 --- a/src/test/java/io/floci/cli/unit/UpdateCommandTest.java +++ b/src/test/java/io/floci/cli/unit/UpdateCommandTest.java @@ -125,11 +125,12 @@ class UpdateCommandTest { } } - @Test - void replacesTheBinaryWithTheVerifiedDownload() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"", "99.0.0", "v99.0.0", " v99.0.0 "}) + void replacesTheBinaryWithTheVerifiedDownload(String version) throws Exception { Path binary = installed(tempDir.resolve("bin")); - Run r = update(binary); + Run r = version.isEmpty() ? update(binary) : update(binary, "--version", version); assertEquals(0, r.exit(), r.err()); assertArrayEquals(FRESH, Files.readAllBytes(binary)); @@ -179,6 +180,36 @@ class UpdateCommandTest { assertEquals(List.of(), downloads); } + @ParameterizedTest + @ValueSource(strings = {"", "v", " v"}) + void pinningTheCurrentVersionDoesNotDownloadOrReplaceIt(String prefix) throws Exception { + Path binary = installed(tempDir.resolve("bin")); + String version = prefix + CliVersion.CLI_VERSION + " "; + + for (String[] args : List.of(new String[]{"--version", version}, + new String[]{"--check", "--version", version})) { + Run r = update(binary, args); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("is up to date"), r.out()); + assertEquals(List.of(), downloads); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + } + + @ParameterizedTest + @ValueSource(strings = {"0.1.0", "v0.1.0"}) + void anExplicitOlderVersionIsStillOffered(String version) throws Exception { + Path binary = installed(tempDir.resolve("bin")); + + Run r = update(binary, "--check", "--version", version); + + assertEquals(1, r.exit(), r.err()); + assertTrue(r.out().contains("update available"), r.out()); + assertEquals(List.of(), downloads); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + @Test void aHomebrewInstallIsLeftToBrew() throws Exception { Path binary = installed(tempDir.resolve("Cellar").resolve("floci").resolve("0.3.0").resolve("bin"));