diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index 12798bc..f870f87 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -16,6 +16,8 @@ import io.floci.cli.update.UpdateNotifier; import picocli.CommandLine; import picocli.CommandLine.*; +import java.util.Arrays; + @Command( name = "floci", description = "Manage your local Floci emulators%n%n" + @@ -74,7 +76,7 @@ public class FlociCli implements Runnable { } public static void main(String[] args) { - if (System.getenv("NO_COLOR") != null || System.console() == null) { + if (colorDisabled(args, System.getenv("NO_COLOR") != null, System.console() != null)) { Ansi.disable(); } @@ -146,6 +148,16 @@ public class FlociCli implements Runnable { }; } + /** + * Whether this invocation prints without ANSI colour. {@code --no-color} is read from the raw + * 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. + */ + 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")); + } + // Returns true when routing should NOT apply: explicit product subgroup, // or a product-independent command like "config" or "completion". private static boolean isExplicitProduct(String[] args) { diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java index 7b2cad8..63e2e2f 100644 --- a/src/main/java/io/floci/cli/commands/StartCommand.java +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -169,7 +169,14 @@ public class StartCommand implements Callable { try { URI uri = URI.create(endpoint); if (uri.getHost() == null) return "http://localhost:" + port; - return new URI(uri.getScheme(), null, uri.getHost(), port, uri.getPath(), null, null).toString(); + // Raw components: the decoding getters would turn ?token=a%26b into ?token=a&b. + StringBuilder url = new StringBuilder(uri.getScheme()).append("://"); + if (uri.getRawUserInfo() != null) url.append(uri.getRawUserInfo()).append('@'); + url.append(uri.getHost()).append(':').append(port); // getHost keeps IPv6 brackets + if (uri.getRawPath() != null) url.append(uri.getRawPath()); + if (uri.getRawQuery() != null) url.append('?').append(uri.getRawQuery()); + if (uri.getRawFragment() != null) url.append('#').append(uri.getRawFragment()); + return url.toString(); } catch (Exception e) { return "http://localhost:" + port; } diff --git a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java index 4eeac82..6e69984 100644 --- a/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java +++ b/src/main/java/io/floci/cli/config/ProfileDefaultValueProvider.java @@ -77,11 +77,16 @@ public class ProfileDefaultValueProvider implements IDefaultValueProvider { String name = profileOption.getValue(); if (name == null) return null; - // Defaults are applied even when -h/-V was requested, so a bad profile must not stop - // `floci start --profile typo --help` from printing its usage. - if (helpRequested(command)) return null; - - Profile profile = resolve(name, command.commandLine()); + // Help renders ${DEFAULT-VALUE} through this provider, so a good profile's values show up + // in `--help`. A bad one must not stop `floci start --profile typo --help` from printing + // its usage, so only then is the failure swallowed. + Profile profile; + try { + profile = resolve(name, command.commandLine()); + } catch (ProfileNotFoundException e) { + if (helpRequested(command)) return null; + throw e; + } for (String optionName : option.names()) { String value = ProfileDefaults.valueFor(profile, optionName); if (value != null) return value; diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index 44d330b..063a041 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -22,6 +22,7 @@ public class FlociHttpClient { public static final String DEFAULT_CONTROL_PREFIX = "/_floci"; private final String endpoint; + private final String query; private final String controlPrefix; private final HttpClient http; @@ -34,7 +35,14 @@ public class FlociHttpClient { * (e.g. {@code /_floci} for AWS/Azure, {@code /_floci-gcp} for GCP). */ public FlociHttpClient(String endpoint, String controlPrefix) { - this.endpoint = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint; + // Request paths go before an endpoint's query: http://h:1/?x=1 + /health is http://h:1/health?x=1. + // A fragment is never sent, so it is dropped. + int fragment = endpoint.indexOf('#'); + String base = fragment >= 0 ? endpoint.substring(0, fragment) : endpoint; + int query = base.indexOf('?'); + this.query = query >= 0 ? base.substring(query) : ""; + base = query >= 0 ? base.substring(0, query) : base; + this.endpoint = base.endsWith("/") ? base.substring(0, base.length() - 1) : base; this.controlPrefix = controlPrefix.endsWith("/") ? controlPrefix.substring(0, controlPrefix.length() - 1) : controlPrefix; @@ -98,7 +106,7 @@ public class FlociHttpClient { public boolean isReachable() { try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(endpoint + controlPrefix + "/health")) + .uri(url(controlPrefix + "/health")) .timeout(Duration.ofSeconds(3)) .GET() .build(); @@ -117,7 +125,7 @@ public class FlociHttpClient { String path = controlPrefix + "/tls-cert"; try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(endpoint + path)) + .uri(url(path)) .timeout(Duration.ofSeconds(10)) .GET() .build(); @@ -169,7 +177,7 @@ public class FlociHttpClient { private JsonNode getJson(String path, Duration timeout) throws FlociException { try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(endpoint + path)) + .uri(url(path)) .timeout(timeout) .header("Accept", "application/json") .GET() @@ -192,7 +200,7 @@ public class FlociHttpClient { private Map postJson(String path, String body) throws FlociException { try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(endpoint + path)) + .uri(url(path)) .timeout(Duration.ofSeconds(30)) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) @@ -215,7 +223,7 @@ public class FlociHttpClient { private void deleteRequest(String path) throws FlociException { try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(endpoint + path)) + .uri(url(path)) .timeout(Duration.ofSeconds(10)) .DELETE() .build(); @@ -233,4 +241,8 @@ public class FlociHttpClient { public record HealthInfo(String version, String edition, String[] services) {} public record ServerInfo(String version, String edition) {} public record InitState(boolean boot, boolean start, boolean ready, boolean shutdown) {} + + private URI url(String path) { + return URI.create(endpoint + path + query); + } } diff --git a/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java b/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java index 201f317..aab6fd9 100644 --- a/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java +++ b/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java @@ -31,4 +31,15 @@ class FlociCliParsingTest { int code = new CommandLine(new FlociCli()).execute("doctor", "--help"); assertEquals(0, code); } + + /** BL-024: a parse error is printed before any printer exists, so --no-color is read raw. */ + @Test + void noColorFlagDisablesColourBeforeParsing() { + assertTrue(FlociCli.colorDisabled(new String[]{"start", "--profile", "typo", "--no-color"}, false, true)); + assertFalse(FlociCli.colorDisabled(new String[]{"start", "--profile", "typo"}, false, true)); + assertTrue(FlociCli.colorDisabled(new String[]{"start"}, true, true)); + assertTrue(FlociCli.colorDisabled(new String[]{"start"}, false, false)); + assertTrue(FlociCli.colorDisabled(new String[]{"start", "--no-color=true"}, false, true)); + assertFalse(FlociCli.colorDisabled(new String[]{"start", "--no-color=false"}, false, true)); + } } diff --git a/src/test/java/io/floci/cli/unit/FlociHttpClientUrlTest.java b/src/test/java/io/floci/cli/unit/FlociHttpClientUrlTest.java new file mode 100644 index 0000000..b39c31c --- /dev/null +++ b/src/test/java/io/floci/cli/unit/FlociHttpClientUrlTest.java @@ -0,0 +1,39 @@ +package io.floci.cli.unit; + +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.http.FlociHttpClient; +import org.junit.jupiter.api.Test; + +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +/** Request paths go before an endpoint's query, not after it. */ +class FlociHttpClientUrlTest { + + @Test + void theHealthPathIsInsertedBeforeTheEndpointsQuery() throws Exception { + AtomicReference seen = new AtomicReference<>(); + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + seen.set(exchange.getRequestURI().toString()); + byte[] body = "{\"version\":\"1.2.3\",\"services\":[]}".getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + server.start(); + try { + String endpoint = "http://127.0.0.1:" + server.getAddress().getPort() + "/?token=a%26b#frag"; + + assertEquals("1.2.3", new FlociHttpClient(endpoint, "/_floci").health().version()); + assertEquals("/_floci/health?token=a%26b", seen.get()); + } finally { + server.stop(0); + } + } +} diff --git a/src/test/java/io/floci/cli/unit/MissingProfileTest.java b/src/test/java/io/floci/cli/unit/MissingProfileTest.java index c088d93..cfc57b0 100644 --- a/src/test/java/io/floci/cli/unit/MissingProfileTest.java +++ b/src/test/java/io/floci/cli/unit/MissingProfileTest.java @@ -69,6 +69,26 @@ class MissingProfileTest { assertEquals(2, exit[0]); } + /** BL-014: help renders defaults through the provider, so a good profile's values show. */ + @Test + void helpShowsTheProfilesDefaults() throws Exception { + writeProfile("probe", "port: 4599\nimage: floci/floci:enforced\n"); + + PrintStream original = System.out; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); + int exit; + try { + exit = cli().execute("start", "--profile", "probe", "--help"); + } finally { + System.setOut(original); + } + + assertEquals(0, exit); + assertTrue(out.toString().contains("(default: 4599)"), out.toString()); + assertTrue(out.toString().contains("enforced"), out.toString()); // help wraps the image value + } + @Test void helpStillWorksWithABadProfile() { int[] exit = new int[1]; diff --git a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java index 087df0e..34ca95c 100644 --- a/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java +++ b/src/test/java/io/floci/cli/unit/StartCommandArgsTest.java @@ -196,5 +196,12 @@ class StartCommandArgsTest { assertEquals("http://floci.internal:4599", StartCommand.withPort("http://floci.internal:4566", 4599)); assertEquals("http://localhost:4599", StartCommand.withPort("http://localhost:4566", 4599)); assertEquals("http://localhost:4599", StartCommand.withPort("not a url", 4599)); + // BL-015: only the port changes. + assertEquals("http://user:pw@floci.internal:4599/base?x=1#f", + StartCommand.withPort("http://user:pw@floci.internal:4566/base?x=1#f", 4599)); + // Escaped characters stay escaped: %26 must not turn into a second query parameter. + assertEquals("http://floci.internal:4599/b?token=a%26b", + StartCommand.withPort("http://floci.internal:4566/b?token=a%26b", 4599)); + assertEquals("http://[::1]:4599", StartCommand.withPort("http://[::1]:4566", 4599)); } }