fix(completion): offer only bash and zsh, the shells a script is generated for (#59)

The help listed fish and powershell, which only produced an error; an unsupported shell is now a usage error (exit 2) with nothing on stdout. Container details are read from docker's inspect JSON instead of a pipe-delimited template, which a value containing the delimiter could shift.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-11 08:58:31 -05:00
1 parent bd4fa0f134
commit 804e355936
5 files changed
+198 -28

No files matched your search

+2
View File
@@ -844,6 +844,8 @@ floci completion bash >> ~/.bashrc
floci completion zsh >> ~/.zshrc
```
Completion scripts are generated for bash and zsh. Any other shell name is a usage error (exit 2).
### `floci update`
Self-update the CLI in place: downloads the release binary from GitHub, verifies its
@@ -21,7 +21,9 @@ public class CompletionCommand implements Callable<Integer> {
@Spec
Model.CommandSpec spec;
@Parameters(index = "0", description = "Shell type: bash, zsh, fish, powershell", paramLabel = "bash|zsh|fish|powershell")
// Only the shells a script is generated for: picocli writes bash completion, which zsh loads
// through bashcompinit. Listing fish and powershell here promised scripts that do not exist.
@Parameters(index = "0", description = "Shell type: bash or zsh", paramLabel = "bash|zsh")
String shell;
@Override
@@ -36,13 +38,13 @@ public class CompletionCommand implements Callable<Integer> {
case "bash" -> AutoComplete.bash("floci", root);
case "zsh" -> AutoComplete.bash("floci", root); // zsh is bash-compatible; picocli bash script works for zsh too
default -> {
printer.error("Shell '" + shell + "' not supported. Supported: bash, zsh\n" +
"For fish and powershell, track https://github.com/floci-io/floci-cli/issues");
printer.error("Shell '" + shell + "' is not supported.\nUse bash or zsh.");
yield null;
}
};
if (script == null) return 1;
// A value the command cannot accept, like any other bad argument.
if (script == null) return ExitCode.USAGE;
System.out.print(script);
return 0;
}
@@ -67,18 +67,10 @@ public class DockerClient {
private static final ObjectMapper JSON = new ObjectMapper();
public Optional<RunSettings> inspectRunSettings(String name, int containerPort) throws DockerException {
String out;
Optional<JsonNode> document = inspectDocument(name);
if (document.isEmpty()) return Optional.empty();
try {
out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name);
} catch (DockerException e) {
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) {
return Optional.empty();
}
throw e;
}
if (out.isBlank()) return Optional.empty();
try {
JsonNode c = JSON.readTree(out);
JsonNode c = document.get();
String image = textOrNull(c.path("Config").path("Image"));
Integer hostPort = null;
JsonNode binding = c.path("HostConfig").path("PortBindings").path(containerPort + "/tcp");
@@ -133,26 +125,56 @@ public class DockerClient {
}
public Optional<ContainerInfo> inspectContainer(String name) throws DockerException {
Optional<JsonNode> document = inspectDocument(name);
if (document.isEmpty()) return Optional.empty();
JsonNode c = document.get();
String reported = c.path("Name").asText("").replaceFirst("^/", "");
return Optional.of(new ContainerInfo(
c.path("Id").asText(""),
reported.isBlank() ? name : reported,
c.path("Config").path("Image").asText(""),
c.path("State").path("Status").asText(""),
publishedPorts(c.path("NetworkSettings").path("Ports"))));
}
/**
* The published ports of an inspect document as {@code "14566->4566/tcp 18080->8080/tcp"}:
* host port, then the container side. A port that is exposed but not published has no
* binding and is left out.
*/
public static String publishedPorts(JsonNode ports) {
StringBuilder published = new StringBuilder();
for (var port : ports.properties()) {
JsonNode bindings = port.getValue();
if (!bindings.isArray() || bindings.isEmpty()) continue;
String hostPort = bindings.get(0).path("HostPort").asText("");
if (hostPort.isBlank()) continue;
if (!published.isEmpty()) published.append(' ');
published.append(hostPort).append("->").append(port.getKey());
}
return published.toString();
}
// The container's whole inspect document, or empty when there is no such container. One
// JSON read serves every caller; a field-by-field Go template had to be split on a
// delimiter, which a value could contain.
private Optional<JsonNode> inspectDocument(String name) throws DockerException {
String out;
try {
String out = run("docker", "container", "inspect",
"--format",
"{{.Id}}|{{.Name}}|{{.Config.Image}}|{{.State.Status}}|" +
"{{range $p, $b := .NetworkSettings.Ports}}{{if $b}}{{(index $b 0).HostPort}}->{{$p}} {{end}}{{end}}",
"--", name);
if (out.isBlank()) return Optional.empty();
String[] parts = out.trim().split("\\|", -1);
return Optional.of(new ContainerInfo(
parts.length > 0 ? parts[0] : "", // id
parts.length > 1 ? parts[1].replaceFirst("^/", "") : name,
parts.length > 2 ? parts[2] : "", // image
parts.length > 3 ? parts[3] : "", // status
parts.length > 4 ? parts[4].trim() : "")); // ports
out = run("docker", "container", "inspect", "--format", "{{json .}}", "--", name);
} catch (DockerException e) {
if (e.getMessage() != null && e.getMessage().toLowerCase().contains("no such")) {
return Optional.empty();
}
throw e;
}
if (out.isBlank()) return Optional.empty();
try {
return Optional.of(JSON.readTree(out));
} catch (Exception e) {
throw new DockerException("Could not read the details of container '" + name + "': " + e.getMessage()
+ "\n" + CHECK_DOCKER);
}
}
public boolean isImagePresent(String image) throws DockerException {
@@ -0,0 +1,72 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/** BL-054: completion offers the shells it can generate a script for, and only those. */
class CompletionCommandTest {
@TempDir
Path tempDir;
private record Run(int exit, String out, String err) {}
private Run run(String... args) {
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(args);
return new Run(exit, outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
@Test
void theHelpListsOnlyTheShellsThatWork() {
CommandLine completion = FlociCli.buildCommandLine(new ProfileStore(tempDir)).getSubcommands().get("completion");
assertEquals("bash|zsh", completion.getCommandSpec().positionalParameters().get(0).paramLabel());
String usage = completion.getUsageMessage(CommandLine.Help.Ansi.OFF);
assertFalse(usage.contains("fish"), usage);
assertFalse(usage.contains("powershell"), usage);
}
@ParameterizedTest
@ValueSource(strings = {"bash", "zsh", "BASH"})
void aSupportedShellGetsAScript(String shell) {
Run r = run("completion", shell);
assertEquals(0, r.exit(), r.err());
assertTrue(r.out().contains("floci"), "a completion script for the floci command");
assertEquals("", r.err());
}
/** A shell there is no script for is a usage error, and nothing is written to stdout to be sourced. */
@ParameterizedTest
@ValueSource(strings = {"fish", "powershell", "nushell"})
void anUnsupportedShellIsAUsageError(String shell) {
Run r = run("completion", shell);
assertEquals(2, r.exit());
assertEquals("", r.out());
assertTrue(r.err().contains("Shell '" + shell + "' is not supported."), r.err());
assertTrue(r.err().contains("Use bash or zsh."), r.err());
}
}
@@ -1,5 +1,7 @@
package io.floci.cli.unit;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.cli.GlobalOptions;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
@@ -271,4 +273,74 @@ class DockerClientProcessTest {
assertTrue(errBuf.toString().contains("+ docker rm"), errBuf.toString());
assertTrue(errBuf.toString().contains("floci-x"), errBuf.toString());
}
private DockerClient dockerPrinting(String inspectJson) throws Exception {
Path json = Files.createTempFile(tempDir, "inspect", ".json");
Files.writeString(json, inspectJson);
Path fakeDocker = Files.createTempFile(tempDir, "docker", "");
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
assertTrue(fakeDocker.toFile().setExecutable(true));
return new DockerClient(fakeDocker.toString());
}
/** BL-046: container details come from the inspect document, not from a delimiter-split template. */
@Test
@DisabledOnOs(OS.WINDOWS)
void containerDetailsAreReadFromTheInspectDocument() throws Exception {
DockerClient docker = dockerPrinting("""
{"Id":"0123abcd","Name":"/floci-team-b","Config":{"Image":"floci/floci:1.6.0"},
"State":{"Status":"running"},
"NetworkSettings":{"Ports":{"4566/tcp":[{"HostIp":"0.0.0.0","HostPort":"14566"},{"HostIp":"::","HostPort":"14566"}],
"8080/tcp":null}}}
""");
DockerClient.ContainerInfo info = docker.inspectContainer("floci-team-b").orElseThrow();
assertEquals("0123abcd", info.id());
assertEquals("floci-team-b", info.name());
assertEquals("floci/floci:1.6.0", info.image());
assertEquals("running", info.state());
assertEquals("14566->4566/tcp", info.ports());
}
/** A value with the old delimiter in it cannot shift the fields any more. */
@Test
@DisabledOnOs(OS.WINDOWS)
void aPipeInAValueDoesNotShiftTheFields() throws Exception {
DockerClient docker = dockerPrinting("""
{"Id":"0123abcd","Name":"/floci","Config":{"Image":"registry.local/team|floci:latest"},
"State":{"Status":"exited"},"NetworkSettings":{"Ports":{}}}
""");
DockerClient.ContainerInfo info = docker.inspectContainer("floci").orElseThrow();
assertEquals("registry.local/team|floci:latest", info.image());
assertEquals("exited", info.state());
assertEquals("", info.ports());
}
@Test
void publishedPortsListEveryBindingAndSkipWhatIsNotPublished() throws Exception {
JsonNode ports = new ObjectMapper().readTree("""
{"4566/tcp":[{"HostIp":"","HostPort":"14566"}],"8080/tcp":null,"9000/tcp":[],
"4510/tcp":[{"HostIp":"","HostPort":"24510"}]}
""");
assertEquals("14566->4566/tcp 24510->4510/tcp", DockerClient.publishedPorts(ports));
assertEquals("", DockerClient.publishedPorts(new ObjectMapper().readTree("{}")));
}
@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());
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());
}
}