diff --git a/README.md b/README.md index 493bf7c..40a8dc3 100644 --- a/README.md +++ b/README.md @@ -957,6 +957,8 @@ floci completion zsh >> ~/.zshrc ``` Completion scripts are generated for bash and zsh. Any other shell name is a usage error (exit 2). +The zsh script loads the bash completion through `bashcompinit` and sets up `floci` only: your shell +options and aliases are left as they were. ### `floci update` diff --git a/src/main/java/io/floci/cli/commands/CompletionCommand.java b/src/main/java/io/floci/cli/commands/CompletionCommand.java index a70de55..72a477e 100644 --- a/src/main/java/io/floci/cli/commands/CompletionCommand.java +++ b/src/main/java/io/floci/cli/commands/CompletionCommand.java @@ -6,6 +6,7 @@ import picocli.AutoComplete; import picocli.CommandLine; import picocli.CommandLine.*; +import java.util.List; import java.util.concurrent.Callable; @Command( @@ -36,7 +37,8 @@ public class CompletionCommand implements Callable { String script = switch (shell.toLowerCase()) { case "bash" -> AutoComplete.bash("floci", root); - case "zsh" -> AutoComplete.bash("floci", root); // zsh is bash-compatible; picocli bash script works for zsh too + // zsh loads picocli's bash script through bashcompinit. + case "zsh" -> forZsh(AutoComplete.bash("floci", root)); default -> { printer.error("Shell '" + shell + "' is not supported.\nUse bash or zsh."); yield null; @@ -48,4 +50,27 @@ public class CompletionCommand implements Callable { System.out.print(script); return 0; } + + /** + * Lines picocli's script runs at the top level of a zsh, which change the user's shell rather + * than floci's completion (#82). {@code COMPLETE_ALIASES} stays on for the whole shell, so every + * alias completes as a command of its own instead of as what it stands for. The {@code compopt} + * alias is left behind too, and it gets expanded into the completion functions as + * {@code complete +o default}, which bashcompinit's {@code complete} turns into completions for + * commands named {@code +o} and {@code default}. Neither does anything for floci's own + * completion: bashcompinit has no {@code compopt}, and the functions skip it when it is absent. + */ + public static final List ZSH_SHELL_CHANGES = List.of(" setopt COMPLETE_ALIASES", " alias compopt=complete"); + + /** {@code bashScript} without {@link #ZSH_SHELL_CHANGES}. */ + public static String forZsh(String bashScript) { + StringBuilder out = new StringBuilder(bashScript.length()); + for (String line : bashScript.split("\n", -1)) { + if (ZSH_SHELL_CHANGES.contains(line.stripTrailing())) continue; + out.append(line).append('\n'); + } + // split(-1) yields a final empty element for a trailing newline; drop the one it added. + out.setLength(out.length() - 1); + return out.toString(); + } } diff --git a/src/test/java/io/floci/cli/unit/ZshCompletionTest.java b/src/test/java/io/floci/cli/unit/ZshCompletionTest.java new file mode 100644 index 0000000..25a56ff --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ZshCompletionTest.java @@ -0,0 +1,127 @@ +package io.floci.cli.unit; + +import io.floci.cli.FlociCli; +import io.floci.cli.commands.CompletionCommand; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.Test; +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.ValueSource; +import picocli.AutoComplete; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** #82: sourcing the zsh script sets up floci's completion and changes nothing else in the shell. */ +class ZshCompletionTest { + + @TempDir + Path tempDir; + + private String script(String shell) { + PrintStream out = System.out; + ByteArrayOutputStream buf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(buf)); + try { + assertEquals(0, FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute("completion", shell)); + } finally { + System.setOut(out); + } + return buf.toString(StandardCharsets.UTF_8); + } + + private String picocliScript() { + return AutoComplete.bash("floci", FlociCli.buildCommandLine(new ProfileStore(tempDir))); + } + + /** + * Guards the filter itself: if a picocli upgrade rewords these lines, the removal silently stops + * matching. This fails first, so the change is looked at instead of shipped. + */ + @Test + void picocliStillEmitsTheLinesThatAreRemoved() { + List lines = picocliScript().lines().toList(); + + for (String change : CompletionCommand.ZSH_SHELL_CHANGES) { + assertTrue(lines.contains(change), "picocli no longer emits '" + change.strip() + "'"); + } + } + + @Test + void theZshScriptIsPicocliWithoutThoseLines() { + String zsh = script("zsh"); + + for (String change : CompletionCommand.ZSH_SHELL_CHANGES) { + assertFalse(zsh.lines().anyMatch(change::equals), change); + } + List expected = picocliScript().lines() + .filter(line -> !CompletionCommand.ZSH_SHELL_CHANGES.contains(line)).toList(); + assertEquals(expected, zsh.lines().toList()); + assertTrue(zsh.contains("autoload -U +X bashcompinit && bashcompinit"), "zsh still loads bash completion"); + assertTrue(zsh.endsWith("\n") == picocliScript().endsWith("\n"), "the final newline is kept as picocli wrote it"); + } + + @Test + void theBashScriptIsUnchanged() { + assertEquals(picocliScript(), script("bash")); + } + + @ParameterizedTest + @ValueSource(strings = {"unsetopt", "setopt"}) + @DisabledOnOs(OS.WINDOWS) + void sourcingItLeavesTheShellAsItWas(String completeAliases) throws Exception { + assumeTrue(Files.isExecutable(Path.of("/bin/zsh")) || onPath("zsh"), "zsh is not installed"); + Path completion = tempDir.resolve("floci.zsh"); + Files.writeString(completion, script("zsh")); + String probe = String.join("\n", + "autoload -U compinit && compinit -u -d " + tempDir.resolve("zcompdump"), + completeAliases + " COMPLETE_ALIASES", + "alias mr='mise run'", + "before=$([[ -o completealiases ]] && echo on || echo off)", + "source " + completion, + "comps=${#_comps}", + // A completion run under the old script registered '+o' and 'default' here. + "COMP_WORDS=(floci start --pull ''); COMP_CWORD=3; _picocli_floci_start", + "print -r -- \"before=$before\"", + "print -r -- \"after=$([[ -o completealiases ]] && echo on || echo off)\"", + "print -r -- \"compopt=$(alias compopt >/dev/null && echo alias || echo none)\"", + "print -r -- \"mr=${aliases[mr]}\"", + "print -r -- \"comps=$(( ${#_comps} - comps ))\"", + "print -r -- \"floci=${_comps[floci]}\"", + "print -r -- \"start=${#COMPREPLY}\""); + + Process zsh = new ProcessBuilder("zsh", "-f", "-c", probe).redirectErrorStream(true).start(); + assertTrue(zsh.waitFor(30, TimeUnit.SECONDS), "zsh did not finish"); + String out = new String(zsh.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + List lines = out.lines().toList(); + + String expected = completeAliases.equals("setopt") ? "on" : "off"; + assertTrue(lines.contains("before=" + expected), out); + assertTrue(lines.contains("after=" + expected), out); + assertTrue(lines.contains("compopt=none"), out); + assertTrue(lines.contains("mr=mise run"), out); + assertTrue(lines.contains("comps=0"), out); + assertTrue(lines.contains("floci=_bash_complete -F _complete_floci -o default"), out); + assertTrue(lines.stream().anyMatch(l -> l.startsWith("start=") && !l.equals("start=0")), out); + } + + private static boolean onPath(String command) { + String path = System.getenv("PATH"); + if (path == null) return false; + for (String dir : path.split(File.pathSeparator)) { + if (Files.isExecutable(Path.of(dir, command))) return true; + } + return false; + } +}