From ec21287549b3e9808d802b763bf7bceed6c7d03d Mon Sep 17 00:00:00 2001 From: nandithebull Date: Thu, 26 Nov 2026 22:40:18 -0800 Subject: [PATCH] Use moonbitlang/async for process and file IO Process execution and file access go through @process and @fs. The spinner is a background task in a task group, and the C stub keeps only getenv, exit, isatty, symlink and stderr output. orbit info reads installed state only, and it records and restores package descriptions. just install adds Orbit's bin directory to ~/.bashrc once. Co-Authored-By: Claude Haiku 5.5 --- README.md | 7 +- justfile | 6 +- moon.mod | 1 + src/main/channels.mbt | 6 +- src/main/main.mbt | 10 +-- src/main/model.mbt | 21 +++++- src/main/moon.pkg | 3 + src/main/ops.mbt | 144 ++++++++++++++++++++++++------------------ src/main/registry.mbt | 22 +++++-- src/main/stub.c | 104 ++++++------------------------ src/main/sys.mbt | 125 ++++++++++++++++++++++-------------- 11 files changed, 236 insertions(+), 213 deletions(-) diff --git a/README.md b/README.md index 3bdb268..3ab1b0f 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,10 @@ moon test --target native # semver / manifest unit tests ``` Or run `just install` to build and copy the binary to `~/.local/bin/orbit`. +It also adds Orbit's package bin directory to `~/.bashrc` if the setup line +isn't already there. Open a new Bash shell or run `source ~/.bashrc` to pick +up the change in your current shell. `~/.local/bin` must already be on `PATH` +to run `orbit` itself by name. Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`. @@ -171,4 +175,5 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp - Dependency resolution is greedy (highest satisfying version, first come), not a SAT solver. - There's no lock file for concurrent runs, and no install hooks, by design. -- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit info ` there. +- `orbit info ` reads installed package details without contacting the registry. Use `orbit versions ` to check published versions. +- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions ` if you already know the package name. diff --git a/justfile b/justfile index b43d3b3..818cadd 100644 --- a/justfile +++ b/justfile @@ -10,6 +10,10 @@ build: test: moon test --target native -# Build orbit and install it to ~/.local/bin. +# Install Orbit to ~/.local/bin and set up its package PATH for Bash. install: build install -Dm755 _build/native/release/build/main/main.exe "$HOME/.local/bin/orbit" + @line='export PATH="${ORBIT_ROOT:-$HOME/.orbit}/bin:$PATH"'; rc="$HOME/.bashrc"; \ + if [ ! -f "$rc" ] || ! grep -Fqx -- "$line" "$rc"; then \ + printf '\n%s\n' "$line" >> "$rc"; \ + fi diff --git a/moon.mod b/moon.mod index 10377b6..9e61525 100644 --- a/moon.mod +++ b/moon.mod @@ -14,4 +14,5 @@ source = "src" import { "moonbit-community/toml@0.5.1", + "moonbitlang/async@0.22.9", } diff --git a/src/main/channels.mbt b/src/main/channels.mbt index dfbefa1..bb7cad1 100644 --- a/src/main/channels.mbt +++ b/src/main/channels.mbt @@ -162,7 +162,7 @@ fn parse_legacy_config(text : String) -> Array[Channel] raise OrbitError { } ///| -fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError { +async fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError { match read_text(root + "/config.toml") { Some(t) => parse_config(t) None => @@ -186,7 +186,7 @@ fn channel_toml(c : Channel) -> String { ///| /// Append a channel at the lowest priority, keeping the file's comments. -fn cmd_channel_add( +async fn cmd_channel_add( root : String, name : String, url : String, @@ -264,7 +264,7 @@ fn split_channel(spec : String) -> (String?, String) { /// The channel to get `name` from, with its tags there. A pinned channel is /// used as is. Otherwise the first channel that has the package wins, even if /// a lower one has a newer version. -fn locate( +async fn locate( ctx : Ctx, name : String, pin : String?, diff --git a/src/main/main.mbt b/src/main/main.mbt index 3652280..a76c1b8 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -16,7 +16,7 @@ let usage : String = #| orbit upgrade [name...] upgrade within constraints #| orbit rollback switch to the previous build #| orbit list installed packages - #| orbit info local and remote details + #| orbit info [channel::] installed package details (local only) #| orbit versions published versions #| orbit search [term] list repositories (needs catalog API) #| orbit gc delete unused builds from the store @@ -30,7 +30,7 @@ let usage : String = ///| /// Create the directories, and a config.toml if there is no config yet. -fn cmd_init() -> Unit raise OrbitError { +async fn cmd_init() -> Unit raise OrbitError { let root = orbit_root() sh_ok( "mkdir -p " + @@ -60,7 +60,7 @@ fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError } ///| -fn dispatch(args : Array[String]) -> Unit raise OrbitError { +async fn dispatch(args : Array[String]) -> Unit raise OrbitError { if args.length() == 0 { println(usage) return @@ -125,7 +125,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError { } "list" | "ls" => cmd_list(load_ctx()) "info" => { - need(pos, 1, "info ") + need(pos, 1, "info [channel::]") cmd_info(load_ctx(), pos[0]) } "versions" => { @@ -140,7 +140,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError { } ///| -fn main { +async fn main { if sh("command -v oras >/dev/null 2>&1") != 0 { println("orbit: error: `oras` not found on PATH (https://oras.land)") c_exit(1) diff --git a/src/main/model.mbt b/src/main/model.mbt index d2a992f..d31f17d 100644 --- a/src/main/model.mbt +++ b/src/main/model.mbt @@ -23,6 +23,7 @@ struct Gen { channel : String version : String digest : String + description : String bins : Array[String] depends : Map[String, String] } @@ -33,6 +34,7 @@ struct Installed { mut channel : String mut version : String mut digest : String + mut description : String mut explicit : Bool mut constraint : String mut bins : Array[String] @@ -213,6 +215,7 @@ fn gen_json(g : Gen) -> Json { o["channel"] = Json::string(g.channel) o["version"] = Json::string(g.version) o["digest"] = Json::string(g.digest) + o["description"] = Json::string(g.description) o["bin"] = strs_json(g.bins) o["depends"] = map_json(g.depends) Json::object(o) @@ -224,6 +227,7 @@ fn installed_json(p : Installed) -> Json { o["channel"] = Json::string(p.channel) o["version"] = Json::string(p.version) o["digest"] = Json::string(p.digest) + o["description"] = Json::string(p.description) o["explicit"] = bool_json(p.explicit) o["constraint"] = Json::string(p.constraint) o["bin"] = strs_json(p.bins) @@ -267,6 +271,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { channel: jstr(h, "channel", MAIN_CHANNEL), version: jstr(h, "version", ""), digest: jstr(h, "digest", ""), + description: jstr(h, "description", ""), bins: jstrs(h, "bin"), depends: jmap(h, "depends"), }) @@ -280,6 +285,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { channel: jstr(o, "channel", MAIN_CHANNEL), version: jstr(o, "version", ""), digest: jstr(o, "digest", ""), + description: jstr(o, "description", ""), explicit: jbool(o, "explicit", false), constraint: jstr(o, "constraint", "*"), bins: jstrs(o, "bin"), @@ -295,6 +301,17 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { out } +///| +test "installed and rollback descriptions round trip with legacy entries" { + let text = + #|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}} + let state = state_from_text(state_to_text(state_from_text(text))) + guard state.get("tool") is Some(p) else { fail("missing installed package") } + assert_eq(p.description, "Current build") + assert_eq(p.history[0].description, "Previous build") + assert_eq(p.history[1].description, "") +} + // ---------------------------------------------------------------- context ///| @@ -309,7 +326,7 @@ fn orbit_root() -> String { ///| /// Load channels and state. -fn load_ctx() -> Ctx raise OrbitError { +async fn load_ctx() -> Ctx raise OrbitError { let root = orbit_root() let channels = resolve_channels( load_listed_channels(root), @@ -324,7 +341,7 @@ fn load_ctx() -> Ctx raise OrbitError { } ///| -fn save_state(ctx : Ctx) -> Unit raise OrbitError { +async fn save_state(ctx : Ctx) -> Unit raise OrbitError { write_text_atomic(ctx.root + "/state.json", state_to_text(ctx.state)) } diff --git a/src/main/moon.pkg b/src/main/moon.pkg index 9b8c1ff..d0e8c77 100644 --- a/src/main/moon.pkg +++ b/src/main/moon.pkg @@ -1,6 +1,9 @@ import { "moonbitlang/core/json", "moonbit-community/toml", + "moonbitlang/async", + "moonbitlang/async/fs", + "moonbitlang/async/process", } pkgtype(kind: "executable") diff --git a/src/main/ops.mbt b/src/main/ops.mbt index c601f32..a87e9cc 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -26,7 +26,7 @@ fn manifest_of_installed(p : Installed) -> Manifest { Manifest::{ name: p.name, version: p.version, - description: "", + description: p.description, documentation: "", depends: p.depends, bins: p.bins, @@ -75,7 +75,7 @@ fn constraints_for( } ///| -fn visit( +async fn visit( p : Planner, name : String, requested : String, @@ -206,26 +206,35 @@ fn owner_of_bin(ctx : Ctx, bin : String) -> String? { } ///| -fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit { +async fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit noraise { for b in bins { - sh("rm -f " + sq(bin_dir(ctx) + "/" + basename(b))) |> ignore + let path = bin_dir(ctx) + "/" + basename(b) + try { + @fs.remove(path) + } catch { + _ => () + } } } ///| -fn link_bins( +async fn link_bins( ctx : Ctx, dir : String, bins : Array[String], ) -> Unit raise OrbitError { - sh_ok("mkdir -p " + sq(bin_dir(ctx))) + try { + @fs.mkdir(bin_dir(ctx), recursive=true) + } catch { + e => raise OrbitError("cannot create bin dir: " + e.to_string()) + } for b in bins { - sh_ok( - "ln -sfn " + - sq(dir + "/" + b) + - " " + - sq(bin_dir(ctx) + "/" + basename(b)), - ) + let target = dir + "/" + b + let linkpath = bin_dir(ctx) + "/" + basename(b) + let rc = c_symlink(utf8_encode(target), utf8_encode(linkpath)) + if rc != 0 { + raise OrbitError("cannot symlink " + linkpath + " -> " + target) + } } } @@ -250,7 +259,7 @@ fn check_bin_conflicts( ///| /// Switch `name` to a fetched build, keeping the old one for rollback. -fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { +async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { let ch = find_channel(ctx, st.channel) let dir = fetch_into_store(ctx, ch, st.name, st.digest) for b in st.manifest.bins { @@ -266,6 +275,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { channel: inst.channel, version: inst.version, digest: inst.digest, + description: inst.description, bins: inst.bins, depends: inst.depends, }) @@ -275,6 +285,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { inst.channel = st.channel inst.version = st.version inst.digest = st.digest + inst.description = st.manifest.description inst.bins = st.manifest.bins inst.depends = st.manifest.depends inst.explicit = st.explicit @@ -289,6 +300,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { channel: st.channel, version: st.version, digest: st.digest, + description: st.manifest.description, explicit: st.explicit, constraint: st.constraint, bins: st.manifest.bins, @@ -304,13 +316,14 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { } ///| -fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError { +async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError { let mut changed = 0 for st in p.order { if st.keep { match ctx.state.get(st.name) { Some(inst) => { inst.channel = st.channel + inst.description = st.manifest.description inst.explicit = st.explicit inst.constraint = st.constraint } @@ -333,7 +346,7 @@ fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner { } ///| -fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { +async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { if specs.length() == 0 { raise OrbitError("usage: orbit install [channel::][@constraint]...") } @@ -348,7 +361,7 @@ fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { ///| /// Upgrade the named packages (or everything) to the newest versions their /// constraints allow. Dependencies are moved only when required. -fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { +async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { let targets : Array[String] = [] if names.length() == 0 { for name, _ in ctx.state { @@ -384,7 +397,7 @@ fn reverse_deps(ctx : Ctx, name : String) -> Array[String] { } ///| -fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { +async fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { match ctx.state.get(name) { Some(inst) => { unlink_bins(ctx, inst.bins) @@ -398,7 +411,7 @@ fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { ///| /// Remove dependencies nobody needs any more. -fn autoremove(ctx : Ctx) -> Unit raise OrbitError { +async fn autoremove(ctx : Ctx) -> Unit raise OrbitError { let mut changed = true while changed { changed = false @@ -416,7 +429,7 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError { } ///| -fn cmd_remove( +async fn cmd_remove( ctx : Ctx, names : Array[String], force : Bool, @@ -451,7 +464,7 @@ fn cmd_remove( ///| /// Swap the current build with the previous one (run twice to undo). -fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { +async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { let inst = match ctx.state.get(name) { Some(i) => i None => raise OrbitError("\{name} is not installed") @@ -471,6 +484,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { channel: inst.channel, version: inst.version, digest: inst.digest, + description: inst.description, bins: inst.bins, depends: inst.depends, }) @@ -478,6 +492,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { let from = inst.version inst.version = prev.version inst.digest = prev.digest + inst.description = prev.description inst.bins = prev.bins inst.depends = prev.depends check_bin_conflicts(ctx, name, inst.bins) @@ -503,14 +518,19 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { ///| /// Delete store entries that are neither current nor kept for rollback. -fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { +async fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { let store = ctx.root + "/store" if !exists(store) { println("store is empty") return } let mut freed = 0 - for pkg in lines(capture("ls -1 " + sq(store))) { + let pkgs = try { + @fs.readdir(store) + } catch { + _ => [] + } + for pkg in pkgs { match ctx.state.get(pkg) { None => { sh_ok("rm -rf " + sq(store + "/" + pkg)) @@ -521,7 +541,12 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { for g in inst.history { keep.push(store_id(g.digest)) } - for id in lines(capture("ls -1 " + sq(store + "/" + pkg))) { + let ids = try { + @fs.readdir(store + "/" + pkg) + } catch { + _ => [] + } + for id in ids { if !keep.contains(id) { sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id)) freed = freed + 1 @@ -531,7 +556,7 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { } } let tmp = ctx.root + "/tmp" - ignore(sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp))) + let _ = sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp)) println("removed \{freed} store entries") } @@ -551,7 +576,7 @@ fn cmd_list(ctx : Ctx) -> Unit { ///| /// Where to look up "[channel::]name": the channel asked for, else the one it /// was installed from, else by priority. -fn locate_spec( +async fn locate_spec( ctx : Ctx, spec : String, ) -> (String, Channel, Array[String]) raise OrbitError { @@ -566,44 +591,38 @@ fn locate_spec( ///| fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError { - let (_, name) = split_channel(spec) - match ctx.state.get(name) { - Some(p) => { - println("\{name} \{p.version} (installed)") - println(" channel: \{p.channel}") - println(" digest: \{p.digest}") - println(" constraint: \{p.constraint}") - println(" bin: \{join(p.bins, " ")}") - let deps : Array[String] = [] - for d, c in p.depends { - deps.push(d + "@" + c) - } - println(" depends: \{join(deps, " ")}") - let rd = reverse_deps(ctx, name) - println(" needed by: \{join(rd, " ")}") - let hist : Array[String] = [] - for g in p.history { - hist.push(g.version) - } - println(" rollback: \{join(hist, " ")}") - } - None => () + let (pin, name) = split_channel(spec) + let p = match ctx.state.get(name) { + Some(p) => p + None => raise OrbitError("\{spec} is not installed") } - let (_, ch, tags) = locate_spec(ctx, spec) - match pick_tag(tags, ["*"]) { - Some(t) => { - let m = fetch_manifest(ch, name, resolve_digest(ch, name, t)) - println("\{name} \{m.version} (latest in \{ch.name}: \{ch.url})") - if m.description != "" { - println(" \{m.description}") - } - } - None => println("\{name}: no stable versions published") + if pin is Some(channel) && channel != p.channel { + raise OrbitError("\{spec} is not installed (installed from '\{p.channel}')") } + println("\{name} \{p.version} (installed)") + if p.description != "" { + println(" description: \{p.description}") + } + println(" channel: \{p.channel}") + println(" digest: \{p.digest}") + println(" constraint: \{p.constraint}") + println(" bin: \{join(p.bins, " ")}") + let deps : Array[String] = [] + for d, c in p.depends { + deps.push(d + "@" + c) + } + println(" depends: \{join(deps, " ")}") + let rd = reverse_deps(ctx, name) + println(" needed by: \{join(rd, " ")}") + let hist : Array[String] = [] + for g in p.history { + hist.push(g.version) + } + println(" rollback: \{join(hist, " ")}") } ///| -fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError { +async fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError { let (name, ch, tags) = locate_spec(ctx, spec) for v in sorted_versions(tags) { let mark = match ctx.state.get(name) { @@ -615,10 +634,13 @@ fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError { } ///| -fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { +async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { let mut listed = 0 for ch in ctx.channels { - let out = capture(oras(ch, "repo ls " + sq(ch.url))) catch { + let out = capture( + oras(ch, "repo ls " + sq(ch.url)), + progress="Listing packages in \{ch.name}", + ) catch { _ => { println("warning: channel '\{ch.name}' does not allow listing packages") continue @@ -633,7 +655,7 @@ fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { } if listed == 0 { raise OrbitError( - "no channel allows listing packages (catalog API); try `orbit info `", + "no channel allows listing packages (catalog API); try `orbit versions `", ) } } diff --git a/src/main/registry.mbt b/src/main/registry.mbt index 5744b30..928650b 100644 --- a/src/main/registry.mbt +++ b/src/main/registry.mbt @@ -23,10 +23,14 @@ fn is_missing_repo(err : String) -> Bool { /// The tags of `name` in a channel, or None if the channel doesn't have it. /// Any other failure is an error: falling through to a lower priority channel /// could install a different package with the same name. -fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError { +async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError { let errfile = trim(capture("mktemp")) let cmd = oras(ch, "repo tags " + sq(repo_of(ch, name))) + " 2>" + sq(errfile) - let out = Some(capture(cmd)) catch { _ => None } + let out = Some( + capture(cmd, progress="Checking versions of \{ch.name}::\{name}"), + ) catch { + _ => None + } let err = match read_text(errfile) { Some(t) => trim(t) None => "" @@ -44,13 +48,16 @@ fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError { } ///| -fn resolve_digest( +async fn resolve_digest( ch : Channel, name : String, tag : String, ) -> String raise OrbitError { let d = trim( - capture(oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag))), + capture( + oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag)), + progress="Resolving \{ch.name}::\{name}@\{tag}", + ), ) if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) { raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'") @@ -60,13 +67,14 @@ fn resolve_digest( ///| /// Fetch only the config blob (orbit.json); no layer download needed to plan. -fn fetch_manifest( +async fn fetch_manifest( ch : Channel, name : String, digest : String, ) -> Manifest raise OrbitError { let text = capture( oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)), + progress="Reading metadata for \{ch.name}::\{name}", ) let m = parse_manifest(text) if m.name != name { @@ -81,7 +89,7 @@ fn fetch_manifest( /// Pull a package layer by digest and unpack it into the store. /// Unpacks into a temp dir first, then renames, so a store dir is either /// complete or absent. -fn fetch_into_store( +async fn fetch_into_store( ctx : Ctx, ch : Channel, name : String, @@ -176,7 +184,7 @@ test "package config exposes Gitea labels and preserves Orbit metadata" { ///| /// Pack `/files` and push it with the enriched Orbit config blob. -fn publish( +async fn publish( ch : Channel, dir : String, also_latest : Bool, diff --git a/src/main/stub.c b/src/main/stub.c index bffbb9e..462848e 100644 --- a/src/main/stub.c +++ b/src/main/stub.c @@ -1,17 +1,10 @@ -// Native glue for orbit: process execution, file IO and environment access. -// Every string crosses the boundary as UTF-8 `Bytes` (not NUL-terminated). -// Arguments are never decref'd here: if the compiler passes them owned we leak -// a few bytes in a short-lived CLI, which is harmless; if it passes them -// borrowed, decref'ing would be a use-after-free. +#include #include #include #include -#include #include "moonbit.h" -static int last_status = 0; - static char *to_cstr(moonbit_bytes_t b) { int32_t n = Moonbit_array_length(b); char *s = (char *)malloc((size_t)n + 1); @@ -27,84 +20,6 @@ static moonbit_bytes_t from_buf(const char *buf, size_t len) { return out; } -static int decode_status(int r) { - if (r == -1) return -1; - if (WIFEXITED(r)) return WEXITSTATUS(r); - return 128; -} - -int32_t orbit_run(moonbit_bytes_t cmd) { - char *c = to_cstr(cmd); - fflush(stdout); - int r = system(c); - free(c); - return decode_status(r); -} - -moonbit_bytes_t orbit_capture(moonbit_bytes_t cmd) { - char *c = to_cstr(cmd); - fflush(stdout); - FILE *p = popen(c, "r"); - free(c); - if (!p) { - last_status = -1; - return from_buf("", 0); - } - size_t cap = 4096, len = 0; - char *buf = (char *)malloc(cap); - size_t got; - while ((got = fread(buf + len, 1, cap - len, p)) > 0) { - len += got; - if (len == cap) { - cap *= 2; - buf = (char *)realloc(buf, cap); - if (!buf) abort(); - } - } - last_status = decode_status(pclose(p)); - moonbit_bytes_t out = from_buf(buf, len); - free(buf); - return out; -} - -int32_t orbit_last_status(void) { return last_status; } - -moonbit_bytes_t orbit_read_file(moonbit_bytes_t path) { - char *p = to_cstr(path); - FILE *f = fopen(p, "rb"); - free(p); - if (!f) { - last_status = -1; - return from_buf("", 0); - } - size_t cap = 4096, len = 0, got; - char *buf = (char *)malloc(cap); - while ((got = fread(buf + len, 1, cap - len, f)) > 0) { - len += got; - if (len == cap) { - cap *= 2; - buf = (char *)realloc(buf, cap); - if (!buf) abort(); - } - } - fclose(f); - last_status = 0; - moonbit_bytes_t out = from_buf(buf, len); - free(buf); - return out; -} - -int32_t orbit_write_file(moonbit_bytes_t path, moonbit_bytes_t data) { - char *p = to_cstr(path); - FILE *f = fopen(p, "wb"); - free(p); - if (!f) return -1; - int32_t n = Moonbit_array_length(data); - size_t w = fwrite(data, 1, (size_t)n, f); - int rc = fclose(f); - return (w == (size_t)n && rc == 0) ? 0 : -1; -} - moonbit_bytes_t orbit_getenv(moonbit_bytes_t name) { char *n = to_cstr(name); const char *v = getenv(n); @@ -117,3 +32,20 @@ void orbit_exit(int32_t code) { fflush(stdout); exit(code); } + +int32_t orbit_symlink(moonbit_bytes_t target, moonbit_bytes_t linkpath) { + char *t = to_cstr(target); + char *l = to_cstr(linkpath); + unlink(l); + int rc = symlink(t, l); + free(t); + free(l); + return rc; +} + +void orbit_print_err(moonbit_bytes_t msg) { + char *m = to_cstr(msg); + fputs(m, stderr); + fflush(stderr); + free(m); +} diff --git a/src/main/sys.mbt b/src/main/sys.mbt index 1fb6e11..c3fe7f0 100644 --- a/src/main/sys.mbt +++ b/src/main/sys.mbt @@ -1,31 +1,10 @@ -// System access through the C stub, plus small string helpers. -// Helpers are written against `for c in s` only, to stay independent of -// String APIs that have changed between MoonBit releases. +// System access through process execution, MoonBit async fs/process, and small helpers. ///| suberror OrbitError { OrbitError(String) } -///| -#borrow(cmd) -extern "C" fn c_run(cmd : Bytes) -> Int32 = "orbit_run" - -///| -#borrow(cmd) -extern "C" fn c_capture(cmd : Bytes) -> Bytes = "orbit_capture" - -///| -extern "C" fn c_last_status() -> Int32 = "orbit_last_status" - -///| -#borrow(path) -extern "C" fn c_read_file(path : Bytes) -> Bytes = "orbit_read_file" - -///| -#borrow(path, data) -extern "C" fn c_write_file(path : Bytes, data : Bytes) -> Int32 = "orbit_write_file" - ///| #borrow(name) extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv" @@ -33,6 +12,17 @@ extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv" ///| extern "C" fn c_exit(code : Int32) = "orbit_exit" +///| +extern "C" fn c_isatty(fd : Int32) -> Int32 = "isatty" + +///| +#borrow(msg) +extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err" + +///| +#borrow(target, linkpath) +extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink" + // ---------------------------------------------------------------- UTF-8 ///| @@ -266,15 +256,19 @@ fn sq(s : String) -> String { sb.to_string() } -// ---------------------------------------------------------------- process / fs +// ---------------------------------------------------------------- process / fs (async) ///| -fn sh(cmd : String) -> Int32 { - c_run(utf8_encode(cmd)) +async fn sh(cmd : String) -> Int32 noraise { + try { + @process.run("sh", ["-c", cmd]) + } catch { + _ => 128 + } } ///| -fn sh_ok(cmd : String) -> Unit raise OrbitError { +async fn sh_ok(cmd : String) -> Unit raise OrbitError { let code = sh(cmd) if code != 0 { raise OrbitError("command failed (exit \{code}): \{cmd}") @@ -282,39 +276,72 @@ fn sh_ok(cmd : String) -> Unit raise OrbitError { } ///| -/// Run a command and return its stdout; stderr goes to the terminal. -fn capture(cmd : String) -> String raise OrbitError { - let out = utf8_decode(c_capture(utf8_encode(cmd))) - let code = c_last_status() - if code != 0 { - raise OrbitError("command failed (exit \{code}): \{cmd}") +/// Return stdout; stderr goes to the terminal unless captured. A label enables delayed progress spinner. +async fn capture(cmd : String, progress? : String = "") -> String raise OrbitError { + let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb" + let res : Result[String, Error] = try { + let out = @async.with_task_group((group) => { + if is_tty && progress != "" { + group.spawn_bg(async fn() { + @async.sleep(250) + let frames = ["|", "/", "-", "\\"] + let mut i = 0 + while true { + c_print_err(utf8_encode("\r\u001B[2K" + frames[i % 4] + " " + progress)) + i = i + 1 + @async.sleep(100) + } + }) + } + let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd]) + if is_tty && progress != "" { + c_print_err(utf8_encode("\r\u001B[2K")) + } + if code != 0 { + raise OrbitError("command failed (exit \{code}): \{cmd}") + } + stdout.text() + }) + Ok(out) + } catch { + e => Err(e) + } + match res { + Ok(s) => s + Err(OrbitError(msg)) => raise OrbitError(msg) + Err(e) => raise OrbitError(e.to_string()) } - out } ///| -fn exists(path : String) -> Bool { - sh("test -e " + sq(path)) == 0 +async fn exists(path : String) -> Bool noraise { + try { + @fs.exists(path) + } catch { + _ => false + } } ///| -fn read_text(path : String) -> String? { - let b = c_read_file(utf8_encode(path)) - if c_last_status() != 0 { - None - } else { - Some(utf8_decode(b)) +async fn read_text(path : String) -> String? noraise { + try { + let data = @fs.read_file(path) + Some(data.text()) + } catch { + _ => None } } ///| /// Write via a temp file and rename, so readers never see a half-written file. -fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError { +async fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError { let tmp = path + ".tmp" - if c_write_file(utf8_encode(tmp), utf8_encode(text)) != 0 { - raise OrbitError("cannot write \{tmp}") + try { + @fs.write_file(tmp, text, create_mode=CreateOrTruncate) + @fs.rename(tmp, path) + } catch { + e => raise OrbitError("cannot write " + path + ": " + e.to_string()) } - sh_ok("mv -f " + sq(tmp) + " " + sq(path)) } ///| @@ -324,8 +351,12 @@ fn getenv(name : String) -> String { ///| /// Command-line arguments without the program name (Linux: /proc/self/cmdline). -fn cli_args() -> Array[String] { - let raw = c_read_file(utf8_encode("/proc/self/cmdline")) +async fn cli_args() -> Array[String] noraise { + let raw = try { + @fs.read_file("/proc/self/cmdline").binary() + } catch { + _ => Default::default() + } let out : Array[String] = [] let cur : Array[Byte] = [] for i = 0; i < raw.length(); i = i + 1 {