fix(cli): keep the next step when an error's cause has several lines

A failed docker run with more than one line of output lost its 'floci doctor' hint, and a profile or Compose file that does not parse was reported with the parser's source-location line instead of what to do. Causes are now shown as one line, and docker's own output always gets its next step.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-10-11 09:55:23 -05:00
1 parent 97eaa5e820
commit 8c0e06bd0b
12 files changed
+147 -26

No files matched your search

@@ -377,8 +377,10 @@ public class StartCommand implements Callable<Integer> {
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;
}
@@ -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<Integer> {
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;
}
@@ -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<Integer> {
}
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<Integer> {
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<Integer> {
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<Integer> {
}
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<Integer> {
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<Integer> {
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;
}
}
@@ -9,6 +9,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;
@@ -63,7 +64,7 @@ public class ConfigValidateCommand implements Callable<Integer> {
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;
}
@@ -76,8 +77,7 @@ public class ConfigValidateCommand implements Callable<Integer> {
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'
@@ -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 {
@@ -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,
@@ -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);
@@ -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();
}
}
@@ -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(" ")));
}
}
@@ -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<String> 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());
}
}
@@ -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);
}
}
@@ -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<String> args) {
public String startContainer(List<String> 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<String> 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)