mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
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:
1 parent
6b06382516
commit
de3ca7f171
16 files changed
+660
-20
No files matched your search
@@ -12,6 +12,7 @@ import io.floci.cli.config.ProfileDefaultValueProvider;
|
||||
import io.floci.cli.config.ProfileNotFoundException;
|
||||
import io.floci.cli.config.ProfileStore;
|
||||
import io.floci.cli.output.Ansi;
|
||||
import io.floci.cli.output.Glyphs;
|
||||
import io.floci.cli.update.UpdateNotifier;
|
||||
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)) {
|
||||
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.
|
||||
// "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) {
|
||||
UpdateNotifier.pendingNotice(CliVersion.CLI_VERSION).ifPresent(latest ->
|
||||
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"));
|
||||
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
|
||||
* 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) {
|
||||
return noColorEnv || !interactive || Arrays.stream(args)
|
||||
.anyMatch(a -> a.equals("--no-color") || a.equalsIgnoreCase("--no-color=true"));
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.cli;
|
||||
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
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 picocli.CommandLine.Model.CommandSpec;
|
||||
@@ -61,6 +62,9 @@ public class GlobalOptions {
|
||||
paramLabel = "text|json|yaml")
|
||||
public OutputFormat output;
|
||||
|
||||
@Option(names = {"--json"}, description = "Shorthand for --output json")
|
||||
public boolean json;
|
||||
|
||||
@Option(names = {"--quiet", "-q"}, description = "Suppress non-error output")
|
||||
public boolean quiet;
|
||||
|
||||
@@ -70,6 +74,9 @@ public class GlobalOptions {
|
||||
@Option(names = {"--no-color"}, description = "Disable ANSI colors")
|
||||
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() {
|
||||
this(ProductProfile.AWS);
|
||||
}
|
||||
@@ -131,7 +138,23 @@ public class GlobalOptions {
|
||||
if (verbose) {
|
||||
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.
|
||||
|
||||
@@ -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.PortAvailableCheck;
|
||||
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 picocli.CommandLine.*;
|
||||
@@ -226,9 +227,9 @@ public class DoctorCommand implements Callable<Integer> {
|
||||
|
||||
public static void printResult(Printer printer, CheckResult r) {
|
||||
String icon = switch (r.status()) {
|
||||
case ok -> Ansi.green("✓");
|
||||
case warn -> Ansi.yellow("⚠");
|
||||
case fail -> Ansi.red("✗");
|
||||
case ok -> Ansi.green(Glyphs.ok());
|
||||
case warn -> Ansi.yellow(Glyphs.warn());
|
||||
case fail -> Ansi.red(Glyphs.fail());
|
||||
};
|
||||
String namePadded = String.format("%-26s", r.name());
|
||||
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.FlociHttpClient;
|
||||
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 picocli.CommandLine.*;
|
||||
@@ -166,7 +167,7 @@ public class ResetCommand implements Callable<Integer> {
|
||||
printer.structured(out);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.http.FlociHttpClient;
|
||||
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 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("");
|
||||
for (String svc : services) {
|
||||
printer.println(" " + Ansi.green("✓") + " " + svc);
|
||||
printer.println(" " + Ansi.green(Glyphs.ok()) + " " + svc);
|
||||
}
|
||||
if (services.isEmpty()) {
|
||||
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.ProductProfile;
|
||||
import io.floci.cli.ServerCompatibility;
|
||||
import io.floci.cli.docker.DockerClient;
|
||||
import io.floci.cli.docker.DockerException;
|
||||
import io.floci.cli.http.FlociHttpClient;
|
||||
@@ -76,6 +77,8 @@ public class StatusCommand implements Callable<Integer> {
|
||||
serverEdition = health.edition();
|
||||
reachable = true;
|
||||
} 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<>();
|
||||
data.put("container", global.container);
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.cli.CliVersion;
|
||||
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.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).
|
||||
// Pinned --version keeps exact equality so deliberate downgrades still work.
|
||||
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;
|
||||
}
|
||||
|
||||
printer.println("update available: " + current + " → " + Ansi.bold(target));
|
||||
printer.println("update available: " + current + " " + Glyphs.arrow() + " " + Ansi.bold(target));
|
||||
if (check) {
|
||||
printer.println(Ansi.gray(installHint()));
|
||||
// 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);
|
||||
fetchFile(ReleaseChannel.assetUrl(downloadBase, target, asset), fresh);
|
||||
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);
|
||||
} finally {
|
||||
deleteRecursively(work);
|
||||
}
|
||||
|
||||
printer.println(Ansi.green("✓") + " updated: " + current + " → " + target
|
||||
printer.println(Ansi.green(Glyphs.ok()) + " updated: " + current + " " + Glyphs.arrow() + " " + target
|
||||
+ Ansi.gray(" (" + binary + ")"));
|
||||
return 0;
|
||||
} catch (UpdateException e) {
|
||||
@@ -314,7 +315,7 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
private String fetchString(String url) throws IOException, InterruptedException {
|
||||
HttpResponse<String> resp = http().send(get(url), HttpResponse.BodyHandlers.ofString());
|
||||
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()) {
|
||||
// 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 {
|
||||
HttpResponse<Path> resp = http().send(get(url), HttpResponse.BodyHandlers.ofFile(dest));
|
||||
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?)" : ""));
|
||||
}
|
||||
if (Files.size(dest) == 0) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.cli.commands;
|
||||
import io.floci.cli.CliVersion;
|
||||
import io.floci.cli.GlobalOptions;
|
||||
import io.floci.cli.ProductProfile;
|
||||
import io.floci.cli.ServerCompatibility;
|
||||
import io.floci.cli.http.FlociHttpClient;
|
||||
import io.floci.cli.output.Ansi;
|
||||
import io.floci.cli.output.OutputFormat;
|
||||
@@ -52,6 +53,8 @@ public class VersionCommand implements Callable<Integer> {
|
||||
serverVersion = info.version();
|
||||
serverEdition = info.edition();
|
||||
} 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 {
|
||||
|
||||
@@ -12,6 +12,7 @@ import picocli.CommandLine.*;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
@@ -19,6 +20,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
@Command(
|
||||
name = "profile",
|
||||
@@ -45,15 +47,23 @@ public class ConfigProfileCommand implements Callable<Integer> {
|
||||
|
||||
/** Test seam: a store pointed at a temporary profiles directory. */
|
||||
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.store = store;
|
||||
this.env = env;
|
||||
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;
|
||||
|
||||
@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;
|
||||
|
||||
// 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 "show" -> showProfile(printer, store);
|
||||
case "create" -> createProfile(printer, store);
|
||||
case "edit" -> editProfile(printer, store);
|
||||
case "delete" -> deleteProfile(printer, store);
|
||||
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;
|
||||
}
|
||||
};
|
||||
@@ -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) {
|
||||
if (name == null) { printer.error(nameRequired()); return 1; }
|
||||
try {
|
||||
|
||||
@@ -51,7 +51,7 @@ public class ConfigShowCommand implements Callable<Integer> {
|
||||
data.put("profile", global.profile != null ? global.profile : "default");
|
||||
data.put("endpoint", global.endpoint);
|
||||
data.put("container", global.container);
|
||||
data.put("output", global.output != null ? global.output.name() : "text");
|
||||
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
|
||||
// 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.ProductProfile;
|
||||
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 picocli.CommandLine.*;
|
||||
@@ -102,13 +103,13 @@ public class ConfigValidateCommand implements Callable<Integer> {
|
||||
printer.println("");
|
||||
|
||||
for (String issue : report.errors()) {
|
||||
printer.println(" " + Ansi.red("✗") + " " + issue);
|
||||
printer.println(" " + Ansi.red(Glyphs.fail()) + " " + issue);
|
||||
}
|
||||
for (String warn : report.warnings()) {
|
||||
printer.println(" " + Ansi.yellow("⚠") + " " + warn);
|
||||
printer.println(" " + Ansi.yellow(Glyphs.warn()) + " " + warn);
|
||||
}
|
||||
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("");
|
||||
|
||||
@@ -98,6 +98,10 @@ public class ProfileStore {
|
||||
// The one read path, so list and show agree on a profile's name.
|
||||
private static Profile read(Path file) throws IOException {
|
||||
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.
|
||||
if (profile.name == null || profile.name.isBlank()) {
|
||||
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; }
|
||||
}
|
||||
Reference in new issue
Block a user