Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec64fb07cf | ||
|
|
44d7ac2346 | ||
|
|
984494f556 | ||
|
|
8eadda5815 | ||
|
|
6a369dfa5e | ||
|
|
a999db54a8 | ||
|
|
83a1784fca | ||
|
|
ec21287549 | ||
|
|
65e5dc966f | ||
|
|
2eff722311 | ||
|
|
6069a261db |
No files matched your search
@@ -36,7 +36,7 @@ mypkg/
|
||||
}
|
||||
```
|
||||
|
||||
In a channel this becomes `<channel url>/mytool:1.4.0`, plus the `latest` tag:
|
||||
In a channel this becomes `<channel url>/mytool:1.4.0`, plus the `latest` tag. The manifest sets `artifactType` to `application/vnd.latha.orbit.v1`, which is how `orbit search` tells Orbit packages apart from other OCI artifacts such as Helm charts. Packages published before this have no `artifactType`, so search also recognises the Orbit config media type:
|
||||
|
||||
| Part | Media type |
|
||||
|---|---|
|
||||
@@ -114,6 +114,10 @@ moon test --target native # semver / manifest unit tests
|
||||
```
|
||||
|
||||
Or run `just install` to build and copy the binary to `~/.local/bin/orbit`.
|
||||
It also adds Orbit's package bin directory to `~/.bashrc` if the setup line
|
||||
isn't already there. Open a new Bash shell or run `source ~/.bashrc` to pick
|
||||
up the change in your current shell. `~/.local/bin` must already be on `PATH`
|
||||
to run `orbit` itself by name.
|
||||
|
||||
Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`.
|
||||
|
||||
@@ -171,4 +175,5 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp
|
||||
|
||||
- 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.
|
||||
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit info <name>` there.
|
||||
- `orbit info <name>` reads installed package details without contacting the registry. Use `orbit versions <name>` to check published versions.
|
||||
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions <name>` if you already know the package name.
|
||||
@@ -0,0 +1,11 @@
|
||||
# greet
|
||||
|
||||
`greet` is an example Orbit package from the `example` channel. It installs a
|
||||
small greeting command and depends on `hello` from the built-in `main`
|
||||
channel.
|
||||
|
||||
- [Installation and usage](files/share/doc/greet/README.md)
|
||||
- [Package on Gitea](https://git.site.latha.org/nandi/-/packages/container/example%2Fgreet/latest)
|
||||
|
||||
This directory contains the package manifest (`orbit.json`) and the files Orbit
|
||||
installs (`files/`).
|
||||
@@ -10,6 +10,10 @@ build:
|
||||
test:
|
||||
moon test --target native
|
||||
|
||||
# Build orbit and install it to ~/.local/bin.
|
||||
# Install Orbit to ~/.local/bin and set up its package PATH for Bash.
|
||||
install: build
|
||||
install -Dm755 _build/native/release/build/main/main.exe "$HOME/.local/bin/orbit"
|
||||
@line='export PATH="${ORBIT_ROOT:-$HOME/.orbit}/bin:$PATH"'; rc="$HOME/.bashrc"; \
|
||||
if [ ! -f "$rc" ] || ! grep -Fqx -- "$line" "$rc"; then \
|
||||
printf '\n%s\n' "$line" >> "$rc"; \
|
||||
fi
|
||||
@@ -14,4 +14,5 @@ source = "src"
|
||||
|
||||
import {
|
||||
"moonbit-community/toml@0.5.1",
|
||||
"moonbitlang/async@0.22.9",
|
||||
}
|
||||
@@ -162,7 +162,7 @@ fn parse_legacy_config(text : String) -> Array[Channel] raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError {
|
||||
async fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError {
|
||||
match read_text(root + "/config.toml") {
|
||||
Some(t) => parse_config(t)
|
||||
None =>
|
||||
@@ -186,7 +186,7 @@ fn channel_toml(c : Channel) -> String {
|
||||
|
||||
///|
|
||||
/// Append a channel at the lowest priority, keeping the file's comments.
|
||||
fn cmd_channel_add(
|
||||
async fn cmd_channel_add(
|
||||
root : String,
|
||||
name : String,
|
||||
url : String,
|
||||
@@ -264,7 +264,7 @@ fn split_channel(spec : String) -> (String?, String) {
|
||||
/// 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(
|
||||
async fn locate(
|
||||
ctx : Ctx,
|
||||
name : String,
|
||||
pin : String?,
|
||||
|
||||
+5
-5
@@ -16,7 +16,7 @@ let usage : String =
|
||||
#| orbit upgrade [name...] upgrade within constraints
|
||||
#| orbit rollback <name> switch to the previous build
|
||||
#| orbit list installed packages
|
||||
#| orbit info <name> local and remote details
|
||||
#| orbit info [channel::]<name> installed package details (local only)
|
||||
#| orbit versions <name> published versions
|
||||
#| orbit search [term] list repositories (needs catalog API)
|
||||
#| orbit gc delete unused builds from the store
|
||||
@@ -30,7 +30,7 @@ let usage : String =
|
||||
|
||||
///|
|
||||
/// Create the directories, and a config.toml if there is no config yet.
|
||||
fn cmd_init() -> Unit raise OrbitError {
|
||||
async fn cmd_init() -> Unit raise OrbitError {
|
||||
let root = orbit_root()
|
||||
sh_ok(
|
||||
"mkdir -p " +
|
||||
@@ -60,7 +60,7 @@ fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError
|
||||
}
|
||||
|
||||
///|
|
||||
fn dispatch(args : Array[String]) -> Unit raise OrbitError {
|
||||
async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
|
||||
if args.length() == 0 {
|
||||
println(usage)
|
||||
return
|
||||
@@ -125,7 +125,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError {
|
||||
}
|
||||
"list" | "ls" => cmd_list(load_ctx())
|
||||
"info" => {
|
||||
need(pos, 1, "info <name>")
|
||||
need(pos, 1, "info [channel::]<name>")
|
||||
cmd_info(load_ctx(), pos[0])
|
||||
}
|
||||
"versions" => {
|
||||
@@ -140,7 +140,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn main {
|
||||
async fn main {
|
||||
if sh("command -v oras >/dev/null 2>&1") != 0 {
|
||||
println("orbit: error: `oras` not found on PATH (https://oras.land)")
|
||||
c_exit(1)
|
||||
|
||||
+23
-2
@@ -3,6 +3,10 @@
|
||||
///|
|
||||
const CONFIG_MEDIA_TYPE : String = "application/vnd.latha.orbit.config.v1+json"
|
||||
|
||||
///|
|
||||
/// Manifest artifactType that marks a repository as an Orbit package.
|
||||
const ORBIT_ARTIFACT_TYPE : String = "application/vnd.latha.orbit.v1"
|
||||
|
||||
///|
|
||||
const LAYER_MEDIA_TYPE : String = "application/vnd.latha.orbit.layer.v1.tar+gzip"
|
||||
|
||||
@@ -23,6 +27,7 @@ struct Gen {
|
||||
channel : String
|
||||
version : String
|
||||
digest : String
|
||||
description : String
|
||||
bins : Array[String]
|
||||
depends : Map[String, String]
|
||||
}
|
||||
@@ -33,6 +38,7 @@ struct Installed {
|
||||
mut channel : String
|
||||
mut version : String
|
||||
mut digest : String
|
||||
mut description : String
|
||||
mut explicit : Bool
|
||||
mut constraint : String
|
||||
mut bins : Array[String]
|
||||
@@ -213,6 +219,7 @@ fn gen_json(g : Gen) -> Json {
|
||||
o["channel"] = Json::string(g.channel)
|
||||
o["version"] = Json::string(g.version)
|
||||
o["digest"] = Json::string(g.digest)
|
||||
o["description"] = Json::string(g.description)
|
||||
o["bin"] = strs_json(g.bins)
|
||||
o["depends"] = map_json(g.depends)
|
||||
Json::object(o)
|
||||
@@ -224,6 +231,7 @@ fn installed_json(p : Installed) -> Json {
|
||||
o["channel"] = Json::string(p.channel)
|
||||
o["version"] = Json::string(p.version)
|
||||
o["digest"] = Json::string(p.digest)
|
||||
o["description"] = Json::string(p.description)
|
||||
o["explicit"] = bool_json(p.explicit)
|
||||
o["constraint"] = Json::string(p.constraint)
|
||||
o["bin"] = strs_json(p.bins)
|
||||
@@ -267,6 +275,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
|
||||
channel: jstr(h, "channel", MAIN_CHANNEL),
|
||||
version: jstr(h, "version", ""),
|
||||
digest: jstr(h, "digest", ""),
|
||||
description: jstr(h, "description", ""),
|
||||
bins: jstrs(h, "bin"),
|
||||
depends: jmap(h, "depends"),
|
||||
})
|
||||
@@ -280,6 +289,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
|
||||
channel: jstr(o, "channel", MAIN_CHANNEL),
|
||||
version: jstr(o, "version", ""),
|
||||
digest: jstr(o, "digest", ""),
|
||||
description: jstr(o, "description", ""),
|
||||
explicit: jbool(o, "explicit", false),
|
||||
constraint: jstr(o, "constraint", "*"),
|
||||
bins: jstrs(o, "bin"),
|
||||
@@ -295,6 +305,17 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
test "installed and rollback descriptions round trip with legacy entries" {
|
||||
let text =
|
||||
#|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}}
|
||||
let state = state_from_text(state_to_text(state_from_text(text)))
|
||||
guard state.get("tool") is Some(p) else { fail("missing installed package") }
|
||||
assert_eq(p.description, "Current build")
|
||||
assert_eq(p.history[0].description, "Previous build")
|
||||
assert_eq(p.history[1].description, "")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- context
|
||||
|
||||
///|
|
||||
@@ -309,7 +330,7 @@ fn orbit_root() -> String {
|
||||
|
||||
///|
|
||||
/// Load channels and state.
|
||||
fn load_ctx() -> Ctx raise OrbitError {
|
||||
async fn load_ctx() -> Ctx raise OrbitError {
|
||||
let root = orbit_root()
|
||||
let channels = resolve_channels(
|
||||
load_listed_channels(root),
|
||||
@@ -324,7 +345,7 @@ fn load_ctx() -> Ctx raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn save_state(ctx : Ctx) -> Unit raise OrbitError {
|
||||
async fn save_state(ctx : Ctx) -> Unit raise OrbitError {
|
||||
write_text_atomic(ctx.root + "/state.json", state_to_text(ctx.state))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import {
|
||||
"moonbitlang/core/json",
|
||||
"moonbit-community/toml",
|
||||
"moonbitlang/async",
|
||||
"moonbitlang/async/fs",
|
||||
"moonbitlang/async/process",
|
||||
}
|
||||
|
||||
pkgtype(kind: "executable")
|
||||
|
||||
+304
-49
@@ -26,7 +26,7 @@ fn manifest_of_installed(p : Installed) -> Manifest {
|
||||
Manifest::{
|
||||
name: p.name,
|
||||
version: p.version,
|
||||
description: "",
|
||||
description: p.description,
|
||||
documentation: "",
|
||||
depends: p.depends,
|
||||
bins: p.bins,
|
||||
@@ -75,7 +75,7 @@ fn constraints_for(
|
||||
}
|
||||
|
||||
///|
|
||||
fn visit(
|
||||
async fn visit(
|
||||
p : Planner,
|
||||
name : String,
|
||||
requested : String,
|
||||
@@ -148,8 +148,17 @@ fn visit(
|
||||
}
|
||||
}
|
||||
let digest = resolve_digest(ch, name, tag)
|
||||
let m = fetch_manifest(ch, name, digest)
|
||||
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,
|
||||
@@ -206,26 +215,31 @@ fn owner_of_bin(ctx : Ctx, bin : String) -> String? {
|
||||
}
|
||||
|
||||
///|
|
||||
fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit {
|
||||
async fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit noraise {
|
||||
for b in bins {
|
||||
sh("rm -f " + sq(bin_dir(ctx) + "/" + basename(b))) |> ignore
|
||||
let path = bin_dir(ctx) + "/" + basename(b)
|
||||
@fs.remove(path) catch {
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn link_bins(
|
||||
async fn link_bins(
|
||||
ctx : Ctx,
|
||||
dir : String,
|
||||
bins : Array[String],
|
||||
) -> Unit raise OrbitError {
|
||||
sh_ok("mkdir -p " + sq(bin_dir(ctx)))
|
||||
@fs.mkdir(bin_dir(ctx), recursive=true) catch {
|
||||
e => raise OrbitError("cannot create bin dir: " + e.to_string())
|
||||
}
|
||||
for b in bins {
|
||||
sh_ok(
|
||||
"ln -sfn " +
|
||||
sq(dir + "/" + b) +
|
||||
" " +
|
||||
sq(bin_dir(ctx) + "/" + basename(b)),
|
||||
)
|
||||
let target = dir + "/" + b
|
||||
let linkpath = bin_dir(ctx) + "/" + basename(b)
|
||||
let rc = c_symlink(utf8_encode(target), utf8_encode(linkpath))
|
||||
if rc != 0 {
|
||||
raise OrbitError("cannot symlink " + linkpath + " -> " + target)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +264,7 @@ 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 {
|
||||
async fn activate(ctx : Ctx, st : Step) -> Unit 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 {
|
||||
@@ -266,6 +280,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
|
||||
channel: inst.channel,
|
||||
version: inst.version,
|
||||
digest: inst.digest,
|
||||
description: inst.description,
|
||||
bins: inst.bins,
|
||||
depends: inst.depends,
|
||||
})
|
||||
@@ -275,6 +290,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
|
||||
inst.channel = st.channel
|
||||
inst.version = st.version
|
||||
inst.digest = st.digest
|
||||
inst.description = st.manifest.description
|
||||
inst.bins = st.manifest.bins
|
||||
inst.depends = st.manifest.depends
|
||||
inst.explicit = st.explicit
|
||||
@@ -289,6 +305,7 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
|
||||
channel: st.channel,
|
||||
version: st.version,
|
||||
digest: st.digest,
|
||||
description: st.manifest.description,
|
||||
explicit: st.explicit,
|
||||
constraint: st.constraint,
|
||||
bins: st.manifest.bins,
|
||||
@@ -304,13 +321,14 @@ fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
|
||||
async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError {
|
||||
let mut changed = 0
|
||||
for st in p.order {
|
||||
if st.keep {
|
||||
match ctx.state.get(st.name) {
|
||||
Some(inst) => {
|
||||
inst.channel = st.channel
|
||||
inst.description = st.manifest.description
|
||||
inst.explicit = st.explicit
|
||||
inst.constraint = st.constraint
|
||||
}
|
||||
@@ -333,7 +351,7 @@ fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner {
|
||||
}
|
||||
|
||||
///|
|
||||
fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError {
|
||||
async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError {
|
||||
if specs.length() == 0 {
|
||||
raise OrbitError("usage: orbit install [channel::]<name>[@constraint]...")
|
||||
}
|
||||
@@ -348,7 +366,7 @@ fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError {
|
||||
///|
|
||||
/// Upgrade the named packages (or everything) to the newest versions their
|
||||
/// constraints allow. Dependencies are moved only when required.
|
||||
fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError {
|
||||
async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError {
|
||||
let targets : Array[String] = []
|
||||
if names.length() == 0 {
|
||||
for name, _ in ctx.state {
|
||||
@@ -384,7 +402,7 @@ fn reverse_deps(ctx : Ctx, name : String) -> Array[String] {
|
||||
}
|
||||
|
||||
///|
|
||||
fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
async fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
match ctx.state.get(name) {
|
||||
Some(inst) => {
|
||||
unlink_bins(ctx, inst.bins)
|
||||
@@ -398,7 +416,7 @@ fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
|
||||
///|
|
||||
/// Remove dependencies nobody needs any more.
|
||||
fn autoremove(ctx : Ctx) -> Unit raise OrbitError {
|
||||
async fn autoremove(ctx : Ctx) -> Unit raise OrbitError {
|
||||
let mut changed = true
|
||||
while changed {
|
||||
changed = false
|
||||
@@ -416,7 +434,7 @@ fn autoremove(ctx : Ctx) -> Unit raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn cmd_remove(
|
||||
async fn cmd_remove(
|
||||
ctx : Ctx,
|
||||
names : Array[String],
|
||||
force : Bool,
|
||||
@@ -451,7 +469,7 @@ fn cmd_remove(
|
||||
|
||||
///|
|
||||
/// Swap the current build with the previous one (run twice to undo).
|
||||
fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
let inst = match ctx.state.get(name) {
|
||||
Some(i) => i
|
||||
None => raise OrbitError("\{name} is not installed")
|
||||
@@ -471,6 +489,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
channel: inst.channel,
|
||||
version: inst.version,
|
||||
digest: inst.digest,
|
||||
description: inst.description,
|
||||
bins: inst.bins,
|
||||
depends: inst.depends,
|
||||
})
|
||||
@@ -478,6 +497,7 @@ fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError {
|
||||
let from = inst.version
|
||||
inst.version = prev.version
|
||||
inst.digest = prev.digest
|
||||
inst.description = prev.description
|
||||
inst.bins = prev.bins
|
||||
inst.depends = prev.depends
|
||||
check_bin_conflicts(ctx, name, inst.bins)
|
||||
@@ -503,14 +523,15 @@ 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 {
|
||||
async fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError {
|
||||
let store = ctx.root + "/store"
|
||||
if !exists(store) {
|
||||
println("store is empty")
|
||||
return
|
||||
}
|
||||
let mut freed = 0
|
||||
for pkg in lines(capture("ls -1 " + sq(store))) {
|
||||
let pkgs = @fs.readdir(store) catch { _ => [] }
|
||||
for pkg in pkgs {
|
||||
match ctx.state.get(pkg) {
|
||||
None => {
|
||||
sh_ok("rm -rf " + sq(store + "/" + pkg))
|
||||
@@ -521,7 +542,8 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError {
|
||||
for g in inst.history {
|
||||
keep.push(store_id(g.digest))
|
||||
}
|
||||
for id in lines(capture("ls -1 " + sq(store + "/" + pkg))) {
|
||||
let ids = @fs.readdir(store + "/" + pkg) catch { _ => [] }
|
||||
for id in ids {
|
||||
if !keep.contains(id) {
|
||||
sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id))
|
||||
freed = freed + 1
|
||||
@@ -531,7 +553,7 @@ fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError {
|
||||
}
|
||||
}
|
||||
let tmp = ctx.root + "/tmp"
|
||||
ignore(sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp)))
|
||||
let _ = sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp))
|
||||
println("removed \{freed} store entries")
|
||||
}
|
||||
|
||||
@@ -551,7 +573,7 @@ fn cmd_list(ctx : Ctx) -> Unit {
|
||||
///|
|
||||
/// Where to look up "[channel::]name": the channel asked for, else the one it
|
||||
/// was installed from, else by priority.
|
||||
fn locate_spec(
|
||||
async fn locate_spec(
|
||||
ctx : Ctx,
|
||||
spec : String,
|
||||
) -> (String, Channel, Array[String]) raise OrbitError {
|
||||
@@ -566,10 +588,18 @@ fn locate_spec(
|
||||
|
||||
///|
|
||||
fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError {
|
||||
let (_, name) = split_channel(spec)
|
||||
match ctx.state.get(name) {
|
||||
Some(p) => {
|
||||
let (pin, name) = split_channel(spec)
|
||||
let p = match ctx.state.get(name) {
|
||||
Some(p) => p
|
||||
None => raise OrbitError("\{spec} is not installed")
|
||||
}
|
||||
if pin is Some(channel) && channel != p.channel {
|
||||
raise OrbitError("\{spec} is not installed (installed from '\{p.channel}')")
|
||||
}
|
||||
println("\{name} \{p.version} (installed)")
|
||||
if p.description != "" {
|
||||
println(" description: \{p.description}")
|
||||
}
|
||||
println(" channel: \{p.channel}")
|
||||
println(" digest: \{p.digest}")
|
||||
println(" constraint: \{p.constraint}")
|
||||
@@ -586,24 +616,10 @@ fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError {
|
||||
hist.push(g.version)
|
||||
}
|
||||
println(" rollback: \{join(hist, " ")}")
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
let (_, ch, tags) = locate_spec(ctx, spec)
|
||||
match pick_tag(tags, ["*"]) {
|
||||
Some(t) => {
|
||||
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}")
|
||||
}
|
||||
}
|
||||
None => println("\{name}: no stable versions published")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError {
|
||||
async 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) {
|
||||
@@ -615,25 +631,264 @@ fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
|
||||
/// What search shows about one Orbit package, read from its manifest.
|
||||
struct RepoInfo {
|
||||
version : String
|
||||
description : String
|
||||
}
|
||||
|
||||
///|
|
||||
fn is_orbit_object(o : Map[String, Json]) -> Bool {
|
||||
if jstr(o, "artifactType", "") == ORBIT_ARTIFACT_TYPE {
|
||||
return true
|
||||
}
|
||||
match o.get("config") {
|
||||
Some(Json::Object(c)) => jstr(c, "mediaType", "") == CONFIG_MEDIA_TYPE
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// The package info from a manifest, or None if it isn't an Orbit package.
|
||||
/// Version and description come from the standard OCI annotations that publish
|
||||
/// writes, so no extra request is needed.
|
||||
fn orbit_info(text : String) -> RepoInfo? {
|
||||
let parsed : Map[String, Json]? = Some(parse_object(text, "manifest")) catch {
|
||||
_ => None
|
||||
}
|
||||
match parsed {
|
||||
Some(o) =>
|
||||
if is_orbit_object(o) {
|
||||
let annotations : Map[String, Json] = match o.get("annotations") {
|
||||
Some(Json::Object(a)) => a
|
||||
_ => Map([])
|
||||
}
|
||||
Some(RepoInfo::{
|
||||
version: jstr(annotations, "org.opencontainers.image.version", ""),
|
||||
description: jstr(
|
||||
annotations, "org.opencontainers.image.description", "",
|
||||
),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
None => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Look at one repository's latest manifest (or any tag if there is no latest).
|
||||
/// Any failure counts as "not an Orbit package", so one broken repo can't hide
|
||||
/// the others.
|
||||
async fn orbit_repo_info(ch : Channel, repo : String) -> RepoInfo? noraise {
|
||||
let tags = lines(capture(oras(ch, "repo tags " + sq(repo_of(ch, repo))))) catch {
|
||||
_ => return None
|
||||
}
|
||||
if tags.length() == 0 {
|
||||
return None
|
||||
}
|
||||
let tag = if tags.contains("latest") { "latest" } else { tags[0] }
|
||||
let text = capture(
|
||||
oras(ch, "manifest fetch " + sq(repo_of(ch, repo) + ":" + tag)),
|
||||
) catch {
|
||||
_ => return None
|
||||
}
|
||||
orbit_info(text)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Check many repositories at once, with one spinner for the whole batch.
|
||||
async fn find_orbit_repos(
|
||||
ch : Channel,
|
||||
repos : Array[String],
|
||||
) -> Array[RepoInfo?] raise OrbitError {
|
||||
if repos.length() == 0 {
|
||||
return []
|
||||
}
|
||||
let label = "Checking \{repos.length()} repositories in \{ch.name}"
|
||||
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
|
||||
@async.with_task_group(group => {
|
||||
let spinner = if is_tty {
|
||||
Some(
|
||||
group.spawn(() => ignore(@async.handle_cancellation(() => spin(label)))),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let tasks : Array[@async.Task[RepoInfo?]] = []
|
||||
for r in repos {
|
||||
tasks.push(group.spawn(() => orbit_repo_info(ch, r)))
|
||||
}
|
||||
let results : Array[RepoInfo?] = []
|
||||
for t in tasks {
|
||||
results.push(t.wait())
|
||||
}
|
||||
match spinner {
|
||||
Some(s) => s.cancel()
|
||||
None => ()
|
||||
}
|
||||
if is_tty {
|
||||
c_print_err(utf8_encode("\r\u001B[2K"))
|
||||
}
|
||||
results
|
||||
}) catch {
|
||||
e => raise OrbitError(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Pad on the right to `width` characters, for the table columns.
|
||||
fn pad_right(s : String, width : Int32) -> String {
|
||||
let sb = StringBuilder()
|
||||
sb.write_string(s)
|
||||
let mut n = chars(s).length()
|
||||
while n < width {
|
||||
sb.write_char(' ')
|
||||
n = n + 1
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Print rows as a table. The first row is the header. The last column is not
|
||||
/// padded, so long descriptions don't leave trailing spaces.
|
||||
fn print_table(rows : Array[Array[String]]) -> Unit {
|
||||
let ncols = rows[0].length()
|
||||
let widths : Array[Int32] = []
|
||||
for c = 0; c < ncols; c = c + 1 {
|
||||
widths.push(0)
|
||||
}
|
||||
for row in rows {
|
||||
for c = 0; c < ncols; c = c + 1 {
|
||||
let n = chars(row[c]).length()
|
||||
if n > widths[c] {
|
||||
widths[c] = n
|
||||
}
|
||||
}
|
||||
}
|
||||
for row in rows {
|
||||
let sb = StringBuilder()
|
||||
for c = 0; c < ncols; c = c + 1 {
|
||||
if c > 0 {
|
||||
sb.write_string(" ")
|
||||
}
|
||||
if c < ncols - 1 {
|
||||
sb.write_string(pad_right(row[c], widths[c]))
|
||||
} else {
|
||||
sb.write_string(row[c])
|
||||
}
|
||||
}
|
||||
println(sb.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError {
|
||||
let rows : Array[Array[String]] = [
|
||||
["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"],
|
||||
]
|
||||
let mut listed = 0
|
||||
for ch in ctx.channels {
|
||||
let out = capture(oras(ch, "repo ls " + sq(ch.url))) catch {
|
||||
let out = capture(
|
||||
oras(ch, "repo ls " + sq(ch.url)),
|
||||
progress="Listing packages in \{ch.name}",
|
||||
) catch {
|
||||
_ => {
|
||||
println("warning: channel '\{ch.name}' does not allow listing packages")
|
||||
continue
|
||||
}
|
||||
}
|
||||
listed = listed + 1
|
||||
let candidates : Array[String] = []
|
||||
for r in lines(out) {
|
||||
if contains_str(r, term) {
|
||||
println("\{ch.name}::\{r}")
|
||||
// A name with "/" is a nested channel namespace (e.g. example/greet under
|
||||
// main), not a package name that `orbit install` could use.
|
||||
if valid_name(r) && contains_str(r, term) {
|
||||
candidates.push(r)
|
||||
}
|
||||
}
|
||||
let found = find_orbit_repos(ch, candidates)
|
||||
for i, r in candidates {
|
||||
match found[i] {
|
||||
Some(info) =>
|
||||
rows.push([
|
||||
r,
|
||||
ch.name,
|
||||
if info.version == "" {
|
||||
"-"
|
||||
} else {
|
||||
info.version
|
||||
},
|
||||
if info.description == "" {
|
||||
"-"
|
||||
} else {
|
||||
info.description
|
||||
},
|
||||
])
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
if listed == 0 {
|
||||
raise OrbitError(
|
||||
"no channel allows listing packages (catalog API); try `orbit info <name>`",
|
||||
"no channel allows listing packages (catalog API); try `orbit versions <name>`",
|
||||
)
|
||||
}
|
||||
if rows.length() == 1 {
|
||||
if term == "" {
|
||||
println("no packages found")
|
||||
} else {
|
||||
println("no packages match '\{term}'")
|
||||
}
|
||||
return
|
||||
}
|
||||
print_table(rows)
|
||||
}
|
||||
|
||||
///|
|
||||
test "orbit manifests are recognised by artifactType or config media type" {
|
||||
assert_true(
|
||||
orbit_info(
|
||||
"{\"artifactType\":\"application/vnd.latha.orbit.v1\",\"config\":{\"mediaType\":\"x\"}}",
|
||||
)
|
||||
is Some(_),
|
||||
)
|
||||
assert_true(
|
||||
orbit_info(
|
||||
"{\"artifactType\":null,\"config\":{\"mediaType\":\"application/vnd.latha.orbit.config.v1+json\"}}",
|
||||
)
|
||||
is Some(_),
|
||||
)
|
||||
assert_true(
|
||||
orbit_info(
|
||||
"{\"artifactType\":\"application/vnd.cncf.helm.chart.content.v1.tar+gzip\",\"config\":{\"mediaType\":\"application/vnd.cncf.helm.config.v1+json\"}}",
|
||||
)
|
||||
is None,
|
||||
)
|
||||
assert_true(orbit_info("not json") is None)
|
||||
assert_true(orbit_info("{\"config\":\"string\"}") is None)
|
||||
}
|
||||
|
||||
///|
|
||||
test "search info comes from OCI annotations" {
|
||||
let info = orbit_info(
|
||||
"{\"artifactType\":\"application/vnd.latha.orbit.v1\",\"annotations\":{\"org.opencontainers.image.version\":\"1.2.3\",\"org.opencontainers.image.description\":\"A tool\"}}",
|
||||
).unwrap()
|
||||
assert_eq(info.version, "1.2.3")
|
||||
assert_eq(info.description, "A tool")
|
||||
let bare = orbit_info("{\"artifactType\":\"application/vnd.latha.orbit.v1\"}").unwrap()
|
||||
assert_eq(bare.version, "")
|
||||
assert_eq(bare.description, "")
|
||||
}
|
||||
|
||||
///|
|
||||
test "search skips nested channel namespaces" {
|
||||
assert_true(valid_name("greet"))
|
||||
assert_true(!valid_name("example/greet"))
|
||||
}
|
||||
|
||||
///|
|
||||
test "table columns line up" {
|
||||
assert_eq(pad_right("ab", 4), "ab ")
|
||||
assert_eq(pad_right("abcd", 2), "abcd")
|
||||
}
|
||||
+17
-7
@@ -23,10 +23,14 @@ fn is_missing_repo(err : String) -> Bool {
|
||||
/// 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 {
|
||||
async 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 out = Some(
|
||||
capture(cmd, progress="Checking versions of \{ch.name}::\{name}"),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
let err = match read_text(errfile) {
|
||||
Some(t) => trim(t)
|
||||
None => ""
|
||||
@@ -44,13 +48,16 @@ fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
fn resolve_digest(
|
||||
async fn resolve_digest(
|
||||
ch : Channel,
|
||||
name : String,
|
||||
tag : String,
|
||||
) -> String raise OrbitError {
|
||||
let d = trim(
|
||||
capture(oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag))),
|
||||
capture(
|
||||
oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag)),
|
||||
progress="Resolving \{ch.name}::\{name}@\{tag}",
|
||||
),
|
||||
)
|
||||
if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) {
|
||||
raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'")
|
||||
@@ -60,13 +67,14 @@ fn resolve_digest(
|
||||
|
||||
///|
|
||||
/// Fetch only the config blob (orbit.json); no layer download needed to plan.
|
||||
fn fetch_manifest(
|
||||
async fn fetch_manifest(
|
||||
ch : Channel,
|
||||
name : String,
|
||||
digest : String,
|
||||
) -> Manifest raise OrbitError {
|
||||
let text = capture(
|
||||
oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)),
|
||||
progress="Reading metadata for \{ch.name}::\{name}",
|
||||
)
|
||||
let m = parse_manifest(text)
|
||||
if m.name != name {
|
||||
@@ -81,7 +89,7 @@ fn fetch_manifest(
|
||||
/// Pull a package layer by digest and unpack it into the store.
|
||||
/// Unpacks into a temp dir first, then renames, so a store dir is either
|
||||
/// complete or absent.
|
||||
fn fetch_into_store(
|
||||
async fn fetch_into_store(
|
||||
ctx : Ctx,
|
||||
ch : Channel,
|
||||
name : String,
|
||||
@@ -176,7 +184,7 @@ test "package config exposes Gitea labels and preserves Orbit metadata" {
|
||||
|
||||
///|
|
||||
/// Pack `<dir>/files` and push it with the enriched Orbit config blob.
|
||||
fn publish(
|
||||
async fn publish(
|
||||
ch : Channel,
|
||||
dir : String,
|
||||
also_latest : Bool,
|
||||
@@ -210,6 +218,8 @@ fn publish(
|
||||
ch,
|
||||
"push " +
|
||||
sq(repo_of(ch, m.name) + ":" + tags) +
|
||||
" --artifact-type " +
|
||||
sq(ORBIT_ARTIFACT_TYPE) +
|
||||
" --config " +
|
||||
sq("orbit.json:" + CONFIG_MEDIA_TYPE) +
|
||||
" --annotation " +
|
||||
|
||||
+18
-86
@@ -1,17 +1,10 @@
|
||||
// Native glue for orbit: process execution, file IO and environment access.
|
||||
// Every string crosses the boundary as UTF-8 `Bytes` (not NUL-terminated).
|
||||
// Arguments are never decref'd here: if the compiler passes them owned we leak
|
||||
// a few bytes in a short-lived CLI, which is harmless; if it passes them
|
||||
// borrowed, decref'ing would be a use-after-free.
|
||||
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include "moonbit.h"
|
||||
|
||||
static int last_status = 0;
|
||||
|
||||
static char *to_cstr(moonbit_bytes_t b) {
|
||||
int32_t n = Moonbit_array_length(b);
|
||||
char *s = (char *)malloc((size_t)n + 1);
|
||||
@@ -27,84 +20,6 @@ static moonbit_bytes_t from_buf(const char *buf, size_t len) {
|
||||
return out;
|
||||
}
|
||||
|
||||
static int decode_status(int r) {
|
||||
if (r == -1) return -1;
|
||||
if (WIFEXITED(r)) return WEXITSTATUS(r);
|
||||
return 128;
|
||||
}
|
||||
|
||||
int32_t orbit_run(moonbit_bytes_t cmd) {
|
||||
char *c = to_cstr(cmd);
|
||||
fflush(stdout);
|
||||
int r = system(c);
|
||||
free(c);
|
||||
return decode_status(r);
|
||||
}
|
||||
|
||||
moonbit_bytes_t orbit_capture(moonbit_bytes_t cmd) {
|
||||
char *c = to_cstr(cmd);
|
||||
fflush(stdout);
|
||||
FILE *p = popen(c, "r");
|
||||
free(c);
|
||||
if (!p) {
|
||||
last_status = -1;
|
||||
return from_buf("", 0);
|
||||
}
|
||||
size_t cap = 4096, len = 0;
|
||||
char *buf = (char *)malloc(cap);
|
||||
size_t got;
|
||||
while ((got = fread(buf + len, 1, cap - len, p)) > 0) {
|
||||
len += got;
|
||||
if (len == cap) {
|
||||
cap *= 2;
|
||||
buf = (char *)realloc(buf, cap);
|
||||
if (!buf) abort();
|
||||
}
|
||||
}
|
||||
last_status = decode_status(pclose(p));
|
||||
moonbit_bytes_t out = from_buf(buf, len);
|
||||
free(buf);
|
||||
return out;
|
||||
}
|
||||
|
||||
int32_t orbit_last_status(void) { return last_status; }
|
||||
|
||||
moonbit_bytes_t orbit_read_file(moonbit_bytes_t path) {
|
||||
char *p = to_cstr(path);
|
||||
FILE *f = fopen(p, "rb");
|
||||
free(p);
|
||||
if (!f) {
|
||||
last_status = -1;
|
||||
return from_buf("", 0);
|
||||
}
|
||||
size_t cap = 4096, len = 0, got;
|
||||
char *buf = (char *)malloc(cap);
|
||||
while ((got = fread(buf + len, 1, cap - len, f)) > 0) {
|
||||
len += got;
|
||||
if (len == cap) {
|
||||
cap *= 2;
|
||||
buf = (char *)realloc(buf, cap);
|
||||
if (!buf) abort();
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
last_status = 0;
|
||||
moonbit_bytes_t out = from_buf(buf, len);
|
||||
free(buf);
|
||||
return out;
|
||||
}
|
||||
|
||||
int32_t orbit_write_file(moonbit_bytes_t path, moonbit_bytes_t data) {
|
||||
char *p = to_cstr(path);
|
||||
FILE *f = fopen(p, "wb");
|
||||
free(p);
|
||||
if (!f) return -1;
|
||||
int32_t n = Moonbit_array_length(data);
|
||||
size_t w = fwrite(data, 1, (size_t)n, f);
|
||||
int rc = fclose(f);
|
||||
return (w == (size_t)n && rc == 0) ? 0 : -1;
|
||||
}
|
||||
|
||||
moonbit_bytes_t orbit_getenv(moonbit_bytes_t name) {
|
||||
char *n = to_cstr(name);
|
||||
const char *v = getenv(n);
|
||||
@@ -117,3 +32,20 @@ void orbit_exit(int32_t code) {
|
||||
fflush(stdout);
|
||||
exit(code);
|
||||
}
|
||||
|
||||
int32_t orbit_symlink(moonbit_bytes_t target, moonbit_bytes_t linkpath) {
|
||||
char *t = to_cstr(target);
|
||||
char *l = to_cstr(linkpath);
|
||||
unlink(l);
|
||||
int rc = symlink(t, l);
|
||||
free(t);
|
||||
free(l);
|
||||
return rc;
|
||||
}
|
||||
|
||||
void orbit_print_err(moonbit_bytes_t msg) {
|
||||
char *m = to_cstr(msg);
|
||||
fputs(m, stderr);
|
||||
fflush(stderr);
|
||||
free(m);
|
||||
}
|
||||
+91
-45
@@ -1,31 +1,10 @@
|
||||
// System access through the C stub, plus small string helpers.
|
||||
// Helpers are written against `for c in s` only, to stay independent of
|
||||
// String APIs that have changed between MoonBit releases.
|
||||
// System access through process execution, MoonBit async fs/process, and small helpers.
|
||||
|
||||
///|
|
||||
suberror OrbitError {
|
||||
OrbitError(String)
|
||||
}
|
||||
|
||||
///|
|
||||
#borrow(cmd)
|
||||
extern "C" fn c_run(cmd : Bytes) -> Int32 = "orbit_run"
|
||||
|
||||
///|
|
||||
#borrow(cmd)
|
||||
extern "C" fn c_capture(cmd : Bytes) -> Bytes = "orbit_capture"
|
||||
|
||||
///|
|
||||
extern "C" fn c_last_status() -> Int32 = "orbit_last_status"
|
||||
|
||||
///|
|
||||
#borrow(path)
|
||||
extern "C" fn c_read_file(path : Bytes) -> Bytes = "orbit_read_file"
|
||||
|
||||
///|
|
||||
#borrow(path, data)
|
||||
extern "C" fn c_write_file(path : Bytes, data : Bytes) -> Int32 = "orbit_write_file"
|
||||
|
||||
///|
|
||||
#borrow(name)
|
||||
extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv"
|
||||
@@ -33,6 +12,17 @@ extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv"
|
||||
///|
|
||||
extern "C" fn c_exit(code : Int32) = "orbit_exit"
|
||||
|
||||
///|
|
||||
extern "C" fn c_isatty(fd : Int32) -> Int32 = "isatty"
|
||||
|
||||
///|
|
||||
#borrow(msg)
|
||||
extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err"
|
||||
|
||||
///|
|
||||
#borrow(target, linkpath)
|
||||
extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink"
|
||||
|
||||
// ---------------------------------------------------------------- UTF-8
|
||||
|
||||
///|
|
||||
@@ -266,15 +256,19 @@ fn sq(s : String) -> String {
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- process / fs
|
||||
// ---------------------------------------------------------------- process / fs (async)
|
||||
|
||||
///|
|
||||
fn sh(cmd : String) -> Int32 {
|
||||
c_run(utf8_encode(cmd))
|
||||
async fn sh(cmd : String) -> Int32 noraise {
|
||||
try {
|
||||
@process.run("sh", ["-c", cmd])
|
||||
} catch {
|
||||
_ => 128
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn sh_ok(cmd : String) -> Unit raise OrbitError {
|
||||
async fn sh_ok(cmd : String) -> Unit raise OrbitError {
|
||||
let code = sh(cmd)
|
||||
if code != 0 {
|
||||
raise OrbitError("command failed (exit \{code}): \{cmd}")
|
||||
@@ -282,39 +276,87 @@ fn sh_ok(cmd : String) -> Unit raise OrbitError {
|
||||
}
|
||||
|
||||
///|
|
||||
/// Run a command and return its stdout; stderr goes to the terminal.
|
||||
fn capture(cmd : String) -> String raise OrbitError {
|
||||
let out = utf8_decode(c_capture(utf8_encode(cmd)))
|
||||
let code = c_last_status()
|
||||
/// Braille spinner on stderr until cancelled.
|
||||
async fn spin(label : String) -> Unit noraise {
|
||||
let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
|
||||
let mut i = 0
|
||||
while true {
|
||||
c_print_err(utf8_encode("\r\u001B[2K" + frames[i % 10] + " " + label))
|
||||
i = i + 1
|
||||
@async.sleep(80)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Return stdout; stderr goes to the terminal unless captured. A label shows a
|
||||
/// braille spinner on a terminal while the command runs. The spinner is a child
|
||||
/// task that is cancelled as soon as the command finishes, so nothing keeps the
|
||||
/// group alive.
|
||||
async fn capture(cmd : String, progress~ : String = "") -> String raise OrbitError {
|
||||
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
|
||||
let spinning = is_tty && progress != ""
|
||||
let res : Result[String, Error] = try {
|
||||
let out = @async.with_task_group(group => {
|
||||
let spinner = if spinning {
|
||||
Some(group.spawn(() => {
|
||||
ignore(@async.handle_cancellation(() => spin(progress)))
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let (code, stdout, _) = @process.collect_output("sh", ["-c", cmd])
|
||||
match spinner {
|
||||
Some(task) => task.cancel()
|
||||
None => ()
|
||||
}
|
||||
if spinning {
|
||||
c_print_err(utf8_encode("\r\u001B[2K"))
|
||||
}
|
||||
if code != 0 {
|
||||
raise OrbitError("command failed (exit \{code}): \{cmd}")
|
||||
}
|
||||
out
|
||||
stdout.text()
|
||||
})
|
||||
Ok(out)
|
||||
} catch {
|
||||
e => Err(e)
|
||||
}
|
||||
match res {
|
||||
Ok(s) => s
|
||||
Err(OrbitError(msg)) => raise OrbitError(msg)
|
||||
Err(e) => raise OrbitError(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn exists(path : String) -> Bool {
|
||||
sh("test -e " + sq(path)) == 0
|
||||
async fn exists(path : String) -> Bool noraise {
|
||||
try {
|
||||
@fs.exists(path)
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn read_text(path : String) -> String? {
|
||||
let b = c_read_file(utf8_encode(path))
|
||||
if c_last_status() != 0 {
|
||||
None
|
||||
} else {
|
||||
Some(utf8_decode(b))
|
||||
async fn read_text(path : String) -> String? noraise {
|
||||
try {
|
||||
let data = @fs.read_file(path)
|
||||
Some(data.text())
|
||||
} catch {
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Write via a temp file and rename, so readers never see a half-written file.
|
||||
fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError {
|
||||
async fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError {
|
||||
let tmp = path + ".tmp"
|
||||
if c_write_file(utf8_encode(tmp), utf8_encode(text)) != 0 {
|
||||
raise OrbitError("cannot write \{tmp}")
|
||||
try {
|
||||
@fs.write_file(tmp, text, create_mode=CreateOrTruncate)
|
||||
@fs.rename(tmp, path)
|
||||
} catch {
|
||||
e => raise OrbitError("cannot write " + path + ": " + e.to_string())
|
||||
}
|
||||
sh_ok("mv -f " + sq(tmp) + " " + sq(path))
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -324,8 +366,12 @@ fn getenv(name : String) -> String {
|
||||
|
||||
///|
|
||||
/// Command-line arguments without the program name (Linux: /proc/self/cmdline).
|
||||
fn cli_args() -> Array[String] {
|
||||
let raw = c_read_file(utf8_encode("/proc/self/cmdline"))
|
||||
async fn cli_args() -> Array[String] noraise {
|
||||
let raw = try {
|
||||
@fs.read_file("/proc/self/cmdline").binary()
|
||||
} catch {
|
||||
_ => Default::default()
|
||||
}
|
||||
let out : Array[String] = []
|
||||
let cur : Array[Byte] = []
|
||||
for i = 0; i < raw.length(); i = i + 1 {
|
||||
|
||||
Reference in new issue
Block a user