fix(env): show how to load the variables in the chosen shell and reject unknown shells (#46)

The closing hint of floci env (all four products) now uses source for fish and Invoke-Expression for PowerShell instead of always suggesting eval, and an unknown --shell exits 2 with the accepted values instead of silently printing bash syntax. zsh, sh and pwsh are accepted by name.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-09 22:17:21 -05:00
1 parent 030d468fd3
commit fbdc3ef713
7 files changed
+119 -15

No files matched your search

@@ -1,5 +1,7 @@
package io.floci.cli.output;
import java.util.Set;
/**
* Renders {@code export KEY=VALUE} lines for the {@code env} commands of every product tree.
*
@@ -10,9 +12,33 @@ package io.floci.cli.output;
*/
public final class ShellExport {
/** The {@code --shell} values the env commands accept. */
public static final Set<String> SHELLS = Set.of("bash", "zsh", "sh", "fish", "powershell", "pwsh", "ps1");
private ShellExport() {
}
public static boolean isSupported(String shell) {
return shell != null && SHELLS.contains(shell.toLowerCase());
}
/** The error for an unsupported {@code --shell}, ending with what to pass instead. */
public static String unsupported(String shell) {
return "Unknown shell '" + shell + "'.\nUse --shell bash, zsh, sh, fish or powershell.";
}
/**
* How to load {@code command}'s output in the given shell: {@code eval} only works in POSIX
* shells, fish and PowerShell read the lines from a pipe instead.
*/
public static String loadHint(String shell, String command) {
return switch (shell.toLowerCase()) {
case "fish" -> command + " --shell fish | source";
case "powershell", "pwsh", "ps1" -> command + " --shell powershell | Invoke-Expression";
default -> "eval \"$(" + command + ")\"";
};
}
/** 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()) {
@@ -20,7 +46,7 @@ public final class ShellExport {
case "fish" -> "set -x " + key + " '"
+ value.replace("\\", "\\\\").replace("'", "\\'") + "'";
// PowerShell single quotes: literal except '' for a quote
case "powershell", "ps1" -> "$env:" + key + " = '" + value.replace("'", "''") + "'";
case "powershell", "pwsh", "ps1" -> "$env:" + key + " = '" + value.replace("'", "''") + "'";
// POSIX single quotes: close, escaped quote, reopen
default -> "export " + key + "='" + value.replace("'", "'\\''") + "'";
};
@@ -30,7 +56,7 @@ public final class ShellExport {
public static String formatUnset(String shell, String key) {
return switch (shell.toLowerCase()) {
case "fish" -> "set -e " + key;
case "powershell", "ps1" -> "Remove-Item Env:" + key + " -ErrorAction SilentlyContinue";
case "powershell", "pwsh", "ps1" -> "Remove-Item Env:" + key + " -ErrorAction SilentlyContinue";
default -> "unset " + key;
};
}