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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhg7TTpuaCymoNQWmQ
This commit is contained in:
Claude committed 2026-11-26 17:21:17 -08:00
commit efeaa326c8
13 files changed
+1983

No files matched your search

+539
View File
@@ -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 <name>[@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 <name>...")
}
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 <name>`",
)
}
for r in lines(out) {
if contains_str(r, term) {
println(r)
}
}
}