refactor(profile): read the parse's profile snapshot in restart and config show (#34)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-08 22:25:23 -05:00
1 parent 5c0cc339bf
commit bc59dff8c3
7 files changed
+90 -95

No files matched your search

+1 -1
View File
@@ -113,7 +113,7 @@ Rules when touching this:
- 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.
- A command that reads the profile back after parsing (`RestartCommand` building its `StartCommand`, `ConfigShowCommand`) gets the parse's provider with `ProfileDefaultValueProvider.of(spec)` (an `@Spec CommandSpec spec` field) and passes it to `StartCommand.resolvedFor`. The provider memoizes the profile it resolved, so this reuses the parse's snapshot; never construct a `ProfileStore` or a second provider in a command.
- Use `FlociCli.buildCommandLine(ProfileStore)` in tests — `new CommandLine(new FlociCli())` has none of the wiring.
### Multiple instances
@@ -3,9 +3,10 @@ package io.floci.cli.commands;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.config.ProfileNotFoundException;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.output.Printer;
import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec;
import java.util.concurrent.Callable;
@@ -18,23 +19,18 @@ public class RestartCommand implements Callable<Integer> {
protected final ProductProfile profile;
private final ProfileStore store;
@Mixin
protected GlobalOptions global;
@Spec
CommandSpec spec;
public RestartCommand() {
this(ProductProfile.AWS);
}
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);
}
@@ -82,15 +78,12 @@ public class RestartCommand implements Callable<Integer> {
* directory on {@code start} and a different one on {@code restart}.
*/
public StartCommand buildStartCommand() {
StartCommand start = StartCommand.resolvedFor(profile, store, global.profile);
// The outer parse's provider: its memoized profile is the snapshot the globals below were
// resolved from, so the start settings cannot come from a newer version of the file.
StartCommand start = StartCommand.resolvedFor(profile, ProfileDefaultValueProvider.of(spec), global.profile);
// The real invocation's globals win: they already carry the profile plus any flag the
// user passed, resolved once by the outer parse.
//
// Known residual: those globals come from the outer parse's read of the profile while the
// fields above come from resolvedFor's, so a profile edited between the two would mix
// snapshots. Closing it means making the outer provider reachable from commands, which is
// a wider change than this fix; tracked as batman LAY-1.
start.global = global;
start.pull = "missing";
start.detach = false;
@@ -3,7 +3,6 @@ package io.floci.cli.commands;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import io.floci.cli.output.Ansi;
@@ -71,15 +70,11 @@ public class StartCommand implements Callable<Integer> {
* interpolation. Anything that needs to know what a profile would start with must go through
* here rather than reading the {@link io.floci.cli.config.Profile} bean, or it silently
* disagrees with {@code start} on any interpolated value.
*/
public static StartCommand resolvedFor(ProductProfile product, ProfileStore store, String profileName) {
return resolvedFor(product, new ProfileDefaultValueProvider(store), profileName);
}
/**
* As above, but with the provider supplied so a caller can read back the one profile snapshot
* it resolved ({@link ProfileDefaultValueProvider#resolved()}) instead of reading the file a
* second time and risking a mix of two versions.
*
* <p>Pass the provider the outer parse used ({@link ProfileDefaultValueProvider#of}): it
* memoizes the profile it resolved, so this applies that same snapshot instead of reading the
* file again, and a caller can read the snapshot back through
* {@link ProfileDefaultValueProvider#resolved()}.
*/
public static StartCommand resolvedFor(ProductProfile product,
ProfileDefaultValueProvider provider,
@@ -6,11 +6,11 @@ import io.floci.cli.commands.StartCommand;
import io.floci.cli.config.Profile;
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.output.OutputFormat;
import io.floci.cli.output.Printer;
import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -26,23 +26,18 @@ public class ConfigShowCommand implements Callable<Integer> {
protected final ProductProfile profile;
private final ProfileStore store;
@Mixin
protected GlobalOptions global;
@Spec
CommandSpec spec;
public ConfigShowCommand() {
this(ProductProfile.AWS);
}
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);
}
@@ -85,14 +80,14 @@ public class ConfigShowCommand implements Callable<Integer> {
// interpolated persistDir reads here exactly as 'start' would use it. The bean is consulted
// for presence, so a product default never shows up looking like a profile value.
//
// Both come from ONE snapshot: the provider memoizes the profile it read, so presence and
// values cannot disagree if another process edits the file mid-command. If the profile has
// gone since the outer parse resolved it, resolvedFor throws and the command fails loudly,
// which beats printing half of an old profile next to half of a new one.
// All of it comes from ONE snapshot, the one the outer parse took for the global rows above:
// the provider is that parse's, and it memoizes the profile it read, so no row can come from a
// newer version of the file. Built by hand, outside FlociCli's wiring, the provider is fresh
// and reads the file here; if it has gone, resolvedFor throws and call() exits 2.
private void addStartSettings(Map<String, Object> data) {
if (global.profile == null) return;
ProfileDefaultValueProvider provider = new ProfileDefaultValueProvider(store);
ProfileDefaultValueProvider provider = ProfileDefaultValueProvider.of(spec);
StartCommand resolved = StartCommand.resolvedFor(profile, provider, global.profile);
Optional<Profile> declared = provider.resolved();
if (declared.isEmpty()) return;
@@ -32,15 +32,30 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider {
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;
}
/**
* The provider {@code FlociCli.buildCommandLine} registered, as picocli propagated it to
* {@code spec}'s command. A command that reads a profile back after parsing goes through here,
* so it reuses the store the CLI was built with and the snapshot the parse already took, never a
* second read of the file. A command built by hand, outside that wiring, gets a fresh provider
* over the default store.
*/
public static ProfileDefaultValueProvider of(CommandSpec spec) {
if (spec != null && spec.commandLine() != null
&& spec.commandLine().getDefaultValueProvider() instanceof ProfileDefaultValueProvider provider) {
return provider;
}
return new ProfileDefaultValueProvider(new ProfileStore());
}
/** The store profiles are read from. */
public ProfileStore store() {
return store;
}
/**
* The profile this provider resolved during the last parse, if any. Reading it costs nothing
* and, crucially, costs no second read of the file: a caller that needs both which keys the
@@ -1,5 +1,6 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.config.ConfigProfileCommand;
import io.floci.cli.commands.config.ConfigShowCommand;
@@ -9,12 +10,15 @@ 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.ParseResult;
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.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -33,15 +37,18 @@ class ConfigCommandsTest {
Files.writeString(tempDir.resolve(name + ".yaml"), yaml);
}
// Through the real wiring, so config show sees the provider the parse used.
private String runShow(ProductProfile product, String... args) {
CommandLine cmd = new CommandLine(new ConfigShowCommand(product, store()))
.setCaseInsensitiveEnumValuesAllowed(true)
.setDefaultValueProvider(new ProfileDefaultValueProvider(store()));
List<String> all = new ArrayList<>();
if (product != ProductProfile.AWS) all.add(product.name());
all.addAll(List.of("config", "show"));
all.addAll(List.of(args));
CommandLine cmd = FlociCli.buildCommandLine(store());
PrintStream original = System.out;
ByteArrayOutputStream captured = new ByteArrayOutputStream();
System.setOut(new PrintStream(captured));
try {
assertEquals(0, cmd.execute(args));
assertEquals(0, cmd.execute(all.toArray(String[]::new)));
} finally {
System.setOut(original);
}
@@ -293,23 +300,25 @@ class ConfigCommandsTest {
assertTrue(store().get("dev").isEmpty());
}
/** BL-003: same cause as a bad --profile at parse time, so the same exit code. */
/** Every row comes from the snapshot the parse took, even if the file goes away afterwards. */
@Test
void showExitsTwoWhenTheProfileIsGoneAfterTheParse() throws Exception {
writeProfile("gone", "container: floci-az-gone\n");
ConfigShowCommand show = new ConfigShowCommand(ProductProfile.AZ, store());
// A real parse: the provider reads the profile while it still exists.
new CommandLine(show)
.setDefaultValueProvider(new ProfileDefaultValueProvider(store()))
.parseArgs("--profile", "gone");
Files.delete(tempDir.resolve("gone.yaml"));
void showReportsTheParsesSnapshotEvenIfTheFileIsDeletedAfterwards() throws Exception {
writeProfile("snap", "container: floci-snap\npersistDir: /from-the-parse\n");
CommandLine cmd = FlociCli.buildCommandLine(store());
ParseResult parsed = cmd.parseArgs("config", "show", "--profile", "snap", "-o", "json");
while (parsed.hasSubcommand()) parsed = parsed.subcommand();
Files.delete(tempDir.resolve("snap.yaml"));
PrintStream err = System.err;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
PrintStream original = System.out;
ByteArrayOutputStream captured = new ByteArrayOutputStream();
System.setOut(new PrintStream(captured));
try {
assertEquals(CommandLine.ExitCode.USAGE, show.call());
assertEquals(0, ((ConfigShowCommand) parsed.commandSpec().userObject()).call());
} finally {
System.setErr(err);
System.setOut(original);
}
String out = captured.toString();
assertTrue(out.contains("\"container\" : \"floci-snap\""), out);
assertTrue(out.contains("\"persistDir\" : \"/from-the-parse\""), out);
}
}
@@ -1,18 +1,19 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.RestartCommand;
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 picocli.CommandLine.ParseResult;
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.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -29,10 +30,15 @@ class RestartCommandTest {
@TempDir
Path tempDir;
// Through the real wiring, so restart sees the provider the parse used.
private RestartCommand parse(ProductProfile product, String... args) {
RestartCommand restart = new RestartCommand(product, new ProfileStore(tempDir));
new CommandLine(restart).parseArgs(args);
return restart;
List<String> all = new ArrayList<>();
if (product != ProductProfile.AWS) all.add(product.name());
all.add("restart");
all.addAll(List.of(args));
ParseResult r = FlociCli.buildCommandLine(new ProfileStore(tempDir)).parseArgs(all.toArray(String[]::new));
while (r.hasSubcommand()) r = r.subcommand();
return (RestartCommand) r.commandSpec().userObject();
}
private void writeProfile(String name, String yaml) throws IOException {
@@ -128,37 +134,19 @@ class RestartCommandTest {
}
/**
* BL-003: a profile that disappears between the parse and the restart is the same user error
* as a bad --profile at parse time: exit 2, and nothing stopped.
* One snapshot: restart applies the profile the parse read, not a second read of the file, so
* an edit or delete in between cannot mix two versions into one restart.
*/
@Test
void aProfileGoneAfterTheParseExitsTwoBeforeStoppingAnything() throws Exception {
writeProfile("gone", "container: floci-az-never-started\n");
ProfileStore store = new ProfileStore(tempDir);
RestartCommand restart = new RestartCommand(ProductProfile.AZ, store);
// A real parse: the provider reads the profile while it still exists.
new CommandLine(restart)
.setDefaultValueProvider(new ProfileDefaultValueProvider(store))
.parseArgs("--profile", "gone");
Files.delete(tempDir.resolve("gone.yaml"));
void usesTheParsesSnapshotEvenIfTheFileChangesAfterwards() throws Exception {
writeProfile("snap", "container: floci-snap\npersistDir: /from-the-parse\n");
RestartCommand restart = parse(ProductProfile.AWS, "--profile", "snap");
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
int exit;
try {
exit = restart.call();
} finally {
System.setOut(out);
System.setErr(err);
}
writeProfile("snap", "container: floci-snap\npersistDir: /edited-later\n");
List<String> args = restart.buildStartCommand().dockerRunArgs(SOCKET);
assertTrue(args.contains("/from-the-parse:/app/data"), args.toString());
assertEquals(CommandLine.ExitCode.USAGE, exit);
assertTrue(errBuf.toString().contains("Profile 'gone' not found"), errBuf.toString());
// Stop prints this before calling docker; its absence means nothing was stopped.
assertFalse(outBuf.toString().contains("Stopping"), outBuf.toString());
Files.delete(tempDir.resolve("snap.yaml"));
assertTrue(restart.buildStartCommand().dockerRunArgs(SOCKET).contains("/from-the-parse:/app/data"));
}
}