diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java index 77eaca3..6ac4d94 100644 --- a/src/main/java/io/floci/cli/commands/RestartCommand.java +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -2,6 +2,7 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; import io.floci.cli.ProductProfile; +import io.floci.cli.config.ProfileNotFoundException; import io.floci.cli.config.ProfileStore; import io.floci.cli.output.Printer; import picocli.CommandLine.*; @@ -44,7 +45,15 @@ public class RestartCommand implements Callable { // Resolve the profile BEFORE stopping anything. A failure here must not leave the // container stopped, and the values must not be re-read from a file that could change // during the stop plus the one second wait below. - StartCommand start = buildStartCommand(); + StartCommand start; + try { + start = buildStartCommand(); + } catch (ProfileNotFoundException e) { + // Gone or broken since the parse resolved it: nothing has been stopped yet, and the + // exit code matches a bad --profile at parse time. + printer.error(e.getMessage()); + return ExitCode.USAGE; + } String invalid = start.validationError(); if (invalid != null) { printer.error(invalid); 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 a312fcd..f3aaf52 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -11,6 +11,7 @@ import picocli.CommandLine.*; import picocli.CommandLine.Model.CommandSpec; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -78,16 +79,23 @@ public class ConfigProfileCommand implements Callable { public Integer call() { Printer printer = global.printer(); - return switch (action.toLowerCase()) { - case "list" -> listProfiles(printer, store); - case "show" -> showProfile(printer, store); - case "create" -> createProfile(printer, store); - case "delete" -> deleteProfile(printer, store); - default -> { - printer.error("Unknown action '" + action + "'. Use: list, show, create, delete"); - yield 1; - } - }; + try { + return switch (action.toLowerCase()) { + case "list" -> listProfiles(printer, store); + case "show" -> showProfile(printer, store); + case "create" -> createProfile(printer, store); + case "delete" -> deleteProfile(printer, store); + default -> { + printer.error("Unknown action '" + action + "'. Use: list, show, create, delete"); + yield 1; + } + }; + } catch (IllegalArgumentException e) { + // An invalid profile name: the same cause exits 2 from --profile, so it does here too. + // The message already ends with the next step. + printer.error(e.getMessage()); + return ExitCode.USAGE; + } } private int listProfiles(Printer printer, ProfileStore store) { @@ -159,7 +167,7 @@ public class ConfigProfileCommand implements Callable { if (name == null) { printer.error("Profile name required."); return 1; } try { if (store.get(name).isPresent()) { - printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.profileFile(name)); + printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.existingFile(name)); return 1; } if (port != null && (port < 1 || port > 65535)) { @@ -247,11 +255,15 @@ public class ConfigProfileCommand implements Callable { private int deleteProfile(Printer printer, ProfileStore store) { if (name == null) { printer.error("Profile name required."); return 1; } try { - if (!store.delete(name)) { - printer.error("Profile '" + name + "' not found."); + List removed = store.delete(name); + if (removed.isEmpty()) { + printer.error("Profile '" + name + "' not found.\nRun '" + profile.commandPrefix() + " config profile list' to see available profiles."); return 1; } - printer.println(Ansi.green("Deleted") + " profile '" + name + "'"); + String files = removed.size() > 1 + ? " (" + removed.get(0).getFileName() + " and " + removed.get(1).getFileName() + ")" + : ""; + printer.println(Ansi.green("Deleted") + " profile '" + name + "'" + files); return 0; } catch (IOException e) { printer.error("Could not delete profile: " + e.getMessage()); diff --git a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java index 400c1ed..5bee0de 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java @@ -5,6 +5,7 @@ import io.floci.cli.ProductProfile; import io.floci.cli.commands.StartCommand; import io.floci.cli.config.Profile; 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.OutputFormat; @@ -59,7 +60,14 @@ public class ConfigShowCommand implements Callable { // image/port/persistDir/services have no global option, so they are read back from the // profile itself — they only take effect on 'start'. - addStartSettings(data); + try { + addStartSettings(data); + } catch (ProfileNotFoundException e) { + // The profile went away (or broke) after the parse resolved it. Same cause, same exit + // code as a bad --profile at parse time. + printer.error(e.getMessage()); + return ExitCode.USAGE; + } if (printer.format() != OutputFormat.text) { printer.structured(data); diff --git a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java index 469f6c9..8562103 100644 --- a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java +++ b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java @@ -128,6 +128,6 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider { private ProfileNotFoundException invalid(CommandLine commandLine, String name, String detail) { return new ProfileNotFoundException(commandLine, "Profile '" + name + "' is invalid: " + detail + "\n" - + "Edit " + store.profileFile(name) + " and try again."); + + "Edit " + store.existingFile(name) + " and try again."); } } diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java index 76e5d8c..11feac2 100644 --- a/src/main/java/io/floci/cli/config/ProfileStore.java +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -64,15 +64,11 @@ public class ProfileStore { List profiles = new ArrayList<>(); try (var stream = Files.list(profilesDir)) { stream.filter(p -> p.toString().endsWith(".yaml") || p.toString().endsWith(".yml")) + // A file no command can address (".yaml" has an empty name) is not a profile. + .filter(p -> isUsableName(nameOf(p))) .forEach(p -> { try { - Profile profile = YAML.readValue(p.toFile(), Profile.class); - // Hand-written files often omit 'name:'; the file name is the name. - if (profile.name == null || profile.name.isBlank()) { - String file = p.getFileName().toString(); - profile.name = file.substring(0, file.lastIndexOf('.')); - } - profiles.add(profile); + profiles.add(read(p)); } catch (IOException ignored) {} }); } @@ -80,9 +76,33 @@ public class ProfileStore { } public Optional get(String name) throws IOException { - Path file = existingProfileFile(name); + Path file = existingFile(name); if (!Files.exists(file)) return Optional.empty(); - return Optional.of(YAML.readValue(file.toFile(), Profile.class)); + return Optional.of(read(file)); + } + + // 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); + // Hand-written files often omit 'name:'; the file name is the name. + if (profile.name == null || profile.name.isBlank()) { + profile.name = nameOf(file); + } + return profile; + } + + private static boolean isUsableName(String name) { + try { + validateName(name); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + private static String nameOf(Path file) { + String fileName = file.getFileName().toString(); + return fileName.substring(0, fileName.lastIndexOf('.')); } public void save(Profile profile) throws IOException { @@ -90,43 +110,59 @@ public class ProfileStore { YAML.writeValue(profileFile(profile.name).toFile(), profile); } - public boolean delete(String name) throws IOException { - Path file = existingProfileFile(name); - return Files.deleteIfExists(file); + /** + * Deletes every spelling of {@code name}. Removing only the one reads prefer would leave the + * other answering {@code --profile} after a delete that reported success. + * + * @return the files removed: 0 when the profile did not exist + */ + public List delete(String name) throws IOException { + List removed = new ArrayList<>(); + for (Path file : List.of(profileFile(name), resolveInProfilesDir(validateName(name), ".yml"))) { + if (Files.deleteIfExists(file)) removed.add(file); + } + return removed; } /** Where {@link #save} writes {@code name}. Always {@code .yaml}. */ public Path profileFile(String name) { - return resolveInProfilesDir(validateName(name) + ".yaml"); + return resolveInProfilesDir(validateName(name), ".yaml"); } // The traversal guarantee: whatever the name looks like, the file it resolves to must sit // directly in profilesDir. Also the place a name that is illegal on this platform but legal // on another (a colon on Windows) turns into a clean message instead of InvalidPathException. - private Path resolveInProfilesDir(String fileName) { + // Messages quote the name as the user typed it, not the file name with its suffix. + private Path resolveInProfilesDir(String name, String suffix) { Path dir = profilesDir.toAbsolutePath().normalize(); Path resolved; try { - resolved = dir.resolve(fileName).normalize(); + resolved = dir.resolve(name + suffix).normalize(); } catch (InvalidPathException e) { throw new IllegalArgumentException( - "Invalid profile name '" + fileName + "': not a valid file name on this platform.\n" + "Invalid profile name '" + name + "': not a valid file name on this platform.\n" + "Run 'floci config profile list' to see available profiles."); } if (!dir.equals(resolved.getParent())) { throw new IllegalArgumentException( - "Invalid profile name '" + fileName + "': it would resolve outside " + profilesDir + ".\n" + "Invalid profile name '" + name + "': it would resolve outside " + profilesDir + ".\n" + "Run 'floci config profile list' to see available profiles."); } return resolved; } - // list() has always accepted .yml, so reads must too — otherwise a .yml profile shows up in - // 'config profile list' and then reports "not found" when passed to --profile. - private Path existingProfileFile(String name) { + /** + * The file {@code name} is read from: its {@code .yaml}, else its {@code .yml}, else the + * {@code .yaml} path {@link #save} would create. Messages that tell the user which file to + * edit name this one, not {@link #profileFile}. + * + *

list() has always accepted .yml, so reads must too — otherwise a .yml profile shows up in + * 'config profile list' and then reports "not found" when passed to --profile. + */ + public Path existingFile(String name) { Path yaml = profileFile(name); if (Files.exists(yaml)) return yaml; - Path yml = resolveInProfilesDir(validateName(name) + ".yml"); + Path yml = resolveInProfilesDir(validateName(name), ".yml"); return Files.exists(yml) ? yml : yaml; } diff --git a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java index 2170422..acfb6aa 100644 --- a/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java +++ b/src/test/java/io/floci/cli/unit/ConfigCommandsTest.java @@ -268,4 +268,48 @@ class ConfigCommandsTest { assertTrue(json.contains("\"container\" : \"floci-az-b\""), json); assertTrue(json.contains("\"port\" : 14577"), json); } + + /** BL-009: list names a file without 'name:' after the file, so show must too. */ + @Test + void showNamesAHandWrittenProfileAfterItsFile() throws Exception { + writeProfile("handwritten", "container: floci-hand\n"); + + Run r = profileCmd(ProductProfile.AWS, "show", "handwritten"); + + assertEquals(0, r.exit()); + assertTrue(r.out().contains("handwritten"), r.out()); + assertFalse(r.out().contains("null"), r.out()); + } + + @Test + void deleteReportsBothFilesWhenTwoSpellingsExist() throws Exception { + writeProfile("dev", "port: 4599\n"); + Files.writeString(tempDir.resolve("dev.yml"), "port: 4600\n"); + + Run r = profileCmd(ProductProfile.AWS, "delete", "dev"); + + assertEquals(0, r.exit()); + assertTrue(r.out().contains("dev.yaml and dev.yml"), r.out()); + assertTrue(store().get("dev").isEmpty()); + } + + /** BL-003: same cause as a bad --profile at parse time, so the same exit code. */ + @Test + void showExitsTwoWhenTheProfileIsGoneAfterTheParse() throws Exception { + writeProfile("gone", "container: floci-az-gone\n"); + ConfigShowCommand show = new ConfigShowCommand(ProductProfile.AZ, store()); + // A real parse: the provider reads the profile while it still exists. + new CommandLine(show) + .setDefaultValueProvider(new ProfileDefaultValueProvider(store())) + .parseArgs("--profile", "gone"); + Files.delete(tempDir.resolve("gone.yaml")); + + PrintStream err = System.err; + System.setErr(new PrintStream(new ByteArrayOutputStream())); + try { + assertEquals(CommandLine.ExitCode.USAGE, show.call()); + } finally { + System.setErr(err); + } + } } diff --git a/src/test/java/io/floci/cli/unit/MissingProfileTest.java b/src/test/java/io/floci/cli/unit/MissingProfileTest.java index 440ff40..c088d93 100644 --- a/src/test/java/io/floci/cli/unit/MissingProfileTest.java +++ b/src/test/java/io/floci/cli/unit/MissingProfileTest.java @@ -103,6 +103,34 @@ class MissingProfileTest { assertTrue(portErr.contains("port must be between 1 and 65535"), portErr); } + /** BL-018: one cause, one exit code, whichever command validates the name. */ + @Test + void anInvalidProfileNameExitsTwoFromConfigProfileAsFromProfile() { + int[] exit = new int[1]; + String fromProfile = captureStderr(() -> cli().execute("start", "--profile", "../x"), exit); + assertEquals(2, exit[0], fromProfile); + + for (String action : new String[]{"create", "show", "delete"}) { + String err = captureStderr(() -> cli().execute("config", "profile", action, "../x"), exit); + assertEquals(2, exit[0], action + ": " + err); + assertTrue(err.contains("Invalid profile name '../x'"), err); + } + } + + /** BL-010: the message must name the file to open, which for a .yml profile is the .yml. */ + @Test + void anInvalidYmlProfileNamesTheYmlFile() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("bad-port.yml"), "port: 99999\n"); + + int[] exit = new int[1]; + String err = captureStderr(() -> cli().execute("start", "--profile", "bad-port"), exit); + + assertEquals(2, exit[0]); + assertTrue(err.contains("bad-port.yml"), err); + assertFalse(err.contains("bad-port.yaml"), err); + } + @Test void parsingRaisesTheDedicatedException() { assertThrows(ProfileNotFoundException.class, diff --git a/src/test/java/io/floci/cli/unit/ProfileStoreTest.java b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java index d793ff6..5e28772 100644 --- a/src/test/java/io/floci/cli/unit/ProfileStoreTest.java +++ b/src/test/java/io/floci/cli/unit/ProfileStoreTest.java @@ -64,11 +64,11 @@ class ProfileStoreTest { @Test void missingProfileIsEmptyAndDeleteReportsIt() throws Exception { assertTrue(store().get("absent").isEmpty()); - assertFalse(store().delete("absent")); + assertTrue(store().delete("absent").isEmpty()); store().save(new Profile(ProductProfile.AWS, "here")); - assertTrue(store().delete("here")); - assertFalse(store().delete("here")); + assertFalse(store().delete("here").isEmpty()); + assertTrue(store().delete("here").isEmpty()); } @Test @@ -76,7 +76,7 @@ class ProfileStoreTest { Files.writeString(tempDir.resolve("staging.yml"), "container: floci-staging\n"); assertEquals("floci-staging", store().get("staging").orElseThrow().container); - assertTrue(store().delete("staging")); + assertFalse(store().delete("staging").isEmpty()); } @Test @@ -89,6 +89,43 @@ class ProfileStoreTest { assertEquals("handwritten", profiles.get(0).name); } + /** BL-011: deleting only the preferred spelling left the other one answering --profile. */ + @Test + void deleteRemovesEverySpelling() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("dev.yaml"), "port: 4599\n"); + Files.writeString(tempDir.resolve("dev.yml"), "port: 4600\n"); + + assertEquals(2, store().delete("dev").size()); + assertTrue(store().get("dev").isEmpty()); + } + + @Test + void listSkipsFilesNoCommandCanAddress() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve(".yaml"), "port: 4599\n"); + Files.writeString(tempDir.resolve("ok.yaml"), "port: 4599\n"); + + assertEquals(List.of("ok"), store().list().stream().map(p -> p.name).toList()); + } + + @Test + void existingFileIsTheSpellingOnDisk() throws Exception { + Files.createDirectories(tempDir); + assertEquals(tempDir.resolve("dev.yaml").toAbsolutePath(), store().existingFile("dev").toAbsolutePath()); + + Files.writeString(tempDir.resolve("dev.yml"), "port: 4599\n"); + assertEquals(tempDir.resolve("dev.yml").toAbsolutePath(), store().existingFile("dev").toAbsolutePath()); + } + + @Test + void getBackfillsTheNameAsListDoes() throws Exception { + Files.createDirectories(tempDir); + Files.writeString(tempDir.resolve("handwritten.yml"), "container: floci-hand\n"); + + assertEquals("handwritten", store().get("handwritten").orElseThrow().name); + } + @ParameterizedTest @ValueSource(strings = {"ok", "ok-1", "ok_1", "ok.1", "OK"}) void acceptsOrdinaryNames(String name) { @@ -112,7 +149,7 @@ class ProfileStoreTest { Files.writeString(tempDir.resolve("team alpha.yaml"), "container: floci-team\n"); assertEquals("floci-team", store().get("team alpha").orElseThrow().container); - assertTrue(store().delete("team alpha")); + assertFalse(store().delete("team alpha").isEmpty()); assertTrue(store().get("team alpha").isEmpty()); } @@ -138,7 +175,7 @@ class ProfileStoreTest { assertEquals("floci-team", store().get("team\\alpha").orElseThrow().container); assertEquals(tempDir.toAbsolutePath().normalize(), store().profileFile("team\\alpha").getParent()); - assertTrue(store().delete("team\\alpha")); + assertFalse(store().delete("team\\alpha").isEmpty()); } @Test @@ -160,4 +197,13 @@ class ProfileStoreTest { store().profileFile(name).getParent(), name); } } + + /** BL-002: the message names what the user typed, not the file it would have become. */ + @Test + void errorsQuoteTheNameAsTyped() { + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, + () -> store().profileFile("..\u0000x")); + assertTrue(e.getMessage().contains("'..\u0000x'"), e.getMessage()); + assertFalse(e.getMessage().contains(".yaml"), e.getMessage()); + } } diff --git a/src/test/java/io/floci/cli/unit/RestartCommandTest.java b/src/test/java/io/floci/cli/unit/RestartCommandTest.java index c1fd1ab..7fbf1f4 100644 --- a/src/test/java/io/floci/cli/unit/RestartCommandTest.java +++ b/src/test/java/io/floci/cli/unit/RestartCommandTest.java @@ -2,6 +2,7 @@ package io.floci.cli.unit; import io.floci.cli.ProductProfile; import io.floci.cli.commands.RestartCommand; +import io.floci.cli.config.ProfileDefaultValueProvider; import io.floci.cli.config.ProfileStore; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -125,4 +126,39 @@ class RestartCommandTest { System.setErr(err); } } + + /** + * BL-003: a profile that disappears between the parse and the restart is the same user error + * as a bad --profile at parse time: exit 2, and nothing stopped. + */ + @Test + void aProfileGoneAfterTheParseExitsTwoBeforeStoppingAnything() throws Exception { + writeProfile("gone", "container: floci-az-never-started\n"); + ProfileStore store = new ProfileStore(tempDir); + RestartCommand restart = new RestartCommand(ProductProfile.AZ, store); + // A real parse: the provider reads the profile while it still exists. + new CommandLine(restart) + .setDefaultValueProvider(new ProfileDefaultValueProvider(store)) + .parseArgs("--profile", "gone"); + Files.delete(tempDir.resolve("gone.yaml")); + + 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)); + int exit; + try { + exit = restart.call(); + } finally { + System.setOut(out); + System.setErr(err); + } + + assertEquals(CommandLine.ExitCode.USAGE, exit); + assertTrue(errBuf.toString().contains("Profile 'gone' not found"), errBuf.toString()); + // Stop prints this before calling docker; its absence means nothing was stopped. + assertFalse(outBuf.toString().contains("Stopping"), outBuf.toString()); + } }