commit efeaa326c87c020b14eaecd6cb4acd04643d4d42 Author: Claude Date: Thu Nov 26 17:21:17 2026 -0800 orbit: OCI/ORAS-backed package manager in MoonBit Initial, not yet compiled: CLI, semver constraints, dependency planner, content-addressed store, install/remove/upgrade/rollback/gc, publish. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hhg7TTpuaCymoNQWmQ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea492e5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target/ +.mooncakes/ +_build/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..201d08f --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# orbit + +A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, with [ORAS](https://github.com/oras-project/oras) as the transport. + +> **Status: not compiled yet.** This was written without access to a MoonBit toolchain. Expect a few compile fixes on first build. The likeliest spots are listed under *First build* below. + +## What it does + +- **Publish:** `orbit publish ` packs `/files/` into `pkg.tar.gz` and pushes it with `/orbit.json` as the OCI config blob. +- **Install with dependencies:** it reads only the small config blob (`oras manifest fetch-config`) to plan, then pulls the layers by digest. +- **Version constraints:** `1.2.3`, `1.2`, `^1.2.0`, `~1.2.0`, `>=1.2`, `*`. Prereleases match only when the constraint asks for one. +- **Content-addressed store:** packages unpack into `~/.orbit/store///`, and their binaries are symlinked into `~/.orbit/bin/`. +- **File ownership:** two packages can't provide the same binary. +- **Upgrade and rollback:** the previous two builds are kept, and `orbit rollback ` switches back instantly with no network. +- **Remove:** `orbit remove` refuses to delete what other packages need, then autoremoves orphaned dependencies. +- **gc** deletes builds that are neither current nor kept for rollback. + +## Package format + +``` +mypkg/ + orbit.json + files/ + bin/mytool + share/... +``` + +```json +{ + "name": "mytool", + "version": "1.4.0", + "description": "Does a thing", + "bin": ["bin/mytool"], + "depends": { "libfoo": "^2.1.0" } +} +``` + +In the registry this becomes `/mytool:1.4.0`, plus the `latest` tag: + +| Part | Media type | +|---|---| +| config | `application/vnd.latha.orbit.config.v1+json` (the orbit.json) | +| layer `pkg.tar.gz` | `application/vnd.latha.orbit.layer.v1.tar+gzip` | + +Because these are ordinary OCI artifacts, you can sign them with `cosign` or `notation` and attach SBOMs using the registry's own tooling. + +## Usage + +```sh +oras login git.site.latha.org # once, with a Gitea token +orbit init git.site.latha.org/ # Gitea: registry is / +eval "$(orbit env)" + +orbit publish examples/hello +orbit install hello +hello # -> hello from orbit +orbit upgrade +orbit rollback hello +orbit remove hello +``` + +Use `--plain-http` (or `ORBIT_PLAIN_HTTP=1`) for a local `registry:2` without TLS: + +```sh +docker run -d -p 5000:5000 registry:2 +orbit init localhost:5000/pkgs --plain-http +``` + +## Building + +```sh +moon build --target native --release +moon test --target native # semver / manifest unit tests +# the binary is under target/native/release/build/main/ +``` + +Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`. + +## Layout + +``` +src/main/ + stub.c C glue: system(), popen(), file read/write, getenv, exit + sys.mbt FFI bindings, UTF-8, string helpers, shell quoting + semver.mbt versions, constraints, tag selection (+ tests) + model.mbt orbit.json / state.json / config.json (+ tests) + registry.mbt oras wrappers: tags, resolve, fetch-config, pull, push + ops.mbt dependency planner, install/remove/upgrade/rollback/gc + main.mbt CLI +``` + +## First build: likely fix-ups + +The code avoids most of the standard library (string helpers are built on `for c in s` only), but a few calls depend on the compiler version: + +- `suberror OrbitError String` and `raise` in signatures. Older compilers use `type! OrbitError String` and `!` call syntax. +- `Bytes::makei`, `Int::unsafe_to_char`, `StringBuilder::write_char`. +- `@json.parse(String)`, which may want a `StringView`, and `Json::Object` / `Json::String` patterns. +- `Json::stringify(indent=2)`. +- C FFI argument ownership. The stub never decrefs, so the worst case is a small leak. + +## Known limits + +- 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. diff --git a/examples/hello/files/bin/hello b/examples/hello/files/bin/hello new file mode 100755 index 0000000..23e86a5 --- /dev/null +++ b/examples/hello/files/bin/hello @@ -0,0 +1,2 @@ +#!/bin/sh +echo "hello from orbit" diff --git a/examples/hello/orbit.json b/examples/hello/orbit.json new file mode 100644 index 0000000..5f33a5e --- /dev/null +++ b/examples/hello/orbit.json @@ -0,0 +1,7 @@ +{ + "name": "hello", + "version": "1.0.0", + "description": "Example orbit package", + "bin": ["bin/hello"], + "depends": {} +} diff --git a/moon.mod.json b/moon.mod.json new file mode 100644 index 0000000..e24d52a --- /dev/null +++ b/moon.mod.json @@ -0,0 +1,9 @@ +{ + "name": "latha/orbit", + "version": "0.1.0", + "readme": "README.md", + "license": "Apache-2.0", + "keywords": ["package-manager", "oras", "oci"], + "description": "A small package manager that stores packages as OCI artifacts via ORAS", + "source": "src" +} diff --git a/src/main/main.mbt b/src/main/main.mbt new file mode 100644 index 0000000..5e9a112 --- /dev/null +++ b/src/main/main.mbt @@ -0,0 +1,114 @@ +// orbit: a package manager whose repository is any OCI registry, via ORAS. + +///| +let usage : String = + #|orbit - packages as OCI artifacts (via oras) + #| + #|usage: + #| orbit init [--plain-http] set registry, e.g. git.example.org/owner + #| orbit publish [--no-latest] push /orbit.json + /files/ + #| orbit install [@constraint]... install with dependencies + #| orbit remove ... [--force] remove, then drop unused dependencies + #| orbit upgrade [name...] upgrade within constraints + #| orbit rollback switch to the previous build + #| orbit list installed packages + #| orbit info local and remote details + #| orbit versions published versions + #| orbit search [term] list repositories (needs catalog API) + #| orbit gc delete unused builds from the store + #| orbit env print the PATH line for your shell + #| + #|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 * + #|environment: ORBIT_ROOT (default ~/.orbit), ORBIT_REGISTRY, ORBIT_PLAIN_HTTP=1 + #|authentication: run `oras login ` once. + +///| +fn cmd_init(registry : String, plain_http : Bool) -> Unit raise OrbitError { + let root = orbit_root() + sh_ok( + "mkdir -p " + + sq(root + "/bin") + + " " + + sq(root + "/store") + + " " + + sq(root + "/tmp"), + ) + write_text_atomic( + root + "/config.json", + config_to_text(Config::{ registry, plain_http }), + ) + println("orbit root: \{root}") + println("registry: \{registry}") + println("add to your shell profile:") + println(" export PATH=\"\{root}/bin:$PATH\"") +} + +///| +fn need(pos : Array[String], n : Int, what : String) -> Unit raise OrbitError { + if pos.length() < n { + raise OrbitError("usage: orbit \{what}") + } +} + +///| +fn dispatch(args : Array[String]) -> Unit raise OrbitError { + if args.length() == 0 { + println(usage) + return + } + let cmd = args[0] + let pos : Array[String] = [] + let flags : Array[String] = [] + for i = 1; i < args.length(); i = i + 1 { + if has_prefix(args[i], "--") { + flags.push(args[i]) + } else { + pos.push(args[i]) + } + } + match cmd { + "help" | "-h" | "--help" => println(usage) + "init" => { + need(pos, 1, "init [--plain-http]") + cmd_init(pos[0], flags.contains("--plain-http")) + } + "env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"") + "publish" => { + need(pos, 1, "publish ") + publish(load_ctx(), pos[0], not(flags.contains("--no-latest"))) + } + "install" | "add" => cmd_install(load_ctx(), pos) + "remove" | "rm" => cmd_remove(load_ctx(), pos, flags.contains("--force")) + "upgrade" | "up" => cmd_upgrade(load_ctx(), pos) + "rollback" => { + need(pos, 1, "rollback ") + cmd_rollback(load_ctx(), pos[0]) + } + "list" | "ls" => cmd_list(load_ctx()) + "info" => { + need(pos, 1, "info ") + cmd_info(load_ctx(), pos[0]) + } + "versions" => { + need(pos, 1, "versions ") + cmd_versions(load_ctx(), pos[0]) + } + "search" => cmd_search(load_ctx(), if pos.length() > 0 { pos[0] } else { "" }) + "gc" => cmd_gc(load_ctx()) + _ => raise OrbitError("unknown command '\{cmd}' (try `orbit help`)") + } +} + +///| +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) + } + dispatch(cli_args()) catch { + OrbitError(msg) => { + println("orbit: error: \{msg}") + c_exit(1) + } + } +} diff --git a/src/main/model.mbt b/src/main/model.mbt new file mode 100644 index 0000000..a323e7a --- /dev/null +++ b/src/main/model.mbt @@ -0,0 +1,378 @@ +// Package manifest (orbit.json), local state (state.json) and config. + +///| +const CONFIG_MEDIA_TYPE : String = "application/vnd.latha.orbit.config.v1+json" + +///| +const LAYER_MEDIA_TYPE : String = "application/vnd.latha.orbit.layer.v1.tar+gzip" + +/// Contents of orbit.json, which is also the OCI config blob of a package. +struct Manifest { + name : String + version : String + description : String + depends : Map[String, String] + bins : Array[String] +} + +/// A previously installed build, kept for rollback. +struct Gen { + version : String + digest : String + bins : Array[String] + depends : Map[String, String] +} + +///| +struct Installed { + name : String + mut version : String + mut digest : String + mut explicit : Bool + mut constraint : String + mut bins : Array[String] + mut depends : Map[String, String] + history : Array[Gen] +} + +///| +struct Config { + registry : String + plain_http : Bool +} + +///| +struct Ctx { + root : String + cfg : Config + state : Map[String, Installed] +} + +// ---------------------------------------------------------------- JSON helpers + +///| +fn jstr(o : Map[String, Json], k : String, d : String) -> String { + match o.get(k) { + Some(Json::String(s)) => s + _ => d + } +} + +///| +fn jbool(o : Map[String, Json], k : String, d : Bool) -> Bool { + match o.get(k) { + Some(Json::True) => true + Some(Json::False) => false + _ => d + } +} + +///| +fn jstrs(o : Map[String, Json], k : String) -> Array[String] { + let r : Array[String] = [] + match o.get(k) { + Some(Json::Array(xs)) => + for x in xs { + match x { + Json::String(s) => r.push(s) + _ => () + } + } + _ => () + } + r +} + +///| +fn jmap(o : Map[String, Json], k : String) -> Map[String, String] { + let r : Map[String, String] = {} + match o.get(k) { + Some(Json::Object(m)) => + for key, v in m { + match v { + Json::String(s) => r[key] = s + _ => () + } + } + _ => () + } + r +} + +///| +fn strs_json(xs : Array[String]) -> Json { + let a : Array[Json] = [] + for x in xs { + a.push(Json::String(x)) + } + Json::Array(a) +} + +///| +fn map_json(m : Map[String, String]) -> Json { + let o : Map[String, Json] = {} + for k, v in m { + o[k] = Json::String(v) + } + Json::Object(o) +} + +///| +fn bool_json(b : Bool) -> Json { + if b { + Json::True + } else { + Json::False + } +} + +///| +fn parse_object(text : String, what : String) -> Map[String, Json] raise OrbitError { + let j = @json.parse(text) catch { + _ => raise OrbitError("\{what}: invalid JSON") + } + match j { + Json::Object(o) => o + _ => raise OrbitError("\{what}: expected a JSON object") + } +} + +// ---------------------------------------------------------------- manifest + +///| +fn valid_name(s : String) -> Bool { + if s == "" { + return false + } + for c in s { + let ok = (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || + c == '-' || + c == '_' || + c == '.' + if not(ok) { + return false + } + } + not(has_prefix(s, ".")) +} + +/// A bin path must stay inside the package: relative, no "..". +fn valid_rel_path(p : String) -> Bool { + if p == "" || has_prefix(p, "/") { + return false + } + for part in split_on(p, '/') { + if part == ".." { + return false + } + } + true +} + +///| +fn parse_manifest(text : String) -> Manifest raise OrbitError { + let o = parse_object(text, "orbit.json") + let m = Manifest::{ + name: jstr(o, "name", ""), + version: jstr(o, "version", ""), + description: jstr(o, "description", ""), + depends: jmap(o, "depends"), + bins: jstrs(o, "bin"), + } + if not(valid_name(m.name)) { + raise OrbitError( + "orbit.json: invalid name '\{m.name}' (use a-z, 0-9, '-', '_', '.')", + ) + } + if not(is_ver(m.version)) { + raise OrbitError("orbit.json: version '\{m.version}' is not semver") + } + for b in m.bins { + if not(valid_rel_path(b)) { + raise OrbitError("orbit.json: bin path '\{b}' must be relative") + } + } + for dep, _ in m.depends { + if not(valid_name(dep)) { + raise OrbitError("orbit.json: invalid dependency name '\{dep}'") + } + } + m +} + +// ---------------------------------------------------------------- state + +///| +fn gen_json(g : Gen) -> Json { + let o : Map[String, Json] = {} + o["version"] = Json::String(g.version) + o["digest"] = Json::String(g.digest) + o["bin"] = strs_json(g.bins) + o["depends"] = map_json(g.depends) + Json::Object(o) +} + +///| +fn installed_json(p : Installed) -> Json { + let o : Map[String, Json] = {} + o["version"] = Json::String(p.version) + o["digest"] = Json::String(p.digest) + o["explicit"] = bool_json(p.explicit) + o["constraint"] = Json::String(p.constraint) + o["bin"] = strs_json(p.bins) + o["depends"] = map_json(p.depends) + let h : Array[Json] = [] + for g in p.history { + h.push(gen_json(g)) + } + o["history"] = Json::Array(h) + Json::Object(o) +} + +///| +fn state_to_text(state : Map[String, Installed]) -> String { + let pkgs : Map[String, Json] = {} + for name, p in state { + pkgs[name] = installed_json(p) + } + let top : Map[String, Json] = {} + top["format"] = Json::String("orbit-state-v1") + top["packages"] = Json::Object(pkgs) + Json::Object(top).stringify(indent=2) + "\n" +} + +///| +fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { + let top = parse_object(text, "state.json") + let out : Map[String, Installed] = {} + match top.get("packages") { + Some(Json::Object(pkgs)) => + for name, pj in pkgs { + match pj { + Json::Object(o) => { + let history : Array[Gen] = [] + match o.get("history") { + Some(Json::Array(hs)) => + for hj in hs { + match hj { + Json::Object(h) => + history.push(Gen::{ + version: jstr(h, "version", ""), + digest: jstr(h, "digest", ""), + bins: jstrs(h, "bin"), + depends: jmap(h, "depends"), + }) + _ => () + } + } + _ => () + } + out[name] = Installed::{ + name, + version: jstr(o, "version", ""), + digest: jstr(o, "digest", ""), + explicit: jbool(o, "explicit", false), + constraint: jstr(o, "constraint", "*"), + bins: jstrs(o, "bin"), + depends: jmap(o, "depends"), + history, + } + } + _ => () + } + } + _ => () + } + out +} + +// ---------------------------------------------------------------- config + +///| +fn config_to_text(c : Config) -> String { + let o : Map[String, Json] = {} + o["registry"] = Json::String(c.registry) + o["plain_http"] = bool_json(c.plain_http) + Json::Object(o).stringify(indent=2) + "\n" +} + +///| +fn config_from_text(text : String) -> Config raise OrbitError { + let o = parse_object(text, "config.json") + Config::{ + registry: jstr(o, "registry", ""), + plain_http: jbool(o, "plain_http", false), + } +} + +// ---------------------------------------------------------------- context + +///| +fn orbit_root() -> String { + let r = getenv("ORBIT_ROOT") + if r != "" { + r + } else { + getenv("HOME") + "/.orbit" + } +} + +/// Load config and state. ORBIT_REGISTRY / ORBIT_PLAIN_HTTP override the file. +fn load_ctx() -> Ctx raise OrbitError { + let root = orbit_root() + let file_cfg = match read_text(root + "/config.json") { + Some(t) => config_from_text(t) + None => Config::{ registry: "", plain_http: false } + } + let env_reg = getenv("ORBIT_REGISTRY") + let cfg = Config::{ + registry: if env_reg != "" { env_reg } else { file_cfg.registry }, + plain_http: file_cfg.plain_http || getenv("ORBIT_PLAIN_HTTP") == "1", + } + if cfg.registry == "" { + raise OrbitError( + "no registry configured; run `orbit init ` or set ORBIT_REGISTRY", + ) + } + let state = match read_text(root + "/state.json") { + Some(t) => state_from_text(t) + None => Map::new() + } + Ctx::{ root, cfg, state } +} + +///| +fn save_state(ctx : Ctx) -> Unit raise OrbitError { + write_text_atomic(ctx.root + "/state.json", state_to_text(ctx.state)) +} + +/// Short, filesystem-safe id for a digest ("sha256:abcd..." -> "abcd...[:16]"). +fn store_id(digest : String) -> String { + let (_, hex) = split_first(digest, ':') + let a = chars(if hex == "" { digest } else { hex }) + slice(a, 0, if a.length() < 16 { a.length() } else { 16 }) +} + +///| +fn store_dir(ctx : Ctx, name : String, digest : String) -> String { + ctx.root + "/store/" + name + "/" + store_id(digest) +} + +///| +fn bin_dir(ctx : Ctx) -> String { + ctx.root + "/bin" +} + +///| +test "manifest roundtrip" { + let m = parse_manifest( + "{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\"}}", + ) + assert_eq(m.name, "hello") + assert_eq(m.bins, ["bin/hello"]) + assert_eq(m.depends.get("lib"), Some("^1")) + assert_true(not(valid_rel_path("../x"))) + assert_true(not(valid_rel_path("/bin/sh"))) + assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef") +} diff --git a/src/main/moon.pkg.json b/src/main/moon.pkg.json new file mode 100644 index 0000000..1747819 --- /dev/null +++ b/src/main/moon.pkg.json @@ -0,0 +1,4 @@ +{ + "is-main": true, + "native-stub": ["stub.c"] +} diff --git a/src/main/ops.mbt b/src/main/ops.mbt new file mode 100644 index 0000000..8563a48 --- /dev/null +++ b/src/main/ops.mbt @@ -0,0 +1,539 @@ +// Planning and applying installs, removals, upgrades and rollbacks. + +/// One package in an install plan. +struct Step { + name : String + version : String + digest : String + manifest : Manifest + mut explicit : Bool + mut constraint : String + keep : Bool // already installed at this digest; nothing to fetch +} + +///| +struct Planner { + ctx : Ctx + steps : Map[String, Step] + order : Array[Step] // dependencies before dependents + upgrade : Array[String] // names allowed to move even if satisfied +} + +///| +fn manifest_of_installed(p : Installed) -> Manifest { + Manifest::{ + name: p.name, + version: p.version, + description: "", + depends: p.depends, + bins: p.bins, + } +} + +/// Every constraint that currently applies to `name`: the request itself, +/// the user's own constraint if they installed it explicitly, and what each +/// other package requires (using planned manifests for packages being replaced). +fn constraints_for(p : Planner, name : String, requested : String) -> Array[String] { + let cons : Array[String] = [requested] + match p.ctx.state.get(name) { + Some(inst) => + if inst.explicit && inst.constraint != "" && inst.constraint != requested { + cons.push(inst.constraint) + } + None => () + } + for other, inst in p.ctx.state { + if other == name { + continue + } + let deps = match p.steps.get(other) { + Some(st) => st.manifest.depends + None => inst.depends + } + match deps.get(name) { + Some(c) => cons.push(c) + None => () + } + } + for other, st in p.steps { + if other != name && not(p.ctx.state.contains(other)) { + match st.manifest.depends.get(name) { + Some(c) => cons.push(c) + None => () + } + } + } + cons +} + +///| +fn visit(p : Planner, name : String, requested : String, explicit : Bool) -> Unit raise OrbitError { + match p.steps.get(name) { + Some(st) => { + if not(satisfies_all(st.version, [requested])) { + raise OrbitError( + "conflict: \{name} \{st.version} is planned but '\{requested}' is required", + ) + } + if explicit { + st.explicit = true + st.constraint = requested + } + return + } + None => () + } + let cons = constraints_for(p, name, requested) + let upgrading = p.upgrade.contains(name) + match p.ctx.state.get(name) { + Some(inst) => + if not(upgrading) && satisfies_all(inst.version, cons) { + let st = Step::{ + name, + version: inst.version, + digest: inst.digest, + manifest: manifest_of_installed(inst), + explicit: explicit || inst.explicit, + constraint: if explicit { requested } else { inst.constraint }, + keep: true, + } + p.steps[name] = st + p.order.push(st) + return + } + None => () + } + let tags = list_tags(p.ctx, name) + let tag = match pick_tag(tags, cons) { + Some(t) => t + None => { + let avail = sorted_versions(tags) + raise OrbitError( + "no version of \{name} satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}", + ) + } + } + let digest = resolve_digest(p.ctx, name, tag) + let m = fetch_manifest(p.ctx, name, digest) + let prev = p.ctx.state.get(name) + let st = Step::{ + name, + version: m.version, + digest, + manifest: m, + explicit: explicit || + (match prev { + Some(i) => i.explicit + None => false + }), + constraint: if explicit { + requested + } else { + match prev { + Some(i) => i.constraint + None => "*" + } + }, + keep: match prev { + Some(i) => i.digest == digest + None => false + }, + } + // Register before recursing so dependency cycles terminate. + p.steps[name] = st + for dep, dc in m.depends { + visit(p, dep, dc, false) + } + p.order.push(st) +} + +/// "name" or "name@constraint" +fn parse_spec(spec : String) -> (String, String) raise OrbitError { + let (name, c) = split_first(spec, '@') + if not(valid_name(name)) { + raise OrbitError("invalid package name '\{name}'") + } + (name, if c == "" { "*" } else { c }) +} + +///| +fn owner_of_bin(ctx : Ctx, bin : String) -> String? { + for name, p in ctx.state { + for b in p.bins { + if basename(b) == bin { + return Some(name) + } + } + } + None +} + +///| +fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit { + for b in bins { + sh("rm -f " + sq(bin_dir(ctx) + "/" + basename(b))) |> ignore + } +} + +///| +fn link_bins(ctx : Ctx, dir : String, bins : Array[String]) -> Unit raise OrbitError { + sh_ok("mkdir -p " + sq(bin_dir(ctx))) + for b in bins { + sh_ok( + "ln -sfn " + sq(dir + "/" + b) + " " + sq(bin_dir(ctx) + "/" + basename(b)), + ) + } +} + +///| +fn check_bin_conflicts(ctx : Ctx, name : String, bins : Array[String]) -> Unit raise OrbitError { + for b in bins { + match owner_of_bin(ctx, basename(b)) { + Some(other) => + if other != name { + raise OrbitError( + "\{name} wants to provide '\{basename(b)}', which \{other} already provides", + ) + } + None => () + } + } +} + +/// Switch `name` to a fetched build, keeping the old one for rollback. +fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { + let dir = fetch_into_store(ctx, st.name, st.digest) + for b in st.manifest.bins { + if sh("test -f " + sq(dir + "/" + b)) != 0 { + raise OrbitError("\{st.name}: bin '\{b}' missing from package contents") + } + } + check_bin_conflicts(ctx, st.name, st.manifest.bins) + match ctx.state.get(st.name) { + Some(inst) => { + unlink_bins(ctx, inst.bins) + inst.history.push(Gen::{ + version: inst.version, + digest: inst.digest, + bins: inst.bins, + depends: inst.depends, + }) + while inst.history.length() > 2 { + inst.history.remove(0) |> ignore + } + inst.version = st.version + inst.digest = st.digest + inst.bins = st.manifest.bins + inst.depends = st.manifest.depends + inst.explicit = st.explicit + inst.constraint = st.constraint + println(" \{st.name}: \{inst.history[inst.history.length() - 1].version} -> \{st.version}") + } + None => { + ctx.state[st.name] = Installed::{ + name: st.name, + version: st.version, + digest: st.digest, + explicit: st.explicit, + constraint: st.constraint, + bins: st.manifest.bins, + depends: st.manifest.depends, + history: [], + } + println(" \{st.name} \{st.version} installed") + } + } + link_bins(ctx, dir, st.manifest.bins) + // Persist after each package so a later failure leaves accurate state. + save_state(ctx) +} + +///| +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.explicit = st.explicit + inst.constraint = st.constraint + } + None => () + } + continue + } + activate(ctx, st) + changed = changed + 1 + } + save_state(ctx) + if changed == 0 { + println("nothing to do") + } +} + +///| +fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner { + Planner::{ ctx, steps: Map::new(), order: [], upgrade } +} + +///| +fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { + if specs.length() == 0 { + raise OrbitError("usage: orbit install [@constraint]...") + } + let p = new_planner(ctx, []) + for s in specs { + let (name, c) = parse_spec(s) + visit(p, name, c, true) + } + apply_plan(ctx, p) +} + +/// 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 { + let targets : Array[String] = [] + if names.length() == 0 { + for name, _ in ctx.state { + targets.push(name) + } + } else { + for n in names { + if not(ctx.state.contains(n)) { + raise OrbitError("\{n} is not installed") + } + targets.push(n) + } + } + let p = new_planner(ctx, targets) + for n in targets { + match ctx.state.get(n) { + Some(inst) => visit(p, n, "*", inst.explicit) + None => () + } + } + apply_plan(ctx, p) +} + +///| +fn reverse_deps(ctx : Ctx, name : String) -> Array[String] { + let r : Array[String] = [] + for other, p in ctx.state { + if other != name && p.depends.contains(name) { + r.push(other) + } + } + r +} + +///| +fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { + match ctx.state.get(name) { + Some(inst) => { + unlink_bins(ctx, inst.bins) + sh_ok("rm -rf " + sq(ctx.root + "/store/" + name)) + ctx.state.remove(name) + println(" \{name} \{inst.version} removed") + } + None => () + } +} + +/// Remove dependencies nobody needs any more. +fn autoremove(ctx : Ctx) -> Unit raise OrbitError { + let mut changed = true + while changed { + changed = false + let orphans : Array[String] = [] + for name, p in ctx.state { + if not(p.explicit) && reverse_deps(ctx, name).length() == 0 { + orphans.push(name) + } + } + for n in orphans { + remove_one(ctx, n) + changed = true + } + } +} + +///| +fn cmd_remove(ctx : Ctx, names : Array[String], force : Bool) -> Unit raise OrbitError { + if names.length() == 0 { + raise OrbitError("usage: orbit remove ...") + } + for n in names { + if not(ctx.state.contains(n)) { + raise OrbitError("\{n} is not installed") + } + } + for n in names { + let users : Array[String] = [] + for u in reverse_deps(ctx, n) { + if not(names.contains(u)) { + users.push(u) + } + } + if users.length() > 0 && not(force) { + raise OrbitError( + "\{n} is required by \{join(users, ", ")} (use --force to remove anyway)", + ) + } + } + for n in names { + remove_one(ctx, n) + } + autoremove(ctx) + save_state(ctx) +} + +/// Swap the current build with the previous one (run twice to undo). +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") + } + let prev = match inst.history.pop() { + Some(g) => g + None => raise OrbitError("\{name} has no previous version to roll back to") + } + let dir = store_dir(ctx, name, prev.digest) + if not(exists(dir)) { + raise OrbitError("previous build of \{name} (\{prev.version}) is no longer in the store") + } + unlink_bins(ctx, inst.bins) + inst.history.push(Gen::{ + version: inst.version, + digest: inst.digest, + bins: inst.bins, + depends: inst.depends, + }) + let from = inst.version + inst.version = prev.version + inst.digest = prev.digest + inst.bins = prev.bins + inst.depends = prev.depends + check_bin_conflicts(ctx, name, inst.bins) + link_bins(ctx, dir, inst.bins) + save_state(ctx) + println("\{name}: \{from} -> \{prev.version}") + let missing : Array[String] = [] + for dep, c in inst.depends { + match ctx.state.get(dep) { + Some(d) => if not(satisfies_all(d.version, [c])) { missing.push(dep + "@" + c) } + None => missing.push(dep + "@" + c) + } + } + if missing.length() > 0 { + println( + "warning: \{name} \{prev.version} wants \{join(missing, ", ")}; run `orbit install` for them", + ) + } +} + +/// Delete store entries that are neither current nor kept for rollback. +fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { + let store = ctx.root + "/store" + if not(exists(store)) { + println("store is empty") + return + } + let mut freed = 0 + for pkg in lines(capture("ls -1 " + sq(store))) { + match ctx.state.get(pkg) { + None => { + sh_ok("rm -rf " + sq(store + "/" + pkg)) + freed = freed + 1 + } + Some(inst) => { + let keep : Array[String] = [store_id(inst.digest)] + for g in inst.history { + keep.push(store_id(g.digest)) + } + for id in lines(capture("ls -1 " + sq(store + "/" + pkg))) { + if not(keep.contains(id)) { + sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id)) + freed = freed + 1 + } + } + } + } + } + let tmp = ctx.root + "/tmp" + ignore(sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp))) + println("removed \{freed} store entries") +} + +///| +fn cmd_list(ctx : Ctx) -> Unit { + if ctx.state.size() == 0 { + println("no packages installed") + return + } + for name, p in ctx.state { + let kind = if p.explicit { "" } else { " (dependency)" } + println("\{name} \{p.version}\{kind}") + } +} + +///| +fn cmd_info(ctx : Ctx, name : String) -> Unit raise OrbitError { + match ctx.state.get(name) { + Some(p) => { + println("\{name} \{p.version} (installed)") + 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 tags = list_tags(ctx, name) + match pick_tag(tags, ["*"]) { + Some(t) => { + let m = fetch_manifest(ctx, name, resolve_digest(ctx, name, t)) + println("\{name} \{m.version} (latest in \{ctx.cfg.registry})") + if m.description != "" { + println(" \{m.description}") + } + } + None => println("\{name}: no stable versions published") + } +} + +///| +fn cmd_versions(ctx : Ctx, name : String) -> Unit raise OrbitError { + for v in sorted_versions(list_tags(ctx, name)) { + let mark = match ctx.state.get(name) { + Some(p) => if p.version == v { " *" } else { "" } + None => "" + } + println(v + mark) + } +} + +///| +fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { + let out = capture(oras(ctx, "repo ls " + sq(ctx.cfg.registry))) catch { + _ => + raise OrbitError( + "registry does not allow listing repositories (catalog API); try `orbit info `", + ) + } + for r in lines(out) { + if contains_str(r, term) { + println(r) + } + } +} diff --git a/src/main/registry.mbt b/src/main/registry.mbt new file mode 100644 index 0000000..cb6fa05 --- /dev/null +++ b/src/main/registry.mbt @@ -0,0 +1,131 @@ +// Everything that talks to the registry goes through the `oras` CLI. +// Authentication is whatever `oras login` has stored. + +///| +fn oras(ctx : Ctx, args : String) -> String { + "oras " + args + (if ctx.cfg.plain_http { " --plain-http" } else { "" }) +} + +///| +fn repo_of(ctx : Ctx, name : String) -> String { + ctx.cfg.registry + "/" + name +} + +///| +fn list_tags(ctx : Ctx, name : String) -> Array[String] raise OrbitError { + let out = capture(oras(ctx, "repo tags " + sq(repo_of(ctx, name)))) catch { + _ => raise OrbitError("package '\{name}' not found in \{ctx.cfg.registry}") + } + lines(out) +} + +///| +fn resolve_digest(ctx : Ctx, name : String, tag : String) -> String raise OrbitError { + let d = trim(capture(oras(ctx, "resolve " + sq(repo_of(ctx, name) + ":" + tag)))) + if not(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) { + raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'") + } + d +} + +/// Fetch only the config blob (orbit.json); no layer download needed to plan. +fn fetch_manifest(ctx : Ctx, name : String, digest : String) -> Manifest raise OrbitError { + let text = capture( + oras(ctx, "manifest fetch-config " + sq(repo_of(ctx, name) + "@" + digest)), + ) + let m = parse_manifest(text) + if m.name != name { + raise OrbitError( + "\{name}@\{digest} declares name '\{m.name}'; refusing to install", + ) + } + m +} + +/// 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(ctx : Ctx, name : String, digest : String) -> String raise OrbitError { + let dir = store_dir(ctx, name, digest) + if exists(dir) { + return dir + } + let tmp = ctx.root + "/tmp/" + name + "-" + store_id(digest) + sh_ok("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp + "/root")) + sh_ok( + oras(ctx, "pull -o " + sq(tmp) + " " + sq(repo_of(ctx, name) + "@" + digest)) + + " >/dev/null", + ) + if not(exists(tmp + "/pkg.tar.gz")) { + raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer") + } + sh_ok( + "tar -xzf " + + sq(tmp + "/pkg.tar.gz") + + " -C " + + sq(tmp + "/root") + + " --no-same-owner", + ) + sh_ok( + "mkdir -p " + + sq(ctx.root + "/store/" + name) + + " && mv " + + sq(tmp + "/root") + + " " + + sq(dir) + + " && rm -rf " + + sq(tmp), + ) + dir +} + +/// Pack `/files` and push it with `/orbit.json` as the config blob. +fn publish(ctx : Ctx, dir : String, also_latest : Bool) -> Unit raise OrbitError { + let text = match read_text(dir + "/orbit.json") { + Some(t) => t + None => raise OrbitError("\{dir}/orbit.json not found") + } + let m = parse_manifest(text) + let files = dir + "/files" + if not(exists(files)) { + raise OrbitError("\{files} not found (package contents go in files/)") + } + for b in m.bins { + if sh("test -f " + sq(files + "/" + b)) != 0 { + raise OrbitError("bin '\{b}' listed in orbit.json is missing from files/") + } + } + let tmp = trim(capture("mktemp -d")) + sh_ok( + "tar -czf " + + sq(tmp + "/pkg.tar.gz") + + " --owner=0 --group=0 -C " + + sq(files) + + " .", + ) + sh_ok("cp " + sq(dir + "/orbit.json") + " " + sq(tmp + "/orbit.json")) + let tags = if also_latest { m.version + ",latest" } else { m.version } + let push = oras( + ctx, + "push " + + sq(repo_of(ctx, m.name) + ":" + tags) + + " --config " + + sq("orbit.json:" + CONFIG_MEDIA_TYPE) + + " --annotation " + + sq("org.opencontainers.image.version=" + m.version) + + (if m.description != "" { + " --annotation " + + sq("org.opencontainers.image.description=" + m.description) + } else { + "" + }) + + " " + + sq("pkg.tar.gz:" + LAYER_MEDIA_TYPE), + ) + let rc = sh("cd " + sq(tmp) + " && " + push) + sh("rm -rf " + sq(tmp)) |> ignore + if rc != 0 { + raise OrbitError("oras push failed (exit \{rc})") + } + println("published \{m.name} \{m.version} to \{repo_of(ctx, m.name)}") +} diff --git a/src/main/semver.mbt b/src/main/semver.mbt new file mode 100644 index 0000000..37f66ec --- /dev/null +++ b/src/main/semver.mbt @@ -0,0 +1,237 @@ +// Minimal semantic versions and constraints. +// +// Constraint forms: +// "" | "*" | "latest" any stable version +// "1.2.3" | "=1.2.3" exact +// "1" | "1.2" prefix (1.x.x / 1.2.x) +// "^1.2.3" same major (same minor while major is 0), >= base +// "~1.2.3" same major and minor, >= base +// ">=1.2.3" at least base +// Prerelease versions (1.0.0-rc1) only match constraints that mention a '-'. + +///| +struct Ver { + nums : Array[Int] + parts : Int + pre : String +} + +///| +fn parse_nat(s : String) -> Int? { + if s == "" { + return None + } + let mut n = 0 + for c in s { + if c < '0' || c > '9' { + return None + } + n = n * 10 + (c.to_int() - '0'.to_int()) + } + Some(n) +} + +///| +fn parse_ver(s0 : String) -> Ver? { + let s = if has_prefix(s0, "v") { drop_chars(s0, 1) } else { s0 } + let (no_build, _) = split_first(s, '+') + let (main, pre) = split_first(no_build, '-') + let parts = split_on(main, '.') + if parts.length() == 0 || parts.length() > 3 { + return None + } + let nums = [0, 0, 0] + for i = 0; i < parts.length(); i = i + 1 { + match parse_nat(parts[i]) { + Some(n) => nums[i] = n + None => return None + } + } + Some(Ver::{ nums, parts: parts.length(), pre }) +} + +///| +fn is_ver(s : String) -> Bool { + match parse_ver(s) { + Some(_) => true + None => false + } +} + +///| +fn cmp_ver(a : Ver, b : Ver) -> Int { + for i = 0; i < 3; i = i + 1 { + if a.nums[i] != b.nums[i] { + return if a.nums[i] < b.nums[i] { -1 } else { 1 } + } + } + if a.pre == b.pre { + 0 + } else if a.pre == "" { + 1 + } else if b.pre == "" { + -1 + } else { + a.pre.compare(b.pre) + } +} + +///| +fn satisfies(v : Ver, c0 : String) -> Bool { + let c = trim(c0) + if c == "" || c == "*" || c == "latest" { + return v.pre == "" + } + if v.pre != "" && not(has_char(c, '-')) { + return false + } + let with_base = fn(rest : String, rule : (Ver) -> Bool) -> Bool { + match parse_ver(rest) { + Some(b) => cmp_ver(v, b) >= 0 && rule(b) + None => false + } + } + if has_prefix(c, ">=") { + with_base(drop_chars(c, 2), fn(_b) { true }) + } else if has_prefix(c, "^") { + with_base(drop_chars(c, 1), fn(b) { + v.nums[0] == b.nums[0] && (b.nums[0] != 0 || v.nums[1] == b.nums[1]) + }) + } else if has_prefix(c, "~") { + with_base(drop_chars(c, 1), fn(b) { + v.nums[0] == b.nums[0] && v.nums[1] == b.nums[1] + }) + } else { + let exact = if has_prefix(c, "=") { drop_chars(c, 1) } else { c } + match parse_ver(exact) { + Some(b) => + if b.parts == 3 { + cmp_ver(v, b) == 0 + } else { + let mut ok = true + for i = 0; i < b.parts; i = i + 1 { + if v.nums[i] != b.nums[i] { + ok = false + } + } + ok + } + None => false + } + } +} + +///| +fn satisfies_all(version : String, cons : Array[String]) -> Bool { + match parse_ver(version) { + Some(v) => { + for c in cons { + if not(satisfies(v, c)) { + return false + } + } + true + } + // Non-semver tags (e.g. "edge") only satisfy wildcards or themselves. + None => { + for c in cons { + let t = trim(c) + if t != "" && t != "*" && t != version { + return false + } + } + true + } + } +} + +/// Pick the highest tag that satisfies every constraint. Falls back to a +/// literal non-semver tag when a constraint names one exactly. +fn pick_tag(tags : Array[String], cons : Array[String]) -> String? { + let mut best : (String, Ver)? = None + for t in tags { + match parse_ver(t) { + Some(v) => + if satisfies_all(t, cons) { + match best { + None => best = Some((t, v)) + Some((_, bv)) => if cmp_ver(v, bv) > 0 { best = Some((t, v)) } + } + } + None => () + } + } + match best { + Some((t, _)) => Some(t) + None => { + for c in cons { + let t = trim(c) + if t != "" && t != "*" && not(is_ver(t)) && tags.contains(t) { + return Some(t) + } + } + None + } + } +} + +/// Semver tags, highest first. +fn sorted_versions(tags : Array[String]) -> Array[String] { + let out : Array[(String, Ver)] = [] + for t in tags { + match parse_ver(t) { + Some(v) => out.push((t, v)) + None => () + } + } + // insertion sort, descending + for i = 1; i < out.length(); i = i + 1 { + let mut j = i + while j > 0 && cmp_ver(out[j].1, out[j - 1].1) > 0 { + let tmp = out[j] + out[j] = out[j - 1] + out[j - 1] = tmp + j = j - 1 + } + } + let r : Array[String] = [] + for p in out { + r.push(p.0) + } + r +} + +///| +test "parse and compare" { + let a = parse_ver("1.2.3").unwrap() + let b = parse_ver("v1.10.0").unwrap() + assert_true(cmp_ver(a, b) < 0) + assert_true(cmp_ver(parse_ver("1.0.0-rc1").unwrap(), parse_ver("1.0.0").unwrap()) < 0) + assert_true(parse_ver("1.x").is_empty()) +} + +///| +test "constraints" { + let v = parse_ver("1.4.2").unwrap() + assert_true(satisfies(v, "^1.2.0")) + assert_true(not(satisfies(v, "^2.0.0"))) + assert_true(satisfies(v, "~1.4.0")) + assert_true(not(satisfies(v, "~1.3.0"))) + assert_true(satisfies(v, ">=1.0")) + assert_true(satisfies(v, "1")) + assert_true(satisfies(v, "1.4")) + assert_true(not(satisfies(v, "1.5"))) + assert_true(satisfies(v, "*")) + assert_true(not(satisfies(parse_ver("0.3.1").unwrap(), "^0.2.0"))) +} + +///| +test "pick" { + let tags = ["1.0.0", "1.2.0", "2.0.0", "2.1.0-rc1", "latest"] + assert_eq(pick_tag(tags, ["*"]), Some("2.0.0")) + assert_eq(pick_tag(tags, ["^1.0.0"]), Some("1.2.0")) + assert_eq(pick_tag(tags, ["^1.0.0", "~1.0.0"]), Some("1.0.0")) + assert_eq(pick_tag(tags, ["latest"]), Some("2.0.0")) + assert_eq(pick_tag(tags, ["^3"]), None) + assert_eq(sorted_versions(tags), ["2.1.0-rc1", "2.0.0", "1.2.0", "1.0.0"]) +} diff --git a/src/main/stub.c b/src/main/stub.c new file mode 100644 index 0000000..bffbb9e --- /dev/null +++ b/src/main/stub.c @@ -0,0 +1,119 @@ +// 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 "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); + if (!s) abort(); + memcpy(s, b, (size_t)n); + s[n] = 0; + return s; +} + +static moonbit_bytes_t from_buf(const char *buf, size_t len) { + moonbit_bytes_t out = moonbit_make_bytes((int32_t)len, 0); + if (len) memcpy(out, buf, 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); + free(n); + if (!v) return from_buf("", 0); + return from_buf(v, strlen(v)); +} + +void orbit_exit(int32_t code) { + fflush(stdout); + exit(code); +} diff --git a/src/main/sys.mbt b/src/main/sys.mbt new file mode 100644 index 0000000..8214f16 --- /dev/null +++ b/src/main/sys.mbt @@ -0,0 +1,334 @@ +// 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. + +///| +suberror OrbitError String + +///| +extern "C" fn c_run(cmd : Bytes) -> Int = "orbit_run" + +///| +extern "C" fn c_capture(cmd : Bytes) -> Bytes = "orbit_capture" + +///| +extern "C" fn c_last_status() -> Int = "orbit_last_status" + +///| +extern "C" fn c_read_file(path : Bytes) -> Bytes = "orbit_read_file" + +///| +extern "C" fn c_write_file(path : Bytes, data : Bytes) -> Int = "orbit_write_file" + +///| +extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv" + +///| +extern "C" fn c_exit(code : Int) = "orbit_exit" + +// ---------------------------------------------------------------- UTF-8 + +///| +fn utf8_encode(s : String) -> Bytes { + let out : Array[Byte] = [] + for c in s { + let cp = c.to_int() + if cp < 0x80 { + out.push(cp.to_byte()) + } else if cp < 0x800 { + out.push((0xC0 | (cp >> 6)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } else if cp < 0x10000 { + out.push((0xE0 | (cp >> 12)).to_byte()) + out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } else { + out.push((0xF0 | (cp >> 18)).to_byte()) + out.push((0x80 | ((cp >> 12) & 0x3F)).to_byte()) + out.push((0x80 | ((cp >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (cp & 0x3F)).to_byte()) + } + } + Bytes::makei(out.length(), fn(i) { out[i] }) +} + +///| +fn utf8_decode(b : Bytes) -> String { + let sb = StringBuilder::new() + let n = b.length() + let mut i = 0 + while i < n { + let c0 = b[i].to_int() + if c0 < 0x80 { + sb.write_char(Int::unsafe_to_char(c0)) + i = i + 1 + } else if c0 >= 0xC0 && c0 < 0xE0 && i + 1 < n { + let cp = ((c0 & 0x1F) << 6) | (b[i + 1].to_int() & 0x3F) + sb.write_char(Int::unsafe_to_char(cp)) + i = i + 2 + } else if c0 >= 0xE0 && c0 < 0xF0 && i + 2 < n { + let cp = ((c0 & 0x0F) << 12) | + ((b[i + 1].to_int() & 0x3F) << 6) | + (b[i + 2].to_int() & 0x3F) + sb.write_char(Int::unsafe_to_char(cp)) + i = i + 3 + } else if c0 >= 0xF0 && i + 3 < n { + let cp = ((c0 & 0x07) << 18) | + ((b[i + 1].to_int() & 0x3F) << 12) | + ((b[i + 2].to_int() & 0x3F) << 6) | + (b[i + 3].to_int() & 0x3F) + sb.write_char(Int::unsafe_to_char(cp)) + i = i + 4 + } else { + sb.write_char('\u{FFFD}') + i = i + 1 + } + } + sb.to_string() +} + +// ---------------------------------------------------------------- strings + +///| +fn chars(s : String) -> Array[Char] { + let a : Array[Char] = [] + for c in s { + a.push(c) + } + a +} + +///| +fn slice(a : Array[Char], start : Int, end : Int) -> String { + let sb = StringBuilder::new() + for i = start; i < end; i = i + 1 { + sb.write_char(a[i]) + } + sb.to_string() +} + +///| +fn drop_chars(s : String, n : Int) -> String { + let a = chars(s) + if n >= a.length() { + "" + } else { + slice(a, n, a.length()) + } +} + +///| +fn has_prefix(s : String, p : String) -> Bool { + let a = chars(s) + let b = chars(p) + if b.length() > a.length() { + return false + } + for i = 0; i < b.length(); i = i + 1 { + if a[i] != b[i] { + return false + } + } + true +} + +///| +fn has_char(s : String, ch : Char) -> Bool { + for c in s { + if c == ch { + return true + } + } + false +} + +///| +fn contains_str(s : String, sub : String) -> Bool { + let a = chars(s) + let b = chars(sub) + if b.length() == 0 { + return true + } + for i = 0; i + b.length() <= a.length(); i = i + 1 { + let mut ok = true + for j = 0; j < b.length(); j = j + 1 { + if a[i + j] != b[j] { + ok = false + break + } + } + if ok { + return true + } + } + false +} + +///| +fn split_on(s : String, sep : Char) -> Array[String] { + let out : Array[String] = [] + let sb = StringBuilder::new() + let mut cur = sb + for c in s { + if c == sep { + out.push(cur.to_string()) + cur = StringBuilder::new() + } else { + cur.write_char(c) + } + } + out.push(cur.to_string()) + out +} + +/// Split at the first `sep`; the second part is "" when `sep` is absent. +fn split_first(s : String, sep : Char) -> (String, String) { + let a = chars(s) + for i = 0; i < a.length(); i = i + 1 { + if a[i] == sep { + return (slice(a, 0, i), slice(a, i + 1, a.length())) + } + } + (s, "") +} + +///| +fn is_space(c : Char) -> Bool { + c == ' ' || c == '\n' || c == '\t' || c == '\r' +} + +///| +fn trim(s : String) -> String { + let a = chars(s) + let mut start = 0 + let mut end = a.length() + while start < end && is_space(a[start]) { + start = start + 1 + } + while end > start && is_space(a[end - 1]) { + end = end - 1 + } + slice(a, start, end) +} + +/// Non-empty, trimmed lines. +fn lines(s : String) -> Array[String] { + let out : Array[String] = [] + for l in split_on(s, '\n') { + let t = trim(l) + if t != "" { + out.push(t) + } + } + out +} + +///| +fn join(xs : Array[String], sep : String) -> String { + let sb = StringBuilder::new() + for i = 0; i < xs.length(); i = i + 1 { + if i > 0 { + sb.write_string(sep) + } + sb.write_string(xs[i]) + } + sb.to_string() +} + +///| +fn basename(p : String) -> String { + let parts = split_on(p, '/') + parts[parts.length() - 1] +} + +/// Single-quote a string for /bin/sh. +fn sq(s : String) -> String { + let sb = StringBuilder::new() + sb.write_char('\'') + for c in s { + if c == '\'' { + sb.write_string("'\\''") + } else { + sb.write_char(c) + } + } + sb.write_char('\'') + sb.to_string() +} + +// ---------------------------------------------------------------- process / fs + +///| +fn sh(cmd : String) -> Int { + c_run(utf8_encode(cmd)) +} + +///| +fn sh_ok(cmd : String) -> Unit raise OrbitError { + let code = sh(cmd) + if code != 0 { + raise OrbitError("command failed (exit \{code}): \{cmd}") + } +} + +/// 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}") + } + out +} + +///| +fn exists(path : String) -> Bool { + sh("test -e " + sq(path)) == 0 +} + +///| +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)) + } +} + +/// 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 { + let tmp = path + ".tmp" + if c_write_file(utf8_encode(tmp), utf8_encode(text)) != 0 { + raise OrbitError("cannot write \{tmp}") + } + sh_ok("mv -f " + sq(tmp) + " " + sq(path)) +} + +///| +fn getenv(name : String) -> String { + utf8_decode(c_getenv(utf8_encode(name))) +} + +/// 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")) + let out : Array[String] = [] + let cur : Array[Byte] = [] + for i = 0; i < raw.length(); i = i + 1 { + if raw[i].to_int() == 0 { + out.push(utf8_decode(Bytes::makei(cur.length(), fn(k) { cur[k] }))) + cur.clear() + } else { + cur.push(raw[i]) + } + } + if cur.length() > 0 { + out.push(utf8_decode(Bytes::makei(cur.length(), fn(k) { cur[k] }))) + } + let args : Array[String] = [] + for i = 1; i < out.length(); i = i + 1 { + args.push(out[i]) + } + args +}