diff --git a/README.md b/README.md index 201d08f..18ccd73 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 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. +> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` with ORAS 1.2.3. ## What it does @@ -71,7 +71,7 @@ orbit init localhost:5000/pkgs --plain-http ```sh moon build --target native --release moon test --target native # semver / manifest unit tests -# the binary is under target/native/release/build/main/ +# the binary is _build/native/release/build/main/main.exe ``` Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`. @@ -89,15 +89,14 @@ src/main/ main.mbt CLI ``` -## First build: likely fix-ups +## Toolchain notes -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: +Fixes needed for current MoonBit, kept here in case you build with an older compiler: -- `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. +- The project uses `moon.mod` / `moon.pkg` (the `.json` forms are no longer accepted). +- `suberror OrbitError { OrbitError(String) }`, and `@json` is imported explicitly in `moon.pkg`. +- `Json` values are built with `Json::string`, `Json::array`, `Json::object`, `Json::boolean`; the uppercase constructors are only used in patterns. +- C FFI parameters are annotated `#borrow(...)`, matching `stub.c`, which never decrefs its arguments. ## Known limits diff --git a/moon.mod b/moon.mod new file mode 100644 index 0000000..271a5a0 --- /dev/null +++ b/moon.mod @@ -0,0 +1,13 @@ +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" \ No newline at end of file diff --git a/moon.mod.json b/moon.mod.json deleted file mode 100644 index e24d52a..0000000 --- a/moon.mod.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "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 index 5e9a112..c7d2294 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -35,7 +35,7 @@ fn cmd_init(registry : String, plain_http : Bool) -> Unit raise OrbitError { ) write_text_atomic( root + "/config.json", - config_to_text(Config::{ registry, plain_http }), + config_to_text(Config::{ registry, plain_http, }), ) println("orbit root: \{root}") println("registry: \{registry}") @@ -44,7 +44,7 @@ fn cmd_init(registry : String, plain_http : Bool) -> Unit raise OrbitError { } ///| -fn need(pos : Array[String], n : Int, what : String) -> Unit raise OrbitError { +fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError { if pos.length() < n { raise OrbitError("usage: orbit \{what}") } @@ -75,7 +75,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError { "env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"") "publish" => { need(pos, 1, "publish ") - publish(load_ctx(), pos[0], not(flags.contains("--no-latest"))) + publish(load_ctx(), pos[0], !(flags.contains("--no-latest"))) } "install" | "add" => cmd_install(load_ctx(), pos) "remove" | "rm" => cmd_remove(load_ctx(), pos, flags.contains("--force")) @@ -93,7 +93,8 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError { need(pos, 1, "versions ") cmd_versions(load_ctx(), pos[0]) } - "search" => cmd_search(load_ctx(), if pos.length() > 0 { pos[0] } else { "" }) + "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`)") } diff --git a/src/main/model.mbt b/src/main/model.mbt index a323e7a..10044c9 100644 --- a/src/main/model.mbt +++ b/src/main/model.mbt @@ -6,6 +6,7 @@ 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 @@ -15,6 +16,7 @@ struct Manifest { bins : Array[String] } +///| /// A previously installed build, kept for rollback. struct Gen { version : String @@ -85,7 +87,7 @@ fn jstrs(o : Map[String, Json], k : String) -> Array[String] { ///| fn jmap(o : Map[String, Json], k : String) -> Map[String, String] { - let r : Map[String, String] = {} + let r : Map[String, String] = Map([]) match o.get(k) { Some(Json::Object(m)) => for key, v in m { @@ -103,31 +105,34 @@ fn jmap(o : Map[String, Json], k : String) -> Map[String, String] { fn strs_json(xs : Array[String]) -> Json { let a : Array[Json] = [] for x in xs { - a.push(Json::String(x)) + a.push(Json::string(x)) } - Json::Array(a) + Json::array(a) } ///| fn map_json(m : Map[String, String]) -> Json { - let o : Map[String, Json] = {} + let o : Map[String, Json] = Map([]) for k, v in m { - o[k] = Json::String(v) + o[k] = Json::string(v) } - Json::Object(o) + Json::object(o) } ///| fn bool_json(b : Bool) -> Json { if b { - Json::True + Json::boolean(true) } else { - Json::False + Json::boolean(false) } } ///| -fn parse_object(text : String, what : String) -> Map[String, Json] raise OrbitError { +fn parse_object( + text : String, + what : String, +) -> Map[String, Json] raise OrbitError { let j = @json.parse(text) catch { _ => raise OrbitError("\{what}: invalid JSON") } @@ -150,13 +155,14 @@ fn valid_name(s : String) -> Bool { c == '-' || c == '_' || c == '.' - if not(ok) { + if !(ok) { return false } } - not(has_prefix(s, ".")) + !(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, "/") { @@ -180,21 +186,21 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError { depends: jmap(o, "depends"), bins: jstrs(o, "bin"), } - if not(valid_name(m.name)) { + if !(valid_name(m.name)) { raise OrbitError( "orbit.json: invalid name '\{m.name}' (use a-z, 0-9, '-', '_', '.')", ) } - if not(is_ver(m.version)) { + if !(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)) { + if !(valid_rel_path(b)) { raise OrbitError("orbit.json: bin path '\{b}' must be relative") } } for dep, _ in m.depends { - if not(valid_name(dep)) { + if !(valid_name(dep)) { raise OrbitError("orbit.json: invalid dependency name '\{dep}'") } } @@ -205,47 +211,47 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError { ///| fn gen_json(g : Gen) -> Json { - let o : Map[String, Json] = {} - o["version"] = Json::String(g.version) - o["digest"] = Json::String(g.digest) + let o : Map[String, Json] = Map([]) + 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) + 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) + let o : Map[String, Json] = Map([]) + 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["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) + o["history"] = Json::array(h) + Json::object(o) } ///| fn state_to_text(state : Map[String, Installed]) -> String { - let pkgs : Map[String, Json] = {} + let pkgs : Map[String, Json] = Map([]) 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" + let top : Map[String, Json] = Map([]) + 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] = {} + let out : Map[String, Installed] = Map([]) match top.get("packages") { Some(Json::Object(pkgs)) => for name, pj in pkgs { @@ -291,10 +297,10 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { ///| fn config_to_text(c : Config) -> String { - let o : Map[String, Json] = {} - o["registry"] = Json::String(c.registry) + let o : Map[String, Json] = Map([]) + o["registry"] = Json::string(c.registry) o["plain_http"] = bool_json(c.plain_http) - Json::Object(o).stringify(indent=2) + "\n" + Json::object(o).stringify(indent=2) + "\n" } ///| @@ -318,16 +324,21 @@ fn orbit_root() -> String { } } +///| /// 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 } + 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 }, + registry: if env_reg != "" { + env_reg + } else { + file_cfg.registry + }, plain_http: file_cfg.plain_http || getenv("ORBIT_PLAIN_HTTP") == "1", } if cfg.registry == "" { @@ -337,9 +348,9 @@ fn load_ctx() -> Ctx raise OrbitError { } let state = match read_text(root + "/state.json") { Some(t) => state_from_text(t) - None => Map::new() + None => Map([]) } - Ctx::{ root, cfg, state } + Ctx::{ root, cfg, state, } } ///| @@ -347,6 +358,7 @@ 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, ':') @@ -372,7 +384,7 @@ test "manifest roundtrip" { 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_true(!(valid_rel_path("../x"))) + assert_true(!(valid_rel_path("/bin/sh"))) assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef") } diff --git a/src/main/moon.pkg b/src/main/moon.pkg new file mode 100644 index 0000000..0d3cab0 --- /dev/null +++ b/src/main/moon.pkg @@ -0,0 +1,9 @@ +import { + "moonbitlang/core/json", +} + +pkgtype(kind: "executable") + +options( + "native-stub": [ "stub.c" ], +) diff --git a/src/main/moon.pkg.json b/src/main/moon.pkg.json deleted file mode 100644 index 1747819..0000000 --- a/src/main/moon.pkg.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "is-main": true, - "native-stub": ["stub.c"] -} diff --git a/src/main/ops.mbt b/src/main/ops.mbt index 8563a48..7821660 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -1,5 +1,6 @@ // Planning and applying installs, removals, upgrades and rollbacks. +///| /// One package in an install plan. struct Step { name : String @@ -30,10 +31,15 @@ fn manifest_of_installed(p : Installed) -> Manifest { } } +///| /// 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] { +fn constraints_for( + p : Planner, + name : String, + requested : String, +) -> Array[String] { let cons : Array[String] = [requested] match p.ctx.state.get(name) { Some(inst) => @@ -56,7 +62,7 @@ fn constraints_for(p : Planner, name : String, requested : String) -> Array[Stri } } for other, st in p.steps { - if other != name && not(p.ctx.state.contains(other)) { + if other != name && !(p.ctx.state.contains(other)) { match st.manifest.depends.get(name) { Some(c) => cons.push(c) None => () @@ -67,10 +73,15 @@ fn constraints_for(p : Planner, name : String, requested : String) -> Array[Stri } ///| -fn visit(p : Planner, name : String, requested : String, explicit : Bool) -> Unit raise OrbitError { +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])) { + if !(satisfies_all(st.version, [requested])) { raise OrbitError( "conflict: \{name} \{st.version} is planned but '\{requested}' is required", ) @@ -87,14 +98,18 @@ fn visit(p : Planner, name : String, requested : String, explicit : Bool) -> Uni let upgrading = p.upgrade.contains(name) match p.ctx.state.get(name) { Some(inst) => - if not(upgrading) && satisfies_all(inst.version, cons) { + if !(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 }, + constraint: if explicit { + requested + } else { + inst.constraint + }, keep: true, } p.steps[name] = st @@ -147,10 +162,11 @@ fn visit(p : Planner, name : String, requested : String, explicit : Bool) -> Uni 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)) { + if !(valid_name(name)) { raise OrbitError("invalid package name '\{name}'") } (name, if c == "" { "*" } else { c }) @@ -176,17 +192,28 @@ fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit { } ///| -fn link_bins(ctx : Ctx, dir : String, bins : Array[String]) -> Unit raise OrbitError { +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)), + "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 { +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) => @@ -200,6 +227,7 @@ fn check_bin_conflicts(ctx : Ctx, name : String, bins : Array[String]) -> Unit r } } +///| /// 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) @@ -227,7 +255,9 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { 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}") + println( + " \{st.name}: \{inst.history[inst.history.length() - 1].version} -> \{st.version}", + ) } None => { ctx.state[st.name] = Installed::{ @@ -273,7 +303,7 @@ fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError { ///| fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner { - Planner::{ ctx, steps: Map::new(), order: [], upgrade } + Planner::{ ctx, steps: Map([]), order: [], upgrade, } } ///| @@ -289,6 +319,7 @@ fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { 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 { @@ -299,7 +330,7 @@ fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { } } else { for n in names { - if not(ctx.state.contains(n)) { + if !(ctx.state.contains(n)) { raise OrbitError("\{n} is not installed") } targets.push(n) @@ -339,6 +370,7 @@ fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { } } +///| /// Remove dependencies nobody needs any more. fn autoremove(ctx : Ctx) -> Unit raise OrbitError { let mut changed = true @@ -346,7 +378,7 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError { changed = false let orphans : Array[String] = [] for name, p in ctx.state { - if not(p.explicit) && reverse_deps(ctx, name).length() == 0 { + if !(p.explicit) && reverse_deps(ctx, name).length() == 0 { orphans.push(name) } } @@ -358,23 +390,27 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError { } ///| -fn cmd_remove(ctx : Ctx, names : Array[String], force : Bool) -> Unit raise OrbitError { +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)) { + if !(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)) { + if !(names.contains(u)) { users.push(u) } } - if users.length() > 0 && not(force) { + if users.length() > 0 && !(force) { raise OrbitError( "\{n} is required by \{join(users, ", ")} (use --force to remove anyway)", ) @@ -387,6 +423,7 @@ fn cmd_remove(ctx : Ctx, names : Array[String], force : Bool) -> Unit raise Orbi 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) { @@ -398,8 +435,10 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { 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") + if !(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::{ @@ -420,7 +459,10 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { 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) } + Some(d) => + if !(satisfies_all(d.version, [c])) { + missing.push(dep + "@" + c) + } None => missing.push(dep + "@" + c) } } @@ -431,10 +473,11 @@ 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 { let store = ctx.root + "/store" - if not(exists(store)) { + if !(exists(store)) { println("store is empty") return } @@ -451,7 +494,7 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { keep.push(store_id(g.digest)) } for id in lines(capture("ls -1 " + sq(store + "/" + pkg))) { - if not(keep.contains(id)) { + if !(keep.contains(id)) { sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id)) freed = freed + 1 } @@ -466,7 +509,7 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { ///| fn cmd_list(ctx : Ctx) -> Unit { - if ctx.state.size() == 0 { + if ctx.state.length() == 0 { println("no packages installed") return } diff --git a/src/main/registry.mbt b/src/main/registry.mbt index cb6fa05..5fc8bfd 100644 --- a/src/main/registry.mbt +++ b/src/main/registry.mbt @@ -20,16 +20,27 @@ fn list_tags(ctx : Ctx, name : String) -> Array[String] raise OrbitError { } ///| -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:")) { +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 !(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 { +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)), ) @@ -42,10 +53,15 @@ fn fetch_manifest(ctx : Ctx, name : String, digest : String) -> Manifest raise O 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 { +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 @@ -53,10 +69,13 @@ fn fetch_into_store(ctx : Ctx, name : String, digest : String) -> String raise O 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)) + + oras( + ctx, + "pull -o " + sq(tmp) + " " + sq(repo_of(ctx, name) + "@" + digest), + ) + " >/dev/null", ) - if not(exists(tmp + "/pkg.tar.gz")) { + if !(exists(tmp + "/pkg.tar.gz")) { raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer") } sh_ok( @@ -79,15 +98,20 @@ fn fetch_into_store(ctx : Ctx, name : String, digest : String) -> String raise O 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 { +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)) { + if !(exists(files)) { raise OrbitError("\{files} not found (package contents go in files/)") } for b in m.bins { diff --git a/src/main/semver.mbt b/src/main/semver.mbt index 37f66ec..8753183 100644 --- a/src/main/semver.mbt +++ b/src/main/semver.mbt @@ -11,13 +11,13 @@ ///| struct Ver { - nums : Array[Int] - parts : Int + nums : Array[Int32] + parts : Int32 pre : String } ///| -fn parse_nat(s : String) -> Int? { +fn parse_nat(s : String) -> Int32? { if s == "" { return None } @@ -47,7 +47,7 @@ fn parse_ver(s0 : String) -> Ver? { None => return None } } - Some(Ver::{ nums, parts: parts.length(), pre }) + Some(Ver::{ nums, parts: parts.length(), pre, }) } ///| @@ -59,7 +59,7 @@ fn is_ver(s : String) -> Bool { } ///| -fn cmp_ver(a : Ver, b : Ver) -> Int { +fn cmp_ver(a : Ver, b : Ver) -> Int32 { 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 } @@ -82,7 +82,7 @@ fn satisfies(v : Ver, c0 : String) -> Bool { if c == "" || c == "*" || c == "latest" { return v.pre == "" } - if v.pre != "" && not(has_char(c, '-')) { + if v.pre != "" && !(has_char(c, '-')) { return false } let with_base = fn(rest : String, rule : (Ver) -> Bool) -> Bool { @@ -126,7 +126,7 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool { match parse_ver(version) { Some(v) => { for c in cons { - if not(satisfies(v, c)) { + if !(satisfies(v, c)) { return false } } @@ -145,6 +145,7 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool { } } +///| /// 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? { @@ -166,7 +167,7 @@ fn pick_tag(tags : Array[String], cons : Array[String]) -> String? { None => { for c in cons { let t = trim(c) - if t != "" && t != "*" && not(is_ver(t)) && tags.contains(t) { + if t != "" && t != "*" && !(is_ver(t)) && tags.contains(t) { return Some(t) } } @@ -175,6 +176,7 @@ fn pick_tag(tags : Array[String], cons : Array[String]) -> String? { } } +///| /// Semver tags, highest first. fn sorted_versions(tags : Array[String]) -> Array[String] { let out : Array[(String, Ver)] = [] @@ -206,23 +208,25 @@ 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()) + 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 None) } ///| 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, "^2.0.0"))) assert_true(satisfies(v, "~1.4.0")) - assert_true(not(satisfies(v, "~1.3.0"))) + assert_true(!(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, "1.5"))) assert_true(satisfies(v, "*")) - assert_true(not(satisfies(parse_ver("0.3.1").unwrap(), "^0.2.0"))) + assert_true(!(satisfies(parse_ver("0.3.1").unwrap(), "^0.2.0"))) } ///| diff --git a/src/main/sys.mbt b/src/main/sys.mbt index 8214f16..1fb6e11 100644 --- a/src/main/sys.mbt +++ b/src/main/sys.mbt @@ -3,28 +3,35 @@ // String APIs that have changed between MoonBit releases. ///| -suberror OrbitError String +suberror OrbitError { + OrbitError(String) +} ///| -extern "C" fn c_run(cmd : Bytes) -> Int = "orbit_run" +#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() -> Int = "orbit_last_status" +extern "C" fn c_last_status() -> Int32 = "orbit_last_status" ///| +#borrow(path) 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" +#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" ///| -extern "C" fn c_exit(code : Int) = "orbit_exit" +extern "C" fn c_exit(code : Int32) = "orbit_exit" // ---------------------------------------------------------------- UTF-8 @@ -54,30 +61,30 @@ fn utf8_encode(s : String) -> Bytes { ///| fn utf8_decode(b : Bytes) -> String { - let sb = StringBuilder::new() + let sb = StringBuilder() 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)) + sb.write_char(Int32::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)) + sb.write_char(Int32::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)) + sb.write_char(Int32::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)) + sb.write_char(Int32::unsafe_to_char(cp)) i = i + 4 } else { sb.write_char('\u{FFFD}') @@ -99,8 +106,8 @@ fn chars(s : String) -> Array[Char] { } ///| -fn slice(a : Array[Char], start : Int, end : Int) -> String { - let sb = StringBuilder::new() +fn slice(a : Array[Char], start : Int32, end : Int32) -> String { + let sb = StringBuilder() for i = start; i < end; i = i + 1 { sb.write_char(a[i]) } @@ -108,7 +115,7 @@ fn slice(a : Array[Char], start : Int, end : Int) -> String { } ///| -fn drop_chars(s : String, n : Int) -> String { +fn drop_chars(s : String, n : Int32) -> String { let a = chars(s) if n >= a.length() { "" @@ -167,12 +174,12 @@ fn contains_str(s : String, sub : String) -> Bool { ///| fn split_on(s : String, sep : Char) -> Array[String] { let out : Array[String] = [] - let sb = StringBuilder::new() + let sb = StringBuilder() let mut cur = sb for c in s { if c == sep { out.push(cur.to_string()) - cur = StringBuilder::new() + cur = StringBuilder() } else { cur.write_char(c) } @@ -181,6 +188,7 @@ fn split_on(s : String, sep : Char) -> Array[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) @@ -211,6 +219,7 @@ fn trim(s : String) -> String { slice(a, start, end) } +///| /// Non-empty, trimmed lines. fn lines(s : String) -> Array[String] { let out : Array[String] = [] @@ -225,7 +234,7 @@ fn lines(s : String) -> Array[String] { ///| fn join(xs : Array[String], sep : String) -> String { - let sb = StringBuilder::new() + let sb = StringBuilder() for i = 0; i < xs.length(); i = i + 1 { if i > 0 { sb.write_string(sep) @@ -241,9 +250,10 @@ fn basename(p : String) -> String { parts[parts.length() - 1] } +///| /// Single-quote a string for /bin/sh. fn sq(s : String) -> String { - let sb = StringBuilder::new() + let sb = StringBuilder() sb.write_char('\'') for c in s { if c == '\'' { @@ -259,7 +269,7 @@ fn sq(s : String) -> String { // ---------------------------------------------------------------- process / fs ///| -fn sh(cmd : String) -> Int { +fn sh(cmd : String) -> Int32 { c_run(utf8_encode(cmd)) } @@ -271,6 +281,7 @@ 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))) @@ -296,6 +307,7 @@ fn read_text(path : String) -> String? { } } +///| /// 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" @@ -310,6 +322,7 @@ 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"))