feat(cli): add --json, --no-emoji, config profile edit and a warning for servers too old for the CLI (#62)

* feat(cli): add --json, --no-emoji, config profile edit and a warning for servers too old for the CLI

--json is shorthand for --output json. Marks are plain ASCII with --no-emoji, when output is piped and under NO_COLOR. config profile edit opens a profile in VISUAL or EDITOR and checks it still reads. status and version warn on stderr when the AWS server is older than the minimum the CLI supports.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* feat(cli): keep the upgrade hint on the selected instance and read quoted editor commands

The old-server hint names the instance it is about and suggests a restart, which keeps that instance's settings. The update notice follows --no-emoji and NO_COLOR. VISUAL and EDITOR are split like a shell would, so a quoted path with spaces works.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* feat(cli): keep Windows paths in editor values and say what to do for a pinned image

A backslash in VISUAL or EDITOR is an escape only before a space or a quote, so Windows paths come through intact. The old-server hint explains that restart keeps a pinned tag and how to change it.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* feat(config): let profile edit open a profile that no longer parses

edit asked the store to parse the profile before opening it, so the one profile that needed repairing could not be opened. A file holding YAML's null is now reported as a profile without settings instead of failing with an exception.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-11 09:12:44 -05:00
1 parent 6b06382516
commit de3ca7f171
16 files changed
+660 -20

No files matched your search

+17
View File
@@ -312,15 +312,21 @@ All commands support `--help`.
## Global Flags ## Global Flags
Every tree takes the same flags; only the defaults differ. Marks are plain ASCII without
`--no-emoji` too whenever the output is not a terminal (a pipe, a file, CI logs) or `NO_COLOR` is
set. `--json` wins when it is combined with `--output`.
### AWS global flags ### AWS global flags
``` ```
--endpoint <url> Floci server URL (default: http://localhost:4566, env: FLOCI_ENDPOINT) --endpoint <url> Floci server URL (default: http://localhost:4566, env: FLOCI_ENDPOINT)
--container <name> Container name (default: floci, env: FLOCI_CONTAINER) --container <name> Container name (default: floci, env: FLOCI_CONTAINER)
--output|-o text|json|yaml Output format (default: text) --output|-o text|json|yaml Output format (default: text)
--json Shorthand for --output json
--quiet, -q Suppress non-error output --quiet, -q Suppress non-error output
--verbose, -v Debug logging to stderr --verbose, -v Debug logging to stderr
--no-color Disable ANSI colors --no-color Disable ANSI colors
--no-emoji Plain ASCII marks (+ ! x ->) instead of Unicode ones
--profile <name> Load settings from ~/.floci/profiles/<name>.yaml --profile <name> Load settings from ~/.floci/profiles/<name>.yaml
``` ```
@@ -332,9 +338,11 @@ Explicit flags override the profile; the profile overrides the environment varia
--endpoint <url> Floci GCP server URL (default: http://localhost:4588, env: FLOCI_GCP_ENDPOINT) --endpoint <url> Floci GCP server URL (default: http://localhost:4588, env: FLOCI_GCP_ENDPOINT)
--container <name> Container name (default: floci-gcp, env: FLOCI_GCP_CONTAINER) --container <name> Container name (default: floci-gcp, env: FLOCI_GCP_CONTAINER)
--output|-o text|json|yaml Output format (default: text) --output|-o text|json|yaml Output format (default: text)
--json Shorthand for --output json
--quiet, -q Suppress non-error output --quiet, -q Suppress non-error output
--verbose, -v Debug logging to stderr --verbose, -v Debug logging to stderr
--no-color Disable ANSI colors --no-color Disable ANSI colors
--no-emoji Plain ASCII marks (+ ! x ->) instead of Unicode ones
--profile <name> Load settings from ~/.floci/profiles/<name>.yaml --profile <name> Load settings from ~/.floci/profiles/<name>.yaml
``` ```
@@ -346,9 +354,11 @@ Explicit flags override the profile; the profile overrides the environment varia
--endpoint <url> Floci Azure server URL (default: http://localhost:4577, env: FLOCI_AZ_ENDPOINT) --endpoint <url> Floci Azure server URL (default: http://localhost:4577, env: FLOCI_AZ_ENDPOINT)
--container <name> Container name (default: floci-az, env: FLOCI_AZ_CONTAINER) --container <name> Container name (default: floci-az, env: FLOCI_AZ_CONTAINER)
--output|-o text|json|yaml Output format (default: text) --output|-o text|json|yaml Output format (default: text)
--json Shorthand for --output json
--quiet, -q Suppress non-error output --quiet, -q Suppress non-error output
--verbose, -v Debug logging to stderr --verbose, -v Debug logging to stderr
--no-color Disable ANSI colors --no-color Disable ANSI colors
--no-emoji Plain ASCII marks (+ ! x ->) instead of Unicode ones
--profile <name> Load settings from ~/.floci/profiles/<name>.yaml --profile <name> Load settings from ~/.floci/profiles/<name>.yaml
``` ```
@@ -360,9 +370,11 @@ Explicit flags override the profile; the profile overrides the environment varia
--endpoint <url> Floci OCI server URL (default: http://localhost:4599, env: FLOCI_OCI_ENDPOINT) --endpoint <url> Floci OCI server URL (default: http://localhost:4599, env: FLOCI_OCI_ENDPOINT)
--container <name> Container name (default: floci-oci, env: FLOCI_OCI_CONTAINER) --container <name> Container name (default: floci-oci, env: FLOCI_OCI_CONTAINER)
--output|-o text|json|yaml Output format (default: text) --output|-o text|json|yaml Output format (default: text)
--json Shorthand for --output json
--quiet, -q Suppress non-error output --quiet, -q Suppress non-error output
--verbose, -v Debug logging to stderr --verbose, -v Debug logging to stderr
--no-color Disable ANSI colors --no-color Disable ANSI colors
--no-emoji Plain ASCII marks (+ ! x ->) instead of Unicode ones
--profile <name> Load settings from ~/.floci/profiles/<name>.yaml --profile <name> Load settings from ~/.floci/profiles/<name>.yaml
``` ```
@@ -689,6 +701,10 @@ floci version # CLI version, server version, image digest
floci version -o json floci version -o json
``` ```
`floci version` and `floci status` warn on stderr when the AWS server is older than 1.5.0, the
oldest version this CLI supports. The GCP, Azure and OCI emulators are versioned separately and
have no minimum yet.
### `floci services` / `floci gcp services` / `floci az services` / `floci oci services` ### `floci services` / `floci gcp services` / `floci az services` / `floci oci services`
```sh ```sh
@@ -721,6 +737,7 @@ floci config profile list # list saved profiles: container, por
floci config profile create <name> # create a new profile with the tree's defaults floci config profile create <name> # create a new profile with the tree's defaults
floci config profile create <name> --container <c> --port <p> --persist <dir> --services <csv> --image <img> --namespace <ns> floci config profile create <name> --container <c> --port <p> --persist <dir> --services <csv> --image <img> --namespace <ns>
floci config profile show <name> # show a profile floci config profile show <name> # show a profile
floci config profile edit <name> # open the profile in $VISUAL or $EDITOR, then check it still reads
floci config profile delete <name> # delete a profile floci config profile delete <name> # delete a profile
floci config validate -f docker-compose.yml # validate a Compose file floci config validate -f docker-compose.yml # validate a Compose file
``` ```
+14 -1
View File
@@ -12,6 +12,7 @@ import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.config.ProfileNotFoundException; import io.floci.cli.config.ProfileNotFoundException;
import io.floci.cli.config.ProfileStore; import io.floci.cli.config.ProfileStore;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.update.UpdateNotifier; import io.floci.cli.update.UpdateNotifier;
import picocli.CommandLine; import picocli.CommandLine;
import picocli.CommandLine.*; import picocli.CommandLine.*;
@@ -80,6 +81,11 @@ public class FlociCli implements Runnable {
if (colorDisabled(args, System.getenv("NO_COLOR") != null, System.console() != null)) { if (colorDisabled(args, System.getenv("NO_COLOR") != null, System.console() != null)) {
Ansi.disable(); Ansi.disable();
} }
// Decided here too, not only when a command builds its printer: the update notice below
// is printed before any command runs.
if (plainGlyphs(args, System.getenv("NO_COLOR") != null, System.console() != null)) {
Glyphs.plain();
}
// If no explicit product subcommand, route bare commands to the configured default. // If no explicit product subcommand, route bare commands to the configured default.
// "floci az start" and "floci aws start" always win; only bare "floci start" is affected. // "floci az start" and "floci aws start" always win; only bare "floci start" is affected.
@@ -103,7 +109,7 @@ public class FlociCli implements Runnable {
if (notify) { if (notify) {
UpdateNotifier.pendingNotice(CliVersion.CLI_VERSION).ifPresent(latest -> UpdateNotifier.pendingNotice(CliVersion.CLI_VERSION).ifPresent(latest ->
System.err.println(Ansi.yellow("A new release of floci is available: " System.err.println(Ansi.yellow("A new release of floci is available: "
+ CliVersion.CLI_VERSION + " → " + latest + "\n" + CliVersion.CLI_VERSION + " " + Glyphs.arrow() + " " + latest + "\n"
+ "Run 'floci update' to install it") + "\n")); + "Run 'floci update' to install it") + "\n"));
UpdateNotifier.refreshInBackground(); UpdateNotifier.refreshInBackground();
} }
@@ -154,6 +160,13 @@ public class FlociCli implements Runnable {
* arguments here as well as by {@code GlobalOptions.printer()}: a parse error is printed by the * arguments here as well as by {@code GlobalOptions.printer()}: a parse error is printed by the
* exception handlers before any command, and so any printer, exists. * exception handlers before any command, and so any printer, exists.
*/ */
/** Whether marks are plain ASCII for this invocation, read from the raw arguments like {@link #colorDisabled}. */
public static boolean plainGlyphs(String[] args, boolean noColorEnv, boolean interactive) {
boolean flag = Arrays.stream(args)
.anyMatch(a -> a.equals("--no-emoji") || a.equalsIgnoreCase("--no-emoji=true"));
return GlobalOptions.plainGlyphs(flag, interactive, noColorEnv);
}
public static boolean colorDisabled(String[] args, boolean noColorEnv, boolean interactive) { public static boolean colorDisabled(String[] args, boolean noColorEnv, boolean interactive) {
return noColorEnv || !interactive || Arrays.stream(args) return noColorEnv || !interactive || Arrays.stream(args)
.anyMatch(a -> a.equals("--no-color") || a.equalsIgnoreCase("--no-color=true")); .anyMatch(a -> a.equals("--no-color") || a.equalsIgnoreCase("--no-color=true"));
+24 -1
View File
@@ -2,6 +2,7 @@ package io.floci.cli;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
@@ -61,6 +62,9 @@ public class GlobalOptions {
paramLabel = "text|json|yaml") paramLabel = "text|json|yaml")
public OutputFormat output; public OutputFormat output;
@Option(names = {"--json"}, description = "Shorthand for --output json")
public boolean json;
@Option(names = {"--quiet", "-q"}, description = "Suppress non-error output") @Option(names = {"--quiet", "-q"}, description = "Suppress non-error output")
public boolean quiet; public boolean quiet;
@@ -70,6 +74,9 @@ public class GlobalOptions {
@Option(names = {"--no-color"}, description = "Disable ANSI colors") @Option(names = {"--no-color"}, description = "Disable ANSI colors")
public boolean noColor; public boolean noColor;
@Option(names = {"--no-emoji"}, description = "Plain ASCII marks instead of Unicode ones (the default when output is piped)")
public boolean noEmoji;
public GlobalOptions() { public GlobalOptions() {
this(ProductProfile.AWS); this(ProductProfile.AWS);
} }
@@ -131,7 +138,23 @@ public class GlobalOptions {
if (verbose) { if (verbose) {
System.setProperty(VERBOSE_PROPERTY, "true"); System.setProperty(VERBOSE_PROPERTY, "true");
} }
return new Printer(System.out, System.err, output, quiet); if (plainGlyphs(noEmoji, isStdoutTty(), System.getenv("NO_COLOR") != null)) {
Glyphs.plain();
}
return new Printer(System.out, System.err, format(), quiet);
}
/** The output format in effect: {@code --json} is {@code --output json} and wins over it. */
public OutputFormat format() {
return json ? OutputFormat.json : output;
}
/**
* Whether marks are printed as plain ASCII: on request, when nobody is looking at a terminal
* (a pipe, a file, CI logs), or when NO_COLOR asks for undecorated output.
*/
public static boolean plainGlyphs(boolean noEmoji, boolean terminal, boolean noColorEnv) {
return noEmoji || !terminal || noColorEnv;
} }
// Inspects the container and derives the endpoint from its host port mapping. // Inspects the container and derives the endpoint from its host port mapping.
@@ -0,0 +1,40 @@
package io.floci.cli;
import io.floci.cli.doctor.checks.ImageVersionCheck;
import io.floci.cli.update.Version;
import java.util.Optional;
/** Whether a running server is new enough for this CLI. */
public final class ServerCompatibility {
private ServerCompatibility() {}
/**
* What to tell the user when {@code product}'s server reports {@code serverVersion}, or empty
* when there is nothing to say. Only the AWS emulator has a minimum: the others are versioned
* on their own lines (0.x), where the same number would flag every release. A version that
* does not read as one ("unknown", a development build) is not judged.
*
* @param instanceSelector the flags that select the instance the version came from
* ({@link GlobalOptions#instanceSelector()}), so the hint acts on that
* instance and not on the default one
*/
public static Optional<String> warning(ProductProfile product, String serverVersion, String instanceSelector) {
if (!"aws".equals(product.name()) || !Version.isValid(serverVersion)
|| ImageVersionCheck.meetsMinimum(serverVersion, ImageVersionCheck.MIN_VERSION)) {
return Optional.empty();
}
// restart, not stop and start: it brings the instance back with the port, data directory
// and services it has now. It also keeps the image reference, so an instance pinned to an
// old tag needs that changed first; the hint says where.
String prefix = product.commandPrefix();
return Optional.of(product.displayName() + " server " + serverVersion + " is older than "
+ ImageVersionCheck.MIN_VERSION + ", the oldest version this CLI supports; some commands may not work."
+ "\nPull a newer image ('docker pull " + product.defaultImageRef() + "'), then run '"
+ prefix + " restart" + instanceSelector + "'."
+ "\nIf the instance pins an older tag, restart keeps it: change 'image' in its profile first, or run '"
+ prefix + " stop --remove" + instanceSelector + "' and start it again with its usual flags plus"
+ " '--image " + product.defaultImageRef() + "'.");
}
}
@@ -21,6 +21,7 @@ import io.floci.cli.doctor.checks.ImagePresentCheck;
import io.floci.cli.doctor.checks.ImageVersionCheck; import io.floci.cli.doctor.checks.ImageVersionCheck;
import io.floci.cli.doctor.checks.PortAvailableCheck; import io.floci.cli.doctor.checks.PortAvailableCheck;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.*; import picocli.CommandLine.*;
@@ -226,9 +227,9 @@ public class DoctorCommand implements Callable<Integer> {
public static void printResult(Printer printer, CheckResult r) { public static void printResult(Printer printer, CheckResult r) {
String icon = switch (r.status()) { String icon = switch (r.status()) {
case ok -> Ansi.green("✓"); case ok -> Ansi.green(Glyphs.ok());
case warn -> Ansi.yellow("⚠"); case warn -> Ansi.yellow(Glyphs.warn());
case fail -> Ansi.red("✗"); case fail -> Ansi.red(Glyphs.fail());
}; };
String namePadded = String.format("%-26s", r.name()); String namePadded = String.format("%-26s", r.name());
printer.println(" " + icon + " " + namePadded + " " + r.message()); printer.println(" " + icon + " " + namePadded + " " + r.message());
@@ -7,6 +7,7 @@ import io.floci.cli.docker.DockerException;
import io.floci.cli.http.FlociException; import io.floci.cli.http.FlociException;
import io.floci.cli.http.FlociHttpClient; import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.*; import picocli.CommandLine.*;
@@ -166,7 +167,7 @@ public class ResetCommand implements Callable<Integer> {
printer.structured(out); printer.structured(out);
return 0; return 0;
} }
printer.println(Ansi.green("✓") + " " + profile.displayName() + " state reset" + Ansi.gray(" (" + effectiveEndpoint + ")")); printer.println(Ansi.green(Glyphs.ok()) + " " + profile.displayName() + " state reset" + Ansi.gray(" (" + effectiveEndpoint + ")"));
return 0; return 0;
} }
} }
@@ -5,6 +5,7 @@ import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.http.FlociHttpClient; import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.*; import picocli.CommandLine.*;
@@ -61,7 +62,7 @@ public class ServicesCommand implements Callable<Integer> {
printer.println(Ansi.bold(profile.displayName() + " Services") + " " + Ansi.gray("(" + services.size() + " enabled)")); printer.println(Ansi.bold(profile.displayName() + " Services") + " " + Ansi.gray("(" + services.size() + " enabled)"));
printer.println(""); printer.println("");
for (String svc : services) { for (String svc : services) {
printer.println(" " + Ansi.green("✓") + " " + svc); printer.println(" " + Ansi.green(Glyphs.ok()) + " " + svc);
} }
if (services.isEmpty()) { if (services.isEmpty()) {
printer.println(" " + Ansi.gray("(no services reported)")); printer.println(" " + Ansi.gray("(no services reported)"));
@@ -2,6 +2,7 @@ package io.floci.cli.commands;
import io.floci.cli.GlobalOptions; import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.ServerCompatibility;
import io.floci.cli.docker.DockerClient; import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException; import io.floci.cli.docker.DockerException;
import io.floci.cli.http.FlociHttpClient; import io.floci.cli.http.FlociHttpClient;
@@ -76,6 +77,8 @@ public class StatusCommand implements Callable<Integer> {
serverEdition = health.edition(); serverEdition = health.edition();
reachable = true; reachable = true;
} catch (Exception ignored) {} } catch (Exception ignored) {}
// On stderr, so structured output stays one document.
ServerCompatibility.warning(profile, serverVersion, global.instanceSelector()).ifPresent(printer::warn);
Map<String, Object> data = new LinkedHashMap<>(); Map<String, Object> data = new LinkedHashMap<>();
data.put("container", global.container); data.put("container", global.container);
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.cli.CliVersion; import io.floci.cli.CliVersion;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import io.floci.cli.update.ReleaseChannel; import io.floci.cli.update.ReleaseChannel;
@@ -109,11 +110,11 @@ public class UpdateCommand implements Callable<Integer> {
// (0.1.9-rc.1) must not be silently downgraded to the latest stable (0.1.8). // (0.1.9-rc.1) must not be silently downgraded to the latest stable (0.1.8).
// Pinned --version keeps exact equality so deliberate downgrades still work. // Pinned --version keeps exact equality so deliberate downgrades still work.
if (pinned ? target.equals(current) : !Version.isNewer(target, current)) { if (pinned ? target.equals(current) : !Version.isNewer(target, current)) {
printer.println(Ansi.green("✓") + " floci " + current + " is up to date"); printer.println(Ansi.green(Glyphs.ok()) + " floci " + current + " is up to date");
return 0; return 0;
} }
printer.println("update available: " + current + " → " + Ansi.bold(target)); printer.println("update available: " + current + " " + Glyphs.arrow() + " " + Ansi.bold(target));
if (check) { if (check) {
printer.println(Ansi.gray(installHint())); printer.println(Ansi.gray(installHint()));
// Non-zero so scripts can gate on staleness: floci update --check || floci update // Non-zero so scripts can gate on staleness: floci update --check || floci update
@@ -132,13 +133,13 @@ public class UpdateCommand implements Callable<Integer> {
Path fresh = work.resolve(asset); Path fresh = work.resolve(asset);
fetchFile(ReleaseChannel.assetUrl(downloadBase, target, asset), fresh); fetchFile(ReleaseChannel.assetUrl(downloadBase, target, asset), fresh);
verifyChecksum(fresh, asset, fetchString(ReleaseChannel.assetUrl(downloadBase, target, "sha256sums.txt"))); verifyChecksum(fresh, asset, fetchString(ReleaseChannel.assetUrl(downloadBase, target, "sha256sums.txt")));
printer.println(Ansi.green("✓") + " checksum verified"); printer.println(Ansi.green(Glyphs.ok()) + " checksum verified");
replaceAtomically(fresh, binary); replaceAtomically(fresh, binary);
} finally { } finally {
deleteRecursively(work); deleteRecursively(work);
} }
printer.println(Ansi.green("✓") + " updated: " + current + " → " + target printer.println(Ansi.green(Glyphs.ok()) + " updated: " + current + " " + Glyphs.arrow() + " " + target
+ Ansi.gray(" (" + binary + ")")); + Ansi.gray(" (" + binary + ")"));
return 0; return 0;
} catch (UpdateException e) { } catch (UpdateException e) {
@@ -314,7 +315,7 @@ public class UpdateCommand implements Callable<Integer> {
private String fetchString(String url) throws IOException, InterruptedException { private String fetchString(String url) throws IOException, InterruptedException {
HttpResponse<String> resp = http().send(get(url), HttpResponse.BodyHandlers.ofString()); HttpResponse<String> resp = http().send(get(url), HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) { if (resp.statusCode() != 200) {
throw new IOException("GET " + url + " → HTTP " + resp.statusCode()); throw new IOException("GET " + url + " " + Glyphs.arrow() + " HTTP " + resp.statusCode());
} }
if (resp.body().isBlank()) { if (resp.body().isBlank()) {
// GitHub's CDN can intermittently return 200 with an empty body (see install.sh). // GitHub's CDN can intermittently return 200 with an empty body (see install.sh).
@@ -326,7 +327,7 @@ public class UpdateCommand implements Callable<Integer> {
private void fetchFile(String url, Path dest) throws IOException, InterruptedException { private void fetchFile(String url, Path dest) throws IOException, InterruptedException {
HttpResponse<Path> resp = http().send(get(url), HttpResponse.BodyHandlers.ofFile(dest)); HttpResponse<Path> resp = http().send(get(url), HttpResponse.BodyHandlers.ofFile(dest));
if (resp.statusCode() != 200) { if (resp.statusCode() != 200) {
throw new UpdateException("download failed: " + url + " → HTTP " + resp.statusCode() throw new UpdateException("download failed: " + url + " " + Glyphs.arrow() + " HTTP " + resp.statusCode()
+ (resp.statusCode() == 404 ? " (does that release exist?)" : "")); + (resp.statusCode() == 404 ? " (does that release exist?)" : ""));
} }
if (Files.size(dest) == 0) { if (Files.size(dest) == 0) {
@@ -3,6 +3,7 @@ package io.floci.cli.commands;
import io.floci.cli.CliVersion; import io.floci.cli.CliVersion;
import io.floci.cli.GlobalOptions; import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.ServerCompatibility;
import io.floci.cli.http.FlociHttpClient; import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
@@ -52,6 +53,8 @@ public class VersionCommand implements Callable<Integer> {
serverVersion = info.version(); serverVersion = info.version();
serverEdition = info.edition(); serverEdition = info.edition();
} catch (Exception ignored) {} } catch (Exception ignored) {}
// On stderr, so structured output stays one document.
ServerCompatibility.warning(profile, serverVersion, global.instanceSelector()).ifPresent(printer::warn);
// Try to read image digest from Docker (best-effort) // Try to read image digest from Docker (best-effort)
try { try {
@@ -12,6 +12,7 @@ import picocli.CommandLine.*;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
@@ -19,6 +20,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.function.UnaryOperator;
@Command( @Command(
name = "profile", name = "profile",
@@ -45,15 +47,23 @@ public class ConfigProfileCommand implements Callable<Integer> {
/** Test seam: a store pointed at a temporary profiles directory. */ /** Test seam: a store pointed at a temporary profiles directory. */
public ConfigProfileCommand(ProductProfile profile, ProfileStore store) { public ConfigProfileCommand(ProductProfile profile, ProfileStore store) {
this(profile, store, System::getenv);
}
/** Test seam: {@code env} answers the {@code VISUAL}/{@code EDITOR} lookup that {@code edit} makes. */
public ConfigProfileCommand(ProductProfile profile, ProfileStore store, UnaryOperator<String> env) {
this.profile = profile; this.profile = profile;
this.store = store; this.store = store;
this.env = env;
this.global = new GlobalOptions(profile); this.global = new GlobalOptions(profile);
} }
@Parameters(index = "0", description = "Action: list, show, create, delete", paramLabel = "list|show|create|delete") private final UnaryOperator<String> env;
@Parameters(index = "0", description = "Action: list, show, create, edit, delete", paramLabel = "list|show|create|edit|delete")
String action; String action;
@Parameters(index = "1", description = "Profile name (required for show, create, delete)", arity = "0..1", paramLabel = "<name>") @Parameters(index = "1", description = "Profile name (required for show, create, edit, delete)", arity = "0..1", paramLabel = "<name>")
String name; String name;
// create only. With --container they describe one instance, so several profiles can run the // create only. With --container they describe one instance, so several profiles can run the
@@ -85,9 +95,10 @@ public class ConfigProfileCommand implements Callable<Integer> {
case "list" -> listProfiles(printer, store); case "list" -> listProfiles(printer, store);
case "show" -> showProfile(printer, store); case "show" -> showProfile(printer, store);
case "create" -> createProfile(printer, store); case "create" -> createProfile(printer, store);
case "edit" -> editProfile(printer, store);
case "delete" -> deleteProfile(printer, store); case "delete" -> deleteProfile(printer, store);
default -> { default -> {
printer.error("Unknown action '" + action + "'.\nUse one of: list, show, create, delete."); printer.error("Unknown action '" + action + "'.\nUse one of: list, show, create, edit, delete.");
yield 1; yield 1;
} }
}; };
@@ -169,6 +180,124 @@ public class ConfigProfileCommand implements Callable<Integer> {
} }
} }
/**
* Opens the profile's file in the user's editor, then reads it back. The file is the one
* the profile is read from ({@code .yaml} or {@code .yml}); a profile that does not exist is
* not created here, since {@code create} is what writes the product's defaults into it.
*/
private int editProfile(Printer printer, ProfileStore store) {
if (name == null) { printer.error(nameRequired()); return 1; }
String prefix = this.profile.commandPrefix() + " config profile ";
// Asked of the file, not of its contents: a profile that no longer parses is exactly the
// one that has to be opened to be repaired.
Path file = store.existingFile(name);
if (!Files.exists(file)) {
printer.error("Profile '" + name + "' not found.\nRun '" + prefix + "create " + name + "' to create it first.");
return 1;
}
List<String> editor = editorCommand(env.apply("VISUAL"), env.apply("EDITOR"));
if (editor.isEmpty()) {
printer.error("No editor is set, so " + file + " was not opened.\n"
+ "Set EDITOR (for example 'export EDITOR=vi'), or edit the file yourself.");
return 1;
}
List<String> command = new ArrayList<>(editor);
command.add(file.toString());
int exit;
try {
exit = new ProcessBuilder(command).inheritIO().start().waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
printer.error("Interrupted while " + editor.get(0) + " was open.\nRe-run '" + prefix + "edit " + name + "'.");
return 1;
} catch (IOException e) {
printer.error("Could not start the editor '" + String.join(" ", editor) + "': " + e.getMessage(),
"Set EDITOR to a command on your PATH, or edit " + file + " yourself.");
return 1;
}
if (exit != 0) {
printer.error("The editor '" + String.join(" ", editor) + "' exited with code " + exit + ".\n"
+ "Re-run '" + prefix + "edit " + name + "', or edit " + file + " yourself.");
return 1;
}
// Read it back: a typo that breaks the YAML should surface now, not on the next start.
try {
var edited = store.get(name);
if (edited.isEmpty()) {
printer.error("Profile '" + name + "' is gone after the edit.\nRun '" + prefix + "create " + name + "' to create it again.");
return 1;
}
ProfileDefaultValueProvider.warnAboutUnknownKeys(store, name, edited.get());
} catch (IOException e) {
String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable");
printer.error("Profile '" + name + "' is no longer valid: " + reason + "\n"
+ "Re-run '" + prefix + "edit " + name + "' to fix it.");
return 1;
}
printer.println("Profile '" + name + "' saved " + Ansi.gray("(" + file + ")"));
return 0;
}
/**
* The editor to run, as a command and its arguments: {@code VISUAL} first, then
* {@code EDITOR}, as other tools do. Empty when neither is set.
*/
public static List<String> editorCommand(String visual, String editor) {
String chosen = visual != null && !visual.isBlank() ? visual : editor;
if (chosen == null || chosen.isBlank()) return List.of();
return words(chosen);
}
/**
* {@code line} split into words the way a shell would for a simple command: whitespace
* separates, and single and double quotes group (a path with spaces). A backslash is an
* escape only in front of a space or a quote; anywhere else it is an ordinary character, so
* a Windows path ({@code C:\Windows\System32\notepad.exe}, {@code \\server\share\edit})
* comes through intact. Nothing is expanded; the words go straight to the process, never
* through a shell.
*/
static List<String> words(String line) {
List<String> words = new ArrayList<>();
StringBuilder word = new StringBuilder();
boolean inWord = false;
char quote = 0;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (quote != 0) {
if (c == quote) {
quote = 0;
} else if (c == '\\' && quote == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {
word.append(line.charAt(++i));
} else {
word.append(c);
}
} else if (c == '\'' || c == '"') {
quote = c;
inWord = true;
} else if (c == '\\' && i + 1 < line.length() && escapable(line.charAt(i + 1))) {
word.append(line.charAt(++i));
inWord = true;
} else if (Character.isWhitespace(c)) {
if (inWord) {
words.add(word.toString());
word.setLength(0);
inWord = false;
}
} else {
word.append(c);
inWord = true;
}
}
if (inWord) words.add(word.toString());
return List.copyOf(words);
}
private static boolean escapable(char next) {
return Character.isWhitespace(next) || next == '"' || next == '\'';
}
private int createProfile(Printer printer, ProfileStore store) { private int createProfile(Printer printer, ProfileStore store) {
if (name == null) { printer.error(nameRequired()); return 1; } if (name == null) { printer.error(nameRequired()); return 1; }
try { try {
@@ -51,7 +51,7 @@ public class ConfigShowCommand implements Callable<Integer> {
data.put("profile", global.profile != null ? global.profile : "default"); data.put("profile", global.profile != null ? global.profile : "default");
data.put("endpoint", global.endpoint); data.put("endpoint", global.endpoint);
data.put("container", global.container); data.put("container", global.container);
data.put("output", global.output != null ? global.output.name() : "text"); data.put("output", global.format() != null ? global.format().name() : "text");
// image/port/persistDir/services have no global option, so they are read back from the // image/port/persistDir/services have no global option, so they are read back from the
// profile itself — they only take effect on 'start'. // profile itself — they only take effect on 'start'.
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.floci.cli.GlobalOptions; import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile; import io.floci.cli.ProductProfile;
import io.floci.cli.output.Ansi; import io.floci.cli.output.Ansi;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat; import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer; import io.floci.cli.output.Printer;
import picocli.CommandLine.*; import picocli.CommandLine.*;
@@ -102,13 +103,13 @@ public class ConfigValidateCommand implements Callable<Integer> {
printer.println(""); printer.println("");
for (String issue : report.errors()) { for (String issue : report.errors()) {
printer.println(" " + Ansi.red("✗") + " " + issue); printer.println(" " + Ansi.red(Glyphs.fail()) + " " + issue);
} }
for (String warn : report.warnings()) { for (String warn : report.warnings()) {
printer.println(" " + Ansi.yellow("⚠") + " " + warn); printer.println(" " + Ansi.yellow(Glyphs.warn()) + " " + warn);
} }
if (report.errors().isEmpty() && report.warnings().isEmpty()) { if (report.errors().isEmpty() && report.warnings().isEmpty()) {
printer.println(" " + Ansi.green("✓") + " Compose file looks good"); printer.println(" " + Ansi.green(Glyphs.ok()) + " Compose file looks good");
} }
printer.println(""); printer.println("");
@@ -98,6 +98,10 @@ public class ProfileStore {
// The one read path, so list and show agree on a profile's name. // The one read path, so list and show agree on a profile's name.
private static Profile read(Path file) throws IOException { private static Profile read(Path file) throws IOException {
Profile profile = YAML.readValue(file.toFile(), Profile.class); Profile profile = YAML.readValue(file.toFile(), Profile.class);
// 'null' and '~' are valid YAML for "nothing": a document, but not a profile.
if (profile == null) {
throw new IOException(file + " holds no settings: it has to be a mapping, like 'port: 4566'");
}
// Hand-written files often omit 'name:'; the file name is the name. // Hand-written files often omit 'name:'; the file name is the name.
if (profile.name == null || profile.name.isBlank()) { if (profile.name == null || profile.name.isBlank()) {
profile.name = nameOf(file); profile.name = nameOf(file);
@@ -0,0 +1,31 @@
package io.floci.cli.output;
/**
* The marks commands put in front of a line. Like {@link Ansi}, the choice is made once per
* invocation: Unicode for a person at a terminal, plain ASCII with {@code --no-emoji}, when the
* output is piped, or when {@code NO_COLOR} asks for undecorated output.
*/
public final class Glyphs {
/** One set of marks. */
public record Set(String ok, String warn, String fail, String arrow) {}
public static final Set UNICODE = new Set("✓", "⚠", "✗", "→");
public static final Set ASCII = new Set("+", "!", "x", "->");
private static Set current = UNICODE;
private Glyphs() {}
/** Switches to plain ASCII for the rest of this invocation; it cannot be switched back. */
public static void plain() {
current = ASCII;
}
public static String ok() { return current.ok(); }
public static String warn() { return current.warn(); }
public static String fail() { return current.fail(); }
public static String arrow() { return current.arrow(); }
public static boolean isPlain() { return current == ASCII; }
}
@@ -0,0 +1,372 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.FlociCli;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.ServerCompatibility;
import io.floci.cli.commands.config.ConfigProfileCommand;
import io.floci.cli.config.Profile;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.output.Glyphs;
import io.floci.cli.output.OutputFormat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine;
import picocli.CommandLine.ParseResult;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.function.IntSupplier;
import static org.junit.jupiter.api.Assertions.*;
/** BL-059 to BL-062: --json, plain marks, config profile edit and the old-server warning. */
class ErgonomicsTest {
@TempDir
Path tempDir;
private record Run(int exit, String out, String err) {}
private static Run capture(IntSupplier body) {
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));
try {
int exit = body.getAsInt();
return new Run(exit, outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
private Run run(String... args) {
return capture(() -> FlociCli.buildCommandLine(new ProfileStore(tempDir.resolve("profiles"))).execute(args));
}
// ---- --json ------------------------------------------------------------------------------------
@ParameterizedTest
@CsvSource({"'status --json', json", "'status -o yaml', yaml", "'status', text", "'status --json -o yaml', json",
"'gcp doctor --json', json", "'oci services --json', json"})
void jsonIsShorthandForOutputJson(String commandLine, OutputFormat expected) {
ParseResult r = FlociCli.buildCommandLine(new ProfileStore(tempDir)).parseArgs(commandLine.split(" "));
while (r.hasSubcommand()) r = r.subcommand();
GlobalOptions global = (GlobalOptions) r.commandSpec().mixins().values().stream()
.map(m -> m.userObject()).filter(GlobalOptions.class::isInstance).findFirst().orElseThrow();
assertEquals(expected, global.format());
}
@Test
void jsonReachesTheCommandsOutput() throws Exception {
Files.createDirectories(tempDir.resolve("profiles"));
Files.writeString(tempDir.resolve("profiles").resolve("one.yaml"), "port: 4599\n");
Run r = run("config", "profile", "list", "--json");
assertEquals(0, r.exit(), r.err());
assertTrue(r.out().strip().startsWith("[") || r.out().strip().startsWith("{"), r.out());
}
// ---- marks -------------------------------------------------------------------------------------
@ParameterizedTest
@CsvSource({"false, true, false, false", "true, true, false, true", "false, false, false, true", "false, true, true, true"})
void marksArePlainOnRequestInAPipeAndUnderNoColor(boolean noEmoji, boolean terminal, boolean noColorEnv, boolean plain) {
assertEquals(plain, GlobalOptions.plainGlyphs(noEmoji, terminal, noColorEnv));
}
/** The update notice is printed before any command runs, so the choice is made from the raw arguments too. */
@ParameterizedTest
@CsvSource({"'status --no-emoji', false, true, true", "'status', false, true, false", "'status', true, true, true",
"'status', false, false, true", "'--no-emoji=true status', false, true, true"})
void theMarksAreChosenBeforeAnyCommandRuns(String commandLine, boolean noColorEnv, boolean interactive, boolean plain) {
assertEquals(plain, FlociCli.plainGlyphs(commandLine.split(" "), noColorEnv, interactive));
}
@Test
void thePlainSetIsAsciiOnly() {
for (String mark : List.of(Glyphs.ASCII.ok(), Glyphs.ASCII.warn(), Glyphs.ASCII.fail(), Glyphs.ASCII.arrow())) {
assertTrue(mark.chars().allMatch(c -> c < 128), mark);
}
assertEquals("✓", Glyphs.UNICODE.ok());
}
/** A test run is not a terminal, so a command's output here carries the plain marks. */
@Test
void pipedOutputCarriesNoUnicodeMarks() throws Exception {
Path compose = Files.writeString(tempDir.resolve("compose.yml"), """
services:
floci:
image: floci/floci:latest
ports: ["4566:4566"]
volumes: ["/var/run/docker.sock:/var/run/docker.sock"]
""");
Run r = run("config", "validate", "-f", compose.toString(), "--no-emoji");
assertEquals(0, r.exit(), r.out() + r.err());
assertTrue(Glyphs.isPlain());
assertTrue(r.out().contains(Glyphs.ASCII.ok() + " Compose file looks good"), r.out());
assertFalse(r.out().contains("✓"), r.out());
}
// ---- config profile edit -----------------------------------------------------------------------
private ProfileStore store() {
return new ProfileStore(tempDir.resolve("profiles"));
}
private Path editorThat(String body) throws Exception {
Path editor = Files.createTempFile(tempDir, "editor", ".sh");
Files.writeString(editor, "#!/bin/sh\n" + body + "\n");
assertTrue(editor.toFile().setExecutable(true));
return editor;
}
private Run edit(Map<String, String> env, String name) {
ConfigProfileCommand command = new ConfigProfileCommand(ProductProfile.AWS, store(), env::get);
return capture(() -> new CommandLine(command).execute("edit", name));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void editOpensTheProfilesFileAndKeepsTheChange() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Path editor = editorThat("echo 'port: 14566' >> \"$1\"");
Run r = edit(Map.of("EDITOR", editor.toString()), "dev");
assertEquals(0, r.exit(), r.err());
assertEquals(14566, store().get("dev").orElseThrow().port);
assertTrue(r.out().contains("Profile 'dev' saved"), r.out());
}
/** VISUAL wins over EDITOR, and a value with arguments is a command line. */
@Test
@DisabledOnOs(OS.WINDOWS)
void visualWinsAndArgumentsArePassedOn() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Path args = tempDir.resolve("args");
Path visual = editorThat("echo \"$1 $2\" > '" + args + "'");
Path editor = editorThat("exit 9");
Run r = edit(Map.of("VISUAL", visual + " --wait", "EDITOR", editor.toString()), "dev");
assertEquals(0, r.exit(), r.err());
assertEquals("--wait " + store().existingFile("dev"), Files.readString(args).strip());
}
/** A quoted path with spaces is one word, as a shell would read it; nothing else is interpreted. */
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '`', value = {
"\"/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code\" --wait | /Applications/Visual Studio Code.app/Contents/Resources/app/bin/code;--wait",
"'/opt/my editor/bin/edit' -n | /opt/my editor/bin/edit;-n",
"/opt/my\\ editor/bin/edit | /opt/my editor/bin/edit",
"emacsclient -c -a \"emacs --no-splash\" | emacsclient;-c;-a;emacs --no-splash",
"vim -c 'set ft=yaml' | vim;-c;set ft=yaml",
"code --wait | code;--wait",
"nano --rcfile=\"my rc\" | nano;--rcfile=my rc",
"echo \"a \\\"quoted\\\" word\" | echo;a \"quoted\" word",
"C:\\Windows\\System32\\notepad.exe | C:\\Windows\\System32\\notepad.exe",
"\"C:\\Program Files\\Microsoft VS Code\\bin\\code.cmd\" --wait | C:\\Program Files\\Microsoft VS Code\\bin\\code.cmd;--wait",
"\\\\tools\\share\\edit.exe -n | \\\\tools\\share\\edit.exe;-n",
"'C:\\my tools\\edit.exe' | C:\\my tools\\edit.exe",
"ed '' | ed;"})
void anEditorValueIsSplitLikeAShellWould(String value, String expected) {
assertEquals(List.of(expected.split(";", -1)), ConfigProfileCommand.editorCommand(value, null));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void anEditorInADirectoryWithSpacesIsRun() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Path dir = Files.createDirectories(tempDir.resolve("my editors"));
Path editor = Files.writeString(dir.resolve("edit it"), "#!/bin/sh\necho 'port: 14566' >> \"$2\"\n");
assertTrue(editor.toFile().setExecutable(true));
Run r = edit(Map.of("EDITOR", "\"" + editor + "\" --wait"), "dev");
assertEquals(0, r.exit(), r.err());
assertEquals(14566, store().get("dev").orElseThrow().port);
}
@Test
void theEditorIsVisualThenEditorSplitOnSpaces() {
assertEquals(List.of("code", "--wait"), ConfigProfileCommand.editorCommand("code --wait", "vi"));
assertEquals(List.of("vi"), ConfigProfileCommand.editorCommand(null, "vi"));
assertEquals(List.of("vi"), ConfigProfileCommand.editorCommand(" ", " vi "));
assertEquals(List.of(), ConfigProfileCommand.editorCommand(null, null));
assertEquals(List.of(), ConfigProfileCommand.editorCommand("", ""));
}
@Test
void editWithoutAnEditorSaysHowToSetOne() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Run r = edit(Map.of(), "dev");
assertEquals(1, r.exit());
assertTrue(r.err().contains("No editor is set"), r.err());
assertTrue(r.err().contains("export EDITOR="), r.err());
}
@Test
void editingAProfileThatDoesNotExistPointsAtCreate() {
Run r = edit(Map.of("EDITOR", "true"), "nope");
assertEquals(1, r.exit());
assertTrue(r.err().contains("Profile 'nope' not found."), r.err());
assertTrue(r.err().contains("floci config profile create nope"), r.err());
}
@Test
@DisabledOnOs(OS.WINDOWS)
void anEditThatBreaksTheFileIsReportedAtOnce() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Path editor = editorThat("echo 'port: [unterminated' > \"$1\"");
Run r = edit(Map.of("EDITOR", editor.toString()), "dev");
assertEquals(1, r.exit());
assertTrue(r.err().contains("Profile 'dev' is no longer valid"), r.err());
assertTrue(r.err().contains("floci config profile edit dev"), r.err());
}
/** A profile that does not parse, or holds YAML's "nothing", can still be opened and repaired. */
@ParameterizedTest
@ValueSource(strings = {"port: [unterminated\n", "null\n", "~\n", "- a list\n"})
@DisabledOnOs(OS.WINDOWS)
void aBrokenProfileCanBeOpenedAndRepaired(String broken) throws Exception {
Path file = Files.createDirectories(tempDir.resolve("profiles")).resolve("dev.yaml");
Files.writeString(file, broken);
Path editor = editorThat("echo 'port: 14566' > \"$1\"");
Run r = edit(Map.of("EDITOR", editor.toString()), "dev");
assertEquals(0, r.exit(), r.err());
assertEquals(14566, store().get("dev").orElseThrow().port);
}
/** Saving YAML's "nothing" is reported like any other file that is no longer a profile. */
@ParameterizedTest
@ValueSource(strings = {"null", "~"})
@DisabledOnOs(OS.WINDOWS)
void anEditThatLeavesNothingIsReported(String nothing) throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Path editor = editorThat("echo '" + nothing + "' > \"$1\"");
Run r = edit(Map.of("EDITOR", editor.toString()), "dev");
assertEquals(1, r.exit());
assertTrue(r.err().contains("Profile 'dev' is no longer valid"), r.err());
assertTrue(r.err().contains("holds no settings"), r.err());
assertFalse(r.err().contains("Exception"), r.err());
}
@Test
@DisabledOnOs(OS.WINDOWS)
void anEditorThatFailsIsReported() throws Exception {
store().save(new Profile(ProductProfile.AWS, "dev"));
Run failed = edit(Map.of("EDITOR", editorThat("exit 3").toString()), "dev");
Run missing = edit(Map.of("EDITOR", tempDir.resolve("no-such-editor").toString()), "dev");
assertEquals(1, failed.exit());
assertTrue(failed.err().contains("exited with code 3"), failed.err());
assertEquals(1, missing.exit());
assertTrue(missing.err().contains("Could not start the editor"), missing.err());
assertTrue(missing.err().contains("Set EDITOR to a command on your PATH"), missing.err());
}
// ---- the old-server warning --------------------------------------------------------------------
@ParameterizedTest
@ValueSource(strings = {"1.4.9", "1.0.0", "0.9.0"})
void anAwsServerBelowTheMinimumIsWarnedAbout(String version) {
String warning = ServerCompatibility.warning(ProductProfile.AWS, version, "").orElseThrow();
assertTrue(warning.contains("server " + version + " is older than 1.5.0"), warning);
assertTrue(warning.contains("docker pull floci/floci:latest"), warning);
assertTrue(warning.contains("then run 'floci restart'."), warning);
}
@ParameterizedTest
@ValueSource(strings = {"1.5.0", "2.2.0", "unknown", "unavailable", "", "dev-SNAPSHOT"})
void aSupportedOrUnreadableVersionIsNotWarnedAbout(String version) {
assertTrue(ServerCompatibility.warning(ProductProfile.AWS, version, "").isEmpty(), version);
}
/** The other emulators are on 0.x version lines of their own: the AWS minimum says nothing about them. */
@Test
void theOtherProductsHaveNoMinimum() {
for (ProductProfile product : List.of(ProductProfile.GCP, ProductProfile.AZ, ProductProfile.OCI)) {
assertTrue(ServerCompatibility.warning(product, "0.4.2", "").isEmpty(), product.name());
}
assertTrue(ServerCompatibility.warning(ProductProfile.AWS, null, "").isEmpty());
}
/** The hint acts on the instance the version came from, and keeps that instance's settings. */
@Test
void theHintSelectsTheSameInstance() {
String warning = ServerCompatibility.warning(ProductProfile.AWS, "1.4.0", " --profile dev").orElseThrow();
assertTrue(warning.contains("then run 'floci restart --profile dev'."), warning);
// The way out for a pinned tag acts on the same instance too.
assertTrue(warning.contains("floci stop --remove --profile dev"), warning);
}
/** restart keeps the image reference, so the hint says what to do when that reference is the old tag. */
@Test
void theHintCoversAnInstancePinnedToAnOldTag() {
String warning = ServerCompatibility.warning(ProductProfile.AWS, "1.4.0", " --container dev").orElseThrow();
assertTrue(warning.contains("If the instance pins an older tag, restart keeps it"), warning);
assertTrue(warning.contains("change 'image' in its profile"), warning);
assertTrue(warning.contains("'--image floci/floci:latest'"), warning);
}
@Test
void statusWarnsOnStderrAndKeepsStdoutOneDocument() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", exchange -> {
byte[] body = "{\"version\":\"1.4.0\",\"edition\":\"community\",\"services\":[]}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
exchange.close();
});
server.start();
try {
Run r = run("status", "--json", "--container", "floci-ergonomics-none",
"--endpoint", "http://127.0.0.1:" + server.getAddress().getPort());
assertTrue(r.err().contains("server 1.4.0 is older than 1.5.0"), r.err());
assertTrue(r.err().contains("floci restart --container floci-ergonomics-none"), r.err());
assertTrue(r.out().strip().startsWith("{") && r.out().strip().endsWith("}"), r.out());
assertFalse(r.out().contains("older than"), r.out());
} finally {
server.stop(0);
}
}
}