mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-23 06:00:47 -05:00
fix(profile): apply --profile to every command, not just config show (#23)
`--profile <name>` was declared on the shared GlobalOptions mixin but only
ConfigShowCommand ever read it. Every other command, `start` included, fell
through to the built-in defaults, so a profile's container, image, port,
persistDir and services were silently dropped.
The worst consequence was silent data loss: the `-v <dir>:/app/data` mount and
`FLOCI_STORAGE_MODE=persistent` were gated on the `--persist` flag alone, so a
profile with `persistDir` set produced neither. The image declares
`VOLUME /app/data`, so every start attached a fresh anonymous volume and the
server stayed in-memory.
A profile is now applied by a single picocli IDefaultValueProvider registered in
FlociCli.buildCommandLine(). Picocli consults it only for options the user did
not pass, and only after that command's arguments are processed, which gives the
documented precedence without per-command plumbing:
command-line flag > --profile <name> > FLOCI_* env var > product default
Behaviour changes:
- An unknown, unreadable or invalid profile is now an error (exit 2) rather than
a silent fall back to the defaults. `--help` still works with a bad profile.
- `restart --profile <name>` re-applies the profile's persistDir, image, port
and services. It builds its StartCommand programmatically, so it carries the
profile across by hand.
- `config show` merges instead of replacing, so an explicit --endpoint /
--container / -o is no longer discarded when --profile resolves. It now also
reports the profile's start-only fields.
- `config profile create` seeds the file from the tree it was run under;
previously every tree wrote AWS values.
- Profile names are validated, closing a path traversal
(`config profile delete ../../foo` resolved the raw name).
- Reads accept the `.yml` spelling that `config profile list` has always
listed, and `list` backfills a missing `name:` from the file name.
- The readiness poll after `start` keeps the endpoint's host when swapping in
the bound port, instead of always rewriting it to localhost.
Adds 64 tests, including the first coverage of ProfileStore.
Closes #22
This commit is contained in:
1 parent
588edc235a
commit
52c08ecec5
19 files changed
+1193
-62
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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<Integer> {
|
||||
|
||||
protected final ProductProfile profile;
|
||||
|
||||
private final ProfileStore store;
|
||||
|
||||
@Mixin
|
||||
protected GlobalOptions global;
|
||||
|
||||
@@ -24,7 +30,13 @@ public class RestartCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
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<Integer> {
|
||||
// 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<Profile> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Integer> {
|
||||
@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<String> dockerRunArgs(List<String> socketArgs) {
|
||||
List<String> 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<Integer> {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Build docker run arguments
|
||||
List<String> 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<String> args = dockerRunArgs(DockerClient.dockerSocketRunArgs());
|
||||
|
||||
try {
|
||||
printer.println("Starting " + Ansi.gold(profile.displayName()) + " container...");
|
||||
@@ -121,8 +143,9 @@ public class StartCommand implements Callable<Integer> {
|
||||
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..."));
|
||||
|
||||
@@ -22,6 +22,8 @@ public class ConfigProfileCommand implements Callable<Integer> {
|
||||
|
||||
protected final ProductProfile profile;
|
||||
|
||||
private final ProfileStore store;
|
||||
|
||||
@Mixin
|
||||
protected GlobalOptions global;
|
||||
|
||||
@@ -30,7 +32,13 @@ public class ConfigProfileCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
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<Integer> {
|
||||
@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<Integer> {
|
||||
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."));
|
||||
|
||||
@@ -24,6 +24,8 @@ public class ConfigShowCommand implements Callable<Integer> {
|
||||
|
||||
protected final ProductProfile profile;
|
||||
|
||||
private final ProfileStore store;
|
||||
|
||||
@Mixin
|
||||
protected GlobalOptions global;
|
||||
|
||||
@@ -32,38 +34,36 @@ public class ConfigShowCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
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<Profile> 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<String, Object> 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<Integer> {
|
||||
|
||||
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<Profile> 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) + ":";
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
*
|
||||
* <pre>CLI flag > profile > environment variable > product default</pre>
|
||||
*
|
||||
* 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<Profile> 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.");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package io.floci.cli.config;
|
||||
|
||||
import picocli.CommandLine;
|
||||
import picocli.CommandLine.ParameterException;
|
||||
|
||||
/**
|
||||
* Raised while resolving {@code --profile <name>}. 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Profile> list() throws IOException {
|
||||
if (!Files.exists(profilesDir)) return List.of();
|
||||
List<Profile> 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<Profile> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user