mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
fix(cli): keep the selected instance in the commands that hints suggest (#74)
Commands printed by errors, env and doctor now carry --profile, --container and an explicit --endpoint, so pasting one acts on the same instance. After a failed pull, the suggested start also keeps the --port, --image, --persist, --services and --namespace you typed. The env load hint adds -o text after a profile, which may set output: json, and quotes values for the shell it is for. A value containing a line break prints as a placeholder, because the hint is a comment in the output people feed to eval. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
a319e2d242
commit
882c0ea7be
25 files changed
+355
-43
No files matched your search
@@ -854,7 +854,8 @@ expect.
|
||||
|
||||
An instance is a profile. Its **container name** is its identity, its **port** is the only thing
|
||||
that must differ from the other instances, and its **persist dir** keeps its state across
|
||||
container recreation. Every command (`status`, `logs`, `env`, `doctor`, `stop`, ...) finds the
|
||||
container recreation. Hints for follow-up CLI commands preserve the selected profile, container
|
||||
and explicit endpoint, and a retried `start` keeps the flags you typed. Every command (`status`, `logs`, `env`, `doctor`, `stop`, ...) finds the
|
||||
instance through its container, so passing the same `--profile` is all it takes. Any local state
|
||||
the CLI keeps about an instance lives in `~/.floci/<product>/<container>/`.
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
||||
"name": "floci",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.3",
|
||||
"description": "Run, wire up and troubleshoot Floci, the free local emulators for AWS, GCP, Azure and OCI: floci-cli lifecycle, safe wiring of aws, gcloud, az, oci and the SDKs, docker run and Docker Compose files, several instances side by side, and lookups in the published docs.",
|
||||
"author": {
|
||||
"name": "Floci",
|
||||
|
||||
@@ -84,7 +84,8 @@ clouds the user works with; suggest installing them, do not install them unasked
|
||||
recreating anything. If restart fails after removal, follow stderr: a start command that
|
||||
retries with the same settings, or `logs` and `wait` when the new container is up but not
|
||||
ready. Neither restores in-memory state.
|
||||
7. **Never add `-q` to `env`**: it suppresses the exports themselves.
|
||||
7. **Never add `-q` to `env`**: it suppresses the exports themselves. Follow-up command hints
|
||||
keep the instance's flags; keep them when retrying.
|
||||
8. **Do not guess what an emulator supports.** Check `floci <tree> services -o json` and the
|
||||
published docs ([references/docs.md](references/docs.md)) instead of answering from memory.
|
||||
9. **With a profile, start and wait before `env`.** Until the profile's container is running,
|
||||
|
||||
@@ -5,6 +5,7 @@ import io.floci.cli.output.Ansi;
|
||||
import io.floci.cli.output.Glyphs;
|
||||
import io.floci.cli.output.OutputFormat;
|
||||
import io.floci.cli.output.Printer;
|
||||
import io.floci.cli.output.ShellExport;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Option;
|
||||
import picocli.CommandLine.Spec;
|
||||
@@ -105,12 +106,40 @@ public class GlobalOptions {
|
||||
* empty. Values are shell-quoted, because hints are meant to be pasted.
|
||||
*/
|
||||
public String instanceSelector() {
|
||||
return selector(GlobalOptions::shellWord);
|
||||
}
|
||||
|
||||
/**
|
||||
* The flags for a hint that loads {@code env} in {@code shell}: the selector, quoted for that
|
||||
* shell, and {@code -o text} after a profile, which may set {@code output: json} that no shell
|
||||
* can load.
|
||||
*
|
||||
* <p>This hint is a comment in the output people feed to {@code eval}, so a line break in a
|
||||
* value would end the comment and run the rest as code. No quoting survives that: such a value
|
||||
* becomes a placeholder. PLAIN_WORD is a POSIX rule ({@code @team} is a splat in PowerShell),
|
||||
* so other shells always get quotes.
|
||||
*/
|
||||
public String envLoadFlags(String shell) {
|
||||
String selector = selector(value -> {
|
||||
if (ShellExport.breaksLine(value)) return "<value>";
|
||||
return ShellExport.isPosix(shell) && PLAIN_WORD.matcher(value).matches()
|
||||
? value : ShellExport.quoted(shell, value);
|
||||
});
|
||||
return profile != null ? selector + " -o text" : selector;
|
||||
}
|
||||
|
||||
private String selector(UnaryOperator<String> quote) {
|
||||
String selector = "";
|
||||
if (profile != null) {
|
||||
String selector = " --profile " + shellWord(profile);
|
||||
return typed("--container") ? selector + " --container " + shellWord(container) : selector;
|
||||
selector = " --profile " + quote.apply(profile);
|
||||
if (typed("--container")) selector += " --container " + quote.apply(container);
|
||||
} else if (!product.defaultContainer().equals(container)) {
|
||||
selector = " --container " + quote.apply(container);
|
||||
}
|
||||
if (!product.defaultContainer().equals(container)) return " --container " + shellWord(container);
|
||||
return "";
|
||||
if (typed("--endpoint") || (profile == null && !product.defaultEndpoint().equals(endpoint))) {
|
||||
selector += " --endpoint " + quote.apply(endpoint);
|
||||
}
|
||||
return selector;
|
||||
}
|
||||
|
||||
/** Whether {@code option} was given on the command line, as opposed to coming from a profile, the environment or the default. */
|
||||
|
||||
@@ -125,7 +125,7 @@ public class DoctorCommand implements Callable<Integer> {
|
||||
List<Check> selected = selected();
|
||||
if (selected.isEmpty()) {
|
||||
printer.error("Unknown check '" + checkName + "'.\nRun '" + profile.commandPrefix()
|
||||
+ " doctor' to see every check, or pass one of: " + String.join(", ", knownNames()) + ".");
|
||||
+ " doctor" + global.instanceSelector() + "' to see every check, or pass one of: " + String.join(", ", knownNames()) + ".");
|
||||
return ExitCode.USAGE;
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ public class DoctorCommand implements Callable<Integer> {
|
||||
// concurrently; results are still printed in list order as each one becomes available.
|
||||
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
List<Future<CheckResult>> pending = selected.stream()
|
||||
.map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container)))
|
||||
.map(check -> pool.submit(() -> runSafely(check, effectiveEndpoint, global.container, global.instanceSelector())))
|
||||
.toList();
|
||||
for (int i = 0; i < selected.size(); i++) {
|
||||
CheckResult result = await(selected.get(i), pending.get(i));
|
||||
@@ -200,9 +200,9 @@ public class DoctorCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
// One failing check must not abort the run: report it and keep going.
|
||||
private static CheckResult runSafely(Check check, String endpoint, String container) {
|
||||
private static CheckResult runSafely(Check check, String endpoint, String container, String selector) {
|
||||
try {
|
||||
return check.run(endpoint, container);
|
||||
return check.run(endpoint, container, selector);
|
||||
} catch (RuntimeException e) {
|
||||
return failed(check, e);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ import java.util.concurrent.Callable;
|
||||
public class EnvCommand implements Callable<Integer> {
|
||||
|
||||
@Mixin
|
||||
GlobalOptions global;
|
||||
GlobalOptions global = new GlobalOptions();
|
||||
|
||||
@Option(names = {"--host"},
|
||||
description = "Hostname for the AWS endpoint URL (default: localhost.floci.io)",
|
||||
@@ -41,6 +41,12 @@ public class EnvCommand implements Callable<Integer> {
|
||||
paramLabel = "<shell>")
|
||||
String shell;
|
||||
|
||||
private final DockerClient docker;
|
||||
|
||||
public EnvCommand() { this(new DockerClient()); }
|
||||
|
||||
public EnvCommand(DockerClient docker) { this.docker = docker; }
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
@@ -48,7 +54,7 @@ public class EnvCommand implements Callable<Integer> {
|
||||
printer.error(ShellExport.unsupported(shell));
|
||||
return 2;
|
||||
}
|
||||
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
|
||||
String effectiveEndpoint = global.resolvedEndpoint(docker);
|
||||
int port = extractPort(effectiveEndpoint);
|
||||
String endpointUrl = "http://" + host + ":" + port;
|
||||
|
||||
@@ -67,7 +73,7 @@ public class EnvCommand implements Callable<Integer> {
|
||||
printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue()));
|
||||
}
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci env")));
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci env" + global.envLoadFlags(shell))));
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,11 @@ public class LogsCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
protected LogsCommand(ProductProfile profile) {
|
||||
this(profile, new DockerClient());
|
||||
}
|
||||
|
||||
public LogsCommand(ProductProfile profile, DockerClient docker) {
|
||||
this.docker = docker;
|
||||
this.profile = profile;
|
||||
this.global = new GlobalOptions(profile);
|
||||
}
|
||||
@@ -43,15 +48,16 @@ public class LogsCommand implements Callable<Integer> {
|
||||
@Option(names = {"--service"}, description = "Filter to a specific service (not yet supported; requires server-side filtering)", paramLabel = "<name>")
|
||||
String service;
|
||||
|
||||
private final DockerClient docker;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
DockerClient docker = new DockerClient();
|
||||
|
||||
try {
|
||||
var info = docker.inspectContainer(global.container);
|
||||
if (info.isEmpty()) {
|
||||
printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start' to launch one.");
|
||||
printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch one.");
|
||||
return 1;
|
||||
}
|
||||
} catch (DockerException e) {
|
||||
|
||||
@@ -32,16 +32,23 @@ public class ServicesCommand implements Callable<Integer> {
|
||||
}
|
||||
|
||||
protected ServicesCommand(ProductProfile profile) {
|
||||
this(profile, new DockerClient());
|
||||
}
|
||||
|
||||
public ServicesCommand(ProductProfile profile, DockerClient docker) {
|
||||
this.docker = docker;
|
||||
this.profile = profile;
|
||||
this.global = new GlobalOptions(profile);
|
||||
}
|
||||
|
||||
private final DockerClient docker;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
// Resolve the endpoint from the container's port mapping, like status/wait/env do,
|
||||
// so a container started with --port <n> is still found without --endpoint.
|
||||
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
|
||||
String effectiveEndpoint = global.resolvedEndpoint(docker);
|
||||
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
|
||||
|
||||
List<String> services;
|
||||
@@ -50,7 +57,7 @@ public class ServicesCommand implements Callable<Integer> {
|
||||
services = Arrays.asList(health.services());
|
||||
} catch (Exception e) {
|
||||
printer.error("Could not reach " + profile.displayName() + " at " + effectiveEndpoint
|
||||
+ ".\nIs " + profile.displayName() + " running? Try '" + profile.commandPrefix() + " start'.");
|
||||
+ ".\nIs " + profile.displayName() + " running? Try '" + profile.commandPrefix() + " start" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,18 @@ public class StartCommand implements Callable<Integer> {
|
||||
return start;
|
||||
}
|
||||
|
||||
// The rest of what was typed, so a retried start is the same start. Empty for a start built by
|
||||
// restart, which was never parsed.
|
||||
private String typedStartFlags() {
|
||||
StringBuilder flags = new StringBuilder();
|
||||
if (global.typed("--port")) flags.append(" --port ").append(port);
|
||||
if (global.typed("--image")) flags.append(" --image ").append(GlobalOptions.shellWord(image));
|
||||
if (global.typed("--persist")) flags.append(" --persist ").append(GlobalOptions.shellWord(persistDir));
|
||||
if (global.typed("--services")) flags.append(" --services ").append(GlobalOptions.shellWord(services));
|
||||
if (global.typed("--namespace")) flags.append(" --namespace ").append(GlobalOptions.shellWord(namespace));
|
||||
return flags.toString();
|
||||
}
|
||||
|
||||
/** A self-contained POSIX command that recovers the resolved settings after a failed restart. */
|
||||
public String recoveryCommand() {
|
||||
StringBuilder command = new StringBuilder(profile.explicitCommandPrefix()).append(" start");
|
||||
@@ -378,7 +390,7 @@ public class StartCommand implements Callable<Integer> {
|
||||
if (existing.isPresent()) {
|
||||
String state = existing.get().state();
|
||||
if ("running".equals(state)) {
|
||||
printer.error("Container '" + global.container + "' is already running.\nRun '" + profile.commandPrefix() + " stop' first or pass --container <name> to use a different name.");
|
||||
printer.error("Container '" + global.container + "' is already running.\nRun '" + profile.commandPrefix() + " stop" + global.instanceSelector() + "' first or pass --container <name> to use a different name.");
|
||||
return 1;
|
||||
}
|
||||
// Remove stopped container so we can start fresh
|
||||
@@ -416,7 +428,7 @@ public class StartCommand implements Callable<Integer> {
|
||||
docker.pull(image, pull);
|
||||
}
|
||||
} catch (DockerException e) {
|
||||
printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never' to skip pulling.");
|
||||
printer.error("Failed to pull image: " + e.getMessage() + "\nRun '" + profile.commandPrefix() + " start --pull never" + global.instanceSelector() + typedStartFlags() + "' to skip pulling.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -431,7 +443,7 @@ public class StartCommand implements Callable<Integer> {
|
||||
// withNextStep, not the two-argument error: docker's own output is often several
|
||||
// lines, which must not be taken for a next step.
|
||||
printer.error("Failed to start container: " + e.withNextStep(
|
||||
"Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port."));
|
||||
"Run '" + profile.commandPrefix() + " doctor" + global.instanceSelector() + "' to check Docker, the image and the port."));
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -440,7 +452,7 @@ public class StartCommand implements Callable<Integer> {
|
||||
String endpoint = withPort(global.endpoint, port);
|
||||
|
||||
if (detach) {
|
||||
progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait' to poll for readiness."));
|
||||
progress.accept(Ansi.gray("Detached. Run '" + profile.commandPrefix() + " wait" + global.instanceSelector() + "' to poll for readiness."));
|
||||
if (structured) printer.structured(result(id, endpoint, null));
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ public class StatusCommand implements Callable<Integer> {
|
||||
|
||||
if (!reachable && !"running".equals(containerState)) {
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start' to launch " + profile.displayName() + "."));
|
||||
printer.println(Ansi.gray("Run '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch " + profile.displayName() + "."));
|
||||
}
|
||||
|
||||
return exit;
|
||||
|
||||
@@ -64,7 +64,7 @@ public class StopCommand implements Callable<Integer> {
|
||||
try {
|
||||
var info = docker.inspectContainer(global.container);
|
||||
if (info.isEmpty()) {
|
||||
printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start' to launch one.");
|
||||
printer.error("Container '" + global.container + "' not found.\nRun '" + profile.commandPrefix() + " start" + global.instanceSelector() + "' to launch one.");
|
||||
return 1;
|
||||
}
|
||||
if (!"running".equals(info.get().state())) {
|
||||
|
||||
@@ -123,7 +123,7 @@ public class WaitCommand implements Callable<Integer> {
|
||||
|
||||
if (spinner) clearSpinner(printer);
|
||||
printer.error("Timed out waiting for " + profile.displayName() + " after " + timeout
|
||||
+ ".\nIs the container running? Try '" + profile.commandPrefix() + " status'.");
|
||||
+ ".\nIs the container running? Try '" + profile.commandPrefix() + " status" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ public class AzEnvCommand implements Callable<Integer> {
|
||||
paramLabel = "<shell>")
|
||||
String shell;
|
||||
|
||||
private final DockerClient docker;
|
||||
private final Path stateRoot;
|
||||
private final AzSetupCommand.CertSource certSource;
|
||||
|
||||
@@ -81,6 +82,11 @@ public class AzEnvCommand implements Callable<Integer> {
|
||||
* each instance's config dir and CA; {@code certSource} reads the running server's CA.
|
||||
*/
|
||||
public AzEnvCommand(Path stateRoot, AzSetupCommand.CertSource certSource) {
|
||||
this(stateRoot, certSource, new DockerClient());
|
||||
}
|
||||
|
||||
public AzEnvCommand(Path stateRoot, AzSetupCommand.CertSource certSource, DockerClient docker) {
|
||||
this.docker = docker;
|
||||
this.stateRoot = stateRoot;
|
||||
this.certSource = certSource;
|
||||
}
|
||||
@@ -92,7 +98,7 @@ public class AzEnvCommand implements Callable<Integer> {
|
||||
printer.error(ShellExport.unsupported(shell));
|
||||
return 2;
|
||||
}
|
||||
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
|
||||
String effectiveEndpoint = global.resolvedEndpoint(docker);
|
||||
int port = extractPort(effectiveEndpoint);
|
||||
|
||||
boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null;
|
||||
@@ -121,7 +127,7 @@ public class AzEnvCommand implements Callable<Integer> {
|
||||
printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_CONNECTION_STRING", connStr));
|
||||
printAzCliVars(printer, azCliVars);
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env")));
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env" + global.envLoadFlags(shell))));
|
||||
} else {
|
||||
printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_ACCOUNT", account));
|
||||
printer.println(ShellExport.formatExport(shell, "AZURE_STORAGE_KEY", DEV_KEY));
|
||||
@@ -130,7 +136,7 @@ public class AzEnvCommand implements Callable<Integer> {
|
||||
}
|
||||
printAzCliVars(printer, azCliVars);
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env --format sdk-vars")));
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci az env --format sdk-vars" + global.envLoadFlags(shell))));
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -128,11 +128,11 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
return reset ? reset(printer, flociAzDir, cloud) : setup(printer, flociAzDir, cloud);
|
||||
} catch (AzCliNotFoundException e) {
|
||||
printer.error("az CLI not found in PATH.\n"
|
||||
+ "Install it from https://learn.microsoft.com/cli/azure/install-azure-cli, then re-run 'floci az setup'.");
|
||||
+ "Install it from https://learn.microsoft.com/cli/azure/install-azure-cli, then re-run 'floci az setup" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
} catch (StepFailedException e) {
|
||||
printer.error(e.getMessage()
|
||||
+ "\nFix the error above and re-run 'floci az setup', or run 'floci az setup --reset' to start over.");
|
||||
+ "\nFix the error above and re-run 'floci az setup" + global.instanceSelector() + "', or run 'floci az setup --reset" + global.instanceSelector() + "' to start over.");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -149,12 +149,12 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
caPem = fetchWithRetry(certSource, httpEndpoint, CERT_ATTEMPTS, certRetryDelay);
|
||||
} catch (TlsUnavailableException e) {
|
||||
printer.error(e.notYet()
|
||||
? "Floci Azure is still generating its TLS certificate.\nWait a few seconds and re-run 'floci az setup'."
|
||||
? "Floci Azure is still generating its TLS certificate.\nWait a few seconds and re-run 'floci az setup" + global.instanceSelector() + "'."
|
||||
: "Floci Azure is running without TLS, which the az CLI needs to log in.\n"
|
||||
+ "Run 'floci az restart' to enable it, then re-run 'floci az setup'.");
|
||||
+ "Run 'floci az restart" + global.instanceSelector() + "' to enable it, then re-run 'floci az setup" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
} catch (FlociException e) {
|
||||
printer.error(e.getMessage() + "\nRun 'floci az start', then re-run 'floci az setup'.");
|
||||
printer.error(e.getMessage() + "\nRun 'floci az start" + global.instanceSelector() + "', then re-run 'floci az setup" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
printer.error("Could not write the az configuration: " + e.getMessage()
|
||||
+ "\nCheck that " + flociAzDir + " is writable and re-run 'floci az setup'.");
|
||||
+ "\nCheck that " + flociAzDir + " is writable and re-run 'floci az setup" + global.instanceSelector() + "'.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
boolean subscriptionSet = az.run(List.of("account", "set", "--subscription", subscription), env).ok();
|
||||
|
||||
// This instance now uses the default az config. An isolated config left by an earlier
|
||||
// setup would otherwise keep 'floci az env' selecting its old login.
|
||||
// setup would otherwise keep the old login selected by env.
|
||||
boolean isolatedRemoved = false;
|
||||
if (globalConfig && Files.isDirectory(configDir)) {
|
||||
try {
|
||||
@@ -203,7 +203,7 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
isolatedRemoved = true;
|
||||
} catch (IOException e) {
|
||||
printer.warn("Could not remove the old isolated az config " + configDir.toAbsolutePath() + ": "
|
||||
+ e.getMessage() + "\nDelete it by hand, or 'floci az env' keeps selecting it.");
|
||||
+ e.getMessage() + "\nDelete it by hand, or 'floci az env" + global.instanceSelector() + "' keeps selecting it.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +279,7 @@ public class AzSetupCommand implements Callable<Integer> {
|
||||
deleteIfEmpty(flociAzDir);
|
||||
} catch (IOException e) {
|
||||
printer.error("Could not remove " + flociAzDir + ": " + e.getMessage()
|
||||
+ "\nDelete it by hand, then re-run 'floci az setup' if you need it again.");
|
||||
+ "\nDelete it by hand, then re-run 'floci az setup" + global.instanceSelector() + "' if you need it again.");
|
||||
return 1;
|
||||
}
|
||||
out.put("reset", existed);
|
||||
|
||||
@@ -41,6 +41,12 @@ public class GcpEnvCommand implements Callable<Integer> {
|
||||
paramLabel = "<shell>")
|
||||
String shell;
|
||||
|
||||
private final DockerClient docker;
|
||||
|
||||
public GcpEnvCommand() { this(new DockerClient()); }
|
||||
|
||||
public GcpEnvCommand(DockerClient docker) { this.docker = docker; }
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
@@ -48,7 +54,7 @@ public class GcpEnvCommand implements Callable<Integer> {
|
||||
printer.error(ShellExport.unsupported(shell));
|
||||
return 2;
|
||||
}
|
||||
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
|
||||
String effectiveEndpoint = global.resolvedEndpoint(docker);
|
||||
String host = extractHost(effectiveEndpoint);
|
||||
int port = extractPort(effectiveEndpoint);
|
||||
String hostPort = host + ":" + port;
|
||||
@@ -71,7 +77,7 @@ public class GcpEnvCommand implements Callable<Integer> {
|
||||
printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue()));
|
||||
}
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci gcp env")));
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci gcp env" + global.envLoadFlags(shell))));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,12 @@ public class OciEnvCommand implements Callable<Integer> {
|
||||
paramLabel = "<shell>")
|
||||
String shell;
|
||||
|
||||
private final DockerClient docker;
|
||||
|
||||
public OciEnvCommand() { this(new DockerClient()); }
|
||||
|
||||
public OciEnvCommand(DockerClient docker) { this.docker = docker; }
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
@@ -37,7 +43,7 @@ public class OciEnvCommand implements Callable<Integer> {
|
||||
printer.error(ShellExport.unsupported(shell));
|
||||
return 2;
|
||||
}
|
||||
String endpoint = global.resolvedEndpoint(new DockerClient());
|
||||
String endpoint = global.resolvedEndpoint(docker);
|
||||
|
||||
Map<String, String> vars = new LinkedHashMap<>();
|
||||
// OCI SDKs and CLI take one endpoint for every service; ocilocal reads FLOCI_OCI_ENDPOINT.
|
||||
@@ -67,7 +73,7 @@ public class OciEnvCommand implements Callable<Integer> {
|
||||
printer.println(ShellExport.formatExport(shell, entry.getKey(), entry.getValue()));
|
||||
}
|
||||
printer.println("");
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci oci env")));
|
||||
printer.println(Ansi.gray("# Run: " + ShellExport.loadHint(shell, "floci oci env" + global.envLoadFlags(shell))));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@ package io.floci.cli.doctor;
|
||||
public interface Check {
|
||||
CheckResult run(String endpoint, String container);
|
||||
|
||||
/** Instance-aware entry point; checks without CLI hints keep the original contract. */
|
||||
default CheckResult run(String endpoint, String container, String selector) {
|
||||
return run(endpoint, container);
|
||||
}
|
||||
|
||||
/**
|
||||
* The name this check reports under ({@code docker.installed}, ...), so {@code doctor --check}
|
||||
* can select it without running every other check first. {@code null} means unknown until
|
||||
|
||||
@@ -36,6 +36,13 @@ public class ContainerRunningCheck implements Check {
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container) {
|
||||
return run(endpoint, container, "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container, String selector) {
|
||||
String start = this.start + selector;
|
||||
String stop = this.stop + selector;
|
||||
try {
|
||||
var info = docker.inspectContainer(container);
|
||||
if (info.isEmpty()) {
|
||||
|
||||
@@ -37,6 +37,12 @@ public class EndpointReachableCheck implements Check {
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container) {
|
||||
return run(endpoint, container, "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container, String selector) {
|
||||
|
||||
FlociHttpClient client = new FlociHttpClient(endpoint, controlPrefix);
|
||||
try {
|
||||
var health = client.health(Duration.ofSeconds(3));
|
||||
@@ -51,6 +57,6 @@ public class EndpointReachableCheck implements Check {
|
||||
}
|
||||
return CheckResult.fail("endpoint.reachable",
|
||||
"GET " + controlPrefix + "/health at " + endpoint + " did not return 200",
|
||||
"Is Floci running? Try '" + commandPrefix + " start'.");
|
||||
"Is Floci running? Try '" + commandPrefix + " start" + selector + "'.");
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,12 @@ public class ImagePresentCheck implements Check {
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container) {
|
||||
return run(endpoint, container, "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container, String selector) {
|
||||
String pullHint = this.pullHint + selector;
|
||||
try {
|
||||
if (docker.isImagePresent(image)) {
|
||||
return CheckResult.ok("image.present", image + " image present locally");
|
||||
|
||||
@@ -46,6 +46,12 @@ public class ImageVersionCheck implements Check {
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container) {
|
||||
return run(endpoint, container, "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container, String selector) {
|
||||
String pullHint = this.pullHint + selector;
|
||||
try {
|
||||
if (!docker.isImagePresent(image)) {
|
||||
return CheckResult.warn("image.version", image + " not present — version cannot be checked",
|
||||
|
||||
@@ -45,6 +45,12 @@ public class PortAvailableCheck implements Check {
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container) {
|
||||
return run(endpoint, container, "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CheckResult run(String endpoint, String container, String selector) {
|
||||
String startCommand = this.startCommand + selector;
|
||||
int port = extractPort(endpoint, defaultPort);
|
||||
// If a Floci container is already listening on the port, that's fine
|
||||
try {
|
||||
|
||||
@@ -39,6 +39,30 @@ public final class ShellExport {
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether {@code shell} is one of the POSIX family, as opposed to fish or PowerShell. */
|
||||
public static boolean isPosix(String shell) {
|
||||
return switch (shell.toLowerCase()) {
|
||||
case "fish", "powershell", "pwsh", "ps1" -> false;
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether {@code value} could end the comment line it is printed in, in any shell. */
|
||||
public static boolean breaksLine(String value) {
|
||||
return value.chars().anyMatch(c -> Character.isISOControl(c)
|
||||
|| Character.getType(c) == Character.LINE_SEPARATOR
|
||||
|| Character.getType(c) == Character.PARAGRAPH_SEPARATOR);
|
||||
}
|
||||
|
||||
/** {@code value} as one single-quoted argument in the given shell. */
|
||||
public static String quoted(String shell, String value) {
|
||||
return switch (shell.toLowerCase()) {
|
||||
case "fish" -> "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'";
|
||||
case "powershell", "pwsh", "ps1" -> "'" + value.replace("'", "''") + "'";
|
||||
default -> "'" + value.replace("'", "'\\''") + "'";
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders one export line for the given shell ({@code bash}, {@code fish}, {@code powershell}). */
|
||||
public static String formatExport(String shell, String key, String value) {
|
||||
return switch (shell.toLowerCase()) {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
package io.floci.cli.unit;
|
||||
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.commands.DoctorCommand;
|
||||
import io.floci.cli.commands.EnvCommand;
|
||||
import io.floci.cli.commands.LogsCommand;
|
||||
import io.floci.cli.commands.ServicesCommand;
|
||||
import io.floci.cli.commands.StartCommand;
|
||||
import io.floci.cli.commands.StatusCommand;
|
||||
import io.floci.cli.commands.StopCommand;
|
||||
import io.floci.cli.commands.WaitCommand;
|
||||
import io.floci.cli.commands.az.AzEnvCommand;
|
||||
import io.floci.cli.commands.gcp.GcpEnvCommand;
|
||||
import io.floci.cli.commands.oci.OciEnvCommand;
|
||||
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.doctor.checks.ContainerRunningCheck;
|
||||
import io.floci.cli.doctor.checks.ImagePresentCheck;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import picocli.CommandLine;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class InstanceHintsTest {
|
||||
@TempDir Path temp;
|
||||
private static final List<ProductProfile> PRODUCTS = List.of(ProductProfile.AWS, ProductProfile.GCP, ProductProfile.AZ, ProductProfile.OCI);
|
||||
static class FakeDocker extends DockerClient {
|
||||
boolean running;
|
||||
@Override public DockerHost daemonHost() { return new DockerHost(Kind.TCP, null, "tcp://host:2375"); }
|
||||
@Override public Optional<ContainerInfo> inspectContainer(String name) {
|
||||
return running ? Optional.of(new ContainerInfo("id", name, "image", "running", "")) : Optional.empty();
|
||||
}
|
||||
@Override public boolean isImagePresent(String image) { return false; }
|
||||
}
|
||||
private record Run(int exit, String out, String err) { }
|
||||
private Run run(Callable<Integer> command, String... args) throws Exception {
|
||||
Files.writeString(temp.resolve("team alpha.yaml"), "container: other\nendpoint: http://127.0.0.1:1\n");
|
||||
CommandLine cli = new CommandLine(command).setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(temp)));
|
||||
PrintStream out = System.out, err = System.err;
|
||||
ByteArrayOutputStream stdout = new ByteArrayOutputStream(), stderr = new ByteArrayOutputStream();
|
||||
try {
|
||||
System.setOut(new PrintStream(stdout)); System.setErr(new PrintStream(stderr));
|
||||
int exit = cli.execute(args);
|
||||
return new Run(exit, stdout.toString(), stderr.toString());
|
||||
} finally { System.setOut(out); System.setErr(err); }
|
||||
}
|
||||
@Test
|
||||
void lifecycleFailureHintsSelectTheSameProfileAndContainerInEveryTree() throws Exception {
|
||||
for (ProductProfile product : PRODUCTS) {
|
||||
FakeDocker docker = new FakeDocker();
|
||||
for (Callable<Integer> command : List.<Callable<Integer>>of(new StopCommand(product, docker), new LogsCommand(product, docker),
|
||||
new ServicesCommand(product, docker), new WaitCommand(product, docker))) {
|
||||
String[] args = command instanceof WaitCommand
|
||||
? new String[]{"--profile", "team alpha", "--container", "override", "--timeout", "1ms"}
|
||||
: new String[]{"--profile", "team alpha", "--container", "override"};
|
||||
Run result = run(command, args);
|
||||
assertEquals(1, result.exit());
|
||||
assertTrue(result.err().contains("--profile 'team alpha' --container override"), result.err());
|
||||
}
|
||||
docker.running = true;
|
||||
Run start = run(new StartCommand(product, docker), "--profile", "team alpha", "--container", "override");
|
||||
assertTrue(start.err().contains(product.commandPrefix() + " stop --profile 'team alpha' --container override"), start.err());
|
||||
docker.running = false;
|
||||
Run status = run(new StatusCommand(product, docker), "--profile", "team alpha");
|
||||
assertTrue(status.out().contains("start --profile 'team alpha'"), status.out());
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void aFailedPullKeepsTheWholeStartInvocation() throws Exception {
|
||||
FakeDocker docker = new FakeDocker() {
|
||||
@Override public void pull(String image, String policy) throws DockerException { throw new DockerException("no such image"); }
|
||||
@Override public void pull(String image, String policy, PrintStream stream) throws DockerException { throw new DockerException("no such image"); }
|
||||
};
|
||||
Run start = run(new StartCommand(ProductProfile.AWS, docker), "--container", "other", "--port", "14566",
|
||||
"--image", "my image:1", "--pull", "always");
|
||||
assertEquals(1, start.exit());
|
||||
assertTrue(start.err().contains("floci start --pull never --container other --port 14566 --image 'my image:1'"), start.err());
|
||||
}
|
||||
@Test
|
||||
void envLoadHintsPreserveTheProfileInAllFourTrees() throws Exception {
|
||||
FakeDocker docker = new FakeDocker();
|
||||
for (Callable<Integer> env : List.<Callable<Integer>>of(new EnvCommand(docker), new GcpEnvCommand(docker),
|
||||
new OciEnvCommand(docker), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, docker))) {
|
||||
Run result = run(env, "--profile", "team alpha");
|
||||
assertEquals(0, result.exit(), result.err());
|
||||
assertTrue(result.out().contains("env --profile 'team alpha' -o text"), result.out());
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void envLoadHintsQuoteForTheShellTheyAreFor() throws Exception {
|
||||
Files.writeString(temp.resolve("team's.yaml"), "container: other\nendpoint: http://127.0.0.1:1\n");
|
||||
for (Callable<Integer> env : List.<Callable<Integer>>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()),
|
||||
new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) {
|
||||
assertTrue(run(env, "--profile", "team's").out().contains("--profile 'team'\\''s' -o text)\""));
|
||||
}
|
||||
for (Callable<Integer> env : List.<Callable<Integer>>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()),
|
||||
new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) {
|
||||
String out = run(env, "--profile", "team's", "--shell", "powershell").out();
|
||||
assertTrue(out.contains("--profile 'team''s' -o text --shell powershell | Invoke-Expression"), out);
|
||||
}
|
||||
for (Callable<Integer> env : List.<Callable<Integer>>of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()),
|
||||
new OciEnvCommand(new FakeDocker()), new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()))) {
|
||||
String out = run(env, "--profile", "team's", "--shell", "fish").out();
|
||||
assertTrue(out.contains("--profile 'team\\'s' -o text --shell fish | source"), out);
|
||||
}
|
||||
}
|
||||
private List<Callable<Integer>> allEnvCommands() {
|
||||
return List.of(new EnvCommand(new FakeDocker()), new GcpEnvCommand(new FakeDocker()), new OciEnvCommand(new FakeDocker()),
|
||||
new AzEnvCommand(temp, endpoint -> { throw new AssertionError("no cert expected"); }, new FakeDocker()));
|
||||
}
|
||||
@Test
|
||||
void aValueWithALineBreakCannotEscapeTheHintComment() throws Exception {
|
||||
for (String breaker : List.of("\n", "\r", "\u0085", "\u2028", "\u2029")) {
|
||||
for (String shell : List.of("bash", "fish", "powershell")) {
|
||||
for (Callable<Integer> env : allEnvCommands()) {
|
||||
Run result = run(env, "--container", "x" + breaker + "touch injected" + breaker + "#",
|
||||
"--endpoint", "http://localhost:1", "--shell", shell);
|
||||
assertEquals(0, result.exit(), result.err());
|
||||
assertFalse(result.out().contains("touch injected"), result.out());
|
||||
assertTrue(result.out().contains("--container <value>"), result.out());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void nonPosixShellsQuoteEvenAPlainValue() throws Exception {
|
||||
for (Callable<Integer> env : allEnvCommands()) {
|
||||
String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1", "--shell", "powershell").out();
|
||||
assertTrue(out.contains("--container '@team'"), out);
|
||||
}
|
||||
for (Callable<Integer> env : allEnvCommands()) {
|
||||
String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1", "--shell", "fish").out();
|
||||
assertTrue(out.contains("--container '@team'"), out);
|
||||
}
|
||||
for (Callable<Integer> env : allEnvCommands()) {
|
||||
String out = run(env, "--container", "@team", "--endpoint", "http://localhost:1").out();
|
||||
assertTrue(out.contains("--container @team"), out);
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void aProfileThatAsksForJsonStillGetsALoadableHint() throws Exception {
|
||||
Files.writeString(temp.resolve("json.yaml"), "container: other\nendpoint: http://127.0.0.1:1\noutput: json\n");
|
||||
String out = run(new EnvCommand(new FakeDocker()), "--profile", "json", "-o", "text").out();
|
||||
assertTrue(out.contains("eval \"$(floci env --profile json -o text)\""), out);
|
||||
}
|
||||
@Test
|
||||
void aLoadHintWithoutAProfileStaysBare() throws Exception {
|
||||
assertTrue(run(new EnvCommand(new FakeDocker())).out().contains("eval \"$(floci env)\""));
|
||||
}
|
||||
@Test
|
||||
void doctorPassesTheSelectorToCheckFixesInStructuredOutput() throws Exception {
|
||||
for (ProductProfile product : PRODUCTS) {
|
||||
FakeDocker docker = new FakeDocker();
|
||||
DoctorCommand doctor = new DoctorCommand(product, docker, List.of(new ContainerRunningCheck(docker, product), new ImagePresentCheck(product, docker)));
|
||||
Run result = run(doctor, "--profile", "team alpha", "--container", "override", "--json");
|
||||
assertEquals(1, result.exit());
|
||||
assertEquals(2, result.out().split("--profile 'team alpha' --container override", -1).length - 1, result.out());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -294,7 +294,7 @@ class StartPreflightTest {
|
||||
|
||||
assertEquals(1, r.exit());
|
||||
assertTrue(r.err().contains("Failed to start container: docker: Error response from daemon"), r.err());
|
||||
assertTrue(r.err().strip().endsWith("Run 'floci gcp doctor' to check Docker, the image and the port."), r.err());
|
||||
assertTrue(r.err().strip().endsWith("Run 'floci gcp doctor --container floci-gcp-preflight' to check Docker, the image and the port."), r.err());
|
||||
}
|
||||
|
||||
/** A context selected with DOCKER_CONTEXT or 'docker context use' is not in the environment: docker is asked. */
|
||||
|
||||
Reference in new issue
Block a user