Author SHA1 Message Date
nandiandClaude Haiku 5.5 a999db54a8 Fix spinner hang and use braille frames
The spinner ran as a background task that outlived the command, so a
terminal run of orbit search never returned. It is now a child task that
is cancelled once the command finishes, and it starts immediately with
braille frames. upgrade skips the metadata fetch for an unchanged build
whose description is already saved.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 22:59:16 -08:00
nandi 83a1784fca Merge pull request 'Use moonbitlang/async for process and file IO' (#5) from orbit-async-io into main 2026-11-27 06:42:34 +00:00
nandiandClaude Haiku 5.5 ec21287549 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 <noreply@anthropic.com>
2026-11-26 22:40:18 -08:00
nandi 65e5dc966f Merge pull request 'Add README to the greet example directory' (#4) from greet-example-readme into main 2026-11-27 04:43:11 +00:00
11 changed files with 261 additions and 214 deletions

No files matched your search

+6 -1
View File
@@ -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 <name>` there.
- `orbit info <name>` reads installed package details without contacting the registry. Use `orbit versions <name>` to check published versions.
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions <name>` if you already know the package name.
+5 -1
View File
@@ -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
+1
View File
@@ -14,4 +14,5 @@ source = "src"
import {
"moonbit-community/toml@0.5.1",
"moonbitlang/async@0.22.9",
}
+3 -3
View File
@@ -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?,
+5 -5
View File
@@ -16,7 +16,7 @@ let usage : String =
#| orbit upgrade [name...] upgrade within constraints
#| orbit rollback <name> switch to the previous build
#| orbit list installed packages
#| orbit info <name> local and remote details
#| orbit info [channel::]<name> installed package details (local only)
#| orbit versions <name> 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 <name>")
need(pos, 1, "info [channel::]<name>")
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)
+19 -2
View File
@@ -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))
}
+3
View File
@@ -1,6 +1,9 @@
import {
"moonbitlang/core/json",
"moonbit-community/toml",
"moonbitlang/async",
"moonbitlang/async/fs",
"moonbitlang/async/process",
}
pkgtype(kind: "executable")
+93 -62
View File
@@ -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,
@@ -148,8 +148,17 @@ fn visit(
}
}
let digest = resolve_digest(ch, name, tag)
let m = fetch_manifest(ch, name, digest)
let prev = p.ctx.state.get(name)
// An unchanged build with a saved description needs no metadata fetch.
let m = match prev {
Some(i) =>
if i.digest == digest && i.description != "" {
manifest_of_installed(i)
} else {
fetch_manifest(ch, name, digest)
}
None => fetch_manifest(ch, name, digest)
}
let st = Step::{
name,
channel: ch.name,
@@ -206,26 +215,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 +268,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 +284,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 +294,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 +309,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 +325,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 +355,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::]<name>[@constraint]...")
}
@@ -348,7 +370,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 +406,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 +420,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 +438,7 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError {
}
///|
fn cmd_remove(
async fn cmd_remove(
ctx : Ctx,
names : Array[String],
force : Bool,
@@ -451,7 +473,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 +493,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 +501,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 +527,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 +550,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 +565,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 +585,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 +600,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 +643,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 +664,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 <name>`",
"no channel allows listing packages (catalog API); try `orbit versions <name>`",
)
}
}
+15 -7
View File
@@ -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 `<dir>/files` and push it with the enriched Orbit config blob.
fn publish(
async fn publish(
ch : Channel,
dir : String,
also_latest : Bool,
+18 -86
View File
@@ -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 <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#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);
}
+93 -47
View File
@@ -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,87 @@ 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}")
/// Braille spinner on stderr until cancelled.
async fn spin(label : String) -> Unit noraise {
let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
let mut i = 0
while true {
c_print_err(utf8_encode("\r\u001B[2K" + frames[i % 10] + " " + label))
i = i + 1
@async.sleep(80)
}
out
}
///|
fn exists(path : String) -> Bool {
sh("test -e " + sq(path)) == 0
/// Return stdout; stderr goes to the terminal unless captured. A label shows a
/// braille spinner on a terminal while the command runs. The spinner is a child
/// task that is cancelled as soon as the command finishes, so nothing keeps the
/// group alive.
async fn capture(cmd : String, progress~ : String = "") -> String raise OrbitError {
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
let spinning = is_tty && progress != ""
let res : Result[String, Error] = try {
let out = @async.with_task_group(group => {
let spinner = if spinning {
Some(group.spawn(() => {
ignore(@async.handle_cancellation(() => spin(progress)))
}))
} else {
None
}
let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd])
match spinner {
Some(task) => task.cancel()
None => ()
}
if spinning {
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())
}
}
///|
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 exists(path : String) -> Bool noraise {
try {
@fs.exists(path)
} catch {
_ => false
}
}
///|
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 +366,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 {