mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
fix(update): follow symlinked installs, pick arm64 under Rosetta and tell a failed check from a pending update (#56)
* 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 <hectorvent@gmail.com> * fix(update): record a check attempt before the request and bound the Rosetta probe The update check marks its attempt before asking GitHub, so a command that exits while the request is still waiting does not start it again on every run; an attempt is retried after an hour rather than a day and never overwrites a result another process just stored. The sysctl probe waits with its limit before reading. Adds a test for updating through a symlink. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
fa306b38a6
commit
a9edb57aa6
5 files changed
+396
-22
No files matched your search
@@ -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<Integer> {
|
||||
|
||||
@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<Integer> {
|
||||
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<Integer> {
|
||||
|
||||
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<Integer> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +164,7 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
|
||||
private Path resolveSelf() {
|
||||
if (selfPath != null) {
|
||||
return selfPath;
|
||||
return realExecutable(selfPath);
|
||||
}
|
||||
String cmd = ProcessHandle.current().info().command()
|
||||
.orElseThrow(() -> new UpdateException("cannot locate the running executable"));
|
||||
@@ -168,7 +174,31 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
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;
|
||||
return realExecutable(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* The file an update of {@code path} has to replace. 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.
|
||||
*/
|
||||
public static Path realExecutable(Path path) {
|
||||
try {
|
||||
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 +234,24 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
// ── 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 +262,40 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
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 {
|
||||
return "1".equals(probe(Duration.ofSeconds(5), "sysctl", "-n", "hw.optional.arm64"));
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The trimmed output of a short command, or null when it does not finish within {@code limit}.
|
||||
* The wait comes first and a late process is killed: reading first would block for as long as
|
||||
* the process keeps its output open, and the limit would never apply. Only for commands that
|
||||
* print a line or two, which fit the pipe without being drained.
|
||||
*/
|
||||
public static String probe(Duration limit, String... command) throws IOException, InterruptedException {
|
||||
Process p = new ProcessBuilder(command)
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
try {
|
||||
if (!p.waitFor(limit.toMillis(), TimeUnit.MILLISECONDS)) {
|
||||
return null;
|
||||
}
|
||||
return new String(p.getInputStream().readAllBytes()).trim();
|
||||
} finally {
|
||||
p.destroyForcibly(); // a no-op once it has exited
|
||||
}
|
||||
}
|
||||
|
||||
// ── download + verify ────────────────────────────────────────────────────
|
||||
|
||||
private String fetchString(String url) throws IOException, InterruptedException {
|
||||
@@ -275,7 +345,7 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
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.");
|
||||
}
|
||||
@@ -283,7 +353,8 @@ public class UpdateCommand implements Callable<Integer> {
|
||||
|
||||
// ── atomic replace ───────────────────────────────────────────────────────
|
||||
|
||||
private static void replaceAtomically(Path fresh, Path target) throws IOException {
|
||||
/** Puts {@code fresh} in place of {@code target} in one step. Public as a test seam. */
|
||||
public static void replaceAtomically(Path fresh, Path target) throws IOException {
|
||||
// Stage in the TARGET's directory (same filesystem), then atomically rename over it.
|
||||
// The running process keeps its old inode; the path now serves the new binary.
|
||||
Path staged = target.resolveSibling("." + target.getFileName() + ".new");
|
||||
|
||||
@@ -29,6 +29,9 @@ public final class UpdateNotifier {
|
||||
|
||||
static final Duration TTL = Duration.ofHours(24);
|
||||
|
||||
/** How soon a check that did not produce a result (still in flight, or failed) is tried again. */
|
||||
static final Duration RETRY_AFTER = Duration.ofHours(1);
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
/** The in-flight refresh, if this run started one; lets main() grant it a short grace. */
|
||||
@@ -74,22 +77,54 @@ public final class UpdateNotifier {
|
||||
if (cache.isPresent() && !isStale(cache.get())) {
|
||||
return;
|
||||
}
|
||||
// Virtual threads do not keep the JVM alive: a quick exit just drops the check and it
|
||||
// is retried next time; main() grants a short grace via awaitRefresh so commands that
|
||||
// finish fast still get the cache populated eventually.
|
||||
// Virtual threads do not keep the JVM alive: a quick exit just drops the check; main()
|
||||
// grants a short grace via awaitRefresh so commands that finish fast still get the cache
|
||||
// populated eventually.
|
||||
REFRESH.set(Thread.ofVirtual().name("floci-update-check").start(() -> {
|
||||
// The attempt is recorded before the request, not after it fails: a request that is
|
||||
// still waiting when the command exits never reaches a catch block, and every run
|
||||
// would start it again and wait at exit.
|
||||
if (!recordAttempt()) {
|
||||
return; // another process got there first
|
||||
}
|
||||
try {
|
||||
String latest = fetchLatestVersion(latestReleaseUrl);
|
||||
Path path = cachePath();
|
||||
Files.createDirectories(path.getParent());
|
||||
JSON.writeValue(path.toFile(),
|
||||
new UpdateCache(Instant.now().getEpochSecond(), latest));
|
||||
write(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. The attempt is already on record.
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the cache as "checked, try again in {@link #RETRY_AFTER}", keeping the last known
|
||||
* version. The file is read again right before the write: another process may have finished
|
||||
* a check since this one found the cache stale, and its result (or its own attempt) stands.
|
||||
*
|
||||
* @return false when the cache is no longer stale, so there is nothing left to check
|
||||
*/
|
||||
static boolean recordAttempt() {
|
||||
try {
|
||||
Optional<UpdateCache> onDisk = readQuietly();
|
||||
if (onDisk.isPresent() && !isStale(onDisk.get())) {
|
||||
return false;
|
||||
}
|
||||
// Backdated so the entry turns stale again after RETRY_AFTER rather than a full TTL:
|
||||
// an attempt is not a result.
|
||||
long checkedAt = Instant.now().minus(TTL).plus(RETRY_AFTER).getEpochSecond();
|
||||
write(new UpdateCache(checkedAt, onDisk.map(UpdateCache::latestVersion).orElse(null)));
|
||||
} catch (Exception _) {
|
||||
// An unwritable cache must not stop the check itself.
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void write(UpdateCache cache) throws Exception {
|
||||
Path path = cachePath();
|
||||
Files.createDirectories(path.getParent());
|
||||
JSON.writeValue(path.toFile(), cache);
|
||||
}
|
||||
|
||||
/** Give an in-flight refresh a bounded chance to finish before the JVM exits. */
|
||||
public static void awaitRefresh(Duration grace) {
|
||||
Thread refresh = REFRESH.get();
|
||||
|
||||
Reference in new issue
Block a user