diff --git a/README.md b/README.md
index a89e469..a071e11 100644
--- a/README.md
+++ b/README.md
@@ -7,13 +7,14 @@ A small package manager written in MoonBit that uses any OCI registry (Gitea, GH
## 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 from the OCI registry to plan, then streams the layers by digest with SHA-256 verification.
-- **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/`.
+- **Lazy CDCL SAT solver:** resolves global and project dependency graphs with backtracking, conflict explanations, and `channel::pkg` dependency pins, reading only needed config blobs and caching immutable `sha256` manifests under `~/.orbit/cache/manifests/`.
+- **Pixi-style project environments:** `orbit new`, `orbit.toml` manifests, deterministic `orbit.lock` lockfiles, `[tasks]`, `orbit run`, and isolated `.orbit/bin/` environments symlinked from the shared store (`-g` / `--global` targets the global environment inside a project).
+- **Version constraints:** `1.2.3`, `=1.2.3`, `==1.2.3`, `1.2`, `1.2.*`, `^1.2.0`, `~1.2.0`, `>=1.2`, `<=2.0`, `>1.0`, `<2.0`, `!=1.3.0`, `*`, and comma-separated ranges (`>=1.2.0, <2.0.0`). Prereleases match only when the constraint mentions a `-`.
+- **Content-addressed store:** packages unpack into `~/.orbit/store///`, and their binaries are symlinked into `~/.orbit/bin/` (global) or `/.orbit/bin/` (project).
- **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.
+- **Upgrade and rollback:** global installs keep the previous two builds, and `orbit rollback ` switches back instantly with no network.
+- **Remove:** `orbit remove` refuses to delete what other global packages need and autoremoves orphaned dependencies; in projects it updates `orbit.toml` and `orbit.lock`.
+- **gc** deletes store builds that are neither globally current nor kept for rollback.
## Package format
@@ -52,6 +53,8 @@ Because these are ordinary OCI artifacts, you can sign them with `cosign` or `no
## Usage
+### Global environment
+
```sh
orbit login git.site.latha.org # once, with a Gitea token (needed to publish)
eval "$(orbit env)"
@@ -64,6 +67,40 @@ orbit rollback hello
orbit remove hello
```
+### Project workflow (Pixi-style)
+
+Inside a directory with `orbit.toml` (or pass `--manifest-path `), commands target the project unless you pass `-g` / `--global`:
+
+```sh
+orbit new myapp && cd myapp
+orbit add hello example::greet
+orbit run greet
+orbit lock --update
+orbit install --locked
+orbit update
+orbit remove hello
+```
+
+An `orbit.toml` looks like:
+
+```toml
+[project]
+name = "myapp"
+version = "0.1.0"
+channels = ["example", "main"]
+
+[[channels]]
+name = "example"
+url = "git.site.latha.org/nandi/example"
+
+[dependencies]
+hello = "^1.0.0"
+greet = { version = ">=1.0.0, <2.0.0", channel = "example" }
+
+[tasks]
+hi = "greet"
+```
+
Credentials are stored in `~/.orbit/auth.json` (`$ORBIT_ROOT/auth.json`, mode `0600`). Orbit also falls back to `~/.docker/config.json` (`$DOCKER_CONFIG/config.json`) including `credHelpers` and `credsStore`. Use `orbit logout ` to remove stored credentials from Orbit.
## Channels
@@ -159,12 +196,15 @@ src/main/
sha256.mbt streaming FIPS 180-4 SHA-256 (+ tests)
auth.mbt credentials store (~/.orbit/auth.json + Docker config fallback)
oci.mbt OCI Distribution v2 HTTP transport, Bearer/Basic auth, redirects
- semver.mbt versions, constraints, tag selection (+ tests)
+ semver.mbt versions, relational/compound constraints, tag selection (+ tests)
model.mbt orbit.json / state.json / config.json (+ tests)
- registry.mbt OCI registry ops: tags, resolve, fetch, publish, login verify
- ops.mbt dependency planner, install/remove/upgrade/rollback/gc
+ registry.mbt OCI registry ops: tags, resolve, cached manifests, fetch, publish, login
+ solver.mbt lazy Resolvo-style CDCL SAT solver & UNSAT explainer (+ tests)
+ ops.mbt SAT-backed global install/upgrade, remove/rollback/gc/search
+ project.mbt orbit.toml, orbit.lock, .orbit/ environments, project CLI (+ tests)
channels.mbt config.toml, channel priority and lookup (+ tests)
main.mbt CLI
+ registry_wbtest.mbt mock-OCI registry, SAT global, and project workflow tests
```
## Toolchain notes
@@ -178,7 +218,7 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp
## 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.
-- `orbit info ` reads installed package details without contacting the registry. Use `orbit versions ` to check published versions.
+- `orbit gc` only preserves global current and rollback builds (run `orbit install` / `orbit sync` in a project to re-populate missing store entries from its `orbit.lock`).
+- `orbit info ` reads globally installed package details without contacting the registry. Use `orbit versions ` to check published versions.
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions ` if you already know the package name.
diff --git a/src/main/main.mbt b/src/main/main.mbt
index 92acc9f..3e6efc3 100644
--- a/src/main/main.mbt
+++ b/src/main/main.mbt
@@ -4,8 +4,22 @@
let usage : String =
#|orbit - packages as OCI artifacts
#|
- #|usage:
- #| orbit init create folders and config.toml
+ #|usage (project workflow, when orbit.toml is present):
+ #| orbit new [dir] create a project orbit.toml
+ #| orbit add [channel::][@constraint]...
+ #| solve, pin in orbit.toml, lock & sync
+ #| orbit install [--locked | --frozen] sync .orbit/ from orbit.toml / orbit.lock
+ #| orbit sync [--locked | --frozen] same as `orbit install` in a project
+ #| orbit lock [--update] resolve and write orbit.lock
+ #| orbit update [name...] upgrade locked packages within constraints
+ #| orbit remove ... remove from orbit.toml, re-lock & sync
+ #| orbit run [--locked | --frozen] [args...]
+ #| run a command or [tasks] entry in .orbit
+ #| orbit list show locked project packages
+ #| orbit env print PATH for .orbit/bin + global bin
+ #|
+ #|usage (global & registry commands; add -g/--global inside a project):
+ #| orbit init [--project] create ~/.orbit (or --project for orbit.toml)
#| orbit login [-u ] [-p | --password-stdin] [--plain-http]
#| log in to an OCI registry
#| orbit logout remove stored registry credentials
@@ -13,19 +27,21 @@ let usage : String =
#| orbit channel add [--plain-http]
#| orbit publish [--channel ] [--no-latest]
#| push /orbit.json + /files/
- #| orbit install [channel::][@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 install [-g] [channel::][@constraint]...
+ #| install globally with SAT dependency solving
+ #| orbit remove [-g] ... [--force] remove, then drop unused dependencies
+ #| orbit upgrade [-g] [name...] jointly upgrade within constraints
+ #| orbit rollback switch to the previous global build
+ #| orbit list [-g] installed global packages
#| orbit info [channel::] installed package details (local only)
#| 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
+ #| orbit env [-g] print the PATH line for your shell
#|
- #|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 *
+ #|flags: -g, --global --manifest-path --locked --frozen
+ #|constraints: 1.2.3 =1.2.3 ==1.2.3 1.2.* ^1.2.0 ~1.2.0 >=1.2 <2.0 !=1.3.0 *
+ #| (comma-separated clauses are ANDed, e.g. ">=1.2.0, <2.0.0")
#|config: /config.toml
#|credentials: /auth.json (falls back to ~/.docker/config.json)
#|environment: ORBIT_ROOT (default ~/.orbit); ORBIT_REGISTRY and
@@ -62,6 +78,34 @@ fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError
}
}
+///|
+async fn resolve_project_or_none(
+ force_global : Bool,
+ manifest_path : String?,
+) -> String? raise OrbitError {
+ if force_global {
+ if manifest_path is Some(_) {
+ raise OrbitError("--global cannot be used with --manifest-path")
+ }
+ None
+ } else {
+ find_project_manifest(manifest_path)
+ }
+}
+
+///|
+async fn require_project_manifest(
+ manifest_path : String?,
+) -> String raise OrbitError {
+ match find_project_manifest(manifest_path) {
+ Some(mf) => mf
+ None =>
+ raise OrbitError(
+ "no orbit.toml found in current or parent directories (run `orbit new` to create one)",
+ )
+ }
+}
+
///|
async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
if args.length() == 0 {
@@ -74,10 +118,35 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
let mut publish_to = MAIN_CHANNEL
let mut username : String? = None
let mut password : String? = None
+ let mut force_global = false
+ let mut manifest_path : String? = None
let mut i = 1
while i < args.length() {
+ if cmd == "run" && pos.length() > 0 {
+ // Forward all flags/args after the command/task name verbatim.
+ pos.push(args[i])
+ i = i + 1
+ continue
+ }
let a = args[i]
- if a == "--channel" {
+ if a == "--" {
+ i = i + 1
+ while i < args.length() {
+ pos.push(args[i])
+ i = i + 1
+ }
+ break
+ } else if a == "-g" || a == "--global" {
+ force_global = true
+ } else if a == "--manifest-path" {
+ if i + 1 >= args.length() {
+ raise OrbitError("usage: --manifest-path ")
+ }
+ manifest_path = Some(args[i + 1])
+ i = i + 1
+ } else if has_prefix(a, "--manifest-path=") {
+ manifest_path = Some(drop_chars(a, 16))
+ } else if a == "--channel" {
if cmd != "publish" || i + 1 >= args.length() {
raise OrbitError("usage: orbit publish --channel ")
}
@@ -118,14 +187,23 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
}
match cmd {
"help" | "-h" | "--help" => println(usage)
- "init" => {
- if pos.length() > 0 {
- raise OrbitError(
- "init takes no arguments; use `orbit channel add `",
- )
+ "new" => {
+ if force_global {
+ raise OrbitError("--global cannot be used with `orbit new`")
}
- cmd_init()
+ cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
}
+ "init" =>
+ if flags.contains("--project") {
+ cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
+ } else {
+ if pos.length() > 0 {
+ raise OrbitError(
+ "init takes no arguments; use `orbit channel add ` or `orbit new `",
+ )
+ }
+ cmd_init()
+ }
"login" => {
need(
pos,
@@ -160,20 +238,90 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
other => raise OrbitError("unknown channel command '\{other}'")
}
}
- "env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
+ "lock" => {
+ if force_global {
+ raise OrbitError("--global cannot be used with `orbit lock`")
+ }
+ let mf = require_project_manifest(manifest_path)
+ cmd_project_lock(load_ctx(), mf, flags.contains("--update"))
+ }
+ "sync" => {
+ if force_global {
+ raise OrbitError("--global cannot be used with `orbit sync`")
+ }
+ let mf = require_project_manifest(manifest_path)
+ cmd_project_sync(
+ load_ctx(),
+ mf,
+ flags.contains("--locked"),
+ flags.contains("--frozen"),
+ )
+ }
+ "run" => {
+ if force_global {
+ raise OrbitError("--global cannot be used with `orbit run`")
+ }
+ let mf = require_project_manifest(manifest_path)
+ need(pos, 1, "run [--locked|--frozen] [args...]")
+ cmd_project_run(
+ load_ctx(),
+ mf,
+ pos,
+ flags.contains("--locked"),
+ flags.contains("--frozen"),
+ )
+ }
+ "env" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) => cmd_project_env(load_ctx(), mf)
+ None => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
+ }
"publish" => {
need(pos, 1, "publish ")
let ch = find_channel(load_ctx(), publish_to)
publish(ch, pos[0], !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)
+ "install" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) =>
+ if pos.length() == 0 {
+ cmd_project_sync(
+ load_ctx(),
+ mf,
+ flags.contains("--locked"),
+ flags.contains("--frozen"),
+ )
+ } else {
+ raise OrbitError(
+ "in a project (found \{mf}), use `orbit add ...` to add dependencies or `orbit install -g ...` to install globally",
+ )
+ }
+ None => cmd_install(load_ctx(), pos)
+ }
+ "add" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) => cmd_project_add(load_ctx(), mf, pos)
+ None => cmd_install(load_ctx(), pos)
+ }
+ "remove" | "rm" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) => cmd_project_remove(load_ctx(), mf, pos)
+ None => cmd_remove(load_ctx(), pos, flags.contains("--force"))
+ }
+ "upgrade" | "up" | "update" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) => cmd_project_update(load_ctx(), mf, pos)
+ None => cmd_upgrade(load_ctx(), pos)
+ }
"rollback" => {
need(pos, 1, "rollback ")
cmd_rollback(load_ctx(), pos[0])
}
- "list" | "ls" => cmd_list(load_ctx())
+ "list" | "ls" =>
+ match resolve_project_or_none(force_global, manifest_path) {
+ Some(mf) => cmd_project_list(load_ctx(), mf)
+ None => cmd_list(load_ctx())
+ }
"info" => {
need(pos, 1, "info [channel::]")
cmd_info(load_ctx(), pos[0])
diff --git a/src/main/model.mbt b/src/main/model.mbt
index 2a2d10b..a3d7d61 100644
--- a/src/main/model.mbt
+++ b/src/main/model.mbt
@@ -179,6 +179,21 @@ fn valid_rel_path(p : String) -> Bool {
true
}
+///|
+/// Split a dependency key "[channel::]name" into (channel_pin, package_name).
+fn parse_dep_key(key : String) -> (String?, String) {
+ split_channel(key)
+}
+
+///|
+fn valid_dep_key(key : String) -> Bool {
+ let (ch, name) = parse_dep_key(key)
+ match ch {
+ Some(c) => valid_name(c) && valid_name(name)
+ None => valid_name(name)
+ }
+}
+
///|
fn parse_manifest(text : String) -> Manifest raise OrbitError {
let o = parse_object(text, "orbit.json")
@@ -203,10 +218,15 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError {
raise OrbitError("orbit.json: bin path '\{b}' must be relative")
}
}
- for dep, _ in m.depends {
- if !valid_name(dep) {
+ for dep, constraint in m.depends {
+ if !valid_dep_key(dep) {
raise OrbitError("orbit.json: invalid dependency name '\{dep}'")
}
+ if !valid_constraint(constraint) {
+ raise OrbitError(
+ "orbit.json: invalid version constraint '\{constraint}' for '\{dep}'",
+ )
+ }
}
m
}
@@ -367,15 +387,45 @@ fn bin_dir(ctx : Ctx) -> String {
ctx.root + "/bin"
}
+///|
+fn cache_dir(root : String) -> String {
+ root + "/cache/manifests"
+}
+
///|
test "manifest roundtrip" {
let m = parse_manifest(
- "{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\"}}",
+ "{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\",\"example::greet\":\">=1.0.0, <2.0.0\"}}",
)
assert_eq(m.name, "hello")
assert_eq(m.bins, ["bin/hello"])
assert_eq(m.depends.get("lib"), Some("^1"))
+ assert_eq(m.depends.get("example::greet"), Some(">=1.0.0, <2.0.0"))
+ assert_eq(parse_dep_key("example::greet"), (Some("example"), "greet"))
+ assert_eq(parse_dep_key("lib"), (None, "lib"))
assert_true(!valid_rel_path("../x"))
assert_true(!valid_rel_path("/bin/sh"))
assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef")
+
+ let bad_dep = try {
+ parse_manifest(
+ "{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"BadName\":\"^1\"}}",
+ )
+ |> ignore
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(bad_dep)
+
+ let bad_con = try {
+ parse_manifest(
+ "{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"lib\":\">=abc\"}}",
+ )
+ |> ignore
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(bad_con)
}
diff --git a/src/main/ops.mbt b/src/main/ops.mbt
index 179a9af..dad56b8 100644
--- a/src/main/ops.mbt
+++ b/src/main/ops.mbt
@@ -8,19 +8,11 @@ struct Step {
version : String
digest : String
manifest : Manifest
- mut explicit : Bool
- mut constraint : String
+ explicit : Bool
+ 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::{
@@ -34,172 +26,217 @@ 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] {
- 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)
+/// "[channel::]name[@constraint]" -> (channel, name, constraint, has_explicit_constraint)
+fn parse_spec_full(
+ spec : String,
+) -> (String?, String, String, Bool) raise OrbitError {
+ let (channel, rest) = split_channel(spec)
+ match channel {
+ Some(ch) =>
+ if !valid_name(ch) {
+ raise OrbitError("invalid channel name '\{ch}'")
}
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 => ()
+ let (name, c) = split_first(rest, '@')
+ if !valid_name(name) {
+ raise OrbitError("invalid package name '\{name}'")
+ }
+ if c == "" {
+ (channel, name, "*", false)
+ } else {
+ if !valid_constraint(c) {
+ raise OrbitError("invalid version constraint '\{c}' for '\{name}'")
}
+ (channel, name, c, true)
}
- for other, st in p.steps {
- if other != name && !p.ctx.state.contains(other) {
- match st.manifest.depends.get(name) {
- Some(c) => cons.push(c)
- None => ()
- }
- }
- }
- cons
-}
-
-///|
-async fn visit(
- p : Planner,
- name : String,
- requested : String,
- explicit : Bool,
- pin : String?, // channel the user asked for
-) -> Unit raise OrbitError {
- match p.steps.get(name) {
- Some(st) => {
- if pin is Some(c) && c != st.channel {
- raise OrbitError(
- "conflict: \{name} is planned from channel '\{st.channel}' but '\{c}' was requested",
- )
- }
- if !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) => {
- let same_channel = match pin {
- Some(c) => c == inst.channel
- None => true
- }
- if !upgrading && same_channel && satisfies_all(inst.version, cons) {
- let st = Step::{
- name,
- channel: inst.channel,
- 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 => ()
- }
- // An installed package stays on its channel unless the user names another.
- let wanted = match pin {
- Some(c) => Some(c)
- None => p.ctx.state.get(name).map(fn(i) { i.channel })
- }
- let (ch, tags) = locate(p.ctx, name, wanted)
- let tag = match pick_tag(tags, cons) {
- Some(t) => t
- None => {
- let avail = sorted_versions(tags)
- raise OrbitError(
- "no version of \{name} in channel '\{ch.name}' satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}",
- )
- }
- }
- let digest = resolve_digest(ch, name, tag)
- let prev = p.ctx.state.get(name)
- // An unchanged build with a saved description needs no metadata fetch.
- let m = match prev {
- Some(i) =>
- if i.digest == digest && i.description != "" {
- manifest_of_installed(i)
- } else {
- fetch_manifest(ch, name, digest)
- }
- None => fetch_manifest(ch, name, digest)
- }
- let st = Step::{
- name,
- channel: ch.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, None)
- }
- p.order.push(st)
}
///|
/// "[channel::]name[@constraint]"
fn parse_spec(spec : String) -> (String?, String, String) raise OrbitError {
- let (channel, rest) = split_channel(spec)
- let (name, c) = split_first(rest, '@')
- if !valid_name(name) {
- raise OrbitError("invalid package name '\{name}'")
+ let (channel, name, c, _) = parse_spec_full(spec)
+ (channel, name, c)
+}
+
+///|
+/// Build a SAT-solved install/upgrade plan for global state.
+async fn plan_global(
+ ctx : Ctx,
+ req_specs : Array[(String?, String, String, String)],
+ upgrade : Array[String],
+ explicit_new : Map[String, String],
+) -> Array[Step] raise OrbitError {
+ let ch_by_name : Map[String, Channel] = Map([])
+ for c in ctx.channels {
+ ch_by_name[c.name] = c
}
- (channel, name, if c == "" { "*" } else { c })
+ let tags_cache : Map[String, (Channel, Array[String])] = Map([])
+ let digest_cache : Map[String, String] = Map([])
+ let manifest_cache : Map[String, Manifest] = Map([])
+
+ let locked_bins : Map[String, String] = Map([])
+ for name, inst in ctx.state {
+ if !upgrade.contains(name) && !explicit_new.contains(name) {
+ for b in inst.bins {
+ locked_bins[basename(b)] = name
+ }
+ }
+ }
+
+ let provider = SolverProvider::{
+ candidates: async fn(name, pin) {
+ let wanted = match pin {
+ Some(c) => Some(c)
+ None =>
+ match ctx.state.get(name) {
+ Some(inst) => Some(inst.channel)
+ None => None
+ }
+ }
+ let cache_key = name + "|" + wanted.unwrap_or("")
+ let (ch, tags) = match tags_cache.get(cache_key) {
+ Some(pair) => pair
+ None => {
+ let pair = locate(ctx, name, wanted)
+ tags_cache[cache_key] = pair
+ ch_by_name[pair.0.name] = pair.0
+ pair
+ }
+ }
+ let favored = if upgrade.contains(name) {
+ None
+ } else {
+ match ctx.state.get(name) {
+ Some(inst) =>
+ if inst.channel == ch.name {
+ Some((inst.channel, inst.version, inst.digest))
+ } else {
+ None
+ }
+ None => None
+ }
+ }
+ (ch.name, candidates_from_tags(name, ch.name, tags, favored))
+ },
+ details: async fn(cand) {
+ if false {
+ @async.sleep(0)
+ }
+ if cand.favored && cand.digest != "" {
+ match ctx.state.get(cand.name) {
+ Some(inst) =>
+ if inst.digest == cand.digest && inst.channel == cand.channel {
+ return CandidateDetail::{
+ digest: cand.digest,
+ manifest: manifest_of_installed(inst),
+ }
+ }
+ None => ()
+ }
+ }
+ let ch = match ch_by_name.get(cand.channel) {
+ Some(c) => c
+ None => find_channel(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 m = match manifest_cache.get(mkey) {
+ Some(mf) => mf
+ None => {
+ let mf = fetch_manifest_cached(ctx.root, ch, cand.name, digest)
+ manifest_cache[mkey] = mf
+ mf
+ }
+ }
+ CandidateDetail::{ digest, manifest: m }
+ },
+ extra_reqs: fn(pkg_name) {
+ let reqs : Array[SolveReq] = []
+ match ctx.state.get(pkg_name) {
+ Some(inst) =>
+ if inst.explicit && !explicit_new.contains(pkg_name) {
+ reqs.push(SolveReq::{
+ name: pkg_name,
+ channel: Some(inst.channel),
+ constraint: if inst.constraint == "" {
+ "*"
+ } else {
+ inst.constraint
+ },
+ label: "installed \{pkg_name}",
+ })
+ }
+ None => ()
+ }
+ for other, oinst in ctx.state {
+ if other != pkg_name &&
+ !upgrade.contains(other) &&
+ !explicit_new.contains(other) {
+ for dk, dc in oinst.depends {
+ let (dch, dname) = parse_dep_key(dk)
+ if dname == pkg_name {
+ reqs.push(SolveReq::{
+ name: pkg_name,
+ channel: dch,
+ constraint: dc,
+ label: "installed \{other} \{oinst.version}",
+ })
+ }
+ }
+ }
+ }
+ reqs
+ },
+ locked_bins,
+ }
+
+ let reqs : Array[SolveReq] = []
+ for item in req_specs {
+ let (pin, name, constraint, label) = item
+ reqs.push(SolveReq::{ name, channel: pin, constraint, label })
+ }
+ let solved = solve(reqs, provider)
+ let steps : Array[Step] = []
+ for sp in solved {
+ let prev = ctx.state.get(sp.name)
+ let explicit = explicit_new.contains(sp.name) ||
+ (match prev {
+ Some(i) => i.explicit
+ None => false
+ })
+ let constraint = match explicit_new.get(sp.name) {
+ Some(c) => c
+ None =>
+ match prev {
+ Some(i) => i.constraint
+ None => "*"
+ }
+ }
+ let keep = match prev {
+ Some(i) => i.digest == sp.digest && i.channel == sp.channel
+ None => false
+ }
+ steps.push(Step::{
+ name: sp.name,
+ channel: sp.channel,
+ version: sp.version,
+ digest: sp.digest,
+ manifest: sp.manifest,
+ explicit,
+ constraint,
+ keep,
+ })
+ }
+ steps
}
///|
@@ -321,9 +358,9 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
}
///|
-async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
+async fn apply_plan(ctx : Ctx, steps : Array[Step]) -> Unit raise OrbitError {
let mut changed = 0
- for st in p.order {
+ for st in steps {
if st.keep {
match ctx.state.get(st.name) {
Some(inst) => {
@@ -345,57 +382,106 @@ async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
}
}
-///|
-fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner {
- Planner::{ ctx, steps: Map([]), order: [], upgrade, }
-}
-
///|
async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError {
if specs.length() == 0 {
raise OrbitError("usage: orbit install [channel::][@constraint]...")
}
- let p = new_planner(ctx, [])
+ let reqs : Array[(String?, String, String, String)] = []
+ let explicit_new : Map[String, String] = Map([])
for s in specs {
let (channel, name, c) = parse_spec(s)
- visit(p, name, c, true, channel)
+ reqs.push((channel, name, c, "command line"))
+ explicit_new[name] = c
}
- apply_plan(ctx, p)
+ let steps = plan_global(ctx, reqs, [], explicit_new)
+ apply_plan(ctx, steps)
}
///|
-/// Upgrade the named packages (or everything) to the newest versions their
-/// constraints allow. Dependencies are moved only when required.
+/// Upgrade the named packages (or everything) jointly to the newest versions
+/// their constraints allow.
async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError {
let targets : Array[String] = []
+ let reqs : Array[(String?, String, String, String)] = []
if names.length() == 0 {
- for name, _ in ctx.state {
+ if ctx.state.length() == 0 {
+ println("no packages installed")
+ return
+ }
+ let mut has_explicit = false
+ for name, inst in ctx.state {
targets.push(name)
+ if inst.explicit {
+ has_explicit = true
+ reqs.push((
+ Some(inst.channel),
+ name,
+ if inst.constraint == "" {
+ "*"
+ } else {
+ inst.constraint
+ },
+ "installed \{name}",
+ ))
+ }
+ }
+ if !has_explicit {
+ for name, inst in ctx.state {
+ reqs.push((
+ Some(inst.channel),
+ name,
+ if inst.constraint == "" {
+ "*"
+ } else {
+ inst.constraint
+ },
+ "installed \{name}",
+ ))
+ }
}
} else {
for n in names {
- if !ctx.state.contains(n) {
- raise OrbitError("\{n} is not installed")
+ let inst = match ctx.state.get(n) {
+ Some(i) => i
+ None => raise OrbitError("\{n} is not installed")
}
targets.push(n)
+ reqs.push((
+ Some(inst.channel),
+ n,
+ if inst.constraint == "" {
+ "*"
+ } else {
+ inst.constraint
+ },
+ "installed \{n}",
+ ))
}
}
- let p = new_planner(ctx, targets)
- for n in targets {
- match ctx.state.get(n) {
- Some(inst) => visit(p, n, "*", inst.explicit, None)
- None => ()
- }
+ let steps = plan_global(ctx, reqs, targets, Map([]))
+ apply_plan(ctx, steps)
+ if names.length() == 0 {
+ autoremove(ctx)
+ save_state(ctx)
}
- 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)
+ if other != name {
+ let mut uses = false
+ for dk, _ in p.depends {
+ if parse_dep_key(dk).1 == name {
+ uses = true
+ break
+ }
+ }
+ if uses {
+ r.push(other)
+ }
}
}
r
@@ -506,7 +592,8 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
println("\{name}: \{from} -> \{prev.version}")
let missing : Array[String] = []
for dep, c in inst.depends {
- match ctx.state.get(dep) {
+ let (_, dep_name) = parse_dep_key(dep)
+ match ctx.state.get(dep_name) {
Some(d) =>
if !satisfies_all(d.version, [c]) {
missing.push(dep + "@" + c)
diff --git a/src/main/project.mbt b/src/main/project.mbt
new file mode 100644
index 0000000..9253692
--- /dev/null
+++ b/src/main/project.mbt
@@ -0,0 +1,1653 @@
+// 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)
+}
diff --git a/src/main/registry.mbt b/src/main/registry.mbt
index 99b459a..f7d05a7 100644
--- a/src/main/registry.mbt
+++ b/src/main/registry.mbt
@@ -284,13 +284,33 @@ async fn fetch_raw_manifest(
utf8_decode(fetch_raw_manifest_bytes(ch, name, ref_str))
}
+///|
+fn manifest_cache_path(root : String, digest : String) -> String? {
+ if root == "" || !has_prefix(digest, "sha256:") {
+ return None
+ }
+ let hex = drop_chars(digest, 7)
+ if hex == "" {
+ return None
+ }
+ for c in hex {
+ let ok = (c >= '0' && c <= '9') ||
+ (c >= 'a' && c <= 'f') ||
+ (c >= 'A' && c <= 'F')
+ if !ok {
+ return None
+ }
+ }
+ Some(cache_dir(root) + "/" + ascii_lower(hex) + ".json")
+}
+
///|
/// Fetch only the config blob (orbit.json); no layer download needed to plan.
-async fn fetch_manifest(
+async fn fetch_manifest_with_raw(
ch : Channel,
name : String,
digest : String,
-) -> Manifest raise OrbitError {
+) -> (Manifest, String) raise OrbitError {
with_spinner("Reading metadata for \{ch.name}::\{name}", () => {
let repo = channel_repo_path(ch, name)
let manifest_text = fetch_raw_manifest(ch, name, digest)
@@ -323,16 +343,55 @@ async fn fetch_manifest(
)
}
}
- let m = parse_manifest(utf8_decode(body))
+ let raw = utf8_decode(body)
+ let m = parse_manifest(raw)
if m.name != name {
raise OrbitError(
"\{name}@\{digest} declares name '\{m.name}'; refusing to install",
)
}
- m
+ (m, raw)
})
}
+///|
+/// Fetch config blob (orbit.json) using a digest-keyed local cache under
+/// `/cache/manifests/.json`. Pass `root = ""` to skip caching.
+async fn fetch_manifest_cached(
+ root : String,
+ ch : Channel,
+ name : String,
+ digest : String,
+) -> Manifest raise OrbitError {
+ match manifest_cache_path(root, digest) {
+ Some(path) =>
+ match read_text(path) {
+ Some(raw) => {
+ let cached : Manifest? = Some(parse_manifest(raw)) catch { _ => None }
+ match cached {
+ Some(m) => if m.name == name { return m }
+ None => ()
+ }
+ }
+ None => ()
+ }
+ None => ()
+ }
+ let (m, raw) = fetch_manifest_with_raw(ch, name, digest)
+ match manifest_cache_path(root, digest) {
+ Some(path) => {
+ try {
+ @fs.mkdir(cache_dir(root), recursive=true, allow_exist=true)
+ write_text_atomic(path, raw)
+ } catch {
+ _ => ()
+ }
+ }
+ None => ()
+ }
+ m
+}
+
///|
fn find_pkg_layer_digest(manifest_obj : Map[String, Json]) -> String? {
let layers = match manifest_obj.get("layers") {
diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt
index cdd9528..f5aaa29 100644
--- a/src/main/registry_wbtest.mbt
+++ b/src/main/registry_wbtest.mbt
@@ -185,13 +185,15 @@ async test "native OCI publish, search catalog, tags pagination, resolve, and in
let d2 = resolve_digest(ch, "mytool", "1.2.0")
assert_eq(d1, d2)
- let mf = fetch_manifest(ch, "mytool", d1)
+ let mf = fetch_manifest_cached("", ch, "mytool", d1)
assert_eq(mf.name, "mytool")
assert_eq(mf.version, "1.2.0")
assert_eq(mf.description, "Mock OCI tool")
assert_eq(mf.bins, ["bin/mytool"])
let orbit_dir = work + "/orbit"
+ let mf_cached = fetch_manifest_cached(orbit_dir, ch, "mytool", d1)
+ assert_eq(mf_cached.version, "1.2.0")
let ctx = Ctx::{ root: orbit_dir, channels: [ch], state: Map([]) }
let installed_dir = fetch_into_store(ctx, ch, "mytool", d1)
assert_true(exists(installed_dir + "/bin/mytool"))
@@ -374,3 +376,497 @@ async test "channel locate falls through on 404 and fails on 500" {
assert_true(failed)
})
}
+
+///|
+fn split_sub(s : String, sep : String) -> (String, String)? {
+ let a = chars(s)
+ let b = chars(sep)
+ if b.length() == 0 || a.length() < b.length() {
+ return None
+ }
+ 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 Some((slice(a, 0, i), slice(a, i + b.length(), a.length())))
+ }
+ }
+ None
+}
+
+///|
+struct MockOciState {
+ blobs : Map[String, Bytes]
+ manifests : Map[String, Map[String, (String, Bytes)]]
+ tags : Map[String, Array[String]]
+ blob_gets : Ref[Int32]
+}
+
+///|
+fn new_mock_oci_state() -> MockOciState {
+ MockOciState::{
+ blobs: Map([]),
+ manifests: Map([]),
+ tags: Map([]),
+ blob_gets: Ref(0),
+ }
+}
+
+///|
+async fn handle_mock_oci(
+ st : MockOciState,
+ upload_seq : Ref[Int32],
+ req : @http.Request,
+ req_bytes : Bytes,
+ conn : @http.ServerConnection,
+) -> Unit {
+ let (path, query) = strip_query(req.path)
+ if req.meth is Get && path == "/v2/_catalog" {
+ let repos : Array[Json] = []
+ for r, _ in st.tags {
+ repos.push(Json::string(r))
+ }
+ let top : Map[String, Json] = Map([])
+ top["repositories"] = Json::array(repos)
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write(Json::object(top).stringify())
+ conn.end_response()
+ return
+ }
+ if !has_prefix(path, "/v2/") {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ return
+ }
+ let rest = drop_chars(path, 4)
+ match split_sub(rest, "/tags/list") {
+ Some((repo, "")) =>
+ match st.tags.get(repo) {
+ Some(ts) => {
+ let jtags = ts.map(fn(t) { Json::string(t) })
+ let obj : Map[String, Json] = Map([])
+ obj["name"] = Json::string(repo)
+ obj["tags"] = Json::array(jtags)
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/json",
+ })
+ conn.write(Json::object(obj).stringify())
+ conn.end_response()
+ return
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ return
+ }
+ }
+ _ => ()
+ }
+ match split_sub(rest, "/blobs/uploads/") {
+ Some((repo, _id)) => {
+ if req.meth is Post {
+ upload_seq.val = upload_seq.val + 1
+ conn.send_response(202, "Accepted", extra_headers={
+ "Location": "/v2/" + repo + "/blobs/uploads/" + upload_seq.val.to_string(),
+ })
+ conn.end_response()
+ return
+ }
+ if req.meth is Put {
+ let (_, dq) = split_first(query, '=')
+ let digest = @percent.decode(dq) catch { _ => "" }
+ st.blobs[repo + "|" + digest] = req_bytes
+ conn.send_response(201, "Created", extra_headers={
+ "Docker-Content-Digest": digest,
+ })
+ conn.end_response()
+ return
+ }
+ }
+ None => ()
+ }
+ match split_sub(rest, "/blobs/") {
+ Some((repo, digest)) => {
+ match st.blobs.get(repo + "|" + digest) {
+ Some(data) => {
+ if !(req.meth is Head) {
+ st.blob_gets.val = st.blob_gets.val + 1
+ }
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": "application/octet-stream",
+ "Docker-Content-Digest": digest,
+ "Content-Length": data.length().to_string(),
+ })
+ if !(req.meth is Head) {
+ conn.write(data)
+ }
+ conn.end_response()
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ }
+ }
+ return
+ }
+ None => ()
+ }
+ match split_sub(rest, "/manifests/") {
+ Some((repo, ref_str)) => {
+ if req.meth is Put {
+ let d = sha256_digest(req_bytes)
+ let repo_map = match st.manifests.get(repo) {
+ Some(m) => m
+ None => {
+ let m : Map[String, (String, Bytes)] = Map([])
+ st.manifests[repo] = m
+ m
+ }
+ }
+ repo_map[ref_str] = (d, req_bytes)
+ repo_map[d] = (d, req_bytes)
+ let ts = match st.tags.get(repo) {
+ Some(xs) => xs
+ None => {
+ let xs : Array[String] = []
+ st.tags[repo] = xs
+ xs
+ }
+ }
+ if !ts.contains(ref_str) {
+ ts.push(ref_str)
+ }
+ conn.send_response(201, "Created", extra_headers={
+ "Docker-Content-Digest": d,
+ })
+ conn.end_response()
+ return
+ }
+ match st.manifests.get(repo) {
+ Some(repo_map) =>
+ match repo_map.get(ref_str) {
+ Some((d, data)) => {
+ conn.send_response(200, "OK", extra_headers={
+ "Content-Type": OCI_MANIFEST_MEDIA_TYPE,
+ "Docker-Content-Digest": d,
+ "Content-Length": data.length().to_string(),
+ })
+ if !(req.meth is Head) {
+ conn.write(data)
+ }
+ conn.end_response()
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ }
+ }
+ None => {
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+ }
+ }
+ return
+ }
+ None => ()
+ }
+ conn.send_response(404, "Not Found")
+ conn.end_response()
+}
+
+///|
+async fn publish_mock_pkg(
+ ch : Channel,
+ work : String,
+ name : String,
+ version : String,
+ depends : Map[String, String],
+ bins : Array[String],
+ script? : String = "#!/bin/sh\necho ok\n",
+) -> Unit raise Error {
+ let pkg_dir = work + "/stage-" + name + "-" + version
+ @fs.mkdir(pkg_dir + "/files/bin", recursive=true)
+ let mf_obj : Map[String, Json] = Map([])
+ mf_obj["name"] = Json::string(name)
+ mf_obj["version"] = Json::string(version)
+ mf_obj["description"] = Json::string("Mock " + name + " " + version)
+ mf_obj["bin"] = strs_json(bins)
+ mf_obj["depends"] = map_json(depends)
+ @fs.write_file(
+ pkg_dir + "/orbit.json",
+ Json::object(mf_obj).stringify(indent=2) + "\n",
+ create_mode=CreateOrTruncate,
+ )
+ for b in bins {
+ let p = pkg_dir + "/files/" + b
+ @fs.mkdir(path_dirname(p), recursive=true, allow_exist=true)
+ @fs.write_file(p, script, create_mode=CreateOrTruncate, permission=0o755)
+ }
+ publish(ch, pkg_dir, true)
+}
+
+///|
+async test "SAT global install, backtracking, manifest cache, and joint upgrade" {
+ token_cache.clear()
+ let work = @fs.tmpdir(prefix="orbit-wb-sat-global-")
+ defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
+
+ let st = new_mock_oci_state()
+ let upload_seq = Ref(0)
+ let server = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ @async.with_task_group(group => {
+ defer server.close()
+ group.spawn_bg(no_wait=true, () => {
+ server.run_forever((req, body, conn) => {
+ let req_bytes = body.read_all().binary()
+ handle_mock_oci(st, upload_seq, req, req_bytes, conn)
+ })
+ })
+ let addr = "127.0.0.1:" + server.addr.port().to_string()
+ let main_ch = Channel::{
+ name: "main",
+ url: addr + "/main",
+ plain_http: true,
+ }
+ let extra_ch = Channel::{
+ name: "extra",
+ url: addr + "/extra",
+ plain_http: true,
+ }
+
+ publish_mock_pkg(main_ch, work, "lib", "1.0.0", Map([]), [])
+ publish_mock_pkg(main_ch, work, "lib", "2.0.0", Map([]), [])
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "app",
+ "1.0.0",
+ Map([("lib", "^1.0")]),
+ ["bin/app"],
+ script="#!/bin/sh\necho app-1.0.0\n",
+ )
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "app",
+ "2.0.0",
+ Map([("lib", "^2.0")]),
+ ["bin/app"],
+ script="#!/bin/sh\necho app-2.0.0\n",
+ )
+ publish_mock_pkg(
+ extra_ch,
+ work,
+ "helper",
+ "1.0.0",
+ Map([("main::lib", "^1.0")]),
+ ["bin/helper"],
+ script="#!/bin/sh\necho helper-1.0.0\n",
+ )
+
+ let orbit_root = work + "/orbit"
+ let ctx = Ctx::{
+ root: orbit_root,
+ channels: [main_ch, extra_ch],
+ state: Map([]),
+ }
+ cmd_install(ctx, ["app", "helper"])
+ assert_eq(ctx.state["app"].version, "1.0.0")
+ assert_eq(ctx.state["helper"].version, "1.0.0")
+ assert_eq(ctx.state["helper"].channel, "extra")
+ assert_eq(ctx.state["lib"].version, "1.0.0")
+ assert_true(exists(orbit_root + "/bin/app"))
+ assert_true(exists(orbit_root + "/bin/helper"))
+ let cached_files = @fs.readdir(cache_dir(orbit_root))
+ assert_true(cached_files.length() > 0)
+
+ // Verify digest-keyed manifest cache avoids HTTP blob GET on re-solve.
+ let gets_before = st.blob_gets.val
+ let _ = fetch_manifest_cached(
+ orbit_root,
+ main_ch,
+ "app",
+ ctx.state["app"].digest,
+ )
+ assert_eq(st.blob_gets.val, gets_before)
+
+ // Publish helper 2.0.0 compatible with lib ^2.0, then upgrade jointly.
+ publish_mock_pkg(
+ extra_ch,
+ work,
+ "helper",
+ "2.0.0",
+ Map([("main::lib", "^2.0")]),
+ ["bin/helper"],
+ script="#!/bin/sh\necho helper-2.0.0\n",
+ )
+ cmd_upgrade(ctx, [])
+ assert_eq(ctx.state["app"].version, "2.0.0")
+ assert_eq(ctx.state["helper"].version, "2.0.0")
+ assert_eq(ctx.state["lib"].version, "2.0.0")
+ })
+}
+
+///|
+async test "Pixi-style project workflow: new, add, sync --locked, run, update, remove" {
+ try {
+ token_cache.clear()
+ let work = @fs.tmpdir(prefix="orbit-wb-project-")
+ defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
+
+ let st = new_mock_oci_state()
+ let upload_seq = Ref(0)
+ let server = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
+ @async.with_task_group(group => {
+ defer server.close()
+ group.spawn_bg(no_wait=true, () => {
+ server.run_forever((req, body, conn) => {
+ let req_bytes = body.read_all().binary()
+ handle_mock_oci(st, upload_seq, req, req_bytes, conn)
+ })
+ })
+ let addr = "127.0.0.1:" + server.addr.port().to_string()
+ let main_ch = Channel::{
+ name: "main",
+ url: addr + "/main",
+ plain_http: true,
+ }
+
+ publish_mock_pkg(main_ch, work, "lib", "1.0.0", Map([]), [])
+ publish_mock_pkg(main_ch, work, "lib", "2.0.0", Map([]), [])
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "app",
+ "1.0.0",
+ Map([("lib", "^1.0")]),
+ ["bin/app"],
+ script="#!/bin/sh\necho proj-app-1\n",
+ )
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "app",
+ "2.0.0",
+ Map([("lib", "^2.0")]),
+ ["bin/app"],
+ script="#!/bin/sh\necho proj-app-2\n",
+ )
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "helper",
+ "1.0.0",
+ Map([("lib", "^1.0")]),
+ ["bin/helper"],
+ script="#!/bin/sh\nexit 0\n",
+ )
+
+ let proj = work + "/proj"
+ cmd_project_init(Some(proj))
+ let mf = proj + "/orbit.toml"
+ assert_true(exists(mf))
+
+ // Configure project channel + tasks.
+ let m0 = parse_project_manifest(
+ "[project]\nname = \"proj\"\nversion = \"0.1.0\"\n\n[[channels]]\nname = \"main\"\nurl = \"" +
+ main_ch.url +
+ "\"\nplain-http = true\n\n[dependencies]\n\n[tasks]\nshow = \"app\"\ncheck = [\"helper\", \"--ok\"]\n",
+ "proj",
+ )
+ write_text_atomic(mf, project_to_toml(m0))
+
+ let orbit_root = work + "/orbit"
+ let ctx = Ctx::{ root: orbit_root, channels: [main_ch], state: Map([]) }
+
+ // Discovery via explicit directory & manifest path.
+ assert_eq(find_project_manifest(Some(proj)).unwrap(), mf)
+ assert_eq(find_project_manifest(Some(mf)).unwrap(), mf)
+
+ // Add packages -> SAT solver picks 1.0.0 + 1.0.0 + lib 1.0.0, pins ^1.0.0,
+ // writes orbit.lock, and syncs .orbit/bin.
+ cmd_project_add(ctx, mf, ["app", "helper"])
+ let m_after_add = parse_project_manifest(read_text(mf).unwrap(), "proj")
+ assert_eq(m_after_add.dependencies["app"].constraint, "^1.0.0")
+ assert_eq(m_after_add.dependencies["helper"].constraint, "^1.0.0")
+ let lock1 = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
+ assert_eq(lock1.packages.length(), 3)
+ assert_true(exists(proj + "/.orbit/.gitignore"))
+ assert_true(exists(proj + "/.orbit/bin/app"))
+ assert_true(exists(proj + "/.orbit/bin/helper"))
+
+ // Run tasks and direct commands through .orbit/bin.
+ assert_eq(run_project_command(ctx, mf, ["show"], false, false), 0)
+ assert_eq(run_project_command(ctx, mf, ["check"], true, false), 0)
+ assert_eq(run_project_command(ctx, mf, ["helper", "--direct"], true, false), 0)
+
+ // --locked passes while in sync.
+ cmd_project_sync(ctx, mf, true, false)
+
+ // Transactional rollback on failed `orbit add`: files remain identical.
+ let saved_toml = read_text(mf).unwrap()
+ let saved_lock = read_text(proj + "/orbit.lock").unwrap()
+ let bad_add = try {
+ cmd_project_add(ctx, mf, ["missingpkg"])
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(bad_add)
+ assert_eq(read_text(mf).unwrap(), saved_toml)
+ assert_eq(read_text(proj + "/orbit.lock").unwrap(), saved_lock)
+
+ // Require >=2.0.0 so lockfile (at 1.0.0) is out of date -> --locked fails.
+ m_after_add.dependencies["app"].constraint = ">=2.0.0"
+ write_text_atomic(mf, project_to_toml(m_after_add))
+ let locked_fail = try {
+ cmd_project_sync(ctx, mf, true, false)
+ false
+ } catch {
+ OrbitError(_) => true
+ }
+ assert_true(locked_fail)
+
+ // Broaden constraints to "*", re-lock, then publish helper 2.0.0 and update.
+ m_after_add.dependencies["app"].constraint = "*"
+ m_after_add.dependencies["helper"].constraint = "*"
+ write_text_atomic(mf, project_to_toml(m_after_add))
+ cmd_project_lock(ctx, mf, false)
+
+ // Publish helper 2.0.0 -> update upgrades app, helper, lib to 2.0.0.
+ publish_mock_pkg(
+ main_ch,
+ work,
+ "helper",
+ "2.0.0",
+ Map([("lib", "^2.0")]),
+ ["bin/helper"],
+ script="#!/bin/sh\nexit 0\n",
+ )
+ cmd_project_update(ctx, mf, [])
+ let lock2 = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
+ for p in lock2.packages {
+ assert_eq(p.version, "2.0.0")
+ }
+
+ // Remove packages -> cleans dependencies, orbit.lock, and .orbit/bin.
+ cmd_project_remove(ctx, mf, ["app", "helper"])
+ let m_final = parse_project_manifest(read_text(mf).unwrap(), "proj")
+ assert_eq(m_final.dependencies.length(), 0)
+ let lock_final = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
+ assert_eq(lock_final.packages.length(), 0)
+ assert_false(exists(proj + "/.orbit/bin/app"))
+ assert_false(exists(proj + "/.orbit/bin/helper"))
+ })
+ } catch {
+ OrbitError(msg) => fail("unexpected OrbitError: " + msg)
+ e => raise e
+ }
+}
diff --git a/src/main/semver.mbt b/src/main/semver.mbt
index 8753183..87e6452 100644
--- a/src/main/semver.mbt
+++ b/src/main/semver.mbt
@@ -1,12 +1,13 @@
// Minimal semantic versions and constraints.
//
-// Constraint forms:
+// Constraint forms (comma-separated clauses are ANDed together):
// "" | "*" | "latest" any stable version
-// "1.2.3" | "=1.2.3" exact
-// "1" | "1.2" prefix (1.x.x / 1.2.x)
+// "1.2.3" | "=1.2.3" | "==1.2.3" exact
+// "1" | "1.2" | "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
+// "~1.2.3" same major and minor (or major if ~1), >= base
+// ">=1.2.3" | "<=1.2.3" | ">1.2.3" | "<1.2.3" relational
+// "!=1.2.3" | "!=1.2.*" exclusion
// Prerelease versions (1.0.0-rc1) only match constraints that mention a '-'.
///|
@@ -76,6 +77,113 @@ fn cmp_ver(a : Ver, b : Ver) -> Int32 {
}
}
+///|
+fn strip_dot_star(s : String) -> (String, Bool) {
+ let a = chars(s)
+ let n = a.length()
+ if n >= 2 && a[n - 2] == '.' && a[n - 1] == '*' {
+ (slice(a, 0, n - 2), true)
+ } else {
+ (s, false)
+ }
+}
+
+///|
+fn matches_prefix(v : Ver, b : Ver) -> Bool {
+ for i = 0; i < b.parts; i = i + 1 {
+ if v.nums[i] != b.nums[i] {
+ return false
+ }
+ }
+ true
+}
+
+///|
+fn satisfies_clause(v : Ver, cl : String) -> Bool {
+ let c = trim(cl)
+ if c == "*" || c == "latest" {
+ return true
+ }
+ let with_base = fn(rest : String, rule : (Ver) -> Bool) -> Bool {
+ match parse_ver(trim(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, "<=") {
+ match parse_ver(trim(drop_chars(c, 2))) {
+ Some(b) => cmp_ver(v, b) <= 0
+ None => false
+ }
+ } else if has_prefix(c, "!=") {
+ let (ver_str, had_wild) = strip_dot_star(trim(drop_chars(c, 2)))
+ match parse_ver(ver_str) {
+ Some(b) =>
+ if b.parts < 3 || had_wild {
+ if had_wild && b.parts == 3 {
+ false
+ } else {
+ !matches_prefix(v, b)
+ }
+ } else {
+ cmp_ver(v, b) != 0
+ }
+ None => false
+ }
+ } else if has_prefix(c, "==") {
+ let (ver_str, had_wild) = strip_dot_star(trim(drop_chars(c, 2)))
+ match parse_ver(ver_str) {
+ Some(b) =>
+ if had_wild && b.parts == 3 {
+ false
+ } else if b.parts == 3 && !had_wild {
+ cmp_ver(v, b) == 0
+ } else {
+ matches_prefix(v, b)
+ }
+ None => false
+ }
+ } else if has_prefix(c, ">") {
+ match parse_ver(trim(drop_chars(c, 1))) {
+ Some(b) => cmp_ver(v, b) > 0
+ None => false
+ }
+ } else if has_prefix(c, "<") {
+ match parse_ver(trim(drop_chars(c, 1))) {
+ Some(b) => cmp_ver(v, b) < 0
+ None => false
+ }
+ } 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] && (b.parts == 1 || v.nums[1] == b.nums[1])
+ })
+ } else {
+ let exact = if has_prefix(c, "=") {
+ trim(drop_chars(c, 1))
+ } else {
+ c
+ }
+ let (ver_str, had_wild) = strip_dot_star(exact)
+ match parse_ver(ver_str) {
+ Some(b) =>
+ if had_wild && b.parts == 3 {
+ false
+ } else if b.parts == 3 && !had_wild {
+ cmp_ver(v, b) == 0
+ } else {
+ matches_prefix(v, b)
+ }
+ None => false
+ }
+ }
+}
+
///|
fn satisfies(v : Ver, c0 : String) -> Bool {
let c = trim(c0)
@@ -85,42 +193,80 @@ fn satisfies(v : Ver, c0 : String) -> Bool {
if v.pre != "" && !(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)
+ let pieces = split_on(c, ',')
+ for piece in pieces {
+ let p = trim(piece)
+ if p == "" || !satisfies_clause(v, p) {
+ return false
+ }
+ }
+ true
+}
+
+///|
+fn valid_semver_clause(cl : String) -> Bool {
+ let c = trim(cl)
+ if c == "" {
+ return false
+ }
+ if c == "*" || c == "latest" {
+ return true
+ }
+ let check_exact_or_wild = fn(raw : String) -> Bool {
+ let (ver_str, had_wild) = strip_dot_star(trim(raw))
+ match parse_ver(ver_str) {
+ Some(b) => !(had_wild && b.parts == 3)
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]
- })
+ if has_prefix(c, ">=") || has_prefix(c, "<=") {
+ parse_ver(trim(drop_chars(c, 2))) is Some(_)
+ } else if has_prefix(c, "!=") || has_prefix(c, "==") {
+ check_exact_or_wild(drop_chars(c, 2))
+ } else if has_prefix(c, ">") ||
+ has_prefix(c, "<") ||
+ has_prefix(c, "^") ||
+ has_prefix(c, "~") {
+ parse_ver(trim(drop_chars(c, 1))) is Some(_)
+ } else if has_prefix(c, "=") {
+ check_exact_or_wild(drop_chars(c, 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
- }
+ check_exact_or_wild(c)
}
}
+///|
+fn valid_constraint(c0 : String) -> Bool {
+ let c = trim(c0)
+ if c == "" || c == "*" || c == "latest" {
+ return true
+ }
+ if !has_char(c, ',') && valid_semver_clause(c) {
+ return true
+ }
+ if has_char(c, ',') {
+ let pieces = split_on(c, ',')
+ for piece in pieces {
+ if !valid_semver_clause(piece) {
+ return false
+ }
+ }
+ return true
+ }
+ // Allow non-semver literal tag pins (e.g. "edge") when they aren't malformed
+ // version numbers or operator expressions.
+ let a = chars(c)
+ let looks_like_ver = a.length() > 0 &&
+ (
+ (a[0] >= '0' && a[0] <= '9') ||
+ (a.length() > 1 && a[0] == 'v' && a[1] >= '0' && a[1] <= '9')
+ )
+ if looks_like_ver {
+ return false
+ }
+ valid_name(c)
+}
+
///|
fn satisfies_all(version : String, cons : Array[String]) -> Bool {
match parse_ver(version) {
@@ -136,7 +282,11 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
None => {
for c in cons {
let t = trim(c)
- if t != "" && t != "*" && t != version {
+ if t != "" &&
+ t != "*" &&
+ t != version &&
+ t != "=" + version &&
+ t != "==" + version {
return false
}
}
@@ -239,3 +389,49 @@ test "pick" {
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"])
}
+
+///|
+test "compound and relational constraints" {
+ let v142 = parse_ver("1.4.2").unwrap()
+ let v120 = parse_ver("1.2.0").unwrap()
+ let v200 = parse_ver("2.0.0").unwrap()
+ let v150 = parse_ver("1.5.0").unwrap()
+ let v120rc = parse_ver("1.2.0-rc1").unwrap()
+
+ assert_true(satisfies(v142, "<2.0.0"))
+ assert_true(!satisfies(v200, "<2.0.0"))
+ assert_true(satisfies(v200, "<=2.0.0"))
+ assert_true(satisfies(v142, ">1.4.0"))
+ assert_true(!satisfies(v120, ">1.2.0"))
+ assert_true(satisfies(v142, "==1.4.2"))
+ assert_true(!satisfies(v142, "!=1.4.2"))
+ assert_true(satisfies(v150, "!=1.4.2"))
+ assert_true(satisfies(v142, "1.*"))
+ assert_true(satisfies(v142, "1.4.*"))
+ assert_true(!satisfies(v150, "1.4.*"))
+ assert_true(satisfies(v142, "!=1.2.*"))
+ assert_true(!satisfies(v120, "!=1.2.*"))
+ assert_true(satisfies(v142, ">=1.2.0, <2.0.0"))
+ assert_true(!satisfies(v200, ">=1.2.0, <2.0.0"))
+ assert_true(satisfies(v150, ">=1.0, !=1.4.2, <2.0"))
+ assert_true(!satisfies(v142, ">=1.0, !=1.4.2, <2.0"))
+ assert_true(satisfies(v120rc, ">=1.0.0-rc1, <2.0.0"))
+ assert_true(!satisfies(v120rc, ">=1.0.0, <2.0.0"))
+ assert_true(satisfies(v142, "~1"))
+
+ assert_true(satisfies_all("edge", ["edge"]))
+ assert_true(satisfies_all("edge", ["=edge"]))
+ assert_true(satisfies_all("edge", ["==edge"]))
+ assert_true(!satisfies_all("edge", [">=1.0"]))
+
+ assert_true(valid_constraint(">=1.2.0, <2.0.0"))
+ assert_true(valid_constraint("1.4.*"))
+ assert_true(valid_constraint("edge"))
+ assert_false(valid_constraint(">=abc"))
+ assert_false(valid_constraint(">=1,"))
+ assert_false(valid_constraint("<="))
+ assert_false(valid_constraint("^^1.0"))
+ assert_false(valid_constraint("1.2.3.4"))
+ assert_false(valid_constraint("1.2.3.*"))
+ assert_false(valid_constraint("~>1.0"))
+}
diff --git a/src/main/solver.mbt b/src/main/solver.mbt
new file mode 100644
index 0000000..e3d4aaa
--- /dev/null
+++ b/src/main/solver.mbt
@@ -0,0 +1,1568 @@
+// Lazy Resolvo-style CDCL SAT solver for package dependency resolution.
+//
+// Translates package version selection, dependency implications, channel pins,
+// and binary-name ownership conflicts into Boolean clauses lazily as candidate
+// manifests are demanded.
+
+///|
+struct SolveReq {
+ name : String
+ channel : String?
+ constraint : String
+ label : String
+}
+
+///|
+struct CandidateInfo {
+ name : String
+ channel : String
+ tag : String
+ version : String
+ digest : String
+ favored : Bool
+}
+
+///|
+struct CandidateDetail {
+ digest : String
+ manifest : Manifest
+}
+
+///|
+struct SolvedPkg {
+ name : String
+ channel : String
+ tag : String
+ version : String
+ digest : String
+ manifest : Manifest
+}
+
+///|
+struct SolverProvider {
+ candidates : async (String, String?) -> (String, Array[CandidateInfo])
+ details : async (CandidateInfo) -> CandidateDetail
+ extra_reqs : (String) -> Array[SolveReq]
+ locked_bins : Map[String, String]
+}
+
+///|
+#derive(Eq)
+enum Val {
+ Unassigned
+ True
+ False
+}
+
+///|
+enum ClauseOrigin {
+ Root(String, String, String?, String)
+ Dep(Int32, String, String?, String)
+ AtMostOne(String)
+ BinConflict(String, Int32, Int32)
+ LockedBinConflict(String, Int32, String)
+ Learned(Array[Int32])
+}
+
+///|
+struct Clause {
+ lits : Array[Int32]
+ origin : ClauseOrigin
+}
+
+///|
+struct PkgState {
+ name : String
+ mut default_channel : String?
+ loaded_channels : Map[String, Array[Int32]]
+ all_vars : Array[Int32]
+ mut extra_reqs_added : Bool
+}
+
+///|
+struct SatSolver {
+ provider : SolverProvider
+ vars : Array[CandidateInfo]
+ var_pkg : Array[Int32]
+ pkgs : Array[PkgState]
+ pkg_index : Map[String, Int32]
+ clauses : Array[Clause]
+ watches : Array[Array[Int32]]
+ assign : Array[Val]
+ level : Array[Int32]
+ reason : Array[Int32]
+ trail : Array[Int32]
+ trail_lim : Array[Int32]
+ mut qhead : Int32
+ expanded : Array[Bool]
+ details : Array[CandidateDetail?]
+ bin_providers : Map[String, Array[Int32]]
+ pending_reqs : Array[SolveReq]
+}
+
+// ---------------------------------------------------------------- helpers
+
+///|
+fn pos_lit(v : Int32) -> Int32 {
+ v * 2
+}
+
+///|
+fn neg_lit(v : Int32) -> Int32 {
+ v * 2 + 1
+}
+
+///|
+fn lit_var(l : Int32) -> Int32 {
+ l / 2
+}
+
+///|
+fn lit_is_neg(l : Int32) -> Bool {
+ (l % 2) != 0
+}
+
+///|
+fn lit_neg(l : Int32) -> Int32 {
+ if (l % 2) == 0 {
+ l + 1
+ } else {
+ l - 1
+ }
+}
+
+///|
+fn swap_idx(a : Array[Int32], i : Int32, j : Int32) -> Unit {
+ if i != j {
+ let t = a[i]
+ a[i] = a[j]
+ a[j] = t
+ }
+}
+
+///|
+/// Place original indices `i0` and `i1` (with `i0 != i1`) at positions 0 and 1.
+fn put_first_two(a : Array[Int32], i0 : Int32, i1 : Int32) -> Unit {
+ let pos1 = if i1 == 0 { i0 } else { i1 }
+ swap_idx(a, 0, i0)
+ swap_idx(a, 1, pos1)
+}
+
+///|
+/// Build candidate list from OCI tags: optional favored build first, then semver
+/// tags highest-first, then non-semver literal tags (excluding "latest").
+fn candidates_from_tags(
+ name : String,
+ channel : String,
+ tags : Array[String],
+ favored : (String, String, String)?,
+) -> Array[CandidateInfo] {
+ let out : Array[CandidateInfo] = []
+ let seen : Array[String] = []
+ match favored {
+ Some((fch, fver, fdig)) =>
+ if fch == channel && fver != "" {
+ out.push(CandidateInfo::{
+ name,
+ channel,
+ tag: fver,
+ version: fver,
+ digest: fdig,
+ favored: true,
+ })
+ seen.push(fver)
+ }
+ None => ()
+ }
+ for t in sorted_versions(tags) {
+ if !seen.contains(t) {
+ out.push(CandidateInfo::{
+ name,
+ channel,
+ tag: t,
+ version: t,
+ digest: "",
+ favored: false,
+ })
+ seen.push(t)
+ }
+ }
+ for t in tags {
+ if t != "latest" && parse_ver(t) is None && !seen.contains(t) {
+ out.push(CandidateInfo::{
+ name,
+ channel,
+ tag: t,
+ version: t,
+ digest: "",
+ favored: false,
+ })
+ seen.push(t)
+ }
+ }
+ out
+}
+
+///|
+fn cand_matches(
+ cand : CandidateInfo,
+ constraint : String,
+ has_semver : Bool,
+) -> Bool {
+ if parse_ver(cand.tag) is Some(_) {
+ satisfies_all(cand.tag, [constraint])
+ } else {
+ let t = trim(constraint)
+ t == cand.tag ||
+ t == "=" + cand.tag ||
+ t == "==" + cand.tag ||
+ (!has_semver && (t == "" || t == "*"))
+ }
+}
+
+///|
+fn matching_vars(
+ s : SatSolver,
+ var_ids : Array[Int32],
+ constraint : String,
+) -> Array[Int32] {
+ let mut has_semver = false
+ for vid in var_ids {
+ if parse_ver(s.vars[vid].tag) is Some(_) {
+ has_semver = true
+ break
+ }
+ }
+ let out : Array[Int32] = []
+ for vid in var_ids {
+ if cand_matches(s.vars[vid], constraint, has_semver) {
+ out.push(vid)
+ }
+ }
+ out
+}
+
+///|
+fn available_labels(s : SatSolver, var_ids : Array[Int32]) -> String {
+ let xs : Array[String] = []
+ for vid in var_ids {
+ let t = s.vars[vid].tag
+ if !xs.contains(t) {
+ xs.push(t)
+ }
+ }
+ if xs.length() == 0 {
+ "(none)"
+ } else {
+ join(xs, ", ")
+ }
+}
+
+// ---------------------------------------------------------------- SAT core
+
+///|
+fn new_solver(provider : SolverProvider) -> SatSolver {
+ SatSolver::{
+ provider,
+ vars: [],
+ var_pkg: [],
+ pkgs: [],
+ pkg_index: Map([]),
+ clauses: [],
+ watches: [],
+ assign: [],
+ level: [],
+ reason: [],
+ trail: [],
+ trail_lim: [],
+ qhead: 0,
+ expanded: [],
+ details: [],
+ bin_providers: Map([]),
+ pending_reqs: [],
+ }
+}
+
+///|
+fn current_level(s : SatSolver) -> Int32 {
+ s.trail_lim.length()
+}
+
+///|
+fn lit_val(s : SatSolver, l : Int32) -> Val {
+ let v = lit_var(l)
+ match s.assign[v] {
+ Unassigned => Unassigned
+ True => if lit_is_neg(l) { False } else { True }
+ False => if lit_is_neg(l) { True } else { False }
+ }
+}
+
+///|
+fn enqueue(s : SatSolver, l : Int32, reason_cid : Int32) -> Unit {
+ let v = lit_var(l)
+ s.assign[v] = if lit_is_neg(l) { False } else { True }
+ s.level[v] = current_level(s)
+ s.reason[v] = reason_cid
+ s.trail.push(l)
+}
+
+///|
+fn backtrack(s : SatSolver, target_lvl : Int32) -> Unit {
+ if current_level(s) <= target_lvl {
+ return
+ }
+ let stop = s.trail_lim[target_lvl]
+ while s.trail.length() > stop {
+ let p = s.trail.pop().unwrap()
+ let v = lit_var(p)
+ s.assign[v] = Unassigned
+ s.level[v] = -1
+ s.reason[v] = -1
+ }
+ while s.trail_lim.length() > target_lvl {
+ s.trail_lim.pop() |> ignore
+ }
+ if s.qhead > s.trail.length() {
+ s.qhead = s.trail.length()
+ }
+}
+
+///|
+fn attach_watches(s : SatSolver, cid : Int32) -> Unit {
+ let lits = s.clauses[cid].lits
+ if lits.length() >= 2 {
+ s.watches[lit_neg(lits[0])].push(cid)
+ s.watches[lit_neg(lits[1])].push(cid)
+ }
+}
+
+///|
+fn add_clause_dynamic(
+ s : SatSolver,
+ raw_lits : Array[Int32],
+ origin : ClauseOrigin,
+) -> Int32 {
+ let lits : Array[Int32] = []
+ for l in raw_lits {
+ if lits.contains(lit_neg(l)) {
+ return -1 // tautology
+ }
+ if !lits.contains(l) {
+ lits.push(l)
+ }
+ }
+ let n = lits.length()
+ if n == 0 {
+ backtrack(s, 0)
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{ lits, origin })
+ return cid
+ }
+ let mut true_idx : Int32 = -1
+ let unassigned : Array[Int32] = []
+ let mut max_false_lvl : Int32 = 0
+ let mut max_false_idx : Int32 = -1
+ let mut second_false_idx : Int32 = -1
+ let mut second_false_lvl : Int32 = -1
+ for i = 0; i < n; i = i + 1 {
+ match lit_val(s, lits[i]) {
+ True =>
+ if true_idx < 0 || s.level[lit_var(lits[i])] < s.level[lit_var(lits[true_idx])] {
+ true_idx = i
+ }
+ Unassigned => unassigned.push(i)
+ False => {
+ let lvl = s.level[lit_var(lits[i])]
+ if max_false_idx < 0 || lvl > max_false_lvl {
+ second_false_idx = max_false_idx
+ second_false_lvl = max_false_lvl
+ max_false_lvl = lvl
+ max_false_idx = i
+ } else if second_false_idx < 0 || lvl > second_false_lvl {
+ second_false_idx = i
+ second_false_lvl = lvl
+ }
+ }
+ }
+ }
+ if true_idx >= 0 {
+ // Satisfied under current assignment. If it is the sole non-false lit and
+ // was decided above max_false_lvl, avoid leaving an unpropagated watch.
+ if n >= 2 {
+ let mut second : Int32 = -1
+ for i = 0; i < n; i = i + 1 {
+ if i != true_idx && !(lit_val(s, lits[i]) is False) {
+ second = i
+ break
+ }
+ }
+ if second < 0 {
+ second = max_false_idx
+ }
+ put_first_two(lits, true_idx, second)
+ }
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{ lits, origin })
+ attach_watches(s, cid)
+ return -1
+ }
+ if unassigned.length() >= 2 {
+ put_first_two(lits, unassigned[0], unassigned[1])
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{ lits, origin })
+ attach_watches(s, cid)
+ return -1
+ }
+ if unassigned.length() == 1 {
+ let u = unassigned[0]
+ if n >= 2 {
+ put_first_two(lits, u, max_false_idx)
+ }
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{ lits, origin })
+ attach_watches(s, cid)
+ if max_false_lvl < current_level(s) {
+ backtrack(s, max_false_lvl)
+ }
+ if lit_val(s, lits[0]) is Unassigned {
+ enqueue(s, lits[0], cid)
+ }
+ return -1
+ }
+ // Zero unassigned and zero true -> conflict.
+ if n >= 2 {
+ put_first_two(lits, max_false_idx, second_false_idx)
+ }
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{ lits, origin })
+ attach_watches(s, cid)
+ if max_false_lvl < current_level(s) {
+ backtrack(s, max_false_lvl)
+ }
+ cid
+}
+
+///|
+fn alloc_candidates(
+ s : SatSolver,
+ pid : Int32,
+ cands : Array[CandidateInfo],
+) -> Array[Int32] {
+ let pkg = s.pkgs[pid]
+ let ids : Array[Int32] = []
+ for c in cands {
+ let vid = s.vars.length()
+ s.vars.push(c)
+ s.var_pkg.push(pid)
+ s.watches.push([])
+ s.watches.push([])
+ s.assign.push(Unassigned)
+ s.level.push(-1)
+ s.reason.push(-1)
+ s.expanded.push(false)
+ s.details.push(None)
+ pkg.all_vars.push(vid)
+ ids.push(vid)
+ }
+ ids
+}
+
+///|
+async fn provider_candidates(
+ p : SolverProvider,
+ name : String,
+ pin : String?,
+) -> (String, Array[CandidateInfo]) raise OrbitError {
+ try (p.candidates)(name, pin) catch {
+ OrbitError(msg) => raise OrbitError(msg)
+ e => raise OrbitError(e.to_string())
+ }
+}
+
+///|
+async fn provider_details(
+ p : SolverProvider,
+ cand : CandidateInfo,
+) -> CandidateDetail raise OrbitError {
+ try (p.details)(cand) catch {
+ OrbitError(msg) => raise OrbitError(msg)
+ e => raise OrbitError(e.to_string())
+ }
+}
+
+///|
+async fn ensure_pkg_channel(
+ s : SatSolver,
+ name : String,
+ pin : String?,
+) -> (String, Array[Int32]) raise OrbitError {
+ match s.pkg_index.get(name) {
+ None => {
+ let (ch_name, cands) = provider_candidates(s.provider, name, pin)
+ let pid = s.pkgs.length()
+ let pkg = PkgState::{
+ name,
+ default_channel: if pin is Some(_) {
+ None
+ } else {
+ Some(ch_name)
+ },
+ loaded_channels: Map([]),
+ all_vars: [],
+ extra_reqs_added: false,
+ }
+ s.pkgs.push(pkg)
+ s.pkg_index[name] = pid
+ let ids = alloc_candidates(s, pid, cands)
+ pkg.loaded_channels[ch_name] = ids
+ if !pkg.extra_reqs_added {
+ pkg.extra_reqs_added = true
+ for er in (s.provider.extra_reqs)(name) {
+ s.pending_reqs.push(er)
+ }
+ }
+ (ch_name, ids)
+ }
+ Some(pid) => {
+ let pkg = s.pkgs[pid]
+ match pin {
+ Some(ch_name) =>
+ match pkg.loaded_channels.get(ch_name) {
+ Some(ids) => return (ch_name, ids)
+ None => ()
+ }
+ None =>
+ match pkg.default_channel {
+ Some(ch_name) =>
+ match pkg.loaded_channels.get(ch_name) {
+ Some(ids) => return (ch_name, ids)
+ None => ()
+ }
+ None => ()
+ }
+ }
+ let (ch_name, cands) = provider_candidates(s.provider, name, pin)
+ if pin is None {
+ pkg.default_channel = Some(ch_name)
+ }
+ match pkg.loaded_channels.get(ch_name) {
+ Some(ids) => (ch_name, ids)
+ None => {
+ let prev_len = pkg.all_vars.length()
+ let ids = alloc_candidates(s, pid, cands)
+ pkg.loaded_channels[ch_name] = ids
+ // If an earlier candidate of this package is already True, forbid
+ // selecting any candidate from the newly loaded channel.
+ for i = 0; i < prev_len; i = i + 1 {
+ let u = pkg.all_vars[i]
+ if s.assign[u] == True {
+ for w in ids {
+ ignore(
+ add_clause_dynamic(
+ s,
+ [neg_lit(w), neg_lit(u)],
+ AtMostOne(pkg.name),
+ ),
+ )
+ }
+ }
+ }
+ (ch_name, ids)
+ }
+ }
+ }
+ }
+}
+
+///|
+/// Propagate unit implications; returns conflicting clause ID or -1.
+fn propagate(s : SatSolver) -> Int32 {
+ while s.qhead < s.trail.length() {
+ let p = s.trail[s.qhead]
+ s.qhead = s.qhead + 1
+ // Lazy At-Most-One when candidate `v` is assigned True.
+ if !lit_is_neg(p) {
+ let v = lit_var(p)
+ let pkg = s.pkgs[s.var_pkg[v]]
+ for other in pkg.all_vars {
+ if other != v && s.assign[other] != False {
+ let cid = s.clauses.length()
+ s.clauses.push(Clause::{
+ lits: [neg_lit(other), neg_lit(v)],
+ origin: AtMostOne(pkg.name),
+ })
+ attach_watches(s, cid)
+ if s.assign[other] == True {
+ return cid
+ }
+ enqueue(s, neg_lit(other), cid)
+ }
+ }
+ }
+ // Two-watched-literals scan on watches[p].
+ // Watch lists store clauses keyed by `lit_neg(watched_lit)`, so when `p`
+ // becomes True, `lit_neg(p)` became False and watches[p] must be updated.
+ let ws = s.watches[p]
+ let false_lit = lit_neg(p)
+ let mut i : Int32 = 0
+ let mut j : Int32 = 0
+ let n = ws.length()
+ let mut confl : Int32 = -1
+ while i < n {
+ let cid = ws[i]
+ i = i + 1
+ let lits = s.clauses[cid].lits
+ if lits[0] == false_lit {
+ lits[0] = lits[1]
+ lits[1] = false_lit
+ }
+ if lit_val(s, lits[0]) is True {
+ ws[j] = cid
+ j = j + 1
+ continue
+ }
+ let mut found = false
+ for k = 2; k < lits.length(); k = k + 1 {
+ if !(lit_val(s, lits[k]) is False) {
+ lits[1] = lits[k]
+ lits[k] = false_lit
+ s.watches[lit_neg(lits[1])].push(cid)
+ found = true
+ break
+ }
+ }
+ if found {
+ continue
+ }
+ // Keep watching false_lit on this clause.
+ ws[j] = cid
+ j = j + 1
+ if lit_val(s, lits[0]) is False {
+ confl = cid
+ while i < n {
+ ws[j] = ws[i]
+ j = j + 1
+ i = i + 1
+ }
+ break
+ } else {
+ enqueue(s, lits[0], cid)
+ }
+ }
+ while ws.length() > j {
+ ws.pop() |> ignore
+ }
+ if confl >= 0 {
+ return confl
+ }
+ }
+ -1
+}
+
+///|
+/// 1-UIP conflict analysis when current_level > 0.
+fn analyze_conflict(
+ s : SatSolver,
+ confl0 : Int32,
+) -> (Array[Int32], Int32, Array[Int32]) {
+ let cur_lvl = current_level(s)
+ let seen : Array[Bool] = Array::make(s.vars.length(), false)
+ let learned : Array[Int32] = [0]
+ let ants : Array[Int32] = [confl0]
+ let mut counter : Int32 = 0
+
+ let process_clause = fn(cid : Int32, skip_var : Int32) {
+ for q in s.clauses[cid].lits {
+ let qv = lit_var(q)
+ if qv != skip_var && !seen[qv] {
+ seen[qv] = true
+ if s.level[qv] == cur_lvl {
+ counter = counter + 1
+ } else if s.level[qv] > 0 {
+ learned.push(q)
+ } else if s.reason[qv] >= 0 {
+ ants.push(s.reason[qv])
+ }
+ }
+ }
+ }
+
+ process_clause(confl0, -1)
+ let mut idx = s.trail.length() - 1
+ let mut p : Int32 = -1
+ while idx >= 0 {
+ let t = s.trail[idx]
+ let v = lit_var(t)
+ if seen[v] {
+ seen[v] = false
+ counter = counter - 1
+ if counter == 0 {
+ p = t
+ break
+ }
+ let r = s.reason[v]
+ if r >= 0 {
+ ants.push(r)
+ process_clause(r, v)
+ }
+ }
+ idx = idx - 1
+ }
+ learned[0] = lit_neg(p)
+ let mut bt_level : Int32 = 0
+ if learned.length() > 1 {
+ let mut best : Int32 = 1
+ let mut best_lvl = s.level[lit_var(learned[1])]
+ for k = 2; k < learned.length(); k = k + 1 {
+ let lvl = s.level[lit_var(learned[k])]
+ if lvl > best_lvl {
+ best_lvl = lvl
+ best = k
+ }
+ }
+ swap_idx(learned, 1, best)
+ bt_level = best_lvl
+ }
+ (learned, bt_level, ants)
+}
+
+///|
+async fn add_req_clause(s : SatSolver, req : SolveReq) -> Int32 raise OrbitError {
+ let (ch_name, var_ids) = ensure_pkg_channel(s, req.name, req.channel)
+ let matches = matching_vars(s, var_ids, req.constraint)
+ let lits : Array[Int32] = []
+ for vid in matches {
+ lits.push(pos_lit(vid))
+ }
+ add_clause_dynamic(
+ s,
+ lits,
+ Root(req.label, req.name, Some(ch_name), req.constraint),
+ )
+}
+
+///|
+fn first_unexpanded_true(s : SatSolver) -> Int32? {
+ for t in s.trail {
+ if !lit_is_neg(t) {
+ let v = lit_var(t)
+ if !s.expanded[v] {
+ return Some(v)
+ }
+ }
+ }
+ None
+}
+
+///|
+/// Expand the next unassigned-deps candidate on the trail.
+/// Returns (expanded_something, conflict_cid).
+async fn expand_next(s : SatSolver) -> (Bool, Int32) raise OrbitError {
+ let v = match first_unexpanded_true(s) {
+ Some(vid) => vid
+ None => return (false, -1)
+ }
+ s.expanded[v] = true
+ let cand = s.vars[v]
+ let det = provider_details(s.provider, cand)
+ s.details[v] = Some(det)
+
+ let saved_lvl = current_level(s)
+ let mut confl : Int32 = -1
+ let record_confl = fn(c : Int32) {
+ if c >= 0 && confl < 0 {
+ confl = c
+ }
+ }
+
+ // 1. Add dependency implication clauses `[¬v, m1, m2, ...]`.
+ for dep_key, dep_con in det.manifest.depends {
+ let (dep_pin, dep_name) = parse_dep_key(dep_key)
+ let (_, var_ids) = ensure_pkg_channel(s, dep_name, dep_pin)
+ let matches = matching_vars(s, var_ids, dep_con)
+ let lits : Array[Int32] = [neg_lit(v)]
+ for mvid in matches {
+ lits.push(pos_lit(mvid))
+ }
+ let c = add_clause_dynamic(
+ s,
+ lits,
+ Dep(v, dep_name, dep_pin, dep_con),
+ )
+ record_confl(c)
+ }
+
+ // 2. Check binary-name collisions against locked global packages (skipped if
+ // that package is part of this solve) and against active candidates.
+ for b in det.manifest.bins {
+ let bn = basename(b)
+ match s.provider.locked_bins.get(bn) {
+ Some(owner) =>
+ if owner != cand.name && !s.pkg_index.contains(owner) {
+ let c = add_clause_dynamic(
+ s,
+ [neg_lit(v)],
+ LockedBinConflict(bn, v, owner),
+ )
+ record_confl(c)
+ }
+ None => ()
+ }
+ let provs = match s.bin_providers.get(bn) {
+ Some(xs) => xs
+ None => {
+ let xs : Array[Int32] = []
+ s.bin_providers[bn] = xs
+ xs
+ }
+ }
+ for u in provs {
+ if s.var_pkg[u] != s.var_pkg[v] {
+ let c = add_clause_dynamic(
+ s,
+ [neg_lit(v), neg_lit(u)],
+ BinConflict(bn, v, u),
+ )
+ record_confl(c)
+ }
+ }
+ provs.push(v)
+ }
+
+ // 3. Flush any extra requirements discovered when dependencies first loaded.
+ while s.pending_reqs.length() > 0 {
+ let req = s.pending_reqs.remove(0)
+ let c = add_req_clause(s, req)
+ if c >= 0 {
+ return (true, c)
+ }
+ }
+ if current_level(s) < saved_lvl {
+ return (true, -1)
+ }
+ (true, confl)
+}
+
+///|
+/// Pick the next decision literal using MRV on active positive-choice clauses.
+/// Returns None when every active requirement is satisfied.
+fn pick_decision(s : SatSolver) -> Int32? {
+ let mut best_lit : Int32 = -1
+ let mut best_count : Int32 = 2147483647
+ for cl in s.clauses {
+ let mut satisfied = false
+ let mut blocked_by_guard = false
+ let mut first_pos : Int32 = -1
+ let mut pos_count : Int32 = 0
+ for l in cl.lits {
+ let val = lit_val(s, l)
+ if val == True {
+ satisfied = true
+ break
+ }
+ if val == Unassigned {
+ if lit_is_neg(l) {
+ blocked_by_guard = true
+ break
+ }
+ if first_pos < 0 {
+ first_pos = l
+ }
+ pos_count = pos_count + 1
+ }
+ }
+ if !satisfied && !blocked_by_guard && pos_count > 0 && pos_count < best_count {
+ best_count = pos_count
+ best_lit = first_pos
+ if best_count == 1 {
+ break
+ }
+ }
+ }
+ if best_lit >= 0 {
+ Some(best_lit)
+ } else {
+ None
+ }
+}
+
+///|
+fn format_channel_prefix(pin : String?) -> String {
+ match pin {
+ Some(ch) => ch + "::"
+ None => ""
+ }
+}
+
+///|
+fn explain_unsat(s : SatSolver, confl : Int32) -> String {
+ let visited : Array[Bool] = Array::make(s.clauses.length(), false)
+ let queue : Array[Int32] = [confl]
+ visited[confl] = true
+ let lines : Array[String] = []
+ let push_line = fn(line : String) {
+ if !lines.contains(line) {
+ lines.push(line)
+ }
+ }
+ while queue.length() > 0 {
+ let cid = queue.remove(0)
+ let cl = s.clauses[cid]
+ match cl.origin {
+ Learned(ants) =>
+ for a in ants {
+ if a >= 0 && a < visited.length() && !visited[a] {
+ visited[a] = true
+ queue.push(a)
+ }
+ }
+ Root(label, name, pin, constraint) =>
+ push_line(
+ " - \{label} requires \{format_channel_prefix(pin)}\{name} \{constraint}",
+ )
+ Dep(pvid, dep_name, pin, constraint) => {
+ let p = s.vars[pvid]
+ push_line(
+ " - \{p.name} \{p.version} requires \{format_channel_prefix(pin)}\{dep_name} \{constraint}",
+ )
+ }
+ AtMostOne(name) =>
+ push_line(" - only one version of \{name} can be installed")
+ BinConflict(bin, v1, v2) => {
+ let c1 = s.vars[v1]
+ let c2 = s.vars[v2]
+ push_line(
+ " - \{c1.name} \{c1.version} and \{c2.name} \{c2.version} both provide binary '\{bin}'",
+ )
+ }
+ LockedBinConflict(bin, vid, owner) => {
+ let c = s.vars[vid]
+ push_line(
+ " - \{c.name} \{c.version} provides binary '\{bin}', already provided by installed \{owner}",
+ )
+ }
+ }
+ for l in cl.lits {
+ let v = lit_var(l)
+ if s.assign[v] != Unassigned && s.level[v] == 0 {
+ let r = s.reason[v]
+ if r >= 0 && r < visited.length() && !visited[r] {
+ visited[r] = true
+ queue.push(r)
+ }
+ }
+ }
+ }
+ if lines.length() == 0 {
+ return "dependency resolution failed: unsatisfiable constraints"
+ }
+ "cannot satisfy dependencies:\n" + join(lines, "\n")
+}
+
+///|
+fn topo_sort_solution(s : SatSolver) -> Array[SolvedPkg] {
+ let chosen : Map[String, SolvedPkg] = Map([])
+ let names : Array[String] = []
+ for vid = 0; vid < s.vars.length(); vid = vid + 1 {
+ if s.assign[vid] == True {
+ let c = s.vars[vid]
+ let det = s.details[vid].unwrap()
+ let pkg = SolvedPkg::{
+ name: c.name,
+ channel: c.channel,
+ tag: c.tag,
+ version: det.manifest.version,
+ digest: det.digest,
+ manifest: det.manifest,
+ }
+ chosen[c.name] = pkg
+ names.push(c.name)
+ }
+ }
+ let state : Map[String, Int32] = Map([]) // 1 = visiting, 2 = done
+ let out : Array[SolvedPkg] = []
+ fn dfs(name : String) -> Unit {
+ match state.get(name) {
+ Some(1) | Some(2) => return
+ _ => ()
+ }
+ state[name] = 1
+ match chosen.get(name) {
+ Some(pkg) => {
+ for dep_key, _ in pkg.manifest.depends {
+ let (_, dep_name) = parse_dep_key(dep_key)
+ if chosen.contains(dep_name) {
+ dfs(dep_name)
+ }
+ }
+ state[name] = 2
+ out.push(pkg)
+ }
+ None => state[name] = 2
+ }
+ }
+ for name in names {
+ dfs(name)
+ }
+ out
+}
+
+///|
+async fn solve(
+ reqs : Array[SolveReq],
+ provider : SolverProvider,
+) -> Array[SolvedPkg] raise OrbitError {
+ let s = new_solver(provider)
+ for req in reqs {
+ let (ch_name, var_ids) = ensure_pkg_channel(s, req.name, req.channel)
+ let matches = matching_vars(s, var_ids, req.constraint)
+ if matches.length() == 0 {
+ let avail = available_labels(s, var_ids)
+ raise OrbitError(
+ "no version of \{req.name} in channel '\{ch_name}' satisfies '\{req.constraint}'; available: \{avail}",
+ )
+ }
+ let lits : Array[Int32] = []
+ for vid in matches {
+ lits.push(pos_lit(vid))
+ }
+ let c = add_clause_dynamic(
+ s,
+ lits,
+ Root(req.label, req.name, Some(ch_name), req.constraint),
+ )
+ if c >= 0 {
+ raise OrbitError(explain_unsat(s, c))
+ }
+ }
+ while s.pending_reqs.length() > 0 {
+ let req = s.pending_reqs.remove(0)
+ let c = add_req_clause(s, req)
+ if c >= 0 {
+ raise OrbitError(explain_unsat(s, c))
+ }
+ }
+
+ let mut confl : Int32 = -1
+ while true {
+ if confl < 0 {
+ confl = propagate(s)
+ }
+ if confl >= 0 {
+ if current_level(s) == 0 {
+ raise OrbitError(explain_unsat(s, confl))
+ }
+ let (learned, bt_level, ants) = analyze_conflict(s, confl)
+ backtrack(s, bt_level)
+ let c = add_clause_dynamic(s, learned, Learned(ants))
+ confl = c
+ continue
+ }
+ let (expanded_any, exp_confl) = expand_next(s)
+ if exp_confl >= 0 {
+ confl = exp_confl
+ continue
+ }
+ if expanded_any {
+ continue
+ }
+ match pick_decision(s) {
+ Some(dec_lit) => {
+ s.trail_lim.push(s.trail.length())
+ enqueue(s, dec_lit, -1)
+ }
+ None => return topo_sort_solution(s)
+ }
+ }
+ []
+}
+
+// ---------------------------------------------------------------- unit tests
+
+///|
+struct MockEntry {
+ channel : String
+ tag : String
+ manifest : Manifest
+ favored : Bool
+}
+
+///|
+fn mock_manifest(
+ name : String,
+ version : String,
+ depends : Map[String, String],
+ bins? : Array[String] = [],
+) -> Manifest {
+ Manifest::{
+ name,
+ version,
+ description: "",
+ documentation: "",
+ depends,
+ bins,
+ }
+}
+
+///|
+fn make_mock_provider(
+ repo : Map[String, Array[MockEntry]],
+ detail_fetches? : Ref[Int32] = Ref(0),
+ extra_reqs_map? : Map[String, Array[SolveReq]] = Map([]),
+ locked_bins? : Map[String, String] = Map([]),
+) -> SolverProvider {
+ let by_id : Map[String, Manifest] = Map([])
+ for _, entries in repo {
+ for e in entries {
+ by_id[e.channel + "::" + e.manifest.name + "@" + e.tag] = e.manifest
+ }
+ }
+ SolverProvider::{
+ candidates: async fn(name, pin) {
+ if false {
+ @async.sleep(0)
+ }
+ let entries = match repo.get(name) {
+ Some(xs) => xs
+ None => raise OrbitError("package '\{name}' not found")
+ }
+ let ch = match pin {
+ Some(c) => c
+ None => {
+ if entries.length() == 0 {
+ raise OrbitError("package '\{name}' has no candidates")
+ }
+ entries[0].channel
+ }
+ }
+ let tags : Array[String] = []
+ let mut fav : (String, String, String)? = None
+ for e in entries {
+ if e.channel == ch {
+ tags.push(e.tag)
+ if e.favored {
+ fav = Some((ch, e.tag, "sha256:fav-" + name + "-" + e.tag))
+ }
+ }
+ }
+ if tags.length() == 0 {
+ raise OrbitError("package '\{name}' not found in channel '\{ch}'")
+ }
+ (ch, candidates_from_tags(name, ch, tags, fav))
+ },
+ details: async fn(cand) {
+ if false {
+ @async.sleep(0)
+ }
+ detail_fetches.val = detail_fetches.val + 1
+ let key = cand.channel + "::" + cand.name + "@" + cand.tag
+ let m = match by_id.get(key) {
+ Some(m) => m
+ None => raise OrbitError("missing mock manifest " + key)
+ }
+ CandidateDetail::{
+ digest: "sha256:" + cand.channel + "-" + cand.name + "-" + cand.tag,
+ manifest: m,
+ }
+ },
+ extra_reqs: fn(name) {
+ match extra_reqs_map.get(name) {
+ Some(xs) => xs
+ None => []
+ }
+ },
+ locked_bins,
+ }
+}
+
+///|
+fn solved_map(xs : Array[SolvedPkg]) -> Map[String, String] {
+ let m : Map[String, String] = Map([])
+ for p in xs {
+ m[p.name] = p.version
+ }
+ m
+}
+
+///|
+async test "solver basic transitive order and diamond backtracking" {
+ let repo : Map[String, Array[MockEntry]] = Map([
+ (
+ "lib",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("lib", "2.0.0", Map([])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("lib", "1.0.0", Map([])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "app",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("app", "2.0.0", Map([("lib", "^2.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("app", "1.0.0", Map([("lib", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "helper",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("helper", "1.0.0", Map([("lib", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ ])
+ let sol = solve(
+ [
+ SolveReq::{ name: "app", channel: None, constraint: "*", label: "root" },
+ SolveReq::{
+ name: "helper",
+ channel: None,
+ constraint: "*",
+ label: "root",
+ },
+ ],
+ make_mock_provider(repo),
+ )
+ let m = solved_map(sol)
+ assert_eq(m.get("app"), Some("1.0.0"))
+ assert_eq(m.get("helper"), Some("1.0.0"))
+ assert_eq(m.get("lib"), Some("1.0.0"))
+ // Dependencies come before dependents in topological order.
+ let names = sol.map(fn(p) { p.name })
+ let mut lib_idx : Int32 = -1
+ let mut app_idx : Int32 = -1
+ for i, n in names {
+ if n == "lib" {
+ lib_idx = i
+ }
+ if n == "app" {
+ app_idx = i
+ }
+ }
+ assert_true(lib_idx >= 0 && app_idx > lib_idx)
+}
+
+///|
+async test "solver deep backtracking, compound constraints, and lazy fetch count" {
+ let repo : Map[String, Array[MockEntry]] = Map([
+ (
+ "top",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "3.0.0",
+ manifest: mock_manifest("top", "3.0.0", Map([("mid", "^3.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("top", "2.0.0", Map([("mid", "^2.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("top", "1.0.0", Map([("mid", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "mid",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "3.0.0",
+ manifest: mock_manifest("mid", "3.0.0", Map([("leaf", "^3.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("mid", "2.0.0", Map([("leaf", "^2.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.5.0",
+ manifest: mock_manifest("mid", "1.5.0", Map([("leaf", "^1.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.4.0",
+ manifest: mock_manifest("mid", "1.4.0", Map([("leaf", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "leaf",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "3.0.0",
+ manifest: mock_manifest("leaf", "3.0.0", Map([])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("leaf", "2.0.0", Map([])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.2.0",
+ manifest: mock_manifest("leaf", "1.2.0", Map([])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.1.0",
+ manifest: mock_manifest("leaf", "1.1.0", Map([])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "pin",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest(
+ "pin",
+ "1.0.0",
+ Map([("leaf", ">=1.0.0, <2.0.0, !=1.2.0")]),
+ ),
+ favored: false,
+ },
+ ],
+ ),
+ ])
+ let fetches : Ref[Int32] = Ref(0)
+ let sol = solve(
+ [
+ SolveReq::{ name: "top", channel: None, constraint: "*", label: "root" },
+ SolveReq::{ name: "pin", channel: None, constraint: "*", label: "root" },
+ ],
+ make_mock_provider(repo, detail_fetches=fetches),
+ )
+ let m = solved_map(sol)
+ assert_eq(m.get("top"), Some("1.0.0"))
+ assert_eq(m.get("mid"), Some("1.5.0"))
+ assert_eq(m.get("leaf"), Some("1.1.0"))
+ // Lazy check: mid@1.4.0 and leaf@1.2.0 (if not needed? Actually leaf@1.2.0
+ // wasn't even tried because pin restricted leaf to !=1.2.0, and mid@1.4.0 was
+ // never fetched because mid@1.5.0 succeeded!). Total entries = 11; fetches < 11.
+ assert_true(fetches.val < 11)
+}
+
+///|
+async test "solver handles cycles, favored stability, channel pins, and bin conflicts" {
+ // Cyclic deps + favored stability
+ let cyc_repo : Map[String, Array[MockEntry]] = Map([
+ (
+ "a",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.2.0",
+ manifest: mock_manifest("a", "1.2.0", Map([("b", "^1.0")])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.1.0",
+ manifest: mock_manifest("a", "1.1.0", Map([("b", "^1.0")])),
+ favored: true,
+ },
+ ],
+ ),
+ (
+ "b",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.1.0",
+ manifest: mock_manifest("b", "1.1.0", Map([("a", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ ])
+ let sol = solve(
+ [SolveReq::{ name: "a", channel: None, constraint: "^1.0", label: "root" }],
+ make_mock_provider(cyc_repo),
+ )
+ let m = solved_map(sol)
+ // Favored 1.1.0 stays preferred when ^1.0 is satisfied.
+ assert_eq(m.get("a"), Some("1.1.0"))
+ assert_eq(m.get("b"), Some("1.1.0"))
+
+ // Moving constraint forces moving off favored 1.1.0 to 1.2.0.
+ let sol2 = solve(
+ [SolveReq::{ name: "a", channel: None, constraint: ">=1.2.0", label: "root" }],
+ make_mock_provider(cyc_repo),
+ )
+ assert_eq(solved_map(sol2).get("a"), Some("1.2.0"))
+
+ // Channel pin + binary conflict backtracking
+ let bin_repo : Map[String, Array[MockEntry]] = Map([
+ (
+ "x",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("x", "2.0.0", Map([]), bins=["bin/cli"]),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("x", "1.0.0", Map([]), bins=["bin/x"]),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "y",
+ [
+ MockEntry::{
+ channel: "extra",
+ tag: "1.0.0",
+ manifest: mock_manifest("y", "1.0.0", Map([]), bins=["bin/cli"]),
+ favored: false,
+ },
+ ],
+ ),
+ ])
+ let sol3 = solve(
+ [
+ SolveReq::{ name: "x", channel: None, constraint: "*", label: "root" },
+ SolveReq::{
+ name: "y",
+ channel: Some("extra"),
+ constraint: "*",
+ label: "root",
+ },
+ ],
+ make_mock_provider(bin_repo),
+ )
+ let m3 = solved_map(sol3)
+ assert_eq(m3.get("x"), Some("1.0.0"))
+ assert_eq(m3.get("y"), Some("1.0.0"))
+}
+
+///|
+async test "solver UNSAT explanation, channel conflict, and non-semver tags" {
+ let repo : Map[String, Array[MockEntry]] = Map([
+ (
+ "a",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("a", "1.0.0", Map([("c", "^1.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "b",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("b", "1.0.0", Map([("c", "^2.0")])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "c",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "2.0.0",
+ manifest: mock_manifest("c", "2.0.0", Map([])),
+ favored: false,
+ },
+ MockEntry::{
+ channel: "main",
+ tag: "1.0.0",
+ manifest: mock_manifest("c", "1.0.0", Map([])),
+ favored: false,
+ },
+ ],
+ ),
+ (
+ "nightly",
+ [
+ MockEntry::{
+ channel: "main",
+ tag: "edge",
+ manifest: mock_manifest("nightly", "0.0.1", Map([])),
+ favored: false,
+ },
+ ],
+ ),
+ ])
+ let err_msg = try {
+ ignore(
+ solve(
+ [
+ SolveReq::{ name: "a", channel: None, constraint: "*", label: "root" },
+ SolveReq::{ name: "b", channel: None, constraint: "*", label: "root" },
+ ],
+ make_mock_provider(repo),
+ ),
+ )
+ ""
+ } catch {
+ OrbitError(m) => m
+ }
+ assert_true(contains_str(err_msg, "a 1.0.0 requires c ^1.0"))
+ assert_true(contains_str(err_msg, "b 1.0.0 requires c ^2.0"))
+
+ // Non-semver literal tag "edge"
+ let sol_edge = solve(
+ [
+ SolveReq::{
+ name: "nightly",
+ channel: None,
+ constraint: "edge",
+ label: "root",
+ },
+ ],
+ make_mock_provider(repo),
+ )
+ assert_eq(sol_edge[0].tag, "edge")
+ assert_eq(sol_edge[0].version, "0.0.1")
+}