diff --git a/README.md b/README.md index 5651da6..3a02097 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ A small package manager written in MoonBit that uses any OCI registry (Gitea, GH - **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. +- **Conflicts:** packages can declare that they can't be installed together, and a global install offers to replace the one in the way. - **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. @@ -44,6 +45,30 @@ In a channel this becomes `/mytool:1.4.0`, plus the `latest` tag. T | config | `application/vnd.latha.orbit.config.v1+json` (`orbit.json`, with OCI labels for package-page metadata) | | layer `pkg.tar.gz` | `application/vnd.latha.orbit.layer.v1.tar+gzip` | +### Conflicts + +`conflicts` names packages that can't be installed beside this one, with the +versions it applies to (`*` for all): + +```json +{ + "name": "mytool-nightly", + "version": "1.5.0", + "bin": ["bin/mytool"], + "conflicts": { "mytool": "*", "oldplugin": "<2.0.0" } +} +``` + +- Only one of the two packages has to declare it, and the named package need not exist. +- Unlike dependencies, a conflict covers prereleases without naming one. It applies to a package name in any channel. +- The solver looks for versions that don't conflict, and explains the conflict if there are none. +- If a global `orbit install` can't be satisfied beside the installed packages, it asks before removing the ones it conflicts with. Without a terminal it fails unless you pass `--replace`. It never removes a package that another one needs, and downloads everything before removing anything. +- `orbit upgrade` and project commands never replace packages. In a project, `orbit remove` the old one first. +- `orbit rollback` refuses a build that conflicts with an installed package. +- Orbit versions from before this field ignore it, and can't read an `orbit.lock` that contains it. + +### Registry details + The optional `description` and `documentation` fields supply Gitea's **About** text and **Documentation** link. Use a public or otherwise accessible HTTP(S) URL for the link. Gitea does not render a bundled README inline, but you can @@ -255,6 +280,7 @@ src/main/ 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) + conflicts.mbt declared conflicts, replacing installed packages (+ 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 diff --git a/planning/8m9kt-package-conflicts.md b/planning/8m9kt-package-conflicts.md new file mode 100644 index 0000000..eab51d3 --- /dev/null +++ b/planning/8m9kt-package-conflicts.md @@ -0,0 +1,20 @@ +--- +data: + priority: normal + status: done + tags: + - solver + type: feature +id: 8m9kt +title: Package conflicts +--- +Packages such as `moonbit` and `moonbit-nightly` can't be installed together, but only a clash of command names stops it, and the user must remove one by hand first. + +Acceptance criteria: + +- `orbit.json` takes `"conflicts": { "": "" }`, as in Arch. One side declaring it is enough. `*` includes prereleases. +- The solver never selects conflicting packages, in a project or globally, and says why when that leaves no solution. +- A global install that conflicts with installed packages asks before replacing them. Without a terminal it fails unless `--replace` is given. It refuses if another package needs the one to be removed, and downloads first. +- Conflicts are kept in `state.json` and `orbit.lock`; rollback checks them. + +Outcome: `src/main/conflicts.mbt` and the solver. Checked end to end against `registry:2`, including the prompt. `moonbit-nightly` declares its conflict in orbit-packages. Arch's `provides` and `replaces` are not included: one package can't satisfy a dependency on another. diff --git a/src/main/conflicts.mbt b/src/main/conflicts.mbt new file mode 100644 index 0000000..4ce93cd --- /dev/null +++ b/src/main/conflicts.mbt @@ -0,0 +1,401 @@ +// Declared package conflicts (`conflicts` in orbit.json), and replacing the +// installed packages that a global install conflicts with. + +///| +/// What the solver needs to know about an installed package outside the solve. +struct LockedInfo { + version : String + conflicts : Map[String, String] +} + +///| +/// Conflicts apply to versions, so tag names such as "edge" are not allowed. +fn valid_conflict_constraint(c : String) -> Bool { + for piece in split_on(c, ',') { + if !valid_semver_clause(piece) { + return false + } + } + true +} + +///| +/// Whether a conflict on `constraint` covers `version`. Unlike a dependency, it +/// covers prereleases without naming one: a conflict with `*` means every build. +fn conflict_covers(constraint : String, version : String) -> Bool { + match parse_ver(version) { + Some(v) => { + for piece in split_on(constraint, ',') { + if !satisfies_clause(v, piece) { + return false + } + } + true + } + None => false + } +} + +///| +fn declares_conflict( + conflicts : Map[String, String], + name : String, + version : String, +) -> Bool { + match conflicts.get(name) { + Some(c) => conflict_covers(c, version) + None => false + } +} + +///| +/// Either package may declare the conflict. +fn manifests_conflict(a : Manifest, b : Manifest) -> Bool { + declares_conflict(a.conflicts, b.name, b.version) || + declares_conflict(b.conflicts, a.name, a.version) +} + +///| +/// Parse the `conflicts` object of orbit.json. +fn parse_conflicts( + o : Map[String, Json], + self_name : String, +) -> Map[String, String] raise OrbitError { + let out : Map[String, String] = Map([]) + match o.get("conflicts") { + None => () + Some(Json::Object(m)) => + for name, v in m { + let c = match v { + Json::String(s) => s + _ => + raise OrbitError( + "orbit.json: conflict '\{name}' must be a version constraint", + ) + } + if !valid_name(name) || name == self_name { + raise OrbitError("orbit.json: invalid conflict name '\{name}'") + } + if !valid_conflict_constraint(c) { + raise OrbitError( + "orbit.json: invalid version constraint '\{c}' for conflict '\{name}'", + ) + } + out[name] = c + } + Some(_) => + raise OrbitError( + "orbit.json: conflicts must be an object of names and version constraints", + ) + } + out +} + +// ---------------------------------------------------------------- global installs + +///| +/// Pairs of (installed, planned) packages that conflict, where the installed +/// one is not itself in the plan. +fn plan_conflicts( + ctx : Ctx, + steps : Array[Step], +) -> Array[(Installed, Step)] { + let planned : Map[String, Bool] = Map([]) + for st in steps { + planned[st.name] = true + } + let out : Array[(Installed, Step)] = [] + for name, inst in ctx.state { + if planned.contains(name) { + continue + } + let m = manifest_of_installed(inst) + for st in steps { + if manifests_conflict(m, st.manifest) { + out.push((inst, st)) + } + } + } + out +} + +///| +fn conflict_lines(pairs : Array[(Installed, Step)]) -> String { + join( + pairs.map(fn(pair) { + let (inst, st) = pair + " - \{st.name} \{st.version} conflicts with installed \{inst.name} \{inst.version}" + }), + "\n", + ) +} + +///| +/// Fail if the plan conflicts with an installed package that stays. +fn check_plan_conflicts( + ctx : Ctx, + steps : Array[Step], + leaving : Array[String], +) -> Unit raise OrbitError { + let pairs = plan_conflicts(ctx, steps).filter(fn(pair) { + !leaving.contains(pair.0.name) + }) + if pairs.length() > 0 { + raise OrbitError("conflicting packages:\n" + conflict_lines(pairs)) + } +} + +///| +/// Fail if a package that stays needs one that would be removed. +fn check_replaced_unneeded( + ctx : Ctx, + steps : Array[Step], + removals : Array[String], +) -> Unit raise OrbitError { + let planned : Map[String, Manifest] = Map([]) + for st in steps { + planned[st.name] = st.manifest + } + for name, inst in ctx.state { + if removals.contains(name) { + continue + } + let depends = match planned.get(name) { + Some(m) => m.depends + None => inst.depends + } + for dk, _ in depends { + let dep = parse_dep_key(dk).1 + if removals.contains(dep) { + raise OrbitError( + "cannot replace \{dep}: \{name} requires it\n" + + conflict_lines(plan_conflicts(ctx, steps)), + ) + } + } + } +} + +///| +/// Plan an install. If nothing fits beside the installed packages, plan to +/// replace the ones that conflict. Returns the plan and the packages to remove. +async fn plan_install( + ctx : Ctx, + reqs : Array[(String?, String, String, String)], + explicit_new : Map[String, String], +) -> (Array[Step], Array[String]) raise OrbitError { + try plan_global(ctx, reqs, [], explicit_new) catch { + OrbitError(msg) => { + if ctx.state.length() == 0 { + raise OrbitError(msg) + } + // See what the request would choose if nothing were installed. + let free = plan_global(ctx, reqs, [], explicit_new, ignore_installed=true) catch { + _ => raise OrbitError(msg) + } + let removals : Array[String] = [] + for pair in plan_conflicts(ctx, free) { + if !removals.contains(pair.0.name) { + removals.push(pair.0.name) + } + } + if removals.length() == 0 { + raise OrbitError(msg) + } + // Solve again without only those packages. + let steps = plan_global( + ctx, + reqs, + [], + explicit_new, + replacing=removals, + ) + let conflicting = plan_conflicts(ctx, steps).map(fn(p) { p.0.name }) + for name in removals { + if !conflicting.contains(name) { + raise OrbitError(msg) + } + } + check_plan_conflicts(ctx, steps, removals) + check_replaced_unneeded(ctx, steps, removals) + (steps, removals) + } + } noraise { + steps => { + check_plan_conflicts(ctx, steps, []) + (steps, []) + } + } +} + +///| +/// Get the user's agreement to remove conflicting packages. +async fn confirm_replace( + ctx : Ctx, + steps : Array[Step], + removals : Array[String], + interactive : Bool, +) -> Unit raise OrbitError { + let lines = conflict_lines(plan_conflicts(ctx, steps)) + let names = join(removals, ", ") + if !interactive { + raise OrbitError( + "conflicting packages:\n\{lines}\nuse --replace to remove \{names}", + ) + } + c_print_err(utf8_encode("\{lines}\nRemove \{names}? [y/N] ")) + let answer = trim(read_stdin_line()) + if answer != "y" && answer != "Y" && answer != "yes" { + raise OrbitError("nothing installed; \{names} kept") + } +} + +///| +fn stdin_is_interactive() -> Bool { + c_isatty(0) != 0 && c_isatty(2) != 0 +} + +// ---------------------------------------------------------------- unit tests + +///| +test "conflicts parse strictly and cover prereleases" { + let m = parse_manifest( + "{\"name\":\"tool-nightly\",\"version\":\"1.0.0\",\"conflicts\":{\"tool\":\"*\",\"old\":\">=1.0, <2.0\"}}", + ) + assert_true(declares_conflict(m.conflicts, "tool", "1.0.0-rc1")) + assert_true(declares_conflict(m.conflicts, "old", "1.5.0-rc1")) + assert_false(declares_conflict(m.conflicts, "old", "2.0.0")) + assert_false(declares_conflict(m.conflicts, "other", "1.0.0")) + for + bad in [ + "[\"tool\"]", "{\"tool\":1}", "{\"tool\":\"\"}", "{\"tool\":\"edge\"}", "{\"x\":\"*\"}", + "{\"main::tool\":\"*\"}", + ] { + let rejected = try { + parse_manifest( + "{\"name\":\"x\",\"version\":\"1.0.0\",\"conflicts\":\{bad}}", + ) + |> ignore + false + } catch { + OrbitError(_) => true + } + assert_true(rejected, msg=bad) + } +} + +///| +fn mock_entry(manifest : Manifest) -> MockEntry { + MockEntry::{ + channel: "main", + tag: manifest.version, + manifest, + favored: false, + } +} + +///| +fn mock_req(name : String) -> SolveReq { + SolveReq::{ name, channel: None, constraint: "*", label: "root" } +} + +///| +async test "solver keeps conflicting packages apart" { + let none : Map[String, String] = Map([]) + let repo : Map[String, Array[MockEntry]] = Map([ + ("tool", [mock_entry(mock_manifest("tool", "1.0.0", none))]), + ( + "tool-nightly", + [ + mock_entry( + mock_manifest( + "tool-nightly", + "2.0.0", + none, + conflicts=Map([("tool", "*")]), + ), + ), + ], + ), + ( + "app", + [ + mock_entry( + mock_manifest("app", "2.0.0", Map([("tool-nightly", "*")])), + ), + mock_entry(mock_manifest("app", "1.0.0", none)), + ], + ), + ]) + // Both orders fail: the declaring side may be expanded first or second. + for names in [["tool", "tool-nightly"], ["tool-nightly", "tool"]] { + let err = try { + ignore(solve(names.map(mock_req), make_mock_provider(repo))) + "" + } catch { + OrbitError(m) => m + } + assert_true( + contains_str(err, "tool-nightly 2.0.0 conflicts with tool 1.0.0"), + msg=err, + ) + } + // With a shared binary too, the declared conflict is the one reported. + let shared : Map[String, Array[MockEntry]] = Map([ + ("a", [mock_entry(mock_manifest("a", "1.0.0", none, bins=["bin/t"]))]), + ( + "b", + [ + mock_entry( + mock_manifest( + "b", + "1.0.0", + none, + bins=["bin/t"], + conflicts=Map([("a", "*")]), + ), + ), + ], + ), + ]) + let shared_err = try { + ignore(solve([mock_req("a"), mock_req("b")], make_mock_provider(shared))) + "" + } catch { + OrbitError(m) => m + } + assert_true( + contains_str(shared_err, "b 1.0.0 conflicts with a 1.0.0"), + msg=shared_err, + ) + // A dependency's conflict sends the solver to an older version, in any order. + for names in [["tool", "app"], ["app", "tool"]] { + let m = solved_map( + solve(names.map(mock_req), make_mock_provider(repo)), + ) + assert_eq(m.get("app"), Some("1.0.0")) + assert_eq(m.get("tool"), Some("1.0.0")) + assert_false(m.contains("tool-nightly")) + } + // Installed packages outside the solve count too, whichever side declares it. + let locked = make_mock_provider( + repo, + locked=Map([ + ("tool", LockedInfo::{ version: "1.0.0-rc1", conflicts: none }), + ]), + ) + assert_eq(solved_map(solve([mock_req("app")], locked)).get("app"), Some("1.0.0")) + let locked2 = make_mock_provider( + repo, + locked=Map([ + ( + "other", + LockedInfo::{ version: "1.0.0", conflicts: Map([("app", ">=2")]) }, + ), + ]), + ) + assert_eq( + solved_map(solve([mock_req("app")], locked2)).get("app"), + Some("1.0.0"), + ) +} diff --git a/src/main/main.mbt b/src/main/main.mbt index de873c4..11e3d7e 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -35,6 +35,8 @@ let usage : String = #| rebuild the channel's package index #| orbit install [-g] [channel::][@constraint]... #| install globally with SAT dependency solving + #| (--replace: remove conflicting packages + #| without asking) #| 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 @@ -317,12 +319,14 @@ async fn dispatch(args : Array[String]) -> Unit 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) + None => + cmd_install(load_ctx(), pos, replace=flags.contains("--replace")) } "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) + None => + cmd_install(load_ctx(), pos, replace=flags.contains("--replace")) } "remove" | "rm" => match resolve_project_or_none(force_global, manifest_path) { diff --git a/src/main/model.mbt b/src/main/model.mbt index a3d7d61..026f1d9 100644 --- a/src/main/model.mbt +++ b/src/main/model.mbt @@ -18,6 +18,7 @@ struct Manifest { description : String documentation : String depends : Map[String, String] + conflicts : Map[String, String] bins : Array[String] } @@ -30,6 +31,7 @@ struct Gen { description : String bins : Array[String] depends : Map[String, String] + conflicts : Map[String, String] } ///| @@ -43,6 +45,7 @@ struct Installed { mut constraint : String mut bins : Array[String] mut depends : Map[String, String] + mut conflicts : Map[String, String] history : Array[Gen] } @@ -197,12 +200,14 @@ fn valid_dep_key(key : String) -> Bool { ///| fn parse_manifest(text : String) -> Manifest raise OrbitError { let o = parse_object(text, "orbit.json") + let name = jstr(o, "name", "") let m = Manifest::{ - name: jstr(o, "name", ""), + name, version: jstr(o, "version", ""), description: jstr(o, "description", ""), documentation: jstr(o, "documentation", ""), depends: jmap(o, "depends"), + conflicts: parse_conflicts(o, name), bins: jstrs(o, "bin"), } if !valid_name(m.name) { @@ -242,6 +247,7 @@ fn gen_json(g : Gen) -> Json { o["description"] = Json::string(g.description) o["bin"] = strs_json(g.bins) o["depends"] = map_json(g.depends) + o["conflicts"] = map_json(g.conflicts) Json::object(o) } @@ -256,6 +262,7 @@ fn installed_json(p : Installed) -> Json { o["constraint"] = Json::string(p.constraint) o["bin"] = strs_json(p.bins) o["depends"] = map_json(p.depends) + o["conflicts"] = map_json(p.conflicts) let h : Array[Json] = [] for g in p.history { h.push(gen_json(g)) @@ -298,6 +305,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { description: jstr(h, "description", ""), bins: jstrs(h, "bin"), depends: jmap(h, "depends"), + conflicts: jmap(h, "conflicts"), }) _ => () } @@ -314,6 +322,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { constraint: jstr(o, "constraint", "*"), bins: jstrs(o, "bin"), depends: jmap(o, "depends"), + conflicts: jmap(o, "conflicts"), history, } } @@ -328,12 +337,15 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { ///| test "installed and rollback descriptions round trip with legacy entries" { let text = - #|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}} + #|{"packages":{"tool":{"description":"Current build","conflicts":{"a":"*"},"history":[{"description":"Previous build","conflicts":{"b":"<2"}},{}]}}} let state = state_from_text(state_to_text(state_from_text(text))) guard state.get("tool") is Some(p) else { fail("missing installed package") } assert_eq(p.description, "Current build") assert_eq(p.history[0].description, "Previous build") assert_eq(p.history[1].description, "") + assert_eq(p.conflicts.get("a"), Some("*")) + assert_eq(p.history[0].conflicts.get("b"), Some("<2")) + assert_true(p.history[1].conflicts.is_empty()) } // ---------------------------------------------------------------- context diff --git a/src/main/ops.mbt b/src/main/ops.mbt index cafedae..c847700 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -21,6 +21,7 @@ fn manifest_of_installed(p : Installed) -> Manifest { description: p.description, documentation: "", depends: p.depends, + conflicts: p.conflicts, bins: p.bins, } } @@ -60,12 +61,15 @@ fn parse_spec(spec : String) -> (String?, String, String) raise OrbitError { } ///| -/// Build a SAT-solved install/upgrade plan for global state. +/// Build a SAT-solved install/upgrade plan for global state. Packages in +/// `replacing` don't constrain it; with `ignore_installed`, none do. async fn plan_global( ctx : Ctx, req_specs : Array[(String?, String, String, String)], upgrade : Array[String], explicit_new : Map[String, String], + replacing? : Array[String] = [], + ignore_installed? : Bool = false, ) -> Array[Step] raise OrbitError { let ch_by_name : Map[String, Channel] = Map([]) for c in ctx.channels { @@ -76,8 +80,16 @@ async fn plan_global( let manifest_cache : Map[String, Manifest] = Map([]) let locked_bins : Map[String, String] = Map([]) + let locked : Map[String, LockedInfo] = Map([]) for name, inst in ctx.state { - if !upgrade.contains(name) && !explicit_new.contains(name) { + if !ignore_installed && + !upgrade.contains(name) && + !explicit_new.contains(name) && + !replacing.contains(name) { + locked[name] = LockedInfo::{ + version: inst.version, + conflicts: inst.conflicts, + } for b in inst.bins { locked_bins[basename(b)] = name } @@ -161,9 +173,14 @@ async fn plan_global( }, extra_reqs: fn(pkg_name) { let reqs : Array[SolveReq] = [] + if ignore_installed { + return reqs + } match ctx.state.get(pkg_name) { Some(inst) => - if inst.explicit && !explicit_new.contains(pkg_name) { + if inst.explicit && + !explicit_new.contains(pkg_name) && + !replacing.contains(pkg_name) { reqs.push(SolveReq::{ name: pkg_name, channel: Some(inst.channel), @@ -180,7 +197,8 @@ async fn plan_global( for other, oinst in ctx.state { if other != pkg_name && !upgrade.contains(other) && - !explicit_new.contains(other) { + !explicit_new.contains(other) && + !replacing.contains(other) { for dk, dc in oinst.depends { let (dch, dname) = parse_dep_key(dk) if dname == pkg_name { @@ -197,6 +215,7 @@ async fn plan_global( reqs }, locked_bins, + locked, } let reqs : Array[SolveReq] = [] @@ -300,8 +319,8 @@ fn check_bin_conflicts( } ///| -/// Switch `name` to a fetched build, keeping the old one for rollback. -async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { +/// Fetch a step's build into the store and check its contents. +async fn fetch_step(ctx : Ctx, st : Step) -> String raise OrbitError { let ch = find_channel(ctx, st.channel) let dir = fetch_into_store(ctx, ch, st.name, st.digest) for b in st.manifest.bins { @@ -309,6 +328,13 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { raise OrbitError("\{st.name}: bin '\{b}' missing from package contents") } } + dir +} + +///| +/// Switch `name` to a fetched build, keeping the old one for rollback. +async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { + let dir = fetch_step(ctx, st) check_bin_conflicts(ctx, st.name, st.manifest.bins) match ctx.state.get(st.name) { Some(inst) => { @@ -320,6 +346,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { description: inst.description, bins: inst.bins, depends: inst.depends, + conflicts: inst.conflicts, }) while inst.history.length() > 2 { inst.history.remove(0) |> ignore @@ -330,6 +357,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { inst.description = st.manifest.description inst.bins = st.manifest.bins inst.depends = st.manifest.depends + inst.conflicts = st.manifest.conflicts inst.explicit = st.explicit inst.constraint = st.constraint println( @@ -347,6 +375,7 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { constraint: st.constraint, bins: st.manifest.bins, depends: st.manifest.depends, + conflicts: st.manifest.conflicts, history: [], } println(" \{st.name} \{st.version} installed") @@ -358,8 +387,25 @@ async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { } ///| -async fn apply_plan(ctx : Ctx, steps : Array[Step]) -> Unit raise OrbitError { +async fn apply_plan( + ctx : Ctx, + steps : Array[Step], + removals? : Array[String] = [], +) -> Unit raise OrbitError { let mut changed = 0 + if removals.length() > 0 { + // Have the replacements at hand before removing anything. + for st in steps { + if !st.keep { + ignore(fetch_step(ctx, st)) + } + } + for name in removals { + remove_one(ctx, name) + changed = changed + 1 + } + save_state(ctx) + } for st in steps { if st.keep { match ctx.state.get(st.name) { @@ -383,9 +429,14 @@ async fn apply_plan(ctx : Ctx, steps : Array[Step]) -> Unit raise OrbitError { } ///| -async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { +async fn cmd_install( + ctx : Ctx, + specs : Array[String], + replace? : Bool = false, + interactive? : Bool = stdin_is_interactive(), +) -> Unit raise OrbitError { if specs.length() == 0 { - raise OrbitError("usage: orbit install [channel::][@constraint]...") + raise OrbitError("usage: orbit install [--replace] [channel::][@constraint]...") } let reqs : Array[(String?, String, String, String)] = [] let explicit_new : Map[String, String] = Map([]) @@ -394,8 +445,15 @@ async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError reqs.push((channel, name, c, "command line")) explicit_new[name] = c } - let steps = plan_global(ctx, reqs, [], explicit_new) - apply_plan(ctx, steps) + let (steps, removals) = plan_install(ctx, reqs, explicit_new) + if removals.length() > 0 && !replace { + confirm_replace(ctx, steps, removals, interactive) + } + apply_plan(ctx, steps, removals~) + if removals.length() > 0 { + autoremove(ctx) + save_state(ctx) + } } ///| @@ -460,6 +518,16 @@ async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError } } let steps = plan_global(ctx, reqs, targets, Map([])) + // Upgrading everything ends by removing the dependencies nobody needs. + let leaving : Array[String] = [] + if names.length() == 0 { + for name, inst in ctx.state { + if !inst.explicit { + leaving.push(name) + } + } + } + check_plan_conflicts(ctx, steps, leaving) apply_plan(ctx, steps) if names.length() == 0 { autoremove(ctx) @@ -570,6 +638,18 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { "previous build of \{name} (\{prev.version}) is no longer in the store", ) } + for other, oinst in ctx.state { + if other != name && + ( + declares_conflict(prev.conflicts, other, oinst.version) || + declares_conflict(oinst.conflicts, name, prev.version) + ) { + raise OrbitError( + "\{name} \{prev.version} conflicts with installed \{other} \{oinst.version}", + ) + } + } + check_bin_conflicts(ctx, name, prev.bins) unlink_bins(ctx, inst.bins) inst.history.push(Gen::{ channel: inst.channel, @@ -578,6 +658,7 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { description: inst.description, bins: inst.bins, depends: inst.depends, + conflicts: inst.conflicts, }) inst.channel = prev.channel let from = inst.version @@ -586,7 +667,7 @@ async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { inst.description = prev.description inst.bins = prev.bins inst.depends = prev.depends - check_bin_conflicts(ctx, name, inst.bins) + inst.conflicts = prev.conflicts link_bins(ctx, dir, inst.bins) save_state(ctx) println("\{name}: \{from} -> \{prev.version}") @@ -696,6 +777,13 @@ fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError { deps.push(d + "@" + c) } println(" depends: \{join(deps, " ")}") + if !p.conflicts.is_empty() { + let cs : Array[String] = [] + for n, c in p.conflicts { + cs.push(n + "@" + c) + } + println(" conflicts: \{join(cs, " ")}") + } let rd = reverse_deps(ctx, name) println(" needed by: \{join(rd, " ")}") let hist : Array[String] = [] diff --git a/src/main/project.mbt b/src/main/project.mbt index 9253692..9066b7b 100644 --- a/src/main/project.mbt +++ b/src/main/project.mbt @@ -36,6 +36,7 @@ struct LockedPkg { description : String bins : Array[String] depends : Map[String, String] + conflicts : Map[String, String] } ///| @@ -526,6 +527,7 @@ fn parse_lockfile(text : String) -> Lockfile raise OrbitError { let mut description = "" let bins : Array[String] = [] let depends : Map[String, String] = Map([]) + let conflicts : Map[String, String] = Map([]) for pk, pv in pt { match (pk, pv) { ("name", TomlString(s)) => name = s @@ -556,6 +558,16 @@ fn parse_lockfile(text : String) -> Lockfile raise OrbitError { ) } } + ("conflicts", TomlTable(ct)) => + for cn, cv in ct { + match cv { + TomlString(cc) => conflicts[cn] = cc + _ => + raise OrbitError( + "orbit.lock: conflict '\{cn}' on '\{name}' must be a string", + ) + } + } _ => raise OrbitError( "orbit.lock: unknown package key '\{pk}'", @@ -583,6 +595,13 @@ fn parse_lockfile(text : String) -> Lockfile raise OrbitError { ) } } + for cn, cc in conflicts { + if !valid_name(cn) || !valid_conflict_constraint(cc) { + raise OrbitError( + "orbit.lock: invalid conflict '\{cn}' = '\{cc}' on '\{name}'", + ) + } + } packages.push(LockedPkg::{ name, version: pver, @@ -598,6 +617,7 @@ fn parse_lockfile(text : String) -> Lockfile raise OrbitError { description, bins, depends, + conflicts, }) } } @@ -648,16 +668,19 @@ fn lockfile_to_toml(lock : Lockfile) -> String { } 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) + for field in [("depends", p.depends), ("conflicts", p.conflicts)] { + let (key, entries_map) = field + if entries_map.length() > 0 { + let keys : Array[String] = [] + for k, _ in entries_map { + keys.push(k) + } + let entries : Array[String] = [] + for k in sort_strings(keys) { + entries.push(toml_key(k) + " = " + toml_quote(entries_map[k])) + } + sb.write_string(key + " = { " + join(entries, ", ") + " }\n") } - 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() @@ -805,6 +828,14 @@ fn lockfile_satisfies( bin_owners[bn] = p.name } } + for p in lock.packages { + for other, c in p.conflicts { + match pkg_by_name.get(other) { + Some(o) => if conflict_covers(c, o.version) { return false } + None => () + } + } + } let queue : Array[String] = [] let seen : Map[String, Bool] = Map([]) for name, dep in m.dependencies { @@ -849,6 +880,7 @@ fn manifest_of_locked(p : LockedPkg) -> Manifest { description: p.description, documentation: "", depends: p.depends, + conflicts: p.conflicts, bins: p.bins, } } @@ -953,6 +985,7 @@ async fn solve_project( }, extra_reqs: fn(_name) { [] }, locked_bins: Map([]), + locked: Map([]), } let dep_names : Array[String] = [] @@ -991,6 +1024,7 @@ async fn solve_project( description: sp.manifest.description, bins: sp.manifest.bins, depends: sp.manifest.depends, + conflicts: sp.manifest.conflicts, }) } Lockfile::{ version: 1, channels, packages } @@ -1587,6 +1621,7 @@ test "orbit.toml and orbit.lock roundtrip" { description: "Greeter", bins: ["bin/greet"], depends: Map([("main::hello", "^1.0.0")]), + conflicts: Map([("greet-nightly", "*"), ("hello", ">=2")]), }, LockedPkg::{ name: "hello", @@ -1599,6 +1634,7 @@ test "orbit.toml and orbit.lock roundtrip" { description: "", bins: ["bin/hello"], depends: Map([]), + conflicts: Map([]), }, ], } @@ -1613,6 +1649,12 @@ test "orbit.toml and orbit.lock roundtrip" { ]) assert_true(lockfile_satisfies(lock2, m, chs)) + // Locked packages must not conflict. + assert_eq(lock2.packages[0].conflicts.get("greet-nightly"), Some("*")) + lock2.packages[0].conflicts["hello"] = "^1.0.0" + assert_false(lockfile_satisfies(lock2, m, chs)) + lock2.packages[0].conflicts.remove("hello") + // Changing dependency constraint invalidates lockfile check. m.dependencies["hello"].constraint = "^2.0.0" assert_false(lockfile_satisfies(lock2, m, chs)) diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt index f37169a..4d7373e 100644 --- a/src/main/registry_wbtest.mbt +++ b/src/main/registry_wbtest.mbt @@ -591,6 +591,7 @@ async fn publish_mock_pkg( bins : Array[String], script? : String = "#!/bin/sh\necho ok\n", update_index? : Bool = true, + conflicts? : Map[String, String] = Map([]), ) -> Unit raise Error { let pkg_dir = work + "/stage-" + name + "-" + version @fs.mkdir(pkg_dir + "/files/bin", recursive=true) @@ -600,6 +601,7 @@ async fn publish_mock_pkg( mf_obj["description"] = Json::string("Mock " + name + " " + version) mf_obj["bin"] = strs_json(bins) mf_obj["depends"] = map_json(depends) + mf_obj["conflicts"] = map_json(conflicts) @fs.write_file( pkg_dir + "/orbit.json", Json::object(mf_obj).stringify(indent=2) + "\n", @@ -715,6 +717,132 @@ async test "SAT global install, backtracking, manifest cache, and joint upgrade" }) } +///| +async fn install_error( + ctx : Ctx, + specs : Array[String], + replace? : Bool = false, +) -> String { + try { + cmd_install(ctx, specs, replace~, interactive=false) + "" + } catch { + OrbitError(m) => m + } +} + +///| +async test "conflicting packages replace each other only when asked to" { + token_cache.clear() + let work = @fs.tmpdir(prefix="orbit-wb-conflicts-") + 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 main_ch = Channel::{ + name: "main", + url: "127.0.0.1:" + server.addr.port().to_string() + "/main", + plain_http: true, + } + let pub_pkg = async fn( + name : String, + version : String, + depends : Map[String, String], + conflicts : Map[String, String], + bins : Array[String], + ) { + publish_mock_pkg( + main_ch, work, name, version, depends, bins, conflicts~, + ) + } + let vs_tool = Map([("tool", "*")]) + pub_pkg("lib", "1.0.0", Map([]), Map([]), []) + pub_pkg("lib", "2.0.0", Map([]), Map([]), []) + // The two want different versions of lib. + pub_pkg("tool", "1.0.0-rc1", Map([("lib", "^1")]), Map([]), ["bin/tool"]) + pub_pkg("tool-nightly", "1.0.0", Map([("lib", "^2")]), vs_tool, ["bin/tool"]) + pub_pkg("app", "1.0.0", Map([("tool", "1.0.0-rc1")]), Map([]), ["bin/app"]) + pub_pkg("clash", "1.0.0", Map([]), Map([]), ["bin/app"]) + let root = work + "/orbit" + let ctx = Ctx::{ root, channels: [main_ch], state: Map([]) } + + // Together, in either order, they never install. + for specs in [["tool@1.0.0-rc1", "tool-nightly"], ["tool-nightly", "tool@1.0.0-rc1"]] { + assert_true(install_error(ctx, specs, replace=true) != "") + assert_true(ctx.state.is_empty()) + } + + assert_eq(install_error(ctx, ["tool@1.0.0-rc1"]), "") + let err = install_error(ctx, ["tool-nightly"]) + assert_true( + contains_str( + err, "tool-nightly 1.0.0 conflicts with installed tool 1.0.0-rc1", + ), + msg=err, + ) + assert_true(contains_str(err, "use --replace to remove tool"), msg=err) + assert_true(ctx.state.contains("tool")) + + assert_eq(install_error(ctx, ["tool-nightly"], replace=true), "") + assert_false(ctx.state.contains("tool")) + assert_eq(ctx.state["tool-nightly"].conflicts.get("tool"), Some("*")) + assert_eq(ctx.state["lib"].version, "2.0.0") + assert_true(exists(root + "/bin/tool")) + + // Back again: here the installed package is the one declaring the conflict, + // and a dependency is what brings in the other. + assert_true(contains_str(install_error(ctx, ["app"]), "--replace")) + assert_eq(install_error(ctx, ["app"], replace=true), "") + assert_false(ctx.state.contains("tool-nightly")) + assert_eq(ctx.state["lib"].version, "1.0.0") + + // A package something else needs is not replaced. + let needed = install_error(ctx, ["tool-nightly"], replace=true) + assert_true( + contains_str(needed, "cannot replace tool: app requires it"), + msg=needed, + ) + assert_true(ctx.state.contains("tool")) + assert_true(exists(root + "/bin/tool")) + + // --replace doesn't cover undeclared clashes. + assert_true( + contains_str(install_error(ctx, ["clash"], replace=true), "binary 'app'"), + ) + + // Rolling back into a conflict fails and changes nothing. + pub_pkg("other", "1.0.0", Map([]), vs_tool, ["bin/other"]) + pub_pkg("other", "2.0.0", Map([]), Map([]), ["bin/other"]) + assert_eq(install_error(ctx, ["other"]), "") + ctx.state["other"].history.push(Gen::{ + channel: "main", + version: "1.0.0", + digest: ctx.state["other"].digest, + description: "", + bins: ["bin/other"], + depends: Map([]), + conflicts: vs_tool, + }) + let rolled = try { + cmd_rollback(ctx, "other") + "" + } catch { + OrbitError(m) => m + } + assert_true(contains_str(rolled, "conflicts with installed tool"), msg=rolled) + assert_eq(ctx.state["other"].version, "2.0.0") + assert_true(exists(root + "/bin/other")) + }) +} + ///| async test "Pixi-style project workflow: new, add, sync --locked, run, update, remove" { try { diff --git a/src/main/solver.mbt b/src/main/solver.mbt index d9563c1..26621cc 100644 --- a/src/main/solver.mbt +++ b/src/main/solver.mbt @@ -1,7 +1,7 @@ // 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 +// declared conflicts and binary-name ownership into Boolean clauses lazily as candidate // manifests are demanded. ///| @@ -44,6 +44,7 @@ struct SolverProvider { details : async (CandidateInfo) -> CandidateDetail extra_reqs : (String) -> Array[SolveReq] locked_bins : Map[String, String] + locked : Map[String, LockedInfo] } ///| @@ -53,6 +54,8 @@ enum ClauseOrigin { AtMostOne(String) BinConflict(String, Int32, Int32) LockedBinConflict(String, Int32, String) + Conflict(Int32, Int32) + LockedConflict(Int32, String, String) Learned(Array[Int32]) } @@ -89,6 +92,7 @@ struct SatSolver { expanded : Array[Bool] details : Array[CandidateDetail?] bin_providers : Map[String, Array[Int32]] + conflict_declarers : Map[String, Array[Int32]] // by the name conflicted with pending_reqs : Array[SolveReq] } @@ -242,6 +246,7 @@ fn new_solver(provider : SolverProvider) -> SatSolver { expanded: [], details: [], bin_providers: Map([]), + conflict_declarers: Map([]), pending_reqs: [], } } @@ -751,7 +756,67 @@ async fn expand_next(s : SatSolver) -> (Bool, Int32) raise OrbitError { record_confl(c) } - // 2. Check binary-name collisions against locked global packages (skipped if + // 2. Declared conflicts, with installed packages outside this solve and with + // active candidates. Each pair is seen when its second package is expanded. + // Before binaries, so that an explanation names the declared conflict. + let conflict_clause = fn(declarer : Int32, target : Int32) { + let c = add_clause_dynamic( + s, + [@kernel.neg_lit(declarer), @kernel.neg_lit(target)], + Conflict(declarer, target), + ) + record_confl(c) + } + for owner, info in s.provider.locked { + if owner != cand.name && + !s.pkg_index.contains(owner) && + ( + declares_conflict(det.manifest.conflicts, owner, info.version) || + declares_conflict(info.conflicts, cand.name, det.manifest.version) + ) { + let c = add_clause_dynamic( + s, + [@kernel.neg_lit(v)], + LockedConflict(v, owner, info.version), + ) + record_confl(c) + } + } + for target, con in det.manifest.conflicts { + s.conflict_declarers.get_or_init(target, fn() { [] }).push(v) + match s.pkg_index.get(target) { + Some(pid) => + for u in s.pkgs[pid].all_vars { + match s.details[u] { + Some(d) => + if conflict_covers(con, d.manifest.version) { + conflict_clause(v, u) + } + None => () + } + } + None => () + } + } + match s.conflict_declarers.get(cand.name) { + Some(declarers) => + for u in declarers { + match s.details[u] { + Some(d) => + if declares_conflict( + d.manifest.conflicts, + cand.name, + det.manifest.version, + ) { + conflict_clause(u, v) + } + None => () + } + } + None => () + } + + // 3. 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) @@ -788,7 +853,7 @@ async fn expand_next(s : SatSolver) -> (Bool, Int32) raise OrbitError { provs.push(v) } - // 3. Flush any extra requirements discovered when dependencies first loaded. + // 4. 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) @@ -900,6 +965,19 @@ fn explain_unsat(s : SatSolver, confl : Int32) -> String { " - \{c.name} \{c.version} provides binary '\{bin}', already provided by installed \{owner}", ) } + Conflict(v1, v2) => { + let c1 = s.vars[v1] + let c2 = s.vars[v2] + push_line( + " - \{c1.name} \{c1.version} conflicts with \{c2.name} \{c2.version}", + ) + } + LockedConflict(vid, owner, owner_version) => { + let c = s.vars[vid] + push_line( + " - \{c.name} \{c.version} conflicts with installed \{owner} \{owner_version}", + ) + } } for l in cl.lits { let v = @kernel.lit_var(l) @@ -1052,6 +1130,7 @@ fn mock_manifest( version : String, depends : Map[String, String], bins? : Array[String] = [], + conflicts? : Map[String, String] = Map([]), ) -> Manifest { Manifest::{ name, @@ -1059,6 +1138,7 @@ fn mock_manifest( description: "", documentation: "", depends, + conflicts, bins, } } @@ -1069,6 +1149,7 @@ fn make_mock_provider( detail_fetches? : Ref[Int32] = Ref(0), extra_reqs_map? : Map[String, Array[SolveReq]] = Map([]), locked_bins? : Map[String, String] = Map([]), + locked? : Map[String, LockedInfo] = Map([]), ) -> SolverProvider { let by_id : Map[String, Manifest] = Map([]) for _, entries in repo { @@ -1131,6 +1212,7 @@ fn make_mock_provider( } }, locked_bins, + locked, } }