diff --git a/AGENTS.md b/AGENTS.md index 2a3bf2f..e1de8df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,6 +99,23 @@ To add a check: create a class in `doctor/checks/`, then add it to `dockerChecks `ProfileStore` reads/writes YAML files under `~/.floci/profiles/.yaml` via Jackson. `Profile` is a plain bean — keep it `@JsonIgnoreProperties(ignoreUnknown = true)` to stay forward-compatible. The store is shared by all four product trees (no per-product namespacing). `GlobalConfigStore` persists `~/.floci/config.yaml` (currently just `default-product`). +**`--profile` is applied by exactly one class — do not add per-command profile reads.** `ProfileDefaultValueProvider` is a picocli `IDefaultValueProvider` registered once in `FlociCli.buildCommandLine(...)`; picocli propagates it to the whole subcommand tree and consults it *only* for options the user did not pass, *after* that command's arguments have been processed. That yields the documented precedence for free: + +``` +command-line flag > --profile > FLOCI_* env var > product default +``` + +(the env var and product default are the `GlobalOptions` field initial values, which picocli keeps whenever the provider returns `null`). + +Rules when touching this: + +- The field→flag mapping lives in `ProfileDefaults.valueFor` as a pure function, matched on **exact** option names. `--service` (wait/logs/env) is not `--services`; `--profile-name` (`floci oci setup`) is not `--profile`. +- The provider is called for positionals and for commands with no `GlobalOptions` mixin (`update`, the group commands, the root) — both guards must stay. +- Register it **programmatically**. The annotation form `@Command(defaultValueProvider = ...)` makes picocli instantiate it reflectively and would need a `reflect-config.json` entry. +- A bad profile throws `ProfileNotFoundException` (a `ParameterException`), which `FlociCli`'s parameter-exception handler renders without a usage dump and exits 2. The provider returns `null` when `-h`/`-V` was requested so `--help` still works. +- Commands that build another command programmatically (`RestartCommand` → `StartCommand`) are never parsed by picocli, so they must carry the profile across by hand. +- Use `FlociCli.buildCommandLine(ProfileStore)` in tests — `new CommandLine(new FlociCli())` has none of the wiring. + ### Self-update `UpdateCommand` (`floci update`) downloads the release binary for the current platform, verifies its sha256 against the release's `sha256sums.txt`, and atomically replaces the running binary (staged in the same directory, `ATOMIC_MOVE`). It refuses to update Homebrew-managed installs. `--check` exits 0 when up to date, 1 when an update is available. `ReleaseChannel` builds the GitHub release asset URLs. diff --git a/README.md b/README.md index 7dde45c..0ac26b7 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,8 @@ All commands support `--help`. --profile Load settings from ~/.floci/profiles/.yaml ``` +Explicit flags override the profile; the profile overrides the environment variables. + ### GCP global flags ``` @@ -286,6 +288,8 @@ All commands support `--help`. --profile Load settings from ~/.floci/profiles/.yaml ``` +Explicit flags override the profile; the profile overrides the environment variables. + ### Azure global flags ``` @@ -298,6 +302,8 @@ All commands support `--help`. --profile Load settings from ~/.floci/profiles/.yaml ``` +Explicit flags override the profile; the profile overrides the environment variables. + ### OCI global flags ``` @@ -310,6 +316,8 @@ All commands support `--help`. --profile Load settings from ~/.floci/profiles/.yaml ``` +Explicit flags override the profile; the profile overrides the environment variables. + > **Port auto-detection** — `status`, `version`, `wait`, and `env` automatically derive the correct > endpoint from the container's port mapping. You don't need to pass `--endpoint` when using > a non-default port, as long as `--container` points to the right container. @@ -569,8 +577,56 @@ floci config profile delete # delete a profile floci config validate -f docker-compose.yml # validate a Compose file ``` -Profiles are stored in `~/.floci/profiles/.yaml` and can override any global option. -Use `--profile ` on any command to load one. +#### Profiles + +Profiles are stored in `~/.floci/profiles/.yaml`. Pass `--profile ` to any command to +load one; `floci config profile create ` writes a starter file seeded with the defaults of +the tree you run it under. + +```yaml +name: probe +endpoint: http://localhost:4566 +container: floci-probe +image: floci/floci:enforced +port: 4599 +persistDir: /tmp/floci-persist +services: s3,lambda +output: json +``` + +Each field supplies the default for one flag, so a profile field only affects the commands that +have that flag: + +| Profile field | Flag it supplies | Applies to | +|---|---|---| +| `endpoint` | `--endpoint` | every command | +| `container` | `--container` | every command | +| `output` | `--output` / `-o` | every command | +| `image` | `--image` | `start`, `restart` | +| `port` | `--port` | `start`, `restart` | +| `persistDir` | `--persist` | `start`, `restart` | +| `services` | `--services` | `start`, `restart` | + +Resolution order, highest first: + +``` +command-line flag > --profile > FLOCI_* environment variable > built-in default +``` + +So `floci start --profile probe --container other` starts `other`, and a profile beats a +`FLOCI_CONTAINER` exported in your shell. A field the profile leaves out changes nothing. + +An unknown or unreadable profile is an error (exit 2), not a silent fall back to the defaults. +Values are interpolated by the CLI, so `persistDir: ${env:HOME}/floci-data` expands as you would +expect. + +> Profiles are shared by all four product trees — there is one `~/.floci/profiles/` directory, not +> one per product. A profile created under `floci gcp` carries GCP defaults, so passing it to the +> AWS tree will start a GCP container; name them accordingly. + +> `floci restart --profile ` re-applies the profile's `persistDir`, so state survives the +> restart. A plain `floci restart` has no `--persist` flag of its own and still falls back to the +> defaults. ### `floci snapshot` @@ -581,7 +637,7 @@ floci snapshot list floci snapshot save floci snapshot load floci snapshot delete -floci snapshot export -o tarball.tar.gz +floci snapshot export -f tarball.tar.gz floci snapshot import tarball.tar.gz ``` diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index 07acdee..12798bc 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -8,6 +8,9 @@ import io.floci.cli.commands.oci.OciCommand; import io.floci.cli.commands.config.ConfigCommand; import io.floci.cli.commands.snapshot.SnapshotCommand; import io.floci.cli.config.GlobalConfigStore; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileNotFoundException; +import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Ansi; import io.floci.cli.update.UpdateNotifier; import picocli.CommandLine; @@ -102,10 +105,7 @@ public class FlociCli implements Runnable { UpdateNotifier.refreshInBackground(); } - int exitCode = new CommandLine(new FlociCli()) - .setExecutionExceptionHandler(new ExceptionHandler()) - .setCaseInsensitiveEnumValuesAllowed(true) - .execute(effectiveArgs); + int exitCode = buildCommandLine(new ProfileStore()).execute(effectiveArgs); if (notify) { // Fast commands would otherwise exit before the background check persists @@ -115,6 +115,37 @@ public class FlociCli implements Runnable { System.exit(exitCode); } + /** + * The fully configured root command. Shared by {@link #main(String[])} and the tests so that + * profile resolution, the exception handlers and enum leniency cannot drift apart. + * + * The default-value provider is registered programmatically on purpose: the annotation form + * ({@code @Command(defaultValueProvider = ...)}) makes picocli instantiate it reflectively, + * which would need a native-image reflect-config entry. + */ + public static CommandLine buildCommandLine(ProfileStore store) { + CommandLine cmd = new CommandLine(new FlociCli()) + .setExecutionExceptionHandler(new ExceptionHandler()) + .setCaseInsensitiveEnumValuesAllowed(true) + .setDefaultValueProvider(new ProfileDefaultValueProvider(store)); + return cmd.setParameterExceptionHandler(profileAwareParameterExceptionHandler(cmd)); + } + + /** + * A bad {@code --profile} is a user error, not a usage error: print the message on its own + * and skip picocli's usage dump. Everything else keeps picocli's default handling. + */ + static IParameterExceptionHandler profileAwareParameterExceptionHandler(CommandLine cmd) { + IParameterExceptionHandler fallback = cmd.getParameterExceptionHandler(); + return (ex, args) -> { + if (ex instanceof ProfileNotFoundException) { + System.err.println(Ansi.red("Error: ") + ex.getMessage()); + return ExitCode.USAGE; + } + return fallback.handleParseException(ex, args); + }; + } + // Returns true when routing should NOT apply: explicit product subgroup, // or a product-independent command like "config" or "completion". private static boolean isExplicitProduct(String[] args) { diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index d1689e6..6660c26 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -2,9 +2,13 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.io.IOException; +import java.util.Optional; import java.util.concurrent.Callable; @Command( @@ -16,6 +20,8 @@ public class RestartCommand implements Callable { protected final ProductProfile profile; + private final ProfileStore store; + @Mixin protected GlobalOptions global; @@ -24,7 +30,13 @@ public class RestartCommand implements Callable { } protected RestartCommand(ProductProfile profile) { + this(profile, new ProfileStore()); + } + + /** Test seam: a store pointed at a temporary profiles directory. */ + public RestartCommand(ProductProfile profile, ProfileStore store) { this.profile = profile; + this.store = store; this.global = new GlobalOptions(profile); } @@ -42,12 +54,40 @@ public class RestartCommand implements Callable { // Minimal wait to avoid port-already-in-use races try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + return buildStartCommand().call(); + } + + /** + * The {@code start} this restart will run. Picocli never parses this instance, so the profile + * that {@code ProfileDefaultValueProvider} applied to the parsed command line has to be + * carried across by hand — without it, {@code restart --profile x} would silently drop the + * profile's persistence directory and service list. + */ + public StartCommand buildStartCommand() { StartCommand start = new StartCommand(profile); start.global = global; - start.port = profile.defaultPort(); start.pull = "missing"; - start.image = profile.defaultImageRef(); start.detach = false; - return start.call(); + + // port and image already hold the product defaults, set by the StartCommand constructor. + if (global.profile != null) { + loadProfile().ifPresent(p -> { + if (p.port != null) start.port = p.port; + if (p.image != null) start.image = p.image; + if (p.persistDir != null) start.persistDir = p.persistDir; + if (p.services != null) start.services = p.services; + }); + } + return start; + } + + private Optional loadProfile() { + try { + return store.get(global.profile); + } catch (IOException | IllegalArgumentException e) { + // Parsing already resolved this name, so a failure here cannot happen in practice; + // keeping the product defaults beats aborting a restart that has already stopped. + return Optional.empty(); + } } } diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 99b76e6..e6ff40d 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -8,6 +8,7 @@ import io.floci.cli.output.Ansi; import io.floci.cli.output.Printer; import picocli.CommandLine.*; +import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; @@ -53,6 +54,41 @@ public class StartCommand implements Callable { @Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never") String pull; + /** + * The {@code docker run} arguments this invocation would use. Extracted from {@link #call()} + * as a test seam so the persistence mount can be pinned without starting a container; + * {@code socketArgs} is a parameter because {@link DockerClient#dockerSocketRunArgs()} reads + * the ambient {@code DOCKER_HOST} and so differs per machine. + */ + public List dockerRunArgs(List socketArgs) { + List args = new ArrayList<>(); + args.addAll(List.of("-d", "--name", global.container)); + args.addAll(List.of("-p", port + ":" + profile.defaultPort())); + args.addAll(socketArgs); + if (persistDir != null && !persistDir.isBlank()) { + args.addAll(List.of("-v", persistDir + ":/app/data")); + // The server defaults to in-memory storage; enable persistent mode so + // state is actually written to the mounted directory and survives restarts. + args.addAll(List.of("-e", profile.envVar("STORAGE_MODE") + "=persistent")); + } + if (services != null && !services.isBlank()) { + args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services)); + } + args.add(image); + return args; + } + + /** {@code endpoint} with its port replaced, or a localhost URL if it cannot be parsed. */ + public static String withPort(String endpoint, int port) { + try { + URI uri = URI.create(endpoint); + if (uri.getHost() == null) return "http://localhost:" + port; + return new URI(uri.getScheme(), null, uri.getHost(), port, uri.getPath(), null, null).toString(); + } catch (Exception e) { + return "http://localhost:" + port; + } + } + @Override public Integer call() { Printer printer = global.printer(); @@ -91,21 +127,7 @@ public class StartCommand implements Callable { return 1; } - // Build docker run arguments - List args = new ArrayList<>(); - args.addAll(List.of("-d", "--name", global.container)); - args.addAll(List.of("-p", port + ":" + profile.defaultPort())); - args.addAll(DockerClient.dockerSocketRunArgs()); - if (persistDir != null) { - args.addAll(List.of("-v", persistDir + ":/app/data")); - // The server defaults to in-memory storage; enable persistent mode so - // state is actually written to the mounted directory and survives restarts. - args.addAll(List.of("-e", profile.envVar("STORAGE_MODE") + "=persistent")); - } - if (services != null && !services.isBlank()) { - args.addAll(List.of("-e", profile.envVar("SERVICES") + "=" + services)); - } - args.add(image); + List args = dockerRunArgs(DockerClient.dockerSocketRunArgs()); try { printer.println("Starting " + Ansi.gold(profile.displayName()) + " container..."); @@ -121,8 +143,9 @@ public class StartCommand implements Callable { return 0; } - // Update endpoint to match the bound host port before polling readiness - global.endpoint = "http://localhost:" + port; + // Point the readiness poll at the port actually bound, keeping whatever host the + // endpoint already names — a profile or --endpoint may well point somewhere else. + global.endpoint = withPort(global.endpoint, port); // Wait for readiness printer.println(Ansi.gray("Waiting for " + profile.displayName() + " to be ready...")); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index 97a33d1..a600ecc 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -22,6 +22,8 @@ public class ConfigProfileCommand implements Callable { protected final ProductProfile profile; + private final ProfileStore store; + @Mixin protected GlobalOptions global; @@ -30,7 +32,13 @@ public class ConfigProfileCommand implements Callable { } protected ConfigProfileCommand(ProductProfile profile) { + this(profile, new ProfileStore()); + } + + /** Test seam: a store pointed at a temporary profiles directory. */ + public ConfigProfileCommand(ProductProfile profile, ProfileStore store) { this.profile = profile; + this.store = store; this.global = new GlobalOptions(profile); } @@ -43,7 +51,6 @@ public class ConfigProfileCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - ProfileStore store = new ProfileStore(); return switch (action.toLowerCase()) { case "list" -> listProfiles(printer, store); @@ -102,7 +109,7 @@ public class ConfigProfileCommand implements Callable { printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.profileFile(name)); return 1; } - Profile p = new Profile(name); + Profile p = new Profile(profile, name); store.save(p); printer.println(Ansi.green("Created") + " profile '" + name + "' at " + store.profileFile(name)); printer.println(Ansi.gray("Edit the file to customize endpoint, container, image, etc.")); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java index e0444b2..6c427f9 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java @@ -24,6 +24,8 @@ public class ConfigShowCommand implements Callable { protected final ProductProfile profile; + private final ProfileStore store; + @Mixin protected GlobalOptions global; @@ -32,38 +34,36 @@ public class ConfigShowCommand implements Callable { } protected ConfigShowCommand(ProductProfile profile) { + this(profile, new ProfileStore()); + } + + /** Test seam: a store pointed at a temporary profiles directory. */ + public ConfigShowCommand(ProductProfile profile, ProfileStore store) { this.profile = profile; + this.store = store; this.global = new GlobalOptions(profile); } @Override public Integer call() { Printer printer = global.printer(); - ProfileStore store = new ProfileStore(); - - Profile active = new Profile(global.profile != null ? global.profile : "default"); - active.endpoint = global.endpoint; - active.container = global.container; - active.output = global.output != null ? global.output.name() : "text"; - - if (global.profile != null) { - try { - Optional loaded = store.get(global.profile); - if (loaded.isPresent()) { - active = loaded.get(); - } else { - printer.warn("Profile '" + global.profile + "' not found. Using defaults."); - } - } catch (IOException e) { - printer.warn("Could not load profile: " + e.getMessage()); - } - } + // global.* already reflects the profile: ProfileDefaultValueProvider applied it during + // parsing, and only to options the user did not pass, so explicit flags still win here. Map data = new LinkedHashMap<>(); - data.put("profile", active.name); - data.put("endpoint", active.endpoint != null ? active.endpoint : global.endpoint); - data.put("container", active.container != null ? active.container : global.container); - data.put("output", active.output); + data.put("profile", global.profile != null ? global.profile : "default"); + data.put("endpoint", global.endpoint); + data.put("container", global.container); + data.put("output", global.output != null ? global.output.name() : "text"); + + // image/port/persistDir/services have no global option, so they are read back from the + // profile itself — they only take effect on 'start'. + startSettings().ifPresent(p -> { + if (p.image != null) data.put("image", p.image); + if (p.port != null) data.put("port", p.port); + if (p.persistDir != null) data.put("persistDir", p.persistDir); + if (p.services != null) data.put("services", p.services); + }); if (printer.format() != OutputFormat.text) { printer.structured(data); @@ -72,11 +72,22 @@ public class ConfigShowCommand implements Callable { printer.println(Ansi.bold("Active Configuration (" + profile.displayName() + ")")); printer.println(""); - printer.println(" Profile: " + active.name); - printer.println(" Endpoint: " + (active.endpoint != null ? active.endpoint : global.endpoint)); - printer.println(" Container: " + (active.container != null ? active.container : global.container)); - printer.println(" Output: " + (active.output != null ? active.output : "text")); + data.forEach((key, value) -> printer.println(String.format(" %-12s%s", label(key), value))); return 0; } + + private Optional startSettings() { + if (global.profile == null) return Optional.empty(); + try { + return store.get(global.profile); + } catch (IOException | IllegalArgumentException e) { + // Parsing already resolved this name; nothing useful to add here. + return Optional.empty(); + } + } + + private static String label(String key) { + return Character.toUpperCase(key.charAt(0)) + key.substring(1) + ":"; + } } diff --git a/src/main/java/io/floci/cli/config/Profile.java b/src/main/java/io/floci/cli/config/Profile.java index c4d5dc9..b0ed37b 100644 --- a/src/main/java/io/floci/cli/config/Profile.java +++ b/src/main/java/io/floci/cli/config/Profile.java @@ -1,6 +1,7 @@ package io.floci.cli.config; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.floci.cli.ProductProfile; @JsonIgnoreProperties(ignoreUnknown = true) public class Profile { @@ -15,9 +16,12 @@ public class Profile { public Profile() {} - public Profile(String name) { + /** Seeds a new profile with the defaults of the product tree it was created under. */ + public Profile(ProductProfile product, String name) { this.name = name; - this.endpoint = "http://localhost:4566"; - this.container = "floci"; + this.endpoint = product.defaultEndpoint(); + this.container = product.defaultContainer(); + this.image = product.defaultImageRef(); + this.port = product.defaultPort(); } } diff --git a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java new file mode 100644 index 0000000..a705665 --- /dev/null +++ b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java @@ -0,0 +1,124 @@ +package io.floci.cli.config; + +import io.floci.cli.output.OutputFormat; +import picocli.CommandLine; +import picocli.CommandLine.IDefaultValueProvider; +import picocli.CommandLine.Model.ArgSpec; +import picocli.CommandLine.Model.CommandSpec; +import picocli.CommandLine.Model.OptionSpec; + +import java.io.IOException; +import java.util.Optional; + +/** + * Applies a named config profile as the default value of every option it covers. + * + * Registered once on the root {@code CommandLine}; picocli propagates it to the whole subcommand + * hierarchy. Picocli consults a default-value provider only for options that were NOT matched on + * the command line, and only after the command's own arguments have been processed — which gives + * the precedence this CLI documents, for free: + * + *
CLI flag > profile > environment variable > product default
+ * + * The environment variable and product default live in the {@code GlobalOptions} field initial + * values, which picocli keeps whenever this provider returns {@code null}. + */ +public class ProfileDefaultValueProvider implements IDefaultValueProvider { + + private final ProfileStore store; + + // Resolved once per name: the provider is called for every unmatched argument, including + // the positionals and the parent commands, which carry no --profile of their own. + private String resolvedName; + private Profile resolved; + + public ProfileDefaultValueProvider() { + this(new ProfileStore()); + } + + /** Test seam: a store pointed at a temporary profiles directory. */ + public ProfileDefaultValueProvider(ProfileStore store) { + this.store = store; + } + + @Override + public String defaultValue(ArgSpec arg) { + // Positional parameters reach the provider too; only options map to profile fields. + if (!(arg instanceof OptionSpec option)) return null; + + CommandSpec command = arg.command(); + // Group commands, the root, and `update` carry no GlobalOptions mixin. + OptionSpec profileOption = command.findOption("--profile"); + if (profileOption == null) return null; + String name = profileOption.getValue(); + if (name == null) return null; + + // Defaults are applied even when -h/-V was requested, so a bad profile must not stop + // `floci start --profile typo --help` from printing its usage. + if (helpRequested(command)) return null; + + Profile profile = resolve(name, command.commandLine()); + for (String optionName : option.names()) { + String value = ProfileDefaults.valueFor(profile, optionName); + if (value != null) return value; + } + return null; + } + + private static boolean helpRequested(CommandSpec command) { + for (CommandSpec spec = command; spec != null; spec = spec.parent()) { + for (OptionSpec option : spec.options()) { + if ((option.usageHelp() || option.versionHelp()) && Boolean.TRUE.equals(option.getValue())) { + return true; + } + } + } + return false; + } + + private Profile resolve(String name, CommandLine commandLine) { + if (name.equals(resolvedName)) return resolved; + + Optional loaded; + try { + loaded = store.get(name); + } catch (IllegalArgumentException e) { + throw new ProfileNotFoundException(commandLine, e.getMessage()); + } catch (IOException e) { + throw invalid(commandLine, name, e.getMessage()); + } + if (loaded.isEmpty()) { + throw new ProfileNotFoundException(commandLine, + "Profile '" + name + "' not found in " + store.profilesDir() + ".\n" + + "Run 'floci config profile list' to see available profiles, " + + "or 'floci config profile create " + name + "' to create it."); + } + Profile profile = loaded.get(); + validate(commandLine, name, profile); + + resolvedName = name; + resolved = profile; + return resolved; + } + + // Picocli would otherwise reject these while converting, in a message that blames an option + // the user never typed and never names the file the value actually came from. + private void validate(CommandLine commandLine, String name, Profile profile) { + if (profile.port != null && (profile.port < 1 || profile.port > 65535)) { + throw invalid(commandLine, name, "port must be between 1 and 65535, but was " + profile.port); + } + if (profile.output != null) { + try { + OutputFormat.valueOf(profile.output.toLowerCase()); + } catch (IllegalArgumentException e) { + throw invalid(commandLine, name, "output must be text, json or yaml, but was '" + profile.output + "'"); + } + } + } + + private ProfileNotFoundException invalid(CommandLine commandLine, String name, String detail) { + return new ProfileNotFoundException(commandLine, + "Profile '" + name + "' is invalid: " + detail + "\n" + + "Edit " + store.profileFile(name) + " and try again."); + } +} diff --git a/src/main/java/io/floci/cli/config/ProfileDefaults.java b/src/main/java/io/floci/cli/config/ProfileDefaults.java new file mode 100644 index 0000000..8355111 --- /dev/null +++ b/src/main/java/io/floci/cli/config/ProfileDefaults.java @@ -0,0 +1,34 @@ +package io.floci.cli.config; + +/** + * Maps a loaded {@link Profile} onto the CLI options it supplies defaults for. + * + * Kept as a pure function so the mapping can be table-tested without picocli: + * {@link ProfileDefaultValueProvider} is the only adapter around it. + */ +public final class ProfileDefaults { + + private ProfileDefaults() {} + + /** + * The profile's value for {@code optionName}, or {@code null} when the profile is silent + * about that option — in which case picocli keeps the existing default. + * + * Option names are matched exactly. {@code --service} (singular, on wait/logs/env) is + * deliberately NOT {@code --services}, and {@code --profile-name} (the OCI CLI profile + * written by {@code floci oci setup}) is a different concept from {@code --profile}. + */ + public static String valueFor(Profile profile, String optionName) { + if (profile == null || optionName == null) return null; + return switch (optionName) { + case "--endpoint" -> profile.endpoint; + case "--container" -> profile.container; + case "--image" -> profile.image; + case "--port" -> profile.port == null ? null : String.valueOf(profile.port); + case "--persist" -> profile.persistDir; + case "--services" -> profile.services; + case "--output" -> profile.output; + default -> null; + }; + } +} diff --git a/src/main/java/io/floci/cli/config/ProfileNotFoundException.java b/src/main/java/io/floci/cli/config/ProfileNotFoundException.java new file mode 100644 index 0000000..66f2dd0 --- /dev/null +++ b/src/main/java/io/floci/cli/config/ProfileNotFoundException.java @@ -0,0 +1,16 @@ +package io.floci.cli.config; + +import picocli.CommandLine; +import picocli.CommandLine.ParameterException; + +/** + * Raised while resolving {@code --profile }. Extends {@link ParameterException} so picocli + * propagates it unwrapped from the default-value provider; {@code FlociCli} recognises it and + * prints the message alone (no usage dump) with exit code 2. + */ +public class ProfileNotFoundException extends ParameterException { + + public ProfileNotFoundException(CommandLine commandLine, String message) { + super(commandLine, message); + } +} diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java index f201d25..e870b98 100644 --- a/src/main/java/io/floci/cli/config/ProfileStore.java +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -9,11 +9,16 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.regex.Pattern; public class ProfileStore { private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + // A profile name becomes a file name, so it must not be able to traverse out of the + // profiles directory: 'floci config profile delete ../../foo' resolved the raw name. + private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z0-9._-]+"); + private final Path profilesDir; public ProfileStore() { @@ -24,6 +29,24 @@ public class ProfileStore { this.profilesDir = profilesDir; } + /** + * Rejects anything that could escape {@link #profilesDir} or name a hidden path segment. + * @throws IllegalArgumentException with a message suitable for printing to the user + */ + public static String validateName(String name) { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException( + "Profile name must not be empty.\n" + + "Run 'floci config profile list' to see available profiles."); + } + if (".".equals(name) || "..".equals(name) || !VALID_NAME.matcher(name).matches()) { + throw new IllegalArgumentException( + "Invalid profile name '" + name + "'. Use only letters, digits, '.', '_' and '-'.\n" + + "Run 'floci config profile list' to see available profiles."); + } + return name; + } + public List list() throws IOException { if (!Files.exists(profilesDir)) return List.of(); List profiles = new ArrayList<>(); @@ -32,6 +55,11 @@ public class ProfileStore { .forEach(p -> { try { Profile profile = YAML.readValue(p.toFile(), Profile.class); + // Hand-written files often omit 'name:'; the file name is the name. + if (profile.name == null || profile.name.isBlank()) { + String file = p.getFileName().toString(); + profile.name = file.substring(0, file.lastIndexOf('.')); + } profiles.add(profile); } catch (IOException ignored) {} }); @@ -40,7 +68,7 @@ public class ProfileStore { } public Optional get(String name) throws IOException { - Path file = profileFile(name); + Path file = existingProfileFile(name); if (!Files.exists(file)) return Optional.empty(); return Optional.of(YAML.readValue(file.toFile(), Profile.class)); } @@ -51,11 +79,26 @@ public class ProfileStore { } public boolean delete(String name) throws IOException { - Path file = profileFile(name); + Path file = existingProfileFile(name); return Files.deleteIfExists(file); } + /** Where {@link #save} writes {@code name}. Always {@code .yaml}. */ public Path profileFile(String name) { - return profilesDir.resolve(name + ".yaml"); + return profilesDir.resolve(validateName(name) + ".yaml"); + } + + // list() has always accepted .yml, so reads must too — otherwise a .yml profile shows up in + // 'config profile list' and then reports "not found" when passed to --profile. + private Path existingProfileFile(String name) { + Path yaml = profileFile(name); + if (Files.exists(yaml)) return yaml; + Path yml = profilesDir.resolve(validateName(name) + ".yml"); + return Files.exists(yml) ? yml : yaml; + } + + /** The directory profiles are read from, for user-facing messages. */ + public Path profilesDir() { + return profilesDir; } } diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java new file mode 100644 index 0000000..ee84d01 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -0,0 +1,99 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.config.ConfigProfileCommand; +import io.floci.cli.commands.config.ConfigShowCommand; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileDefaultValueProvider; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +/** 'config show' must merge with the profile rather than replace the command line with it. */ +class ConfigCommandsTest { + + @TempDir + Path tempDir; + + private ProfileStore store() { + return new ProfileStore(tempDir); + } + + private void writeProfile(String name, String yaml) throws IOException { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(name + ".yaml"), yaml); + } + + private String runShow(ProductProfile product, String... args) { + CommandLine cmd = new CommandLine(new ConfigShowCommand(product, store())) + .setCaseInsensitiveEnumValuesAllowed(true) + .setDefaultValueProvider(new ProfileDefaultValueProvider(store())); + PrintStream original = System.out; + ByteArrayOutputStream captured = new ByteArrayOutputStream(); + System.setOut(new PrintStream(captured)); + try { + assertEquals(0, cmd.execute(args)); + } finally { + System.setOut(original); + } + return captured.toString(); + } + + @Test + void showsTheProfilesValues() throws Exception { + writeProfile("probe", """ + container: floci-probe + endpoint: http://localhost:4566 + image: floci/floci:enforced + port: 4599 + persistDir: /tmp/floci-persist-test + """); + + String out = runShow(ProductProfile.AWS, "--profile", "probe", "-o", "json"); + assertTrue(out.contains("\"container\" : \"floci-probe\""), out); + assertTrue(out.contains("\"image\" : \"floci/floci:enforced\""), out); + assertTrue(out.contains("\"persistDir\" : \"/tmp/floci-persist-test\""), out); + } + + @Test + void anExplicitFlagIsNoLongerDiscardedByTheProfile() throws Exception { + writeProfile("probe", """ + container: floci-probe + endpoint: http://localhost:4566 + """); + + String out = runShow(ProductProfile.AWS, "--profile", "probe", + "--endpoint", "http://explicit:1234", "-o", "json"); + + assertTrue(out.contains("\"endpoint\" : \"http://explicit:1234\""), out); + assertTrue(out.contains("\"container\" : \"floci-probe\""), out); + } + + @Test + void withoutAProfileItReportsTheProductDefaults() { + String out = runShow(ProductProfile.GCP, "-o", "json"); + assertTrue(out.contains("\"profile\" : \"default\""), out); + assertTrue(out.contains("\"container\" : \"floci-gcp\""), out); + } + + @Test + void createWritesTheDefaultsOfTheTreeItWasRunUnder() throws Exception { + assertEquals(0, new CommandLine(new ConfigProfileCommand(ProductProfile.GCP, store())) + .execute("create", "gcp-profile")); + + Profile created = store().get("gcp-profile").orElseThrow(); + assertEquals("floci-gcp", created.container); + assertEquals("http://localhost:4588", created.endpoint); + assertEquals("floci/floci-gcp:latest", created.image); + assertEquals(4588, created.port); + } +} diff --git a/src/test/java/io/floci/cli/unit/MissingProfileTest.java b/src/test/java/io/floci/cli/unit/MissingProfileTest.java new file mode 100644 index 0000000..440ff40 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/MissingProfileTest.java @@ -0,0 +1,111 @@ +package io.floci.cli.unit; + +import io.floci.cli.FlociCli; +import io.floci.cli.config.ProfileNotFoundException; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * A profile that does not resolve must stop the command rather than silently fall back to the + * built-in defaults — silently falling back is what made issue #22 lose data unnoticed. + */ +class MissingProfileTest { + + @TempDir + Path tempDir; + + private CommandLine cli() { + return FlociCli.buildCommandLine(new ProfileStore(tempDir)); + } + + private void writeProfile(String name, String yaml) throws IOException { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(name + ".yaml"), yaml); + } + + private static String captureStderr(Supplier action, int[] exitCode) { + PrintStream original = System.err; + ByteArrayOutputStream captured = new ByteArrayOutputStream(); + System.setErr(new PrintStream(captured)); + try { + exitCode[0] = action.get(); + } finally { + System.setErr(original); + } + return captured.toString(); + } + + @Test + void unknownProfileExitsTwoWithAMessageThatNamesTheNextStep() { + int[] exit = new int[1]; + String stderr = captureStderr(() -> cli().execute("start", "--profile", "typo"), exit); + + assertEquals(2, exit[0]); + assertTrue(stderr.contains("Profile 'typo' not found"), stderr); + assertTrue(stderr.contains(tempDir.toString()), stderr); + assertTrue(stderr.contains("floci config profile list"), stderr); + // The message stands alone; picocli's usage dump would bury it. + assertFalse(stderr.contains("Usage:"), stderr); + } + + @Test + void failsEvenWhenEveryProfileBackedOptionWasPassedExplicitly() { + int[] exit = new int[1]; + captureStderr(() -> cli().execute("start", "--profile", "typo", + "--endpoint", "http://x:1", "--container", "c", "--image", "i", + "--port", "1", "--persist", "/p", "--services", "s", "-o", "json"), exit); + + assertEquals(2, exit[0]); + } + + @Test + void helpStillWorksWithABadProfile() { + int[] exit = new int[1]; + captureStderr(() -> cli().execute("start", "--profile", "typo", "--help"), exit); + + assertEquals(0, exit[0]); + } + + @Test + void traversalInTheProfileNameIsRejected() { + int[] exit = new int[1]; + String stderr = captureStderr(() -> cli().execute("start", "--profile", "../../escape"), exit); + + assertEquals(2, exit[0]); + assertTrue(stderr.contains("Invalid profile name"), stderr); + } + + @Test + void unusableProfileValuesNameTheFileRatherThanAnOptionTheUserNeverTyped() throws Exception { + writeProfile("bad-output", "output: bogus\n"); + writeProfile("bad-port", "port: 99999\n"); + + int[] exit = new int[1]; + String outputErr = captureStderr(() -> cli().execute("start", "--profile", "bad-output"), exit); + assertEquals(2, exit[0]); + assertTrue(outputErr.contains("bad-output.yaml"), outputErr); + assertTrue(outputErr.contains("output must be text, json or yaml"), outputErr); + + String portErr = captureStderr(() -> cli().execute("start", "--profile", "bad-port"), exit); + assertEquals(2, exit[0]); + assertTrue(portErr.contains("bad-port.yaml"), portErr); + assertTrue(portErr.contains("port must be between 1 and 65535"), portErr); + } + + @Test + void parsingRaisesTheDedicatedException() { + assertThrows(ProfileNotFoundException.class, + () -> cli().parseArgs("start", "--profile", "typo")); + } +} diff --git a/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java new file mode 100644 index 0000000..1e0c710 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ProfileDefaultsTest.java @@ -0,0 +1,68 @@ +package io.floci.cli.unit; + +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileDefaults; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; + +/** Pins which CLI option each Profile field feeds, and which options it must leave alone. */ +class ProfileDefaultsTest { + + private static Profile fullProfile() { + Profile p = new Profile(); + p.name = "probe"; + p.endpoint = "http://localhost:4566"; + p.container = "floci-probe"; + p.image = "floci/floci:enforced"; + p.port = 4599; + p.persistDir = "/tmp/floci-persist-test"; + p.services = "s3,lambda"; + p.output = "json"; + return p; + } + + @ParameterizedTest + @CsvSource({ + "--endpoint, http://localhost:4566", + "--container, floci-probe", + "--image, floci/floci:enforced", + "--port, 4599", + "--persist, /tmp/floci-persist-test", + "--services, 's3,lambda'", + "--output, json", + }) + void mapsEveryProfileField(String option, String expected) { + assertEquals(expected, ProfileDefaults.valueFor(fullProfile(), option), option); + } + + @ParameterizedTest + @ValueSource(strings = { + "--service", // wait/logs/env filter — NOT the profile's 'services' + "--profile-name", // the OCI CLI profile written by 'floci oci setup' + "--profile", + "--pull", + "--timeout", + "--file", + }) + void leavesUnrelatedOptionsAlone(String option) { + assertNull(ProfileDefaults.valueFor(fullProfile(), option), option); + } + + @Test + void unsetFieldsAreSilentSoPicocliKeepsItsOwnDefault() { + Profile empty = new Profile(); + for (String option : new String[]{"--endpoint", "--container", "--image", "--port", "--persist", "--services", "--output"}) { + assertNull(ProfileDefaults.valueFor(empty, option), option); + } + } + + @Test + void nullInputsAreSilent() { + assertNull(ProfileDefaults.valueFor(null, "--endpoint")); + assertNull(ProfileDefaults.valueFor(fullProfile(), null)); + } +} diff --git a/src/test/java/io/floci/cli/unit/ProfilePrecedenceTest.java b/src/test/java/io/floci/cli/unit/ProfilePrecedenceTest.java new file mode 100644 index 0000000..dd89246 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ProfilePrecedenceTest.java @@ -0,0 +1,149 @@ +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 picocli.CommandLine; +import picocli.CommandLine.Model.CommandSpec; +import picocli.CommandLine.ParseResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Pins issue #22: --profile must reach every command, and the command line must still win. + * Precedence is CLI flag > profile > environment variable > product default. + */ +class ProfilePrecedenceTest { + + @TempDir + Path tempDir; + + private static final String FULL_PROFILE = """ + name: probe + endpoint: http://localhost:4566 + container: floci-probe + image: floci/floci:enforced + port: 4599 + persistDir: /tmp/floci-persist-test + services: s3,lambda + output: json + """; + + private void writeProfile(String name, String yaml) throws IOException { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(name + ".yaml"), yaml); + } + + private CommandSpec leafSpec(String... args) { + ParseResult r = FlociCli.buildCommandLine(new ProfileStore(tempDir)).parseArgs(args); + while (r.hasSubcommand()) r = r.subcommand(); + return r.commandSpec(); + } + + @Test + void profileSuppliesEveryStartOption() throws Exception { + writeProfile("probe", FULL_PROFILE); + CommandSpec spec = leafSpec("start", "--profile", "probe"); + + assertEquals("http://localhost:4566", spec.findOption("--endpoint").getValue()); + assertEquals("floci-probe", spec.findOption("--container").getValue()); + assertEquals("floci/floci:enforced", spec.findOption("--image").getValue()); + assertEquals(Integer.valueOf(4599), spec.findOption("--port").getValue()); + assertEquals("/tmp/floci-persist-test", spec.findOption("--persist").getValue()); + assertEquals("s3,lambda", spec.findOption("--services").getValue()); + assertEquals("json", spec.findOption("--output").getValue().toString()); + } + + @Test + void commandLineFlagsBeatTheProfile() throws Exception { + writeProfile("probe", FULL_PROFILE); + CommandSpec spec = leafSpec("start", "--profile", "probe", + "--container", "explicit", "--image", "explicit:1", "--port", "1234", + "--persist", "/explicit", "--services", "sqs", "--endpoint", "http://explicit:1", "-o", "yaml"); + + assertEquals("http://explicit:1", spec.findOption("--endpoint").getValue()); + assertEquals("explicit", spec.findOption("--container").getValue()); + assertEquals("explicit:1", spec.findOption("--image").getValue()); + assertEquals(Integer.valueOf(1234), spec.findOption("--port").getValue()); + assertEquals("/explicit", spec.findOption("--persist").getValue()); + assertEquals("sqs", spec.findOption("--services").getValue()); + assertEquals("yaml", spec.findOption("--output").getValue().toString()); + } + + @Test + void fieldsTheProfileOmitsKeepTheProductDefault() throws Exception { + writeProfile("partial", "container: floci-partial\n"); + CommandSpec spec = leafSpec("start", "--profile", "partial"); + + assertEquals("floci-partial", spec.findOption("--container").getValue()); + assertEquals("floci/floci:latest", spec.findOption("--image").getValue()); + assertEquals(Integer.valueOf(4566), spec.findOption("--port").getValue()); + assertNull(spec.findOption("--persist").getValue()); + assertEquals("text", spec.findOption("--output").getValue().toString()); + } + + @Test + void everyProductTreeAppliesTheProfileAndKeepsItsOwnDefaults() throws Exception { + writeProfile("partial", "container: floci-partial\n"); + String[][] trees = { + {"aws", "4566", "floci/floci:latest"}, + {"gcp", "4588", "floci/floci-gcp:latest"}, + {"az", "4577", "floci/floci-az:latest"}, + {"oci", "4599", "floci/floci-oci:latest"}, + }; + for (String[] tree : trees) { + CommandSpec spec = leafSpec(tree[0], "start", "--profile", "partial"); + assertEquals("floci-partial", spec.findOption("--container").getValue(), tree[0]); + assertEquals(Integer.valueOf(tree[1]), spec.findOption("--port").getValue(), tree[0]); + assertEquals(tree[2], spec.findOption("--image").getValue(), tree[0]); + } + } + + @Test + void profileAppliesToCommandsOtherThanStart() throws Exception { + writeProfile("probe", FULL_PROFILE); + // 'env' is one of the commands that does not pre-initialize its GlobalOptions mixin. + for (String command : new String[]{"status", "logs", "wait", "doctor", "env", "services"}) { + CommandSpec spec = leafSpec(command, "--profile", "probe"); + assertEquals("floci-probe", spec.findOption("--container").getValue(), command); + assertEquals("http://localhost:4566", spec.findOption("--endpoint").getValue(), command); + } + } + + @Test + void singularServiceFilterIsNotTheProfilesServicesList() throws Exception { + writeProfile("probe", FULL_PROFILE); + assertNull(leafSpec("wait", "--profile", "probe").findOption("--service").getValue()); + assertNull(leafSpec("logs", "--profile", "probe").findOption("--service").getValue()); + } + + @Test + void withoutAProfileNothingChanges() { + CommandSpec spec = leafSpec("start"); + assertEquals("floci", spec.findOption("--container").getValue()); + assertEquals("floci/floci:latest", spec.findOption("--image").getValue()); + assertEquals(Integer.valueOf(4566), spec.findOption("--port").getValue()); + assertNull(spec.findOption("--persist").getValue()); + } + + @Test + void commandsWithoutGlobalOptionsAreUntouched() { + // 'update' has no GlobalOptions mixin at all, so the provider must bail out rather + // than dereference a missing --profile option. + assertEquals(Boolean.TRUE, + leafSpec("update", "--check").findOption("--check").getValue()); + } + + @Test + void picocliInterpolatesProfileValues() throws Exception { + // Documented consequence of routing values through picocli's default-value machinery. + writeProfile("interp", "persistDir: ${env:HOME}/floci-data\n"); + assertEquals(System.getenv("HOME") + "/floci-data", + leafSpec("start", "--profile", "interp").findOption("--persist").getValue()); + } +} diff --git a/src/test/java/io/floci/cli/unit/ProfileStoreTest.java b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java new file mode 100644 index 0000000..ac9f280 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java @@ -0,0 +1,112 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.config.Profile; +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 java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** First coverage of the profile persistence layer, including the path-traversal guard. */ +class ProfileStoreTest { + + @TempDir + Path tempDir; + + private ProfileStore store() { + return new ProfileStore(tempDir); + } + + @Test + void roundTripsEveryField() throws Exception { + Profile saved = new Profile(); + saved.name = "probe"; + saved.endpoint = "http://localhost:4566"; + saved.container = "floci-probe"; + saved.image = "floci/floci:enforced"; + saved.port = 4599; + saved.persistDir = "/tmp/floci-persist-test"; + saved.services = "s3,lambda"; + saved.output = "json"; + store().save(saved); + + Profile loaded = store().get("probe").orElseThrow(); + assertEquals("probe", loaded.name); + assertEquals("http://localhost:4566", loaded.endpoint); + assertEquals("floci-probe", loaded.container); + assertEquals("floci/floci:enforced", loaded.image); + assertEquals(4599, loaded.port); + assertEquals("/tmp/floci-persist-test", loaded.persistDir); + assertEquals("s3,lambda", loaded.services); + assertEquals("json", loaded.output); + } + + @Test + void newProfileTakesItsProductsDefaults() throws Exception { + store().save(new Profile(ProductProfile.GCP, "g")); + + Profile loaded = store().get("g").orElseThrow(); + assertEquals("http://localhost:4588", loaded.endpoint); + assertEquals("floci-gcp", loaded.container); + assertEquals("floci/floci-gcp:latest", loaded.image); + assertEquals(4588, loaded.port); + } + + @Test + void missingProfileIsEmptyAndDeleteReportsIt() throws Exception { + assertTrue(store().get("absent").isEmpty()); + assertFalse(store().delete("absent")); + + store().save(new Profile(ProductProfile.AWS, "here")); + assertTrue(store().delete("here")); + assertFalse(store().delete("here")); + } + + @Test + void readsTheYmlSpellingThatListHasAlwaysAccepted() throws Exception { + Files.writeString(tempDir.resolve("staging.yml"), "container: floci-staging\n"); + + assertEquals("floci-staging", store().get("staging").orElseThrow().container); + assertTrue(store().delete("staging")); + } + + @Test + void listBackfillsTheNameFromTheFileName() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("handwritten.yaml"), "container: floci-hand\n"); + + List profiles = store().list(); + assertEquals(1, profiles.size()); + assertEquals("handwritten", profiles.get(0).name); + } + + @ParameterizedTest + @ValueSource(strings = {"ok", "ok-1", "ok_1", "ok.1", "OK"}) + void acceptsOrdinaryNames(String name) { + assertEquals(name, ProfileStore.validateName(name)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", ".", "..", "../x", "../../etc/passwd", "a/b", "a\\b", "/abs", "a:b"}) + void rejectsNamesThatCouldEscapeTheProfilesDirectory(String name) { + assertThrows(IllegalArgumentException.class, () -> ProfileStore.validateName(name), name); + } + + @Test + void rejectsNullName() { + assertThrows(IllegalArgumentException.class, () -> ProfileStore.validateName(null)); + } + + @Test + void traversalNeverEscapesTheProfilesDirectory() { + assertThrows(IllegalArgumentException.class, () -> store().profileFile("../../escaped")); + assertThrows(IllegalArgumentException.class, () -> store().delete("../../escaped")); + } +} diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java new file mode 100644 index 0000000..bfc665c --- /dev/null +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -0,0 +1,83 @@ +package io.floci.cli.unit; + +import io.floci.cli.ProductProfile; +import io.floci.cli.commands.RestartCommand; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Restart builds its StartCommand programmatically, so picocli never applies the profile to it. + * Without the hand-off in buildStartCommand(), 'restart --profile x' would drop the persistence + * directory that 'start --profile x' honours. + */ +class RestartCommandTest { + + private static final List SOCKET = List.of("-v", "/sock:/sock"); + + @TempDir + Path tempDir; + + private RestartCommand parse(ProductProfile product, String... args) { + RestartCommand restart = new RestartCommand(product, new ProfileStore(tempDir)); + new CommandLine(restart).parseArgs(args); + return restart; + } + + private void writeProfile(String name, String yaml) throws IOException { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(name + ".yaml"), yaml); + } + + @Test + void carriesTheProfileIntoTheStartItRuns() throws Exception { + writeProfile("probe", """ + image: floci/floci:enforced + port: 4599 + persistDir: /tmp/floci-persist-test + services: s3,lambda + """); + + List args = parse(ProductProfile.AWS, "--profile", "probe") + .buildStartCommand().dockerRunArgs(SOCKET); + + assertEquals(List.of( + "-d", "--name", "floci", + "-p", "4599:4566", + "-v", "/sock:/sock", + "-v", "/tmp/floci-persist-test:/app/data", + "-e", "FLOCI_STORAGE_MODE=persistent", + "-e", "FLOCI_SERVICES=s3,lambda", + "floci/floci:enforced"), args); + } + + @Test + void withoutAProfileItStillUsesTheProductDefaults() { + List args = parse(ProductProfile.GCP).buildStartCommand().dockerRunArgs(SOCKET); + + assertEquals(List.of("-d", "--name", "floci-gcp", "-p", "4588:4588", + "-v", "/sock:/sock", "floci/floci-gcp:latest"), args); + } + + @Test + void fieldsTheProfileOmitsKeepTheProductDefault() throws Exception { + writeProfile("partial", "persistDir: /tmp/only-persist\n"); + + List args = parse(ProductProfile.OCI, "--profile", "partial") + .buildStartCommand().dockerRunArgs(SOCKET); + + assertEquals(List.of("-d", "--name", "floci-oci", "-p", "4599:4599", + "-v", "/sock:/sock", + "-v", "/tmp/only-persist:/app/data", + "-e", "FLOCI_OCI_STORAGE_MODE=persistent", + "floci/floci-oci:latest"), args); + } +} diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java new file mode 100644 index 0000000..d1543e8 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -0,0 +1,103 @@ +package io.floci.cli.unit; + +import io.floci.cli.FlociCli; +import io.floci.cli.commands.StartCommand; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine.ParseResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * The issue #22 regression: a profile's persistDir must produce the bind mount and the + * persistent storage mode, or every start silently drops state into a fresh anonymous volume. + * Built without touching Docker — the host socket arguments are passed in. + */ +class StartCommandArgsTest { + + private static final List SOCKET = List.of("-v", "/sock:/sock"); + + @TempDir + Path tempDir; + + private StartCommand parse(String... args) { + ParseResult r = FlociCli.buildCommandLine(new ProfileStore(tempDir)).parseArgs(args); + while (r.hasSubcommand()) r = r.subcommand(); + return (StartCommand) r.commandSpec().userObject(); + } + + private void writeProfile(String name, String yaml) throws IOException { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(name + ".yaml"), yaml); + } + + @Test + void profilePersistDirProducesTheBindMountAndPersistentStorageMode() throws Exception { + writeProfile("probe", """ + container: floci-probe + image: floci/floci:enforced + port: 4599 + persistDir: /tmp/floci-persist-test + services: s3,lambda + """); + + assertEquals(List.of( + "-d", "--name", "floci-probe", + "-p", "4599:4566", + "-v", "/sock:/sock", + "-v", "/tmp/floci-persist-test:/app/data", + "-e", "FLOCI_STORAGE_MODE=persistent", + "-e", "FLOCI_SERVICES=s3,lambda", + "floci/floci:enforced"), + parse("start", "--profile", "probe").dockerRunArgs(SOCKET)); + } + + @Test + void perProductEnvPrefixesComeFromTheProductNotTheProfile() throws Exception { + writeProfile("probe", """ + persistDir: /tmp/floci-persist-test + services: storage + """); + + assertEquals(List.of( + "-d", "--name", "floci-gcp", + "-p", "4588:4588", + "-v", "/sock:/sock", + "-v", "/tmp/floci-persist-test:/app/data", + "-e", "FLOCI_GCP_STORAGE_MODE=persistent", + "-e", "FLOCI_GCP_SERVICES=storage", + "floci/floci-gcp:latest"), + parse("gcp", "start", "--profile", "probe").dockerRunArgs(SOCKET)); + } + + @Test + void noPersistDirMeansNoMountAndNoStorageMode() { + List args = parse("start").dockerRunArgs(SOCKET); + + assertEquals(List.of("-d", "--name", "floci", "-p", "4566:4566", + "-v", "/sock:/sock", "floci/floci:latest"), args); + assertFalse(args.contains("/app/data")); + assertFalse(args.stream().anyMatch(a -> a.contains("STORAGE_MODE"))); + } + + @Test + void explicitPersistFlagStillWinsOverTheProfile() throws Exception { + writeProfile("probe", "persistDir: /from-profile\n"); + + assertTrue(parse("start", "--profile", "probe", "--persist", "/from-flag") + .dockerRunArgs(SOCKET).contains("/from-flag:/app/data")); + } + + @Test + void readinessPollKeepsTheHostFromTheEndpointWhenSwappingThePort() { + assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599)); + assertEquals("http://localhost:4599", StartCommand.withPort("http://localhost:4566", 4599)); + assertEquals("http://localhost:4599", StartCommand.withPort("not a url", 4599)); + } +}