// Pixi-style project manifests (orbit.toml), lockfiles (orbit.lock), // and per-project environments (/.orbit/bin backed by ~/.orbit/store). ///| struct ProjectDep { channel : String? mut constraint : String } ///| struct TaskDef { shell : String? argv : Array[String] } ///| struct ProjectManifest { name : String version : String description : String project_channels : Array[String] channel_defs : Array[Channel] dependencies : Map[String, ProjectDep] tasks : Map[String, TaskDef] } ///| struct LockedPkg { name : String version : String tag : String channel : String url : String plain_http : Bool digest : String description : String bins : Array[String] depends : Map[String, String] } ///| struct Lockfile { version : Int32 channels : Array[Channel] packages : Array[LockedPkg] } // ---------------------------------------------------------------- helpers ///| fn sort_strings(xs : Array[String]) -> Array[String] { let out : Array[String] = [] for x in xs { out.push(x) } for i = 1; i < out.length(); i = i + 1 { let mut j = i while j > 0 && out[j].compare(out[j - 1]) < 0 { let tmp = out[j] out[j] = out[j - 1] out[j - 1] = tmp j = j - 1 } } out } ///| fn toml_escape(s : String) -> String { let sb = StringBuilder() for c in s { if c == '\\' { sb.write_string("\\\\") } else if c == '"' { sb.write_string("\\\"") } else if c == '\n' { sb.write_string("\\n") } else if c == '\r' { sb.write_string("\\r") } else if c == '\t' { sb.write_string("\\t") } else { sb.write_char(c) } } sb.to_string() } ///| fn toml_quote(s : String) -> String { "\"" + toml_escape(s) + "\"" } ///| fn is_bare_toml_key(k : String) -> Bool { if k == "" { return false } for c in k { let ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' if !ok { return false } } true } ///| fn toml_key(k : String) -> String { if is_bare_toml_key(k) { k } else { toml_quote(k) } } ///| fn strip_trailing_slashes(p : String) -> String { let a = chars(p) let mut end = a.length() while end > 1 && a[end - 1] == '/' { end = end - 1 } slice(a, 0, end) } ///| fn path_dirname(p0 : String) -> String { let p = strip_trailing_slashes(p0) let a = chars(p) let mut last : Int32 = -1 for i = 0; i < a.length(); i = i + 1 { if a[i] == '/' { last = i } } if last < 0 { "." } else if last == 0 { "/" } else { slice(a, 0, last) } } ///| fn sanitize_project_name(raw : String) -> String { let s = ascii_lower(basename(strip_trailing_slashes(raw))) let sb = StringBuilder() for c in s { let ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' if ok { sb.write_char(c) } else { sb.write_char('-') } } let out = sb.to_string() if valid_name(out) { out } else { "orbit-project" } } ///| fn parse_channel_items( items : Array[@toml.TomlValue], what : String, ) -> Array[Channel] raise OrbitError { let out : Array[Channel] = [] for item in items { let t = match item { TomlTable(t) => t _ => raise OrbitError("\{what}: use [[channels]] blocks") } let mut name = "" let mut url = "" let mut plain_http = false for k, v in t { match (k, v) { ("name", TomlString(s)) => name = s ("url", TomlString(s)) => url = s ("plain-http", TomlBoolean(b)) => plain_http = b _ => raise OrbitError("\{what}: bad channel key '\{k}'") } } if !valid_name(name) { raise OrbitError("\{what}: invalid channel name '\{name}'") } if url == "" && name == MAIN_CHANNEL { url = MAIN_URL } if !valid_url(url) { raise OrbitError( "\{what}: channel '\{name}' needs a url like host/namespace (no https://)", ) } for c in out { if c.name == name { raise OrbitError("\{what}: channel '\{name}' is listed twice") } } out.push(Channel::{ name, url, plain_http }) } out } // ---------------------------------------------------------------- orbit.toml ///| fn parse_project_manifest( text : String, fallback_name : String, ) -> ProjectManifest raise OrbitError { let doc = @toml.parse(text) catch { e => raise OrbitError("orbit.toml: invalid TOML: \{e}") } let top = match doc { TomlTable(t) => t _ => raise OrbitError("orbit.toml: expected a table") } let mut name = fallback_name let mut version = "0.1.0" let mut description = "" let project_channels : Array[String] = [] let mut channel_defs : Array[Channel] = [] let dependencies : Map[String, ProjectDep] = Map([]) let tasks : Map[String, TaskDef] = Map([]) for key, value in top { match key { "project" => { let pt = match value { TomlTable(t) => t _ => raise OrbitError("orbit.toml: [project] must be a table") } for pk, pv in pt { match (pk, pv) { ("name", TomlString(s)) => name = s ("version", TomlString(s)) => version = s ("description", TomlString(s)) => description = s ("channels", TomlArray(xs)) => for item in xs { match item { TomlString(cn) => { if !valid_name(cn) { raise OrbitError( "orbit.toml: invalid channel name '\{cn}' in [project].channels", ) } if !project_channels.contains(cn) { project_channels.push(cn) } } _ => raise OrbitError( "orbit.toml: [project].channels entries must be strings", ) } } _ => raise OrbitError("orbit.toml: unknown [project] key '\{pk}'") } } } "channels" => { let items = match value { TomlArray(a) => a _ => raise OrbitError("orbit.toml: use [[channels]] blocks") } channel_defs = parse_channel_items(items, "orbit.toml") } "dependencies" => { let dt = match value { TomlTable(t) => t _ => raise OrbitError("orbit.toml: [dependencies] must be a table") } for raw_key, dv in dt { let (key_ch, pkg_name) = parse_dep_key(raw_key) match key_ch { Some(kc) => if !valid_name(kc) { raise OrbitError( "orbit.toml: invalid channel name '\{kc}' in dependency '\{raw_key}'", ) } None => () } if !valid_name(pkg_name) { raise OrbitError( "orbit.toml: invalid dependency name '\{raw_key}'", ) } let mut ch : String? = key_ch let mut constraint = "*" match dv { TomlString(s) => { let t = trim(s) constraint = if t == "" { "*" } else { t } } TomlTable(sub) => for sk, sv in sub { match (sk, sv) { ("version", TomlString(s)) => { let t = trim(s) constraint = if t == "" { "*" } else { t } } ("channel", TomlString(c)) => { if !valid_name(c) { raise OrbitError( "orbit.toml: invalid channel '\{c}' for dependency '\{raw_key}'", ) } match key_ch { Some(kc) => if kc != c { raise OrbitError( "orbit.toml: dependency '\{raw_key}' specifies conflicting channel '\{c}'", ) } None => () } ch = Some(c) } _ => raise OrbitError( "orbit.toml: unknown key '\{sk}' in dependency '\{raw_key}'", ) } } _ => raise OrbitError( "orbit.toml: dependency '\{raw_key}' must be a version string or table", ) } if !valid_constraint(constraint) { raise OrbitError( "orbit.toml: invalid version constraint '\{constraint}' for '\{raw_key}'", ) } if dependencies.contains(pkg_name) { raise OrbitError( "orbit.toml: dependency '\{pkg_name}' is listed more than once", ) } dependencies[pkg_name] = ProjectDep::{ channel: ch, constraint } } } "tasks" => { let tt = match value { TomlTable(t) => t _ => raise OrbitError("orbit.toml: [tasks] must be a table") } for tname, tv in tt { if trim(tname) == "" { raise OrbitError("orbit.toml: empty task name") } match tv { TomlString(cmd) => { if trim(cmd) == "" { raise OrbitError("orbit.toml: task '\{tname}' is empty") } tasks[tname] = TaskDef::{ shell: Some(cmd), argv: [] } } TomlArray(xs) => { let argv : Array[String] = [] for item in xs { match item { TomlString(arg) => argv.push(arg) _ => raise OrbitError( "orbit.toml: task '\{tname}' array items must be strings", ) } } if argv.length() == 0 || trim(argv[0]) == "" { raise OrbitError("orbit.toml: task '\{tname}' argv is empty") } tasks[tname] = TaskDef::{ shell: None, argv } } _ => raise OrbitError( "orbit.toml: task '\{tname}' must be a command string or string array", ) } } } _ => raise OrbitError("orbit.toml: unknown key '\{key}'") } } if name == "" || !valid_name(name) { raise OrbitError( "orbit.toml: invalid project name '\{name}' (use a-z, 0-9, '-', '_', '.')", ) } if version != "" && !is_ver(version) { raise OrbitError("orbit.toml: version '\{version}' is not semver") } ProjectManifest::{ name, version, description, project_channels, channel_defs, dependencies, tasks, } } ///| fn project_to_toml(m : ProjectManifest) -> String { let sb = StringBuilder() sb.write_string("[project]\n") sb.write_string("name = " + toml_quote(m.name) + "\n") if m.version != "" { sb.write_string("version = " + toml_quote(m.version) + "\n") } if m.description != "" { sb.write_string("description = " + toml_quote(m.description) + "\n") } if m.project_channels.length() > 0 { let chs = m.project_channels.map(fn(c) { toml_quote(c) }) sb.write_string("channels = [" + join(chs, ", ") + "]\n") } for c in m.channel_defs { sb.write_string("\n" + channel_toml(c)) } sb.write_string("\n[dependencies]\n") let dep_names : Array[String] = [] for name, _ in m.dependencies { dep_names.push(name) } for name in sort_strings(dep_names) { let dep = m.dependencies[name] match dep.channel { Some(ch) => sb.write_string( toml_key(name) + " = { version = " + toml_quote(dep.constraint) + ", channel = " + toml_quote(ch) + " }\n", ) None => sb.write_string( toml_key(name) + " = " + toml_quote(dep.constraint) + "\n", ) } } if m.tasks.length() > 0 { sb.write_string("\n[tasks]\n") let task_names : Array[String] = [] for tn, _ in m.tasks { task_names.push(tn) } for tn in sort_strings(task_names) { let td = m.tasks[tn] match td.shell { Some(cmd) => sb.write_string(toml_key(tn) + " = " + toml_quote(cmd) + "\n") None => { let parts = td.argv.map(fn(a) { toml_quote(a) }) sb.write_string( toml_key(tn) + " = [" + join(parts, ", ") + "]\n", ) } } } } sb.to_string() } // ---------------------------------------------------------------- orbit.lock ///| fn parse_lockfile(text : String) -> Lockfile raise OrbitError { let doc = @toml.parse(text) catch { e => raise OrbitError("orbit.lock: invalid TOML: \{e}") } let top = match doc { TomlTable(t) => t _ => raise OrbitError("orbit.lock: expected a table") } let mut version : Int32 = 0 let mut channels : Array[Channel] = [] let packages : Array[LockedPkg] = [] for key, value in top { match key { "version" => match value { TomlInteger(n) => version = n.to_int() _ => raise OrbitError("orbit.lock: version must be an integer") } "channels" => { let items = match value { TomlArray(a) => a _ => raise OrbitError("orbit.lock: channels must be [[channels]]") } channels = parse_channel_items(items, "orbit.lock") } "package" => { let items = match value { TomlArray(a) => a _ => raise OrbitError("orbit.lock: package must be [[package]]") } for item in items { let pt = match item { TomlTable(t) => t _ => raise OrbitError("orbit.lock: [[package]] must be a table") } let mut name = "" let mut pver = "" let mut tag = "" let mut ch = "" let mut url = "" let mut plain_http = false let mut digest = "" let mut description = "" let bins : Array[String] = [] let depends : Map[String, String] = Map([]) for pk, pv in pt { match (pk, pv) { ("name", TomlString(s)) => name = s ("version", TomlString(s)) => pver = s ("tag", TomlString(s)) => tag = s ("channel", TomlString(s)) => ch = s ("url", TomlString(s)) => url = s ("plain-http", TomlBoolean(b)) => plain_http = b ("digest", TomlString(s)) => digest = s ("description", TomlString(s)) => description = s ("bin", TomlArray(xs)) => for x in xs { match x { TomlString(b) => bins.push(b) _ => raise OrbitError( "orbit.lock: package '\{name}' bin entries must be strings", ) } } ("depends", TomlTable(dt)) => for dk, dv in dt { match dv { TomlString(dc) => depends[dk] = dc _ => raise OrbitError( "orbit.lock: dependency '\{dk}' on '\{name}' must be a string", ) } } _ => raise OrbitError( "orbit.lock: unknown package key '\{pk}'", ) } } if !valid_name(name) || !is_ver(pver) || !valid_name(ch) || !valid_url(url) || digest == "" { raise OrbitError( "orbit.lock: incomplete or invalid [[package]] entry '\{name}'", ) } for b in bins { if !valid_rel_path(b) { raise OrbitError("orbit.lock: invalid bin path '\{b}' on '\{name}'") } } for dk, dc in depends { if !valid_dep_key(dk) || !valid_constraint(dc) { raise OrbitError( "orbit.lock: invalid dependency '\{dk}' = '\{dc}' on '\{name}'", ) } } packages.push(LockedPkg::{ name, version: pver, tag: if tag == "" { pver } else { tag }, channel: ch, url, plain_http, digest, description, bins, depends, }) } } _ => raise OrbitError("orbit.lock: unknown key '\{key}'") } } if version != 1 { raise OrbitError("orbit.lock: unsupported lockfile version \{version}") } Lockfile::{ version, channels, packages } } ///| fn lockfile_to_toml(lock : Lockfile) -> String { let sb = StringBuilder() sb.write_string("# Generated by orbit. Do not edit by hand.\n\n") sb.write_string("version = " + lock.version.to_string() + "\n") for c in lock.channels { sb.write_string("\n[[channels]]\n") sb.write_string("name = " + toml_quote(c.name) + "\n") sb.write_string("url = " + toml_quote(c.url) + "\n") if c.plain_http { sb.write_string("plain-http = true\n") } } let by_name : Map[String, LockedPkg] = Map([]) let names : Array[String] = [] for p in lock.packages { by_name[p.name] = p names.push(p.name) } for name in sort_strings(names) { let p = by_name[name] sb.write_string("\n[[package]]\n") sb.write_string("name = " + toml_quote(p.name) + "\n") sb.write_string("version = " + toml_quote(p.version) + "\n") if p.tag != "" && p.tag != p.version { sb.write_string("tag = " + toml_quote(p.tag) + "\n") } sb.write_string("channel = " + toml_quote(p.channel) + "\n") sb.write_string("url = " + toml_quote(p.url) + "\n") if p.plain_http { sb.write_string("plain-http = true\n") } sb.write_string("digest = " + toml_quote(p.digest) + "\n") if p.description != "" { sb.write_string("description = " + toml_quote(p.description) + "\n") } let bstrs = p.bins.map(fn(b) { toml_quote(b) }) sb.write_string("bin = [" + join(bstrs, ", ") + "]\n") if p.depends.length() > 0 { let dkeys : Array[String] = [] for dk, _ in p.depends { dkeys.push(dk) } let entries : Array[String] = [] for dk in sort_strings(dkeys) { entries.push(toml_key(dk) + " = " + toml_quote(p.depends[dk])) } sb.write_string("depends = { " + join(entries, ", ") + " }\n") } } sb.to_string() } // ---------------------------------------------------------------- discovery & solving ///| async fn find_project_manifest(manifest_path : String?) -> String? raise OrbitError { match manifest_path { Some(p) => { if !exists(p) { raise OrbitError("manifest not found: \{p}") } let k = @fs.kind(p) catch { _ => @fs.FileKind::Unknown } let target = if k is Directory { strip_trailing_slashes(p) + "/orbit.toml" } else { p } if !exists(target) { raise OrbitError("manifest not found: \{target}") } let abs = @fs.realpath(target) catch { e => raise OrbitError("cannot resolve \{target}: \{e}") } Some(abs) } None => { let mut dir = @fs.realpath(".") catch { e => raise OrbitError("cannot resolve current directory: \{e}") } while true { let cand = if dir == "/" { "/orbit.toml" } else { dir + "/orbit.toml" } if exists(cand) { return Some(cand) } let parent = path_dirname(dir) if parent == dir { break } dir = parent } None } } } ///| fn resolve_project_channels( m : ProjectManifest, global_channels : Array[Channel], ) -> Array[Channel] raise OrbitError { if m.project_channels.length() > 0 { let by_name : Map[String, Channel] = Map([]) for c in global_channels { by_name[c.name] = c } for c in m.channel_defs { by_name[c.name] = c } let out : Array[Channel] = [] for name in m.project_channels { match by_name.get(name) { Some(c) => out.push(c) None => raise OrbitError( "orbit.toml: unknown channel '\{name}' (define [[channels]] or configure it globally)", ) } } return out } if m.channel_defs.length() > 0 { return resolve_channels( m.channel_defs, getenv("ORBIT_REGISTRY"), getenv("ORBIT_PLAIN_HTTP") == "1", ) } global_channels } ///| fn locked_pkg_matches_spec( lp : LockedPkg, constraint : String, pin : String?, ch_by_name : Map[String, Channel], ) -> Bool { match pin { Some(c) => if lp.channel != c { return false } None => () } match ch_by_name.get(lp.channel) { Some(ch) => if lp.url != ch.url || lp.plain_http != ch.plain_http { return false } None => return false } let match_ver = if lp.tag != "" && lp.tag != lp.version { lp.tag } else { lp.version } satisfies_all(match_ver, [constraint]) } ///| fn lockfile_satisfies( lock : Lockfile, m : ProjectManifest, channels : Array[Channel], ) -> Bool { if lock.version != 1 { return false } if lock.channels.length() != channels.length() { return false } for i = 0; i < channels.length(); i = i + 1 { let lc = lock.channels[i] let c = channels[i] if lc.name != c.name || lc.url != c.url || lc.plain_http != c.plain_http { return false } } let ch_by_name : Map[String, Channel] = Map([]) for c in channels { ch_by_name[c.name] = c } let pkg_by_name : Map[String, LockedPkg] = Map([]) let bin_owners : Map[String, String] = Map([]) for p in lock.packages { if pkg_by_name.contains(p.name) { return false } pkg_by_name[p.name] = p for b in p.bins { let bn = basename(b) if bin_owners.contains(bn) { return false } bin_owners[bn] = p.name } } let queue : Array[String] = [] let seen : Map[String, Bool] = Map([]) for name, dep in m.dependencies { let lp = match pkg_by_name.get(name) { Some(p) => p None => return false } if !locked_pkg_matches_spec(lp, dep.constraint, dep.channel, ch_by_name) { return false } if !seen.contains(name) { seen[name] = true queue.push(name) } } while queue.length() > 0 { let cur = queue.remove(0) let lp = pkg_by_name[cur] for dk, dc in lp.depends { let (dch, dname) = parse_dep_key(dk) let dp = match pkg_by_name.get(dname) { Some(p) => p None => return false } if !locked_pkg_matches_spec(dp, dc, dch, ch_by_name) { return false } if !seen.contains(dname) { seen[dname] = true queue.push(dname) } } } seen.length() == lock.packages.length() } ///| fn manifest_of_locked(p : LockedPkg) -> Manifest { Manifest::{ name: p.name, version: p.version, description: p.description, documentation: "", depends: p.depends, bins: p.bins, } } ///| async fn solve_project( root : String, m : ProjectManifest, channels : Array[Channel], existing_lock : Lockfile?, upgrade_names : Array[String], upgrade_all : Bool, ) -> Lockfile raise OrbitError { if m.dependencies.length() == 0 { return Lockfile::{ version: 1, channels, packages: [] } } let ch_ctx = Ctx::{ root, channels, state: Map([]) } let ch_by_name : Map[String, Channel] = Map([]) for c in channels { ch_by_name[c.name] = c } let locked_fav : Map[String, LockedPkg] = Map([]) if !upgrade_all { match existing_lock { Some(lock) => for lp in lock.packages { if !upgrade_names.contains(lp.name) { locked_fav[lp.name] = lp } } None => () } } let tags_cache : Map[String, (Channel, Array[String])] = Map([]) let digest_cache : Map[String, String] = Map([]) let manifest_cache : Map[String, Manifest] = Map([]) let provider = SolverProvider::{ candidates: async fn(name, pin) { let cache_key = name + "|" + pin.unwrap_or("") let (ch, tags) = match tags_cache.get(cache_key) { Some(pair) => pair None => { let pair = locate(ch_ctx, name, pin) tags_cache[cache_key] = pair ch_by_name[pair.0.name] = pair.0 pair } } let fav = match locked_fav.get(name) { Some(lp) => if lp.channel == ch.name && lp.url == ch.url && lp.plain_http == ch.plain_http { Some((lp.channel, lp.tag, lp.digest)) } else { None } None => None } (ch.name, candidates_from_tags(name, ch.name, tags, fav)) }, details: async fn(cand) { if false { @async.sleep(0) } if cand.favored && cand.digest != "" { match locked_fav.get(cand.name) { Some(lp) => if lp.digest == cand.digest && lp.channel == cand.channel { return CandidateDetail::{ digest: cand.digest, manifest: manifest_of_locked(lp), } } None => () } } let ch = match ch_by_name.get(cand.channel) { Some(c) => c None => find_channel(ch_ctx, cand.channel) } let dkey = cand.channel + "::" + cand.name + "@" + cand.tag let digest = match digest_cache.get(dkey) { Some(d) => d None => { let d = resolve_digest(ch, cand.name, cand.tag) digest_cache[dkey] = d d } } let mkey = cand.channel + "::" + cand.name + "@" + digest let mf = match manifest_cache.get(mkey) { Some(cached) => cached None => { let fetched = fetch_manifest_cached(root, ch, cand.name, digest) manifest_cache[mkey] = fetched fetched } } CandidateDetail::{ digest, manifest: mf } }, extra_reqs: fn(_name) { [] }, locked_bins: Map([]), } let dep_names : Array[String] = [] for name, _ in m.dependencies { dep_names.push(name) } let reqs : Array[SolveReq] = [] for name in sort_strings(dep_names) { let dep = m.dependencies[name] reqs.push(SolveReq::{ name, channel: dep.channel, constraint: dep.constraint, label: "orbit.toml", }) } let solved = solve(reqs, provider) let by_name : Map[String, SolvedPkg] = Map([]) let out_names : Array[String] = [] for sp in solved { by_name[sp.name] = sp out_names.push(sp.name) } let packages : Array[LockedPkg] = [] for name in sort_strings(out_names) { let sp = by_name[name] let ch = ch_by_name[sp.channel] packages.push(LockedPkg::{ name: sp.name, version: sp.version, tag: sp.tag, channel: sp.channel, url: ch.url, plain_http: ch.plain_http, digest: sp.digest, description: sp.manifest.description, bins: sp.manifest.bins, depends: sp.manifest.depends, }) } Lockfile::{ version: 1, channels, packages } } // ---------------------------------------------------------------- .orbit environment ///| fn project_env_dir(project_dir : String) -> String { if project_dir == "/" { "/.orbit" } else { project_dir + "/.orbit" } } ///| fn read_env_packages(text : String) -> Map[String, String] { let obj : Map[String, Json]? = Some(parse_object(text, "env.json")) catch { _ => None } match obj { Some(o) => jmap(o, "packages") None => Map([]) } } ///| fn env_json_text(packages : Map[String, String]) -> String { let top : Map[String, Json] = Map([]) top["format"] = Json::string("orbit-env-v1") top["packages"] = map_json(packages) Json::object(top).stringify(indent=2) + "\n" } ///| async fn sync_project_env( root : String, project_dir : String, lock : Lockfile, ) -> Int32 raise OrbitError { let bin_owners : Map[String, String] = Map([]) for lp in lock.packages { for b in lp.bins { let bn = basename(b) match bin_owners.get(bn) { Some(other) => raise OrbitError( "\{lp.name} wants to provide '\{bn}', which \{other} already provides", ) None => bin_owners[bn] = lp.name } } } let env_dir = project_env_dir(project_dir) let pbin = env_dir + "/bin" @fs.mkdir(pbin, recursive=true, allow_exist=true) catch { e => raise OrbitError("cannot create \{pbin}: \{e}") } let gi = env_dir + "/.gitignore" if !exists(gi) { write_text_atomic(gi, "*\n") } let env_path = env_dir + "/env.json" let prev_pkgs = match read_text(env_path) { Some(t) => read_env_packages(t) None => Map([]) } let store_ctx = Ctx::{ root, channels: lock.channels, state: Map([]) } let desired_pkgs : Map[String, String] = Map([]) let mut changed : Int32 = 0 for lp in lock.packages { let ch = Channel::{ name: lp.channel, url: lp.url, plain_http: lp.plain_http, } let dir = fetch_into_store(store_ctx, ch, lp.name, lp.digest) for b in lp.bins { if sh("test -f " + sq(dir + "/" + b)) != 0 { raise OrbitError( "\{lp.name}: bin '\{b}' missing from package contents", ) } } desired_pkgs[lp.name] = lp.digest if prev_pkgs.get(lp.name) != Some(lp.digest) { changed = changed + 1 } } for name, _ in prev_pkgs { if !desired_pkgs.contains(name) { changed = changed + 1 } } let mut links_ok = changed == 0 && prev_pkgs.length() == desired_pkgs.length() if links_ok { let existing_bins = @fs.readdir(pbin) catch { _ => [] } if existing_bins.length() != bin_owners.length() { links_ok = false } else { for bn, _ in bin_owners { if !exists(pbin + "/" + bn) { links_ok = false break } } } } if links_ok { return 0 } let old_entries = @fs.readdir(pbin) catch { _ => [] } for name in old_entries { @fs.remove(pbin + "/" + name) catch { _ => () } } for lp in lock.packages { let dir = store_dir(store_ctx, lp.name, lp.digest) for b in lp.bins { let target = dir + "/" + b let linkpath = pbin + "/" + basename(b) let rc = c_symlink(utf8_encode(target), utf8_encode(linkpath)) if rc != 0 { raise OrbitError("cannot symlink " + linkpath + " -> " + target) } } } write_text_atomic(env_path, env_json_text(desired_pkgs)) if changed == 0 { 1 } else { changed } } // ---------------------------------------------------------------- project commands ///| async fn load_project( manifest_file : String, global_channels : Array[Channel], ) -> (String, ProjectManifest, Array[Channel]) raise OrbitError { let project_dir = path_dirname(manifest_file) let fallback = sanitize_project_name(project_dir) let text = match read_text(manifest_file) { Some(t) => t None => raise OrbitError("cannot read \{manifest_file}") } let m = parse_project_manifest(text, fallback) let channels = resolve_project_channels(m, global_channels) (project_dir, m, channels) } ///| async fn read_existing_lock(lock_path : String) -> Lockfile? raise OrbitError { match read_text(lock_path) { Some(t) => Some(parse_lockfile(t)) None => None } } ///| async fn cmd_project_init(dir_arg : String?) -> Unit raise OrbitError { let dir = match dir_arg { Some(d) => { @fs.mkdir(d, recursive=true, allow_exist=true) catch { e => raise OrbitError("cannot create \{d}: \{e}") } d } None => "." } let abs_dir = @fs.realpath(dir) catch { e => raise OrbitError("cannot resolve \{dir}: \{e}") } let manifest_path = if abs_dir == "/" { "/orbit.toml" } else { abs_dir + "/orbit.toml" } if exists(manifest_path) { raise OrbitError("orbit.toml already exists at \{manifest_path}") } let m = ProjectManifest::{ name: sanitize_project_name(abs_dir), version: "0.1.0", description: "", project_channels: [], channel_defs: [], dependencies: Map([]), tasks: Map([]), } write_text_atomic(manifest_path, project_to_toml(m)) println("created \{manifest_path}") } ///| async fn cmd_project_lock( ctx : Ctx, manifest_file : String, update : Bool, ) -> Unit raise OrbitError { let (project_dir, m, channels) = load_project(manifest_file, ctx.channels) let lock_path = project_dir + "/orbit.lock" let existing = if update { None } else { read_existing_lock(lock_path) } let lock = solve_project(ctx.root, m, channels, existing, [], update) write_text_atomic(lock_path, lockfile_to_toml(lock)) println("wrote \{lock_path} (\{lock.packages.length()} package(s))") } ///| async fn ensure_project_synced( ctx : Ctx, manifest_file : String, locked : Bool, frozen : Bool, quiet : Bool, ) -> (String, ProjectManifest, Lockfile) raise OrbitError { let (project_dir, m, channels) = load_project(manifest_file, ctx.channels) let lock_path = project_dir + "/orbit.lock" let existing = read_existing_lock(lock_path) let lock = match existing { Some(lk) => if lockfile_satisfies(lk, m, channels) { lk } else if locked || frozen { raise OrbitError( "orbit.lock is out of date with orbit.toml (run `orbit lock` or `orbit install` without --locked/--frozen)", ) } else { let solved = solve_project(ctx.root, m, channels, Some(lk), [], false) write_text_atomic(lock_path, lockfile_to_toml(solved)) solved } None => if locked || frozen { raise OrbitError( "orbit.lock not found (required by --locked/--frozen; run `orbit lock` first)", ) } else { let solved = solve_project(ctx.root, m, channels, None, [], false) write_text_atomic(lock_path, lockfile_to_toml(solved)) solved } } let synced = sync_project_env(ctx.root, project_dir, lock) if !quiet { if synced == 0 { println("environment is up to date") } else { println( "synced \{lock.packages.length()} package(s) into \{project_env_dir(project_dir)}", ) } } (project_dir, m, lock) } ///| async fn cmd_project_sync( ctx : Ctx, manifest_file : String, locked : Bool, frozen : Bool, ) -> Unit raise OrbitError { ignore(ensure_project_synced(ctx, manifest_file, locked, frozen, false)) } ///| async fn cmd_project_add( ctx : Ctx, manifest_file : String, specs : Array[String], ) -> Unit raise OrbitError { if specs.length() == 0 { raise OrbitError("usage: orbit add [channel::][@constraint]...") } let (project_dir, m, channels) = load_project(manifest_file, ctx.channels) let auto_pin : Map[String, Bool] = Map([]) let added_names : Array[String] = [] for s in specs { let (ch, name, c, has_c) = parse_spec_full(s) if added_names.contains(name) { raise OrbitError("duplicate package '\{name}' in orbit add") } added_names.push(name) auto_pin[name] = !has_c m.dependencies[name] = ProjectDep::{ channel: ch, constraint: c } } let lock_path = project_dir + "/orbit.lock" let existing = read_existing_lock(lock_path) let lock = solve_project( ctx.root, m, channels, existing, added_names, false, ) let solved_by_name : Map[String, LockedPkg] = Map([]) for p in lock.packages { solved_by_name[p.name] = p } for name in added_names { if auto_pin.get(name) == Some(true) { match solved_by_name.get(name) { Some(lp) => { let pinned = if lp.tag != lp.version { lp.tag } else if parse_ver(lp.version) is Some(_) { "^" + lp.version } else { "*" } m.dependencies[name].constraint = pinned } None => () } } } let updated_toml = project_to_toml(m) ignore(parse_project_manifest(updated_toml, m.name)) write_text_atomic(manifest_file, updated_toml) write_text_atomic(lock_path, lockfile_to_toml(lock)) ignore(sync_project_env(ctx.root, project_dir, lock)) for name in added_names { match solved_by_name.get(name) { Some(lp) => println(" added \{lp.name} (\{m.dependencies[name].constraint}) -> \{lp.version}") None => () } } } ///| async fn cmd_project_remove( ctx : Ctx, manifest_file : String, names : Array[String], ) -> Unit raise OrbitError { if names.length() == 0 { raise OrbitError("usage: orbit remove ...") } let (project_dir, m, channels) = load_project(manifest_file, ctx.channels) for n in names { if !m.dependencies.contains(n) { raise OrbitError("'\{n}' is not in orbit.toml [dependencies]") } } for n in names { m.dependencies.remove(n) } let lock_path = project_dir + "/orbit.lock" let existing = read_existing_lock(lock_path) let lock = solve_project(ctx.root, m, channels, existing, [], false) let updated_toml = project_to_toml(m) ignore(parse_project_manifest(updated_toml, m.name)) write_text_atomic(manifest_file, updated_toml) write_text_atomic(lock_path, lockfile_to_toml(lock)) ignore(sync_project_env(ctx.root, project_dir, lock)) for n in names { println(" removed \{n}") } } ///| async fn cmd_project_update( ctx : Ctx, manifest_file : String, names : Array[String], ) -> Unit raise OrbitError { let (project_dir, m, channels) = load_project(manifest_file, ctx.channels) let lock_path = project_dir + "/orbit.lock" let existing = read_existing_lock(lock_path) if names.length() > 0 { let locked_names : Map[String, Bool] = Map([]) match existing { Some(lk) => for p in lk.packages { locked_names[p.name] = true } None => () } for n in names { if !m.dependencies.contains(n) && !locked_names.contains(n) { raise OrbitError("'\{n}' is not in orbit.toml or orbit.lock") } } } let upgrade_all = names.length() == 0 let lock = solve_project( ctx.root, m, channels, existing, names, upgrade_all, ) write_text_atomic(lock_path, lockfile_to_toml(lock)) let synced = sync_project_env(ctx.root, project_dir, lock) if synced == 0 { println("already up to date") } else { println("updated \{lock.packages.length()} package(s)") } } ///| async fn run_project_command( ctx : Ctx, manifest_file : String, cmd_args : Array[String], locked : Bool, frozen : Bool, ) -> Int32 raise OrbitError { if cmd_args.length() == 0 { raise OrbitError("usage: orbit run [--locked|--frozen] [args...]") } let (project_dir, m, _) = ensure_project_synced( ctx, manifest_file, locked, frozen, true, ) let pbin = project_env_dir(project_dir) + "/bin" let cur_path = getenv("PATH") let new_path = if cur_path == "" { pbin } else { pbin + ":" + cur_path } let extra_env = Map([("PATH", new_path), ("ORBIT_PROJECT", project_dir)]) let first = cmd_args[0] let mut prog = first let run_args : Array[String] = [] match m.tasks.get(first) { Some(td) => match td.shell { Some(script) => { let sb = StringBuilder() sb.write_string(script) for i = 1; i < cmd_args.length(); i = i + 1 { sb.write_char(' ') sb.write_string(sq(cmd_args[i])) } prog = "sh" run_args.push("-c") run_args.push(sb.to_string()) } None => { prog = td.argv[0] for i = 1; i < td.argv.length(); i = i + 1 { run_args.push(td.argv[i]) } for i = 1; i < cmd_args.length(); i = i + 1 { run_args.push(cmd_args[i]) } } } None => for i = 1; i < cmd_args.length(); i = i + 1 { run_args.push(cmd_args[i]) } } if !has_char(prog, '/') { let local_bin = pbin + "/" + prog let is_exec = @fs.can_execute(local_bin) catch { _ => false } if is_exec { prog = local_bin } } try { @process.run( prog, run_args[:], extra_env~, inherit_env=true, stdin=@stdio.stdin, stdout=@stdio.stdout, stderr=@stdio.stderr, ) } catch { e => raise OrbitError("cannot run '\{prog}': \{e}") } } ///| async fn cmd_project_run( ctx : Ctx, manifest_file : String, cmd_args : Array[String], locked : Bool, frozen : Bool, ) -> Unit raise OrbitError { let code = run_project_command(ctx, manifest_file, cmd_args, locked, frozen) if code != 0 { c_exit(code) } } ///| async fn cmd_project_list( ctx : Ctx, manifest_file : String, ) -> Unit raise OrbitError { let (project_dir, m, _) = load_project(manifest_file, ctx.channels) let lock_path = project_dir + "/orbit.lock" match read_existing_lock(lock_path) { None => { if m.dependencies.length() == 0 { println("no dependencies in \{manifest_file}") } else { println("not locked yet (run `orbit install` or `orbit lock`)") } } Some(lock) => if lock.packages.length() == 0 { println("no packages in \{lock_path}") } else { for p in lock.packages { let kind = if m.dependencies.contains(p.name) { "" } else { " (dependency)" } let from = if p.channel == MAIN_CHANNEL { "" } else { " [\{p.channel}]" } println("\{p.name} \{p.version}\{from}\{kind}") } } } } ///| fn cmd_project_env(ctx : Ctx, manifest_file : String) -> Unit { let project_dir = path_dirname(manifest_file) let pbin = project_env_dir(project_dir) + "/bin" let gbin = bin_dir(ctx) println("export PATH=\"\{pbin}:\{gbin}:$PATH\"") } // ---------------------------------------------------------------- unit tests ///| test "orbit.toml and orbit.lock roundtrip" { let toml = #|[project] #|name = "my-app" #|version = "0.2.0" #|description = "Demo project" #|channels = ["example", "main"] #| #|[[channels]] #|name = "example" #|url = "localhost:5000/ex" #|plain-http = true #| #|[dependencies] #|hello = "^1.0.0" #|greet = { version = ">=1.0.0, <2.0.0", channel = "example" } #| #|[tasks] #|hi = "greet && hello" #|check = ["hello", "--flag"] let m = parse_project_manifest(toml, "fallback") assert_eq(m.name, "my-app") assert_eq(m.version, "0.2.0") assert_eq(m.project_channels, ["example", "main"]) assert_eq(m.channel_defs[0].plain_http, true) assert_eq(m.dependencies["greet"].channel, Some("example")) assert_eq(m.dependencies["greet"].constraint, ">=1.0.0, <2.0.0") assert_eq(m.tasks["hi"].shell, Some("greet && hello")) assert_eq(m.tasks["check"].argv, ["hello", "--flag"]) let m2 = parse_project_manifest(project_to_toml(m), "fallback") assert_eq(m2.name, m.name) assert_eq(m2.dependencies["greet"].channel, Some("example")) assert_eq(m2.tasks["check"].argv, ["hello", "--flag"]) let lock = Lockfile::{ version: 1, channels: [ Channel::{ name: "example", url: "localhost:5000/ex", plain_http: true }, Channel::{ name: "main", url: MAIN_URL, plain_http: false }, ], packages: [ LockedPkg::{ name: "greet", version: "1.0.1", tag: "1.0.1", channel: "example", url: "localhost:5000/ex", plain_http: true, digest: "sha256:aaaa", description: "Greeter", bins: ["bin/greet"], depends: Map([("main::hello", "^1.0.0")]), }, LockedPkg::{ name: "hello", version: "1.0.0", tag: "1.0.0", channel: "main", url: MAIN_URL, plain_http: false, digest: "sha256:bbbb", description: "", bins: ["bin/hello"], depends: Map([]), }, ], } let lock2 = parse_lockfile(lockfile_to_toml(lock)) assert_eq(lock2.version, 1) assert_eq(lock2.packages.length(), 2) assert_eq(lock2.packages[0].depends.get("main::hello"), Some("^1.0.0")) assert_eq(lock2.packages[0].plain_http, true) let chs = resolve_project_channels(m, [ Channel::{ name: MAIN_CHANNEL, url: MAIN_URL, plain_http: false }, ]) assert_true(lockfile_satisfies(lock2, m, chs)) // Changing dependency constraint invalidates lockfile check. m.dependencies["hello"].constraint = "^2.0.0" assert_false(lockfile_satisfies(lock2, m, chs)) } ///| test "orbit.toml accepts channel::pkg keys and rejects conflicting channels" { let ok = parse_project_manifest( "[dependencies]\n\"example::greet\" = \"^1.0\"\n", "app", ) assert_eq(ok.dependencies["greet"].channel, Some("example")) assert_eq(ok.dependencies["greet"].constraint, "^1.0") let conflict = try { parse_project_manifest( "[dependencies]\n\"example::greet\" = { version = \"^1.0\", channel = \"main\" }\n", "app", ) |> ignore false } catch { OrbitError(_) => true } assert_true(conflict) let dup = try { parse_project_manifest( "[dependencies]\ngreet = \"^1\"\n\"example::greet\" = \"^1\"\n", "app", ) |> ignore false } catch { OrbitError(_) => true } assert_true(dup) }