From 4f6f6f181199da59d53a0fa776ff9644ff6eac38 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Fri, 9 Oct 2026 00:18:15 -0500 Subject: [PATCH] fix(update): follow symlinked installs, pick arm64 under Rosetta and tell a failed check from a pending update floci update replaces the real binary behind a symlink, moves an x86_64 build on Apple Silicon to the arm64 build, refuses a --version that is not a release version, and accepts upper-case checksums. --check now exits 2 when the check itself fails (1 still means an update is available) and on Windows points at the installer instead of 'floci update'. A failed background update check is recorded too, so the next command does not retry it and wait at exit. Signed-off-by: Hector Ventura --- README.md | 4 +- .../io/floci/cli/commands/UpdateCommand.java | 67 ++++++++++++++++--- .../io/floci/cli/update/UpdateNotifier.java | 10 ++- .../io/floci/cli/unit/UpdatePlatformTest.java | 55 +++++++++++++++ .../floci/cli/update/UpdateNotifierTest.java | 50 ++++++++++++++ 5 files changed, 173 insertions(+), 13 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/UpdatePlatformTest.java create mode 100644 src/test/java/io/floci/cli/update/UpdateNotifierTest.java diff --git a/README.md b/README.md index bd89781..b877c87 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ java -jar floci.jar version Native-binary installs (install script, direct download) can self-update: ```sh -floci update --check # exit 0: up to date, exit 1: update available +floci update --check # exit 0: up to date, 1: update available, 2: the check failed floci update # download, verify checksum, replace the binary ``` @@ -832,7 +832,7 @@ sha256 against the release's `sha256sums.txt`, and atomically replaces the runni ```sh floci update # update to the latest release -floci update --check # exit 0: up to date, exit 1: update available +floci update --check # exit 0: up to date, 1: update available, 2: the check failed floci update --version 0.1.7 # install a specific version floci update --check || floci update # script-friendly: update only when stale ``` diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index a6d2c72..4bd0d9b 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -26,6 +26,8 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.HexFormat; import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; /** * Self-update: downloads the target release binary from the public GitHub repository @@ -46,7 +48,7 @@ import java.util.concurrent.Callable; public class UpdateCommand implements Callable { @Option(names = "--check", - description = "Only report whether an update is available (exit 0: up to date, 1: update available)") + description = "Only report whether an update is available (exit 0: up to date, 1: update available, 2: the check failed)") boolean check; // No mixinStandardHelpOptions here: its -V/--version would collide with this option. @@ -84,6 +86,10 @@ public class UpdateCommand implements Callable { try { String current = CliVersion.CLI_VERSION; boolean pinned = to != null && !to.isBlank(); + if (pinned && !Version.isValid(to.trim())) { + // It goes into the download URL; refuse anything that is not a release version. + throw new UpdateException("invalid --version '" + to + "'.\nPass a release version such as 0.3.0."); + } String target = pinned ? to.trim() : fetchLatestVersion(); // Unpinned updates are semantic, not string-equal: a pre-release/snapshot build @@ -96,7 +102,7 @@ public class UpdateCommand implements Callable { printer.println("update available: " + current + " → " + Ansi.bold(target)); if (check) { - printer.println(Ansi.gray("run 'floci update' to install it")); + printer.println(Ansi.gray(installHint())); // Non-zero so scripts can gate on staleness: floci update --check || floci update return 1; } @@ -124,10 +130,10 @@ public class UpdateCommand implements Callable { return 0; } catch (UpdateException e) { printer.error(e.getMessage()); - return 1; + return check ? 2 : 1; // --check keeps 1 for "update available" } catch (Exception e) { - printer.error("update failed: " + e.getMessage()); - return 1; + printer.error("update failed: " + e.getMessage() + "\nCheck your network connection and re-run 'floci update'."); + return check ? 2 : 1; } } @@ -168,7 +174,24 @@ public class UpdateCommand implements Callable { throw new UpdateException("running from a jar (java -jar), not the native binary — " + "nothing to self-update. Reinstall instead: curl -fsSL https://floci.io/install.sh | sh"); } - return path; + try { + // A symlinked install (~/bin/floci -> /opt/floci/floci) must replace the real file, + // not the link; this also resolves a relative argv[0] against the working directory. + return path.toRealPath(); + } catch (IOException e) { + throw new UpdateException("cannot locate the running executable (" + path + ").\n" + + "Reinstall instead: curl -fsSL https://floci.io/install.sh | sh"); + } + } + + // What --check suggests: 'floci update' where it can install, the installer where it cannot. + private static String installHint() { + try { + detectPlatform(); + return "run 'floci update' to install it"; + } catch (UpdateException e) { + return e.getMessage(); + } } /** @@ -204,15 +227,24 @@ public class UpdateCommand implements Callable { // ── platform (mirrors installer/install.sh) ────────────────────────────── static String detectPlatform() { - String os = System.getProperty("os.name", "").toLowerCase(); - String arch = System.getProperty("os.arch", "").toLowerCase(); + return detectPlatform(System.getProperty("os.name", ""), System.getProperty("os.arch", ""), + UpdateCommand::appleSilicon); + } + + /** + * The release asset suffix for this machine. An x86_64 build on a Mac may be running under + * Rosetta on Apple Silicon; it then updates to the arm64 build instead of staying x86 forever. + */ + public static String detectPlatform(String osName, String osArch, BooleanSupplier appleSilicon) { + String os = osName.toLowerCase(); + String arch = osArch.toLowerCase(); String o = null; if (os.contains("mac")) { o = "darwin"; } else if (os.contains("linux")) { o = "linux"; } else if (os.contains("windows")) { - throw new UpdateException("self-update is not supported on Windows — " + throw new UpdateException("self-update is not supported on Windows; " + "re-run the installer: irm https://floci.io/install.ps1 | iex"); } String a = switch (arch) { @@ -223,9 +255,24 @@ public class UpdateCommand implements Callable { if (o == null || a == null) { throw new UpdateException("no published build for this platform (" + os + "/" + arch + ")"); } + if (o.equals("darwin") && a.equals("amd64") && appleSilicon.getAsBoolean()) { + a = "arm64"; + } return o + "-" + a; } + private static boolean appleSilicon() { + try { + Process p = new ProcessBuilder("sysctl", "-n", "hw.optional.arm64") + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + String out = new String(p.getInputStream().readAllBytes()).trim(); + return p.waitFor(5, TimeUnit.SECONDS) && "1".equals(out); + } catch (Exception e) { + return false; + } + } + // ── download + verify ──────────────────────────────────────────────────── private String fetchString(String url) throws IOException, InterruptedException { @@ -275,7 +322,7 @@ public class UpdateCommand implements Callable { in.transferTo(OutputStream.nullOutputStream()); } String actual = HexFormat.of().formatHex(sha256.digest()); - if (!actual.equals(expected)) { + if (!actual.equalsIgnoreCase(expected)) { throw new UpdateException("checksum mismatch for " + asset + "\n expected: " + expected + "\n actual: " + actual + "\nThe download may be corrupt or tampered with. Aborting."); } diff --git a/src/main/java/io/floci/cli/update/UpdateNotifier.java b/src/main/java/io/floci/cli/update/UpdateNotifier.java index 3a85a8e..f0e43b1 100644 --- a/src/main/java/io/floci/cli/update/UpdateNotifier.java +++ b/src/main/java/io/floci/cli/update/UpdateNotifier.java @@ -85,7 +85,15 @@ public final class UpdateNotifier { JSON.writeValue(path.toFile(), new UpdateCache(Instant.now().getEpochSecond(), latest)); } catch (Exception _) { - // Network/parse failure — never surfaced; the stale/absent cache stays as-is. + // Network/parse failure, never surfaced. Record the attempt anyway (keeping the + // last known version), or every interactive run would retry and wait at exit. + try { + Path path = cachePath(); + Files.createDirectories(path.getParent()); + JSON.writeValue(path.toFile(), new UpdateCache(Instant.now().getEpochSecond(), + cache.map(UpdateCache::latestVersion).orElse(null))); + } catch (Exception ignored) { + } } })); } diff --git a/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java b/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java new file mode 100644 index 0000000..5bf6aab --- /dev/null +++ b/src/test/java/io/floci/cli/unit/UpdatePlatformTest.java @@ -0,0 +1,55 @@ +package io.floci.cli.unit; + +import io.floci.cli.commands.UpdateCommand; +import org.junit.jupiter.api.Test; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-049: which release asset floci update picks for the machine it runs on. */ +class UpdatePlatformTest { + + @Test + void picksTheAssetForEachPublishedPlatform() { + assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "aarch64", () -> true)); + assertEquals("linux-amd64", UpdateCommand.detectPlatform("Linux", "amd64", () -> false)); + assertEquals("linux-arm64", UpdateCommand.detectPlatform("Linux", "aarch64", () -> false)); + } + + /** An x86 build under Rosetta must move to the arm64 build, not stay x86 forever. */ + @Test + void anX86BuildOnAppleSiliconUpdatesToArm64() { + assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> true)); + assertEquals("darwin-amd64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> false)); + } + + @Test + void windowsPointsAtTheInstaller() { + RuntimeException e = assertThrows(RuntimeException.class, + () -> UpdateCommand.detectPlatform("Windows 11", "amd64", () -> false)); + assertTrue(e.getMessage().contains("install.ps1"), e.getMessage()); + } + + /** An invalid --version is refused before it reaches a download URL; --check reports it as 2. */ + @Test + void anInvalidVersionIsAFailedCheck() { + PrintStream err = System.err; + PrintStream out = System.out; + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errBuf)); + System.setOut(new PrintStream(new ByteArrayOutputStream())); + int exit; + try { + exit = new CommandLine(new UpdateCommand()).execute("--check", "--version", "../../evil"); + } finally { + System.setErr(err); + System.setOut(out); + } + + assertEquals(2, exit); + assertTrue(errBuf.toString().contains("invalid --version"), errBuf.toString()); + } +} diff --git a/src/test/java/io/floci/cli/update/UpdateNotifierTest.java b/src/test/java/io/floci/cli/update/UpdateNotifierTest.java new file mode 100644 index 0000000..e433320 --- /dev/null +++ b/src/test/java/io/floci/cli/update/UpdateNotifierTest.java @@ -0,0 +1,50 @@ +package io.floci.cli.update; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-026: a failed check is recorded too, so the next run does not retry and wait again. */ +class UpdateNotifierTest { + + @TempDir + Path home; + + private String realHome; + + @BeforeEach + void pointHomeAtATempDir() { + realHome = System.getProperty("user.home"); + System.setProperty("user.home", home.toString()); + } + + @AfterEach + void restoreHome() { + System.setProperty("user.home", realHome); + } + + @Test + void aFailedCheckRefreshesTheTimestampAndKeepsTheLastKnownVersion() throws Exception { + Path cache = home.resolve(".floci").resolve("update-check.json"); + Files.createDirectories(cache.getParent()); + long stale = Instant.now().minus(Duration.ofDays(3)).getEpochSecond(); + Files.writeString(cache, "{\"checkedAtEpochSeconds\":" + stale + ",\"latestVersion\":\"0.2.0\"}"); + + // Port 9 refuses connections, so the fetch fails at once. + UpdateNotifier.refreshInBackground("http://127.0.0.1:9/releases/latest"); + UpdateNotifier.awaitRefresh(Duration.ofSeconds(5)); + + UpdateCache written = new ObjectMapper().readValue(cache.toFile(), UpdateCache.class); + assertEquals("0.2.0", written.latestVersion()); + assertTrue(written.checkedAtEpochSeconds() > stale + 60, "the attempt was recorded"); + } +}