Files
orbit/src/main/model.mbt
T
nandiandClaude Haiku 5.5 ec21287549 Use moonbitlang/async for process and file IO
Process execution and file access go through @process and @fs. The spinner
is a background task in a task group, and the C stub keeps only getenv,
exit, isatty, symlink and stderr output. orbit info reads installed state
only, and it records and restores package descriptions. just install adds
Orbit's bin directory to ~/.bashrc once.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 22:40:18 -08:00

378 lines
9.1 KiB
MoonBit

// 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
documentation : String
depends : Map[String, String]
bins : Array[String]
}
///|
/// A previously installed build, kept for rollback.
struct Gen {
channel : String
version : String
digest : String
description : String
bins : Array[String]
depends : Map[String, String]
}
///|
struct Installed {
name : String
mut channel : String
mut version : String
mut digest : String
mut description : String
mut explicit : Bool
mut constraint : String
mut bins : Array[String]
mut depends : Map[String, String]
history : Array[Gen]
}
///|
struct Ctx {
root : String
channels : Array[Channel] // highest priority first
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] = Map([])
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] = Map([])
for k, v in m {
o[k] = Json::string(v)
}
Json::object(o)
}
///|
fn bool_json(b : Bool) -> Json {
if b {
Json::boolean(true)
} else {
Json::boolean(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 !ok {
return false
}
}
!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", ""),
documentation: jstr(o, "documentation", ""),
depends: jmap(o, "depends"),
bins: jstrs(o, "bin"),
}
if !valid_name(m.name) {
raise OrbitError(
"orbit.json: invalid name '\{m.name}' (use a-z, 0-9, '-', '_', '.')",
)
}
if !is_ver(m.version) {
raise OrbitError("orbit.json: version '\{m.version}' is not semver")
}
for b in m.bins {
if !valid_rel_path(b) {
raise OrbitError("orbit.json: bin path '\{b}' must be relative")
}
}
for dep, _ in m.depends {
if !valid_name(dep) {
raise OrbitError("orbit.json: invalid dependency name '\{dep}'")
}
}
m
}
// ---------------------------------------------------------------- state
///|
fn gen_json(g : Gen) -> Json {
let o : Map[String, Json] = Map([])
o["channel"] = Json::string(g.channel)
o["version"] = Json::string(g.version)
o["digest"] = Json::string(g.digest)
o["description"] = Json::string(g.description)
o["bin"] = strs_json(g.bins)
o["depends"] = map_json(g.depends)
Json::object(o)
}
///|
fn installed_json(p : Installed) -> Json {
let o : Map[String, Json] = Map([])
o["channel"] = Json::string(p.channel)
o["version"] = Json::string(p.version)
o["digest"] = Json::string(p.digest)
o["description"] = Json::string(p.description)
o["explicit"] = bool_json(p.explicit)
o["constraint"] = Json::string(p.constraint)
o["bin"] = strs_json(p.bins)
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] = Map([])
for name, p in state {
pkgs[name] = installed_json(p)
}
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] = Map([])
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::{
channel: jstr(h, "channel", MAIN_CHANNEL),
version: jstr(h, "version", ""),
digest: jstr(h, "digest", ""),
description: jstr(h, "description", ""),
bins: jstrs(h, "bin"),
depends: jmap(h, "depends"),
})
_ => ()
}
}
_ => ()
}
out[name] = Installed::{
name,
channel: jstr(o, "channel", MAIN_CHANNEL),
version: jstr(o, "version", ""),
digest: jstr(o, "digest", ""),
description: jstr(o, "description", ""),
explicit: jbool(o, "explicit", false),
constraint: jstr(o, "constraint", "*"),
bins: jstrs(o, "bin"),
depends: jmap(o, "depends"),
history,
}
}
_ => ()
}
}
_ => ()
}
out
}
///|
test "installed and rollback descriptions round trip with legacy entries" {
let text =
#|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}}
let state = state_from_text(state_to_text(state_from_text(text)))
guard state.get("tool") is Some(p) else { fail("missing installed package") }
assert_eq(p.description, "Current build")
assert_eq(p.history[0].description, "Previous build")
assert_eq(p.history[1].description, "")
}
// ---------------------------------------------------------------- context
///|
fn orbit_root() -> String {
let r = getenv("ORBIT_ROOT")
if r != "" {
r
} else {
getenv("HOME") + "/.orbit"
}
}
///|
/// Load channels and state.
async fn load_ctx() -> Ctx raise OrbitError {
let root = orbit_root()
let channels = resolve_channels(
load_listed_channels(root),
getenv("ORBIT_REGISTRY"),
getenv("ORBIT_PLAIN_HTTP") == "1",
)
let state = match read_text(root + "/state.json") {
Some(t) => state_from_text(t)
None => Map([])
}
Ctx::{ root, channels, state, }
}
///|
async 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(!valid_rel_path("../x"))
assert_true(!valid_rel_path("/bin/sh"))
assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef")
}