diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index ce907ab..1066d1e 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -377,8 +377,10 @@ public class StartCommand implements Callable { id = docker.startContainer(args); progress.accept(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); } catch (DockerException e) { - printer.error("Failed to start container: " + e.getMessage(), - "Run '" + profile.commandPrefix() + " doctor' to check Docker, the image and the port."); + // 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.")); return 1; } diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java index 28343d8..728858b 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -4,6 +4,7 @@ import io.floci.cli.GlobalOptions; import io.floci.cli.config.GlobalConfigStore; import io.floci.cli.output.Ansi; import io.floci.cli.output.Printer; +import io.floci.cli.util.Causes; import picocli.CommandLine.*; import java.io.IOException; @@ -37,7 +38,7 @@ public class ConfigDefaultProductCommand implements Callable { printer.println(Ansi.gray("Config saved to: " + store.configFilePath())); return 0; } catch (IOException e) { - printer.error("Could not save config: " + e.getMessage(), + printer.error("Could not save config: " + Causes.firstLine(e), "Check that " + store.configFilePath().getParent() + " is writable and re-run the command."); return 1; } diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java index dd8f1ea..ae55d42 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -8,6 +8,7 @@ import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; +import io.floci.cli.util.Causes; import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; @@ -149,7 +150,7 @@ public class ConfigProfileCommand implements Callable { } return 0; } catch (IOException e) { - printer.error("Could not list profiles: " + e.getMessage(), + printer.error("Could not list profiles: " + Causes.firstLine(e), "Check the files under ~/.floci/profiles and re-run the command."); return 1; } @@ -175,7 +176,7 @@ public class ConfigProfileCommand implements Callable { if (p.namespace != null) printer.println(" namespace: " + p.namespace); return 0; } catch (IOException e) { - printer.error("Could not read profile: " + e.getMessage(), "Fix or delete the profile file, then re-run the command."); + printer.error("Could not read profile: " + Causes.firstLine(e), "Fix or delete the profile file, then re-run the command."); return 1; } } @@ -212,7 +213,7 @@ public class ConfigProfileCommand implements Callable { 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(), + printer.error("Could not start the editor '" + String.join(" ", editor) + "': " + Causes.firstLine(e), "Set EDITOR to a command on your PATH, or edit " + file + " yourself."); return 1; } @@ -231,8 +232,7 @@ public class ConfigProfileCommand implements Callable { } 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" + printer.error("Profile '" + name + "' is no longer valid: " + Causes.firstLine(e) + "\n" + "Re-run '" + prefix + "edit " + name + "' to fix it."); return 1; } @@ -329,7 +329,7 @@ public class ConfigProfileCommand implements Callable { printer.println(Ansi.gray("Start it with: " + profile.commandPrefix() + " start --profile " + name)); return 0; } catch (IOException e) { - printer.error("Could not create profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command."); + printer.error("Could not create profile: " + Causes.firstLine(e), "Check that ~/.floci/profiles is writable and re-run the command."); return 1; } } @@ -401,7 +401,7 @@ public class ConfigProfileCommand implements Callable { printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files); return 0; } catch (IOException e) { - printer.error("Could not delete profile: " + e.getMessage(), "Check that ~/.floci/profiles is writable and re-run the command."); + printer.error("Could not delete profile: " + Causes.firstLine(e), "Check that ~/.floci/profiles is writable and re-run the command."); return 1; } } diff --git a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java index af11486..23ed1da 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -7,6 +7,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.util.Causes; import picocli.CommandLine.*; import java.io.IOException; @@ -59,7 +60,7 @@ public class ConfigValidateCommand implements Callable { try { content = Files.readString(composeFile); } catch (IOException e) { - printer.error("Could not read " + composeFile + ": " + e.getMessage(), + printer.error("Could not read " + composeFile + ": " + Causes.firstLine(e), "Check the file's permissions, or pass another with --file."); return 1; } @@ -72,8 +73,7 @@ public class ConfigValidateCommand implements Callable { unreadable = "Could not read " + composeFile + " as a Compose file: it has no top-level mapping"; } } catch (IOException e) { - String reason = e.getMessage() == null ? "unreadable" : e.getMessage().lines().findFirst().orElse("unreadable"); - unreadable = "Could not read " + composeFile + " as YAML: " + reason; + unreadable = "Could not read " + composeFile + " as YAML: " + Causes.firstLine(e); } if (unreadable != null) { // Structured output always carries the report, so a script reading it gets 'valid: false' diff --git a/src/main/java/io/floci/cli/commands/config/YamlTree.java b/src/main/java/io/floci/cli/commands/config/YamlTree.java index 4f27ae1..f1f1427 100644 --- a/src/main/java/io/floci/cli/commands/config/YamlTree.java +++ b/src/main/java/io/floci/cli/commands/config/YamlTree.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.cli.util.Causes; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; @@ -85,8 +86,7 @@ public final class YamlTree { Iterator documents = reader.loadAll(yaml).iterator(); first = documents.hasNext() ? documents.next() : null; } catch (YAMLException | IllegalArgumentException e) { - String reason = e.getMessage() == null ? "not valid YAML" : e.getMessage().lines().findFirst().orElse("not valid YAML"); - throw new IOException(reason); + throw new IOException(Causes.firstLine(e)); } return first == null ? NODES.missingNode() : tree(first, new int[] {MAX_NODES}, 0); } diff --git a/src/main/java/io/floci/cli/config/GlobalConfigStore.java b/src/main/java/io/floci/cli/config/GlobalConfigStore.java index 780ea21..889d3a8 100644 --- a/src/main/java/io/floci/cli/config/GlobalConfigStore.java +++ b/src/main/java/io/floci/cli/config/GlobalConfigStore.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.floci.cli.output.Ansi; +import io.floci.cli.util.Causes; import java.io.IOException; import java.nio.file.AccessDeniedException; @@ -49,10 +50,7 @@ public class GlobalConfigStore { private static String reason(IOException e) { if (e instanceof AccessDeniedException) return "permission denied"; - String message = e.getMessage(); - if (message == null) return e.getClass().getSimpleName(); - int newline = message.indexOf('\n'); - return newline >= 0 ? message.substring(0, newline) : message; + return Causes.firstLine(e); } public void setDefaultProduct(String product) throws IOException { diff --git a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java index 271c75d..d932082 100644 --- a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java +++ b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java @@ -2,6 +2,7 @@ package io.floci.cli.config; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; +import io.floci.cli.util.Causes; import picocli.CommandLine; import picocli.CommandLine.IDefaultValueProvider; import picocli.CommandLine.Model.ArgSpec; @@ -117,7 +118,7 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider { } catch (IllegalArgumentException e) { throw new ProfileNotFoundException(commandLine, e.getMessage()); } catch (IOException e) { - throw invalid(commandLine, name, e.getMessage()); + throw invalid(commandLine, name, Causes.firstLine(e)); } if (loaded.isEmpty()) { throw new ProfileNotFoundException(commandLine, diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java index 0db2682..5243db0 100644 --- a/src/main/java/io/floci/cli/config/ProfileStore.java +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -3,6 +3,7 @@ package io.floci.cli.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import io.floci.cli.output.Ansi; +import io.floci.cli.util.Causes; import java.io.IOException; import java.nio.file.Files; @@ -75,7 +76,7 @@ public class ProfileStore { // The cause is quoted, not guessed: this is a parse error or a // file that could not be opened. System.err.println(Ansi.yellow("Warning: ") + "Could not read profile file " + p - + ": " + firstLine(e.getMessage()) + + ": " + Causes.firstLine(e) + "\nCheck the file and its permissions, or delete it."); } }); @@ -89,12 +90,6 @@ public class ProfileStore { return Optional.of(read(file)); } - private static String firstLine(String message) { - if (message == null) return "unreadable"; - int newline = message.indexOf('\n'); - return newline >= 0 ? message.substring(0, newline) : message; - } - // 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); diff --git a/src/main/java/io/floci/cli/util/Causes.java b/src/main/java/io/floci/cli/util/Causes.java new file mode 100644 index 0000000..712a6fd --- /dev/null +++ b/src/main/java/io/floci/cli/util/Causes.java @@ -0,0 +1,23 @@ +package io.floci.cli.util; + +/** + * Turns an exception into the one line a user is shown. Parser errors from Jackson and YAML come + * with a second line of source location ("at [Source: ...; line: 3]"), which is noise in a + * message and, worse, looks like a next step to {@code Printer.error(message, nextStep)}. + */ +public final class Causes { + + private Causes() {} + + /** The first line of {@code e}'s message, or its type name when it has none. */ + public static String firstLine(Throwable e) { + String message = e.getMessage(); + if (message == null || message.isBlank()) return e.getClass().getSimpleName(); + return firstLine(message); + } + + /** The first non-empty line of {@code message}. */ + public static String firstLine(String message) { + return message.strip().lines().findFirst().orElse(message).strip(); + } +} diff --git a/src/test/java/io/floci/cli/unit/CausesTest.java b/src/test/java/io/floci/cli/unit/CausesTest.java new file mode 100644 index 0000000..ad0da07 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/CausesTest.java @@ -0,0 +1,32 @@ +package io.floci.cli.unit; + +import io.floci.cli.util.Causes; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** BL-096: a cause is shown as one line, so the next step that follows it is not mistaken for part of it. */ +class CausesTest { + + @Test + void aParserMessageIsCutAtItsFirstLine() { + IOException jackson = new IOException("Cannot deserialize value of type `java.lang.Integer`\n" + + " at [Source: (File); line: 3, column: 7] (through reference chain: Profile[\"port\"])"); + + assertEquals("Cannot deserialize value of type `java.lang.Integer`", Causes.firstLine(jackson)); + } + + @Test + void aOneLineMessageIsKept() { + assertEquals("Permission denied", Causes.firstLine(new IOException("Permission denied"))); + assertEquals("Permission denied", Causes.firstLine(" Permission denied\n")); + } + + @Test + void anExceptionWithoutAMessageIsNamedByItsType() { + assertEquals("IOException", Causes.firstLine(new IOException())); + assertEquals("IllegalStateException", Causes.firstLine(new IllegalStateException(" "))); + } +} diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index a9591df..4d6a3e3 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -401,4 +401,33 @@ class ConfigCommandsTest { partial.add("port"); assertEquals(partial, jsonKeys(runShow(ProductProfile.AWS, "--profile", "partial", "-o", "json"))); } + + /** + * BL-096: a profile that does not parse is reported in one line of cause, followed by the next + * step. The parser's "at [Source: ...]" line used to stand in for it. + */ + @Test + void aBrokenProfileIsReportedWithItsNextStep() throws Exception { + writeProfile("broken", "port: [unterminated\n"); + + Run show = profileCmd(ProductProfile.AWS, "show", "broken"); + + assertEquals(1, show.exit()); + List lines = show.err().strip().lines().toList(); + assertEquals(2, lines.size(), show.err()); + assertTrue(lines.get(0).contains("Could not read profile: "), show.err()); + assertEquals("Fix or delete the profile file, then re-run the command.", lines.get(1)); + assertFalse(show.err().contains("[Source"), show.err()); + } + + @Test + void creatingOverABrokenProfileKeepsItsNextStepToo() throws Exception { + writeProfile("broken", "port: [unterminated\n"); + + Run create = profileCmd(ProductProfile.AWS, "create", "broken"); + + assertEquals(1, create.exit()); + assertTrue(create.err().strip().endsWith("re-run the command."), create.err()); + assertFalse(create.err().contains("[Source"), create.err()); + } } diff --git a/src/test/java/io/floci/cli/unit/MissingProfileTest.java b/src/test/java/io/floci/cli/unit/MissingProfileTest.java index 190e4a0..997f88a 100644 --- a/src/test/java/io/floci/cli/unit/MissingProfileTest.java +++ b/src/test/java/io/floci/cli/unit/MissingProfileTest.java @@ -192,4 +192,19 @@ class MissingProfileTest { assertThrows(ProfileNotFoundException.class, () -> cli().parseArgs("start", "--profile", "typo")); } + + /** BL-096: --profile on a file that does not parse says so in two lines: the cause, then what to do. */ + @Test + void aProfileThatDoesNotParseIsReportedInTwoLines() throws IOException { + writeProfile("broken", "port: [unterminated\n"); + int[] exit = new int[1]; + + String stderr = captureStderr(() -> cli().execute("status", "--profile", "broken"), exit); + + assertEquals(2, exit[0]); + assertEquals(2, stderr.strip().lines().count(), stderr); + assertTrue(stderr.contains("Profile 'broken' is invalid: "), stderr); + assertTrue(stderr.strip().endsWith("and try again."), stderr); + assertFalse(stderr.contains("[Source"), stderr); + } } diff --git a/src/test/java/io/floci/cli/unit/StartPreflightTest.java b/src/test/java/io/floci/cli/unit/StartPreflightTest.java index 0e8fd82..72cff7c 100644 --- a/src/test/java/io/floci/cli/unit/StartPreflightTest.java +++ b/src/test/java/io/floci/cli/unit/StartPreflightTest.java @@ -11,6 +11,8 @@ 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.ValueSource; import picocli.CommandLine; import java.io.ByteArrayOutputStream; @@ -66,7 +68,7 @@ class StartPreflightTest { } @Override - public String startContainer(List args) { + public String startContainer(List args) throws DockerException { runArgs.addAll(args); calls.add("run"); return "0123456789abcdef"; @@ -272,6 +274,29 @@ class StartPreflightTest { assertEquals(List.of(), docker.calls); } + /** + * BL-096: docker's own error is often several lines. The next step must still follow it; a + * second line of docker output is not advice. + */ + @ParameterizedTest + @ValueSource(strings = { + "docker: Error response from daemon: driver failed programming external connectivity.", + "docker: Error response from daemon: Conflict.\nRun 'docker run --help' for more information.\n"}) + void aFailedDockerRunKeepsItsNextStep(String dockerOutput) { + FakeDocker docker = new FakeDocker(REMOTE) { + @Override + public String startContainer(List args) throws DockerException { + throw DockerException.ofOutput(dockerOutput); + } + }; + + Out r = start(docker, "--container", "floci-gcp-preflight", "--detach"); + + 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()); + } + /** A context selected with DOCKER_CONTEXT or 'docker context use' is not in the environment: docker is asked. */ @Test @DisabledOnOs(OS.WINDOWS)