diff --git a/README.md b/README.md index a6bcfe7..d3cb511 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ mypkg/ } ``` -In the registry this becomes `/mytool:1.4.0`, plus the `latest` tag: +In a channel this becomes `/mytool:1.4.0`, plus the `latest` tag: | Part | Media type | |---|---| @@ -58,13 +58,45 @@ orbit rollback hello orbit remove hello ``` -The default registry is `git.site.latha.org/nandi`, so no setup is needed. Override it for one command or shell with `ORBIT_REGISTRY=/`, or save another one with `orbit init `. The order is `ORBIT_REGISTRY`, then the saved config, then the default. Orbit doesn't record which registry a package came from, so `upgrade` looks in whichever one is active. +## Channels -Use `--plain-http` (or `ORBIT_PLAIN_HTTP=1`) for a local `registry:2` without TLS: +Packages come from **channels**, which work like channels in pixi. A channel is a name for a registry namespace. The built-in `main` channel is `git.site.latha.org/nandi`, so no setup is needed. + +Add your own in `~/.orbit/config.toml` (`$ORBIT_ROOT/config.toml`), highest priority first. [examples/config.toml](examples/config.toml) adds the `example` channel: + +```toml +[[channels]] +name = "example" +url = "git.site.latha.org/nandi/example" # host/namespace, no https:// + +# [[channels]] +# name = "local" +# url = "localhost:5000/pkgs" +# plain-http = true # registry without TLS +``` + +`orbit channel add [--plain-http]` appends one at the lowest priority, and `orbit channel list` shows the order. To remove or reorder channels, edit the file. `orbit init` creates a commented starter file. + +```sh +orbit channel add example git.site.latha.org/nandi/example +orbit install greet # first channel that has greet +orbit install example::greet # from a specific channel +orbit publish examples/greet --channel example # default: main +``` + +- **`main` is always included.** It comes first, so another channel can't silently replace one of its packages. To lower its priority, add a block with only `name = "main"` where you want it. +- **Strict priority.** The first channel that has a package name wins, even if a lower one has a newer or the only matching version. Dependencies are found the same way. +- **Unreachable channels stop the lookup.** Orbit moves to the next channel only when the registry says the package doesn't exist. Network and login errors fail. +- **Packages remember their channel.** `upgrade` and `rollback` keep it. `orbit install other::name` switches it. A package stays tied to its channel *name*, so changing that channel's URL changes where upgrades come from. +- **Environment.** `ORBIT_REGISTRY=/` replaces the URL of `main`, and `ORBIT_PLAIN_HTTP=1` applies to `main`. Other channels aren't affected. + +A `config.json` from an earlier version still sets the URL of `main` until a `config.toml` exists. `orbit channel add` carries it over. + +For a local `registry:2` without TLS: ```sh docker run -d -p 5000:5000 registry:2 -orbit init localhost:5000/pkgs --plain-http +orbit channel add local localhost:5000/pkgs --plain-http ``` ## Building @@ -89,8 +121,7 @@ package_dir=$(sh scripts/package-orbit.sh) && _build/native/release/build/main/main.exe publish "$package_dir" ``` -This publishes to the active registry (set `ORBIT_REGISTRY` to override the -default), so log in with `oras login ` first if needed. The +This publishes to the `main` channel (use `--channel ` for another), so log in with `oras login ` first if needed. The package contains a native Linux binary for the build machine's architecture. Use the same architecture on the install machine. `oras` and `tar` are still system prerequisites; the package does not bundle them. @@ -117,6 +148,7 @@ src/main/ model.mbt orbit.json / state.json / config.json (+ tests) registry.mbt oras wrappers: tags, resolve, fetch-config, pull, push ops.mbt dependency planner, install/remove/upgrade/rollback/gc + channels.mbt config.toml, channel priority and lookup (+ tests) main.mbt CLI ``` diff --git a/examples/config.toml b/examples/config.toml new file mode 100644 index 0000000..28612c6 --- /dev/null +++ b/examples/config.toml @@ -0,0 +1,9 @@ +# Example Orbit configuration: copy to ~/.orbit/config.toml. +# +# Channels are listed highest priority first. The built-in "main" channel +# (git.site.latha.org/nandi) is always included, ahead of the ones below unless +# you add a [[channels]] block with name = "main" to place it lower. + +[[channels]] +name = "example" +url = "git.site.latha.org/nandi/example" diff --git a/examples/greet/files/bin/greet b/examples/greet/files/bin/greet new file mode 100755 index 0000000..0893901 --- /dev/null +++ b/examples/greet/files/bin/greet @@ -0,0 +1,2 @@ +#!/bin/sh +echo "greetings from the example channel" diff --git a/examples/greet/orbit.json b/examples/greet/orbit.json new file mode 100644 index 0000000..0429083 --- /dev/null +++ b/examples/greet/orbit.json @@ -0,0 +1,7 @@ +{ + "name": "greet", + "version": "1.0.0", + "description": "Example package for the example channel", + "bin": ["bin/greet"], + "depends": { "hello": "^1.0.0" } +} diff --git a/moon.mod b/moon.mod index 271a5a0..10377b6 100644 --- a/moon.mod +++ b/moon.mod @@ -10,4 +10,8 @@ keywords = [ "package-manager", "oras", "oci" ] description = "A small package manager that stores packages as OCI artifacts via ORAS" -source = "src" \ No newline at end of file +source = "src" + +import { + "moonbit-community/toml@0.5.1", +} diff --git a/src/main/channels.mbt b/src/main/channels.mbt new file mode 100644 index 0000000..dfbefa1 --- /dev/null +++ b/src/main/channels.mbt @@ -0,0 +1,357 @@ +// Channels: the registries packages come from, listed highest priority first. +// "main" is built in. Configuration lives in /config.toml. + +///| +const MAIN_CHANNEL : String = "main" + +///| +const MAIN_URL : String = "git.site.latha.org/nandi" + +///| +struct Channel { + name : String + url : String // /; a package lives at / + plain_http : Bool +} + +///| +/// What `orbit init` writes. Everything is commented out, so the built-in +/// main channel stays implicit. +let config_template : String = + #|# Orbit configuration. + #|# + #|# Channels are registries that packages come from, highest priority first. + #|# The built-in "main" channel (git.site.latha.org/nandi) is always included. + #|# It has top priority unless you list it lower down. + #|# + #|# A plain `orbit install ` uses the first channel that has . + #|# `orbit install ::` picks one. + #| + #|# [[channels]] + #|# name = "example" + #|# url = "git.site.latha.org/nandi/example" + #| + #|# For a local registry without TLS: + #|# [[channels]] + #|# name = "local" + #|# url = "localhost:5000/pkgs" + #|# plain-http = true + #| + +///| +fn valid_url(url : String) -> Bool { + if url == "" || has_prefix(url, "-") || contains_str(url, "://") { + return false + } + for c in url { + if is_space(c) || c == '"' || c == '\\' { + return false + } + } + !has_prefix(url, "/") && + !has_prefix(drop_chars(url, chars(url).length() - 1), "/") +} + +///| +/// The channels a config file lists, in file order. "main" may omit its url. +/// Unknown keys are errors, so that a typo can't silently change priority. +fn parse_config(text : String) -> Array[Channel] raise OrbitError { + let doc = @toml.parse(text) catch { + e => raise OrbitError("config.toml: invalid TOML: \{e}") + } + let out : Array[Channel] = [] + let top = match doc { + TomlTable(t) => t + _ => raise OrbitError("config.toml: expected a table") + } + for key, value in top { + if key != "channels" { + raise OrbitError("config.toml: unknown key '\{key}'") + } + let items = match value { + TomlArray(a) => a + _ => raise OrbitError("config.toml: use [[channels]] blocks") + } + for item in items { + let t = match item { + TomlTable(t) => t + _ => raise OrbitError("config.toml: 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("config.toml: bad channel key '\{k}'") + } + } + if !valid_name(name) { + raise OrbitError("config.toml: invalid channel name '\{name}'") + } + if url == "" && name == MAIN_CHANNEL { + url = MAIN_URL + } + if !valid_url(url) { + raise OrbitError( + "config.toml: channel '\{name}' needs a url like host/namespace (no https://)", + ) + } + for c in out { + if c.name == name { + raise OrbitError("config.toml: channel '\{name}' is listed twice") + } + } + out.push(Channel::{ name, url, plain_http, }) + } + } + out +} + +///| +/// Add the built-in main channel if it isn't listed, then apply ORBIT_REGISTRY +/// and ORBIT_PLAIN_HTTP, which override main only. +fn resolve_channels( + listed : Array[Channel], + env_url : String, + env_plain_http : Bool, +) -> Array[Channel] { + let all : Array[Channel] = [] + if !listed.iter().any(fn(c) { c.name == MAIN_CHANNEL }) { + all.push(Channel::{ name: MAIN_CHANNEL, url: MAIN_URL, plain_http: false, }) + } + for c in listed { + all.push(c) + } + all.map(fn(c) { + if c.name == MAIN_CHANNEL { + Channel::{ + name: c.name, + url: if env_url != "" { + env_url + } else { + c.url + }, + plain_http: c.plain_http || env_plain_http, + } + } else { + c + } + }) +} + +///| +/// config.json from earlier versions holds a single registry, which stands in +/// for main. It is only read while there is no config.toml. +fn parse_legacy_config(text : String) -> Array[Channel] raise OrbitError { + let o = parse_object(text, "config.json") + let url = jstr(o, "registry", "") + if url == "" { + [] + } else { + [ + Channel::{ + name: MAIN_CHANNEL, + url, + plain_http: jbool(o, "plain_http", false), + }, + ] + } +} + +///| +fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError { + match read_text(root + "/config.toml") { + Some(t) => parse_config(t) + None => + match read_text(root + "/config.json") { + Some(t) => parse_legacy_config(t) + None => [] + } + } +} + +///| +fn channel_toml(c : Channel) -> String { + let url = if c.name == MAIN_CHANNEL && c.url == MAIN_URL { + "" + } else { + "url = \"\{c.url}\"\n" + } + let plain = if c.plain_http { "plain-http = true\n" } else { "" } + "[[channels]]\nname = \"\{c.name}\"\n" + url + plain +} + +///| +/// Append a channel at the lowest priority, keeping the file's comments. +fn cmd_channel_add( + root : String, + name : String, + url : String, + plain_http : Bool, +) -> Unit raise OrbitError { + let path = root + "/config.toml" + let text = match read_text(path) { + Some(t) => t + None => { + // First config.toml: carry over anything set in a legacy config.json. + let mut t = config_template + for c in load_listed_channels(root) { + if c.url != MAIN_URL || c.plain_http { + t = t + "\n" + channel_toml(c) + } + } + t + } + } + for c in parse_config(text) { + if c.name == name { + raise OrbitError("channel '\{name}' already exists; edit \{path}") + } + } + if name == MAIN_CHANNEL { + raise OrbitError( + "main is built in; to move or repoint it, add [[channels]] to \{path}", + ) + } + let sep = if has_prefix(drop_chars(text, chars(text).length() - 1), "\n") { + "\n" + } else { + "\n\n" + } + let updated = text + sep + channel_toml(Channel::{ name, url, plain_http, }) + parse_config(updated) |> ignore // never write a file we can't read back + sh_ok("mkdir -p " + sq(root)) + write_text_atomic(path, updated) + println("added channel \{name} (\{url}) to \{path}") +} + +///| +fn print_channels(channels : Array[Channel]) -> Unit { + for i, c in channels { + let plain = if c.plain_http { " (plain http)" } else { "" } + println("\{i + 1}. \{c.name} \{c.url}\{plain}") + } +} + +///| +fn find_channel(ctx : Ctx, name : String) -> Channel raise OrbitError { + for c in ctx.channels { + if c.name == name { + return c + } + } + raise OrbitError( + "channel '\{name}' is not configured (see `orbit channel list`)", + ) +} + +///| +/// "channel::rest" or just "rest". +fn split_channel(spec : String) -> (String?, String) { + let a = chars(spec) + for i = 0; i + 1 < a.length(); i = i + 1 { + if a[i] == ':' && a[i + 1] == ':' { + return (Some(slice(a, 0, i)), slice(a, i + 2, a.length())) + } + } + (None, spec) +} + +///| +/// The channel to get `name` from, with its tags there. A pinned channel is +/// used as is. Otherwise the first channel that has the package wins, even if +/// a lower one has a newer version. +fn locate( + ctx : Ctx, + name : String, + pin : String?, +) -> (Channel, Array[String]) raise OrbitError { + let candidates = match pin { + Some(p) => [find_channel(ctx, p)] + None => ctx.channels + } + for c in candidates { + match list_tags(c, name) { + Some(tags) => return (c, tags) + None => () + } + } + let searched = candidates.map(fn(c) { c.name }) + raise OrbitError( + "package '\{name}' not found in channel(s): \{join(searched, ", ")}", + ) +} + +///| +test "main is always included, first unless listed" { + let added = resolve_channels( + parse_config( + "[[channels]]\nname = \"b\"\nurl = \"h/b\"\n\n[[channels]]\nname = \"a\"\nurl = \"h/a\"\nplain-http = true\n", + ), + "", + false, + ) + assert_eq(added.map(fn(c) { c.name }), ["main", "b", "a"]) + assert_eq(added[0].url, MAIN_URL) + assert_true(added[2].plain_http) + let lowered = resolve_channels( + parse_config( + "[[channels]]\nname = \"a\"\nurl = \"h/a\"\n[[channels]]\nname = \"main\"\n", + ), + "", + false, + ) + assert_eq(lowered.map(fn(c) { c.name }), ["a", "main"]) + assert_eq(lowered[1].url, MAIN_URL) +} + +///| +test "env overrides main only" { + let cs = resolve_channels( + parse_config("[[channels]]\nname = \"a\"\nurl = \"h/a\"\n"), + "env/r", + true, + ) + assert_eq(cs[0].url, "env/r") + assert_true(cs[0].plain_http) + assert_eq(cs[1].url, "h/a") + assert_true(!cs[1].plain_http) +} + +///| +test "template and bad configs" { + assert_eq(parse_config(config_template).length(), 0) + for + bad in [ + "[[channels]]\nname = \"a\"\n", "[[channels]]\nname = \"a\"\nurl = \"https://h/a\"\n", + "[[channels]]\nname = \"a\"\nurl = \"h/a\"\n[[channels]]\nname = \"a\"\nurl = \"h/b\"\n", + "[[channel]]\nname = \"a\"\nurl = \"h/a\"\n", "[[channels]]\nname = \"a\"\nurl = \"h/a\"\nplain_http = true\n", + "[[channels", + ] { + let ok = try { + parse_config(bad) |> ignore + true + } catch { + _ => false + } + assert_false(ok) + } +} + +///| +test "channel spec" { + assert_eq(split_channel("example::greet@^1"), (Some("example"), "greet@^1")) + assert_eq(split_channel("greet"), (None, "greet")) +} + +///| +test "only a missing repository falls through to the next channel" { + assert_true(is_missing_repo("Error response from registry: name unknown")) + assert_true(is_missing_repo("GET \"u\": response status code 404: Not Found")) + assert_false(is_missing_repo("dial tcp: lookup x: no such host")) + assert_false(is_missing_repo("connect: connection refused")) + assert_false(is_missing_repo("response status code 401: Unauthorized")) +} diff --git a/src/main/main.mbt b/src/main/main.mbt index 99f8119..3652280 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -5,9 +5,13 @@ let usage : String = #|orbit - packages as OCI artifacts (via oras) #| #|usage: - #| orbit init [registry] [--plain-http] set up; optionally save a registry - #| orbit publish [--no-latest] push /orbit.json + /files/ - #| orbit install [@constraint]... install with dependencies + #| orbit init create folders and config.toml + #| orbit channel list channels, highest priority first + #| 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 @@ -19,17 +23,14 @@ let usage : String = #| orbit env print the PATH line for your shell #| #|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 * - #|environment: ORBIT_ROOT (default ~/.orbit), ORBIT_REGISTRY, ORBIT_PLAIN_HTTP=1 - #|default registry: git.site.latha.org/nandi + #|config: /config.toml + #|environment: ORBIT_ROOT (default ~/.orbit); ORBIT_REGISTRY and + #| ORBIT_PLAIN_HTTP=1 override the built-in main channel #|authentication: run `oras login ` once. ///| -/// With no registry, only create the directories: any saved config is left -/// alone and the built-in default is not written to disk. -fn cmd_init(registry : String, plain_http : Bool) -> Unit raise OrbitError { - if registry == "" && plain_http { - raise OrbitError("usage: orbit init --plain-http") - } +/// Create the directories, and a config.toml if there is no config yet. +fn cmd_init() -> Unit raise OrbitError { let root = orbit_root() sh_ok( "mkdir -p " + @@ -39,14 +40,14 @@ fn cmd_init(registry : String, plain_http : Bool) -> Unit raise OrbitError { " " + sq(root + "/tmp"), ) - if registry != "" { - write_text_atomic( - root + "/config.json", - config_to_text(Config::{ registry, plain_http, }), - ) + let config = root + "/config.toml" + // A legacy config.json is still honored, so don't hide it with a new file. + if !exists(config) && !exists(root + "/config.json") { + write_text_atomic(config, config_template) } println("orbit root: \{root}") - println("registry: \{load_ctx().cfg.registry}") + println("channels:") + print_channels(load_ctx().channels) println("add to your shell profile:") println(" export PATH=\"\{root}/bin:$PATH\"") } @@ -67,25 +68,53 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError { let cmd = args[0] let pos : Array[String] = [] let flags : Array[String] = [] - for i = 1; i < args.length(); i = i + 1 { - if has_prefix(args[i], "--") { + let mut publish_to = MAIN_CHANNEL + let mut i = 1 + while i < args.length() { + if args[i] == "--channel" { + if cmd != "publish" || i + 1 >= args.length() { + raise OrbitError("usage: orbit publish --channel ") + } + publish_to = args[i + 1] + i = i + 1 + } else if has_prefix(args[i], "--") { flags.push(args[i]) } else { pos.push(args[i]) } + i = i + 1 } match cmd { "help" | "-h" | "--help" => println(usage) "init" => { - cmd_init( - if pos.length() > 0 { pos[0] } else { "" }, - flags.contains("--plain-http"), - ) + if pos.length() > 0 { + raise OrbitError( + "init takes no arguments; use `orbit channel add `", + ) + } + cmd_init() + } + "channel" => { + need(pos, 1, "channel list|add") + match pos[0] { + "list" => print_channels(load_ctx().channels) + "add" => { + need(pos, 3, "channel add [--plain-http]") + cmd_channel_add( + orbit_root(), + pos[1], + pos[2], + flags.contains("--plain-http"), + ) + } + other => raise OrbitError("unknown channel command '\{other}'") + } } "env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"") "publish" => { need(pos, 1, "publish ") - publish(load_ctx(), pos[0], !(flags.contains("--no-latest"))) + 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")) diff --git a/src/main/model.mbt b/src/main/model.mbt index 68e018a..f8de8b1 100644 --- a/src/main/model.mbt +++ b/src/main/model.mbt @@ -3,9 +3,6 @@ ///| const CONFIG_MEDIA_TYPE : String = "application/vnd.latha.orbit.config.v1+json" -///| -const DEFAULT_REGISTRY : String = "git.site.latha.org/nandi" - ///| const LAYER_MEDIA_TYPE : String = "application/vnd.latha.orbit.layer.v1.tar+gzip" @@ -22,6 +19,7 @@ struct Manifest { ///| /// A previously installed build, kept for rollback. struct Gen { + channel : String version : String digest : String bins : Array[String] @@ -31,6 +29,7 @@ struct Gen { ///| struct Installed { name : String + mut channel : String mut version : String mut digest : String mut explicit : Bool @@ -40,16 +39,10 @@ struct Installed { history : Array[Gen] } -///| -struct Config { - registry : String - plain_http : Bool -} - ///| struct Ctx { root : String - cfg : Config + channels : Array[Channel] // highest priority first state : Map[String, Installed] } @@ -158,11 +151,11 @@ fn valid_name(s : String) -> Bool { c == '-' || c == '_' || c == '.' - if !(ok) { + if !ok { return false } } - !(has_prefix(s, ".")) + !has_prefix(s, ".") } ///| @@ -189,21 +182,21 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError { depends: jmap(o, "depends"), bins: jstrs(o, "bin"), } - if !(valid_name(m.name)) { + if !valid_name(m.name) { raise OrbitError( "orbit.json: invalid name '\{m.name}' (use a-z, 0-9, '-', '_', '.')", ) } - if !(is_ver(m.version)) { + if !is_ver(m.version) { raise OrbitError("orbit.json: version '\{m.version}' is not semver") } for b in m.bins { - if !(valid_rel_path(b)) { + if !valid_rel_path(b) { raise OrbitError("orbit.json: bin path '\{b}' must be relative") } } for dep, _ in m.depends { - if !(valid_name(dep)) { + if !valid_name(dep) { raise OrbitError("orbit.json: invalid dependency name '\{dep}'") } } @@ -215,6 +208,7 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError { ///| fn gen_json(g : Gen) -> Json { let o : Map[String, Json] = Map([]) + o["channel"] = Json::string(g.channel) o["version"] = Json::string(g.version) o["digest"] = Json::string(g.digest) o["bin"] = strs_json(g.bins) @@ -225,6 +219,7 @@ fn gen_json(g : Gen) -> Json { ///| fn installed_json(p : Installed) -> Json { let o : Map[String, Json] = Map([]) + o["channel"] = Json::string(p.channel) o["version"] = Json::string(p.version) o["digest"] = Json::string(p.digest) o["explicit"] = bool_json(p.explicit) @@ -267,6 +262,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { match hj { Json::Object(h) => history.push(Gen::{ + channel: jstr(h, "channel", MAIN_CHANNEL), version: jstr(h, "version", ""), digest: jstr(h, "digest", ""), bins: jstrs(h, "bin"), @@ -279,6 +275,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { } out[name] = Installed::{ name, + channel: jstr(o, "channel", MAIN_CHANNEL), version: jstr(o, "version", ""), digest: jstr(o, "digest", ""), explicit: jbool(o, "explicit", false), @@ -296,25 +293,6 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError { out } -// ---------------------------------------------------------------- config - -///| -fn config_to_text(c : Config) -> String { - let o : Map[String, Json] = Map([]) - o["registry"] = Json::string(c.registry) - o["plain_http"] = bool_json(c.plain_http) - Json::object(o).stringify(indent=2) + "\n" -} - -///| -fn config_from_text(text : String) -> Config raise OrbitError { - let o = parse_object(text, "config.json") - Config::{ - registry: jstr(o, "registry", ""), - plain_http: jbool(o, "plain_http", false), - } -} - // ---------------------------------------------------------------- context ///| @@ -328,34 +306,19 @@ fn orbit_root() -> String { } ///| -/// ORBIT_REGISTRY wins, then config.json, then the built-in default. -fn pick_registry(env : String, file : String) -> String { - if env != "" { - env - } else if file != "" { - file - } else { - DEFAULT_REGISTRY - } -} - -///| -/// Load config and state. ORBIT_REGISTRY / ORBIT_PLAIN_HTTP override the file. +/// Load channels and state. fn load_ctx() -> Ctx raise OrbitError { let root = orbit_root() - let file_cfg = match read_text(root + "/config.json") { - Some(t) => config_from_text(t) - None => Config::{ registry: "", plain_http: false, } - } - let cfg = Config::{ - registry: pick_registry(getenv("ORBIT_REGISTRY"), file_cfg.registry), - plain_http: file_cfg.plain_http || getenv("ORBIT_PLAIN_HTTP") == "1", - } + let channels = resolve_channels( + load_listed_channels(root), + getenv("ORBIT_REGISTRY"), + getenv("ORBIT_PLAIN_HTTP") == "1", + ) let state = match read_text(root + "/state.json") { Some(t) => state_from_text(t) None => Map([]) } - Ctx::{ root, cfg, state, } + Ctx::{ root, channels, state, } } ///| @@ -389,14 +352,7 @@ test "manifest roundtrip" { assert_eq(m.name, "hello") assert_eq(m.bins, ["bin/hello"]) assert_eq(m.depends.get("lib"), Some("^1")) - assert_true(!(valid_rel_path("../x"))) - assert_true(!(valid_rel_path("/bin/sh"))) + assert_true(!valid_rel_path("../x")) + assert_true(!valid_rel_path("/bin/sh")) assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef") } - -///| -test "registry precedence" { - assert_eq(pick_registry("env/r", "file/r"), "env/r") - assert_eq(pick_registry("", "file/r"), "file/r") - assert_eq(pick_registry("", ""), DEFAULT_REGISTRY) -} diff --git a/src/main/moon.pkg b/src/main/moon.pkg index 0d3cab0..9b8c1ff 100644 --- a/src/main/moon.pkg +++ b/src/main/moon.pkg @@ -1,5 +1,6 @@ import { "moonbitlang/core/json", + "moonbit-community/toml", } pkgtype(kind: "executable") diff --git a/src/main/ops.mbt b/src/main/ops.mbt index 7821660..e63433b 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -4,6 +4,7 @@ /// One package in an install plan. struct Step { name : String + channel : String version : String digest : String manifest : Manifest @@ -62,7 +63,7 @@ fn constraints_for( } } for other, st in p.steps { - if other != name && !(p.ctx.state.contains(other)) { + if other != name && !p.ctx.state.contains(other) { match st.manifest.depends.get(name) { Some(c) => cons.push(c) None => () @@ -78,10 +79,16 @@ fn visit( name : String, requested : String, explicit : Bool, + pin : String?, // channel the user asked for ) -> Unit raise OrbitError { match p.steps.get(name) { Some(st) => { - if !(satisfies_all(st.version, [requested])) { + 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", ) @@ -97,10 +104,15 @@ fn visit( let cons = constraints_for(p, name, requested) let upgrading = p.upgrade.contains(name) match p.ctx.state.get(name) { - Some(inst) => - if !(upgrading) && satisfies_all(inst.version, cons) { + 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), @@ -116,23 +128,30 @@ fn visit( p.order.push(st) return } + } None => () } - let tags = list_tags(p.ctx, name) + // 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} satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}", + "no version of \{name} in channel '\{ch.name}' satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}", ) } } - let digest = resolve_digest(p.ctx, name, tag) - let m = fetch_manifest(p.ctx, name, digest) + let digest = resolve_digest(ch, name, tag) + let m = fetch_manifest(ch, name, digest) let prev = p.ctx.state.get(name) let st = Step::{ name, + channel: ch.name, version: m.version, digest, manifest: m, @@ -157,19 +176,20 @@ fn visit( // Register before recursing so dependency cycles terminate. p.steps[name] = st for dep, dc in m.depends { - visit(p, dep, dc, false) + visit(p, dep, dc, false, None) } p.order.push(st) } ///| -/// "name" or "name@constraint" -fn parse_spec(spec : String) -> (String, String) raise OrbitError { - let (name, c) = split_first(spec, '@') - if !(valid_name(name)) { +/// "[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}'") } - (name, if c == "" { "*" } else { c }) + (channel, name, if c == "" { "*" } else { c }) } ///| @@ -230,7 +250,8 @@ fn check_bin_conflicts( ///| /// Switch `name` to a fetched build, keeping the old one for rollback. fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { - let dir = fetch_into_store(ctx, st.name, st.digest) + let ch = find_channel(ctx, st.channel) + let dir = fetch_into_store(ctx, ch, st.name, st.digest) for b in st.manifest.bins { if sh("test -f " + sq(dir + "/" + b)) != 0 { raise OrbitError("\{st.name}: bin '\{b}' missing from package contents") @@ -241,6 +262,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { Some(inst) => { unlink_bins(ctx, inst.bins) inst.history.push(Gen::{ + channel: inst.channel, version: inst.version, digest: inst.digest, bins: inst.bins, @@ -249,6 +271,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { while inst.history.length() > 2 { inst.history.remove(0) |> ignore } + inst.channel = st.channel inst.version = st.version inst.digest = st.digest inst.bins = st.manifest.bins @@ -262,6 +285,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { None => { ctx.state[st.name] = Installed::{ name: st.name, + channel: st.channel, version: st.version, digest: st.digest, explicit: st.explicit, @@ -285,6 +309,7 @@ fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError { if st.keep { match ctx.state.get(st.name) { Some(inst) => { + inst.channel = st.channel inst.explicit = st.explicit inst.constraint = st.constraint } @@ -309,12 +334,12 @@ fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner { ///| fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { if specs.length() == 0 { - raise OrbitError("usage: orbit install [@constraint]...") + raise OrbitError("usage: orbit install [channel::][@constraint]...") } let p = new_planner(ctx, []) for s in specs { - let (name, c) = parse_spec(s) - visit(p, name, c, true) + let (channel, name, c) = parse_spec(s) + visit(p, name, c, true, channel) } apply_plan(ctx, p) } @@ -330,7 +355,7 @@ fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { } } else { for n in names { - if !(ctx.state.contains(n)) { + if !ctx.state.contains(n) { raise OrbitError("\{n} is not installed") } targets.push(n) @@ -339,7 +364,7 @@ fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { let p = new_planner(ctx, targets) for n in targets { match ctx.state.get(n) { - Some(inst) => visit(p, n, "*", inst.explicit) + Some(inst) => visit(p, n, "*", inst.explicit, None) None => () } } @@ -378,7 +403,7 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError { changed = false let orphans : Array[String] = [] for name, p in ctx.state { - if !(p.explicit) && reverse_deps(ctx, name).length() == 0 { + if !p.explicit && reverse_deps(ctx, name).length() == 0 { orphans.push(name) } } @@ -399,18 +424,18 @@ fn cmd_remove( raise OrbitError("usage: orbit remove ...") } for n in names { - if !(ctx.state.contains(n)) { + if !ctx.state.contains(n) { raise OrbitError("\{n} is not installed") } } for n in names { let users : Array[String] = [] for u in reverse_deps(ctx, n) { - if !(names.contains(u)) { + if !names.contains(u) { users.push(u) } } - if users.length() > 0 && !(force) { + if users.length() > 0 && !force { raise OrbitError( "\{n} is required by \{join(users, ", ")} (use --force to remove anyway)", ) @@ -435,18 +460,20 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { None => raise OrbitError("\{name} has no previous version to roll back to") } let dir = store_dir(ctx, name, prev.digest) - if !(exists(dir)) { + if !exists(dir) { raise OrbitError( "previous build of \{name} (\{prev.version}) is no longer in the store", ) } unlink_bins(ctx, inst.bins) inst.history.push(Gen::{ + channel: inst.channel, version: inst.version, digest: inst.digest, bins: inst.bins, depends: inst.depends, }) + inst.channel = prev.channel let from = inst.version inst.version = prev.version inst.digest = prev.digest @@ -460,7 +487,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { for dep, c in inst.depends { match ctx.state.get(dep) { Some(d) => - if !(satisfies_all(d.version, [c])) { + if !satisfies_all(d.version, [c]) { missing.push(dep + "@" + c) } None => missing.push(dep + "@" + c) @@ -477,7 +504,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { /// Delete store entries that are neither current nor kept for rollback. fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { let store = ctx.root + "/store" - if !(exists(store)) { + if !exists(store) { println("store is empty") return } @@ -494,7 +521,7 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { keep.push(store_id(g.digest)) } for id in lines(capture("ls -1 " + sq(store + "/" + pkg))) { - if !(keep.contains(id)) { + if !keep.contains(id) { sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id)) freed = freed + 1 } @@ -515,15 +542,34 @@ fn cmd_list(ctx : Ctx) -> Unit { } for name, p in ctx.state { let kind = if p.explicit { "" } else { " (dependency)" } - println("\{name} \{p.version}\{kind}") + let from = if p.channel == MAIN_CHANNEL { "" } else { " [\{p.channel}]" } + println("\{name} \{p.version}\{from}\{kind}") } } ///| -fn cmd_info(ctx : Ctx, name : String) -> Unit raise OrbitError { +/// Where to look up "[channel::]name": the channel asked for, else the one it +/// was installed from, else by priority. +fn locate_spec( + ctx : Ctx, + spec : String, +) -> (String, Channel, Array[String]) raise OrbitError { + let (pin, name) = split_channel(spec) + let wanted = match pin { + Some(c) => Some(c) + None => ctx.state.get(name).map(fn(i) { i.channel }) + } + let (ch, tags) = locate(ctx, name, wanted) + (name, ch, tags) +} + +///| +fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError { + let (_, name) = split_channel(spec) match ctx.state.get(name) { Some(p) => { println("\{name} \{p.version} (installed)") + println(" channel: \{p.channel}") println(" digest: \{p.digest}") println(" constraint: \{p.constraint}") println(" bin: \{join(p.bins, " ")}") @@ -542,11 +588,11 @@ fn cmd_info(ctx : Ctx, name : String) -> Unit raise OrbitError { } None => () } - let tags = list_tags(ctx, name) + let (_, ch, tags) = locate_spec(ctx, spec) match pick_tag(tags, ["*"]) { Some(t) => { - let m = fetch_manifest(ctx, name, resolve_digest(ctx, name, t)) - println("\{name} \{m.version} (latest in \{ctx.cfg.registry})") + let m = fetch_manifest(ch, name, resolve_digest(ch, name, t)) + println("\{name} \{m.version} (latest in \{ch.name}: \{ch.url})") if m.description != "" { println(" \{m.description}") } @@ -556,10 +602,11 @@ fn cmd_info(ctx : Ctx, name : String) -> Unit raise OrbitError { } ///| -fn cmd_versions(ctx : Ctx, name : String) -> Unit raise OrbitError { - for v in sorted_versions(list_tags(ctx, name)) { +fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError { + let (name, ch, tags) = locate_spec(ctx, spec) + for v in sorted_versions(tags) { let mark = match ctx.state.get(name) { - Some(p) => if p.version == v { " *" } else { "" } + Some(p) => if p.version == v && p.channel == ch.name { " *" } else { "" } None => "" } println(v + mark) @@ -568,15 +615,24 @@ fn cmd_versions(ctx : Ctx, name : String) -> Unit raise OrbitError { ///| fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { - let out = capture(oras(ctx, "repo ls " + sq(ctx.cfg.registry))) catch { - _ => - raise OrbitError( - "registry does not allow listing repositories (catalog API); try `orbit info `", - ) - } - for r in lines(out) { - if contains_str(r, term) { - println(r) + let mut listed = 0 + for ch in ctx.channels { + let out = capture(oras(ch, "repo ls " + sq(ch.url))) catch { + _ => { + println("warning: channel '\{ch.name}' does not allow listing packages") + continue + } + } + listed = listed + 1 + for r in lines(out) { + if contains_str(r, term) { + println("\{ch.name}::\{r}") + } } } + if listed == 0 { + raise OrbitError( + "no channel allows listing packages (catalog API); try `orbit info `", + ) + } } diff --git a/src/main/registry.mbt b/src/main/registry.mbt index 5fc8bfd..2350650 100644 --- a/src/main/registry.mbt +++ b/src/main/registry.mbt @@ -2,31 +2,55 @@ // Authentication is whatever `oras login` has stored. ///| -fn oras(ctx : Ctx, args : String) -> String { - "oras " + args + (if ctx.cfg.plain_http { " --plain-http" } else { "" }) +fn oras(ch : Channel, args : String) -> String { + "oras " + args + (if ch.plain_http { " --plain-http" } else { "" }) } ///| -fn repo_of(ctx : Ctx, name : String) -> String { - ctx.cfg.registry + "/" + name +fn repo_of(ch : Channel, name : String) -> String { + ch.url + "/" + name } ///| -fn list_tags(ctx : Ctx, name : String) -> Array[String] raise OrbitError { - let out = capture(oras(ctx, "repo tags " + sq(repo_of(ctx, name)))) catch { - _ => raise OrbitError("package '\{name}' not found in \{ctx.cfg.registry}") +/// Whether oras output says the repository doesn't exist, as opposed to the +/// registry being unreachable or refusing access. +fn is_missing_repo(err : String) -> Bool { + contains_str(err, "name unknown") || + contains_str(err, "response status code 404") +} + +///| +/// The tags of `name` in a channel, or None if the channel doesn't have it. +/// Any other failure is an error: falling through to a lower priority channel +/// could install a different package with the same name. +fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError { + let errfile = trim(capture("mktemp")) + let cmd = oras(ch, "repo tags " + sq(repo_of(ch, name))) + " 2>" + sq(errfile) + let out = Some(capture(cmd)) catch { _ => None } + let err = match read_text(errfile) { + Some(t) => trim(t) + None => "" + } + sh("rm -f " + sq(errfile)) |> ignore + match out { + Some(o) => Some(lines(o)) + None => + if is_missing_repo(err) { + None + } else { + raise OrbitError("channel '\{ch.name}' (\{ch.url}): \{err}") + } } - lines(out) } ///| fn resolve_digest( - ctx : Ctx, + ch : Channel, name : String, tag : String, ) -> String raise OrbitError { let d = trim( - capture(oras(ctx, "resolve " + sq(repo_of(ctx, name) + ":" + tag))), + capture(oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag))), ) if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) { raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'") @@ -37,12 +61,12 @@ fn resolve_digest( ///| /// Fetch only the config blob (orbit.json); no layer download needed to plan. fn fetch_manifest( - ctx : Ctx, + ch : Channel, name : String, digest : String, ) -> Manifest raise OrbitError { let text = capture( - oras(ctx, "manifest fetch-config " + sq(repo_of(ctx, name) + "@" + digest)), + oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)), ) let m = parse_manifest(text) if m.name != name { @@ -59,6 +83,7 @@ fn fetch_manifest( /// complete or absent. fn fetch_into_store( ctx : Ctx, + ch : Channel, name : String, digest : String, ) -> String raise OrbitError { @@ -69,13 +94,10 @@ fn fetch_into_store( let tmp = ctx.root + "/tmp/" + name + "-" + store_id(digest) sh_ok("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp + "/root")) sh_ok( - oras( - ctx, - "pull -o " + sq(tmp) + " " + sq(repo_of(ctx, name) + "@" + digest), - ) + + oras(ch, "pull -o " + sq(tmp) + " " + sq(repo_of(ch, name) + "@" + digest)) + " >/dev/null", ) - if !(exists(tmp + "/pkg.tar.gz")) { + if !exists(tmp + "/pkg.tar.gz") { raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer") } sh_ok( @@ -101,7 +123,7 @@ fn fetch_into_store( ///| /// Pack `/files` and push it with `/orbit.json` as the config blob. fn publish( - ctx : Ctx, + ch : Channel, dir : String, also_latest : Bool, ) -> Unit raise OrbitError { @@ -111,7 +133,7 @@ fn publish( } let m = parse_manifest(text) let files = dir + "/files" - if !(exists(files)) { + if !exists(files) { raise OrbitError("\{files} not found (package contents go in files/)") } for b in m.bins { @@ -130,9 +152,9 @@ fn publish( sh_ok("cp " + sq(dir + "/orbit.json") + " " + sq(tmp + "/orbit.json")) let tags = if also_latest { m.version + ",latest" } else { m.version } let push = oras( - ctx, + ch, "push " + - sq(repo_of(ctx, m.name) + ":" + tags) + + sq(repo_of(ch, m.name) + ":" + tags) + " --config " + sq("orbit.json:" + CONFIG_MEDIA_TYPE) + " --annotation " + @@ -151,5 +173,5 @@ fn publish( if rc != 0 { raise OrbitError("oras push failed (exit \{rc})") } - println("published \{m.name} \{m.version} to \{repo_of(ctx, m.name)}") + println("published \{m.name} \{m.version} to \{repo_of(ch, m.name)}") }