mnix: Nix binary-cache client PoC in MoonBit (install hello from cache.nixos.org) #1
No files matched your search
Vendored
+6
-1
@@ -24,10 +24,15 @@ pub fn Cache::new(
|
||||
pub async fn http_get(
|
||||
url : String,
|
||||
allow_404~ : Bool = false,
|
||||
accept_json~ : Bool = false,
|
||||
) -> Bytes? raise @store.NixError {
|
||||
let headers : Map[@http.CaseInsensitiveString, String] = Map([])
|
||||
if accept_json {
|
||||
headers["Accept"] = "application/json"
|
||||
}
|
||||
let mut cur = url
|
||||
for _ in 0..<8 {
|
||||
let (resp, body) = @http.get(cur) catch {
|
||||
let (resp, body) = @http.get(cur, headers~) catch {
|
||||
e => raise Network("GET \{cur} failed: \{e}")
|
||||
}
|
||||
let code = resp.code.to_int()
|
||||
|
||||
Vendored
+1
-1
@@ -12,7 +12,7 @@ pub fn decompress(String, Bytes) -> Bytes raise @store.NixError
|
||||
|
||||
pub let default_cache_url : String
|
||||
|
||||
pub async fn http_get(String, allow_404? : Bool) -> Bytes? raise @store.NixError
|
||||
pub async fn http_get(String, allow_404? : Bool, accept_json? : Bool) -> Bytes? raise @store.NixError
|
||||
|
||||
pub fn verify_nar_download(@narinfo.NarInfo, Bytes) -> Bytes raise @store.NixError
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
///|
|
||||
/// pname from a store-path name: everything before the first "-<digit>".
|
||||
fn pname_of(name : String) -> String {
|
||||
let chars = name.to_array()
|
||||
for i in 0..<chars.length() {
|
||||
if chars[i] == '-' && i + 1 < chars.length() {
|
||||
let n = chars[i + 1]
|
||||
if n >= '0' && n <= '9' {
|
||||
return name[0:i].to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
///|
|
||||
async fn resolve_target(
|
||||
cfg : Config,
|
||||
target : String,
|
||||
) -> (@store.StorePath, String) raise @store.NixError {
|
||||
if target.has_prefix("/") {
|
||||
let sp = @store.StorePath::parse(target)
|
||||
return (sp, pname_of(sp.name))
|
||||
}
|
||||
// "<hash>-<name>" base name given directly?
|
||||
if target.length() > 33 && target[32:33].to_string() == "-" {
|
||||
let sp = @store.StorePath::parse_base(target)
|
||||
return (sp, pname_of(sp.name))
|
||||
}
|
||||
let url = cfg.channel.job_url(target, cfg.system)
|
||||
eprintln("resolving '\{target}' via \{url}")
|
||||
let body = match @cache.http_get(url, allow_404=true, accept_json=true) {
|
||||
Some(b) => b
|
||||
None =>
|
||||
raise Network(
|
||||
"attribute '\{target}' has no successful \{cfg.system} build in \{cfg.channel.name} (Hydra \{cfg.channel.project}/\{cfg.channel.jobset})",
|
||||
)
|
||||
}
|
||||
let text = @utf8.decode(body) catch {
|
||||
_ => raise Parse("Hydra response is not UTF-8")
|
||||
}
|
||||
let (path, _) = @resolve.parse_hydra_build(text)
|
||||
(@store.StorePath::parse(path), target)
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_resolve(
|
||||
cfg : Config,
|
||||
target : String,
|
||||
) -> Unit raise @store.NixError {
|
||||
let (sp, _) = resolve_target(cfg, target)
|
||||
println(sp.logical())
|
||||
}
|
||||
|
||||
///|
|
||||
async fn fetch_closure(
|
||||
cfg : Config,
|
||||
sp : @store.StorePath,
|
||||
) -> Array[@narinfo.NarInfo] raise @store.NixError {
|
||||
@closure.compute([sp.base_name()], async fn(
|
||||
h,
|
||||
) -> @narinfo.NarInfo? raise @store.NixError {
|
||||
cfg.cache.fetch_narinfo(h)
|
||||
})
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_closure(
|
||||
cfg : Config,
|
||||
target : String,
|
||||
) -> Unit raise @store.NixError {
|
||||
let (sp, _) = resolve_target(cfg, target)
|
||||
let c = fetch_closure(cfg, sp)
|
||||
let mut total = 0L
|
||||
for ni in c {
|
||||
total += ni.nar_size
|
||||
println("\{ni.store_path} \{ni.nar_size} bytes")
|
||||
}
|
||||
println("\{c.length()} paths, \{total} bytes (unpacked NAR size)")
|
||||
}
|
||||
|
||||
///|
|
||||
async fn install_one(
|
||||
cfg : Config,
|
||||
ni : @narinfo.NarInfo,
|
||||
) -> Bool raise @store.NixError {
|
||||
let sp = @store.StorePath::parse(ni.store_path)
|
||||
if @installer.lexists("\{cfg.store_dir}/\{sp.base_name()}") {
|
||||
return false
|
||||
}
|
||||
eprintln(
|
||||
"fetching \{sp.base_name()} (\{ni.file_size} bytes, \{ni.compression})",
|
||||
)
|
||||
let raw = cfg.cache.fetch_nar(ni)
|
||||
let node = @nar.parse(raw)
|
||||
@installer.install_node(cfg.store_dir, sp.base_name(), node)
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_install(
|
||||
cfg : Config,
|
||||
target : String,
|
||||
no_profile : Bool,
|
||||
dry_run : Bool,
|
||||
) -> Unit raise @store.NixError {
|
||||
let (sp, name) = resolve_target(cfg, target)
|
||||
eprintln("target: \{sp.logical()}")
|
||||
let c = fetch_closure(cfg, sp)
|
||||
eprintln("closure: \{c.length()} paths (all signatures verified)")
|
||||
if dry_run {
|
||||
for ni in c {
|
||||
println(ni.store_path)
|
||||
}
|
||||
return
|
||||
}
|
||||
if cfg.store_dir != @store.default_store_dir {
|
||||
eprintln(
|
||||
"note: installing into \{cfg.store_dir}; binaries hardcode /nix/store, use `mnix run` (see README)",
|
||||
)
|
||||
}
|
||||
let mut fresh = 0
|
||||
for ni in c {
|
||||
if install_one(cfg, ni) {
|
||||
fresh += 1
|
||||
}
|
||||
}
|
||||
eprintln(
|
||||
"installed \{fresh} new paths, \{c.length() - fresh} already present",
|
||||
)
|
||||
if !no_profile {
|
||||
let installed = "\{cfg.store_dir}/\{sp.base_name()}"
|
||||
let e = cfg.profile.add(name, installed)
|
||||
println("\{e.name}: \{e.path}")
|
||||
let bl = e.bins.join(", ")
|
||||
println("linked: \{bl} -> \{cfg.profile.dir}/bin")
|
||||
} else {
|
||||
println("\{cfg.store_dir}/\{sp.base_name()}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_list(cfg : Config) -> Unit raise @store.NixError {
|
||||
let es = cfg.profile.list()
|
||||
if es.length() == 0 {
|
||||
println("(profile \{cfg.profile.dir} is empty)")
|
||||
}
|
||||
for e in es {
|
||||
let bl = e.bins.join(", ")
|
||||
println("\{e.name}\t\{e.path}\t[\{bl}]")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_remove(cfg : Config, name : String) -> Unit raise @store.NixError {
|
||||
let e = cfg.profile.remove(name)
|
||||
println(
|
||||
"removed \{e.name} (store path \{e.path} kept; no garbage collector yet)",
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
fn cmd_env(cfg : Config) -> Unit {
|
||||
println("export PATH=\"\{cfg.profile.dir}/bin:$PATH\"")
|
||||
}
|
||||
|
||||
///|
|
||||
async fn cmd_search(cfg : Config, term : String) -> Unit {
|
||||
let cache_dir = "\{cfg.root}/cache"
|
||||
let cache_file = "\{cache_dir}/\{cfg.channel.name}-store-paths.txt"
|
||||
let text = if @installer.lexists(cache_file) {
|
||||
eprintln("using cached \{cache_file} (delete it to refresh)")
|
||||
@utf8.decode(@fs.read_file(cache_file).binary())
|
||||
} else {
|
||||
let url = "\{cfg.channel.releases_url}/store-paths.xz"
|
||||
eprintln("downloading \{url}")
|
||||
let raw = match @cache.http_get(url) {
|
||||
Some(b) => b
|
||||
None => raise @store.Network("unreachable")
|
||||
}
|
||||
eprintln("decompressing \{raw.length()} bytes of xz")
|
||||
let data = @xz.decompress(raw) catch {
|
||||
_ => raise @store.Verify("store-paths.xz failed to decompress")
|
||||
}
|
||||
let text = @utf8.decode(data)
|
||||
@fs.mkdir(cache_dir, recursive=true, allow_exist=true)
|
||||
@fs.write_file(cache_file, text, create_mode=CreateOrTruncate)
|
||||
text
|
||||
}
|
||||
let paths = @resolve.parse_store_paths(text)
|
||||
let res = @resolve.search(paths, term)
|
||||
let mut n = 0
|
||||
for r in res {
|
||||
if n >= 50 {
|
||||
println("... (\{res.length() - 50} more)")
|
||||
break
|
||||
}
|
||||
println("\{r.0}\t(\{r.1} path(s) across platforms)")
|
||||
n += 1
|
||||
}
|
||||
if res.length() == 0 {
|
||||
println("no store path names contain '\{term}'")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Shell used to make `<store_dir>` appear at /nix/store inside a private
|
||||
/// user+mount namespace (no root needed): build a tmpfs root that mirrors
|
||||
/// the real root via recursive bind mounts, bind the store at /nix/store,
|
||||
/// chroot into it.
|
||||
let run_script : String =
|
||||
#|set -e
|
||||
#|STORE="$1"; shift
|
||||
#|R=$(mktemp -d "${TMPDIR:-/tmp}/mnix-root.XXXXXX")
|
||||
#|mount -t tmpfs none "$R"
|
||||
#|for d in /*; do
|
||||
#| n=${d#/}
|
||||
#| [ "$n" = nix ] && continue
|
||||
#| if [ -L "$d" ]; then ln -s "$(readlink "$d")" "$R/$n"; continue; fi
|
||||
#| [ -d "$d" ] || continue
|
||||
#| mkdir "$R/$n"
|
||||
#| mount --rbind "$d" "$R/$n"
|
||||
#|done
|
||||
#|mkdir -p "$R/nix/store"
|
||||
#|mount --bind "$STORE" "$R/nix/store"
|
||||
#|exec chroot "$R" /bin/sh -c 'cd "$0" && exec "$@"' "$PWD" "$@"
|
||||
|
||||
///|
|
||||
async fn cmd_run(
|
||||
cfg : Config,
|
||||
argv : Array[String],
|
||||
) -> Int32 raise @store.NixError {
|
||||
if argv.length() == 0 {
|
||||
raise Parse("run: no command given")
|
||||
}
|
||||
let path = match @env.get_env_var("PATH") {
|
||||
Some(p) => p
|
||||
None => ""
|
||||
}
|
||||
let extra : Map[String, String] = { "PATH": "\{cfg.profile.dir}/bin:\{path}" }
|
||||
try {
|
||||
if cfg.store_dir == @store.default_store_dir {
|
||||
@process.run(argv[0], argv[1:], extra_env=extra)
|
||||
} else {
|
||||
let args = ["-rm", "sh", "-c", run_script, "mnix-run", cfg.store_dir]
|
||||
for a in argv {
|
||||
args.push(a)
|
||||
}
|
||||
@process.run("unshare", args, extra_env=extra)
|
||||
}
|
||||
} catch {
|
||||
e => raise Io("running \{argv[0]}: \{e}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
///|
|
||||
/// Resolved global configuration for one invocation.
|
||||
priv struct Config {
|
||||
root : String // state dir: <root>/store, <root>/profile, <root>/cache
|
||||
store_dir : String
|
||||
profile : @profile.Profile
|
||||
channel : @resolve.Channel
|
||||
system : String
|
||||
cache : @cache.Cache
|
||||
}
|
||||
|
||||
///|
|
||||
fn opt(m : @argparse.Matches, key : String) -> String? {
|
||||
match m.values.get(key) {
|
||||
Some([v, ..]) => Some(v)
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn detect_system() -> String raise @store.NixError {
|
||||
let (code, out, _) = @process.collect_output("uname", ["-m"]) catch {
|
||||
e => raise Io("running uname: \{e}")
|
||||
}
|
||||
if code != 0 {
|
||||
raise Io("uname -m exited with \{code}")
|
||||
}
|
||||
let arch = out.text().trim().to_string() catch {
|
||||
e => raise Io("decoding uname output: \{e}")
|
||||
}
|
||||
match arch {
|
||||
"x86_64" => "x86_64-linux"
|
||||
"aarch64" => "aarch64-linux"
|
||||
a =>
|
||||
raise Unsupported(
|
||||
"unsupported machine architecture '\{a}' (use --system)",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn load_config(m : @argparse.Matches) -> Config raise @store.NixError {
|
||||
let root = match opt(m, "root") {
|
||||
Some(r) => r
|
||||
None =>
|
||||
match @env.get_env_var("HOME") {
|
||||
Some(h) => "\{h}/.mnix"
|
||||
None => raise Io("HOME is not set; pass --root")
|
||||
}
|
||||
}
|
||||
let store_dir = match opt(m, "store") {
|
||||
Some(s) => s.trim_end(chars="/").to_string()
|
||||
None => "\{root}/store"
|
||||
}
|
||||
let channel = @resolve.Channel::parse(opt(m, "channel").unwrap())
|
||||
let system = match opt(m, "system") {
|
||||
Some(s) => s
|
||||
None => detect_system()
|
||||
}
|
||||
let cache = match opt(m, "cache") {
|
||||
Some(u) => @cache.Cache::new(url=u)
|
||||
None => @cache.Cache::new()
|
||||
}
|
||||
{
|
||||
root,
|
||||
store_dir,
|
||||
profile: { dir: "\{root}/profile", },
|
||||
channel,
|
||||
system,
|
||||
cache,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
///|
|
||||
fn build_command() -> @argparse.Command {
|
||||
let g : Array[@argparse.OptionArg] = [
|
||||
OptionArg(
|
||||
"root",
|
||||
long="root",
|
||||
about="state directory (default: $HOME/.mnix)",
|
||||
global=true,
|
||||
),
|
||||
OptionArg(
|
||||
"store",
|
||||
long="store",
|
||||
about="store directory (default: <root>/store; /nix/store runs binaries natively)",
|
||||
global=true,
|
||||
),
|
||||
OptionArg(
|
||||
"channel",
|
||||
long="channel",
|
||||
about="nixos-unstable | nixpkgs-unstable | nixos-YY.MM",
|
||||
default_values=["nixos-unstable"],
|
||||
global=true,
|
||||
),
|
||||
OptionArg(
|
||||
"system",
|
||||
long="system",
|
||||
about="platform, e.g. x86_64-linux (default: detected)",
|
||||
global=true,
|
||||
),
|
||||
OptionArg(
|
||||
"cache",
|
||||
long="cache",
|
||||
about="binary cache URL (default: https://cache.nixos.org)",
|
||||
global=true,
|
||||
),
|
||||
]
|
||||
@argparse.Command(
|
||||
"mnix",
|
||||
about="Proof-of-concept Nix binary-cache client written in MoonBit",
|
||||
options=g,
|
||||
subcommand_required=true,
|
||||
subcommands=[
|
||||
@argparse.Command(
|
||||
"install",
|
||||
about="install a package (attr like `hello`, or /nix/store/<hash>-name) with its closure",
|
||||
flags=[
|
||||
FlagArg(
|
||||
"no-profile",
|
||||
long="no-profile",
|
||||
about="do not link into the profile",
|
||||
),
|
||||
FlagArg(
|
||||
"dry-run",
|
||||
long="dry-run",
|
||||
about="only resolve + verify the closure; download nothing",
|
||||
),
|
||||
],
|
||||
positionals=[
|
||||
PositionArg("target", num_args=@argparse.ValueRange::single()),
|
||||
],
|
||||
),
|
||||
@argparse.Command(
|
||||
"resolve",
|
||||
about="print the store path of an attribute",
|
||||
positionals=[
|
||||
PositionArg("target", num_args=@argparse.ValueRange::single()),
|
||||
],
|
||||
),
|
||||
@argparse.Command(
|
||||
"closure",
|
||||
about="print the transitive closure (verified narinfos) of a package",
|
||||
positionals=[
|
||||
PositionArg("target", num_args=@argparse.ValueRange::single()),
|
||||
],
|
||||
),
|
||||
@argparse.Command(
|
||||
"search",
|
||||
about="search store-path names of the channel (store-paths.xz)",
|
||||
positionals=[
|
||||
PositionArg("term", num_args=@argparse.ValueRange::single()),
|
||||
],
|
||||
),
|
||||
@argparse.Command("list", about="list profile contents"),
|
||||
@argparse.Command("remove", about="remove a package from the profile", positionals=[
|
||||
PositionArg("name", num_args=@argparse.ValueRange::single()),
|
||||
]),
|
||||
@argparse.Command(
|
||||
"env",
|
||||
about="print a shell snippet that puts the profile on PATH",
|
||||
),
|
||||
@argparse.Command(
|
||||
"run",
|
||||
about="run a command with the profile on PATH (inside a /nix/store namespace if needed)",
|
||||
positionals=[
|
||||
PositionArg(
|
||||
"command",
|
||||
num_args=@argparse.ValueRange::new(lower=1),
|
||||
allow_hyphen_values=true,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
async fn run_cli() -> Int32 {
|
||||
// `run` takes arbitrary trailing arguments: split argv at the subcommand
|
||||
// so flags meant for the child are not interpreted by mnix.
|
||||
let argv = @env.args()
|
||||
let args = argv[1:].to_array()
|
||||
let mut run_tail : Array[String]? = None
|
||||
let mut head = args
|
||||
for i in 0..<args.length() {
|
||||
if args[i] == "run" {
|
||||
// only treat as the subcommand if it is the first non-option token
|
||||
let mut ok = true
|
||||
let mut j = 0
|
||||
while j < i {
|
||||
let a = args[j]
|
||||
if a.has_prefix("--") {
|
||||
j += 2
|
||||
} else {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
head = args[0:i + 1].to_array()
|
||||
run_tail = Some(args[i + 1:].to_array())
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
let cmd = build_command()
|
||||
let m = match run_tail {
|
||||
Some(_) => cmd.parse(argv=head + ["--"] + ["_"])
|
||||
None => cmd.parse(argv=head)
|
||||
}
|
||||
guard m.subcommand is Some((name, sub)) else {
|
||||
raise Failure("no subcommand")
|
||||
}
|
||||
let cfg = load_config(m)
|
||||
fn arg(k : String) -> String {
|
||||
opt(sub, k).unwrap()
|
||||
}
|
||||
|
||||
match name {
|
||||
"install" => {
|
||||
cmd_install(
|
||||
cfg,
|
||||
arg("target"),
|
||||
sub.flags.get("no-profile").unwrap_or(false),
|
||||
sub.flags.get("dry-run").unwrap_or(false),
|
||||
)
|
||||
0
|
||||
}
|
||||
"resolve" => {
|
||||
cmd_resolve(cfg, arg("target"))
|
||||
0
|
||||
}
|
||||
"closure" => {
|
||||
cmd_closure(cfg, arg("target"))
|
||||
0
|
||||
}
|
||||
"search" => {
|
||||
cmd_search(cfg, arg("term"))
|
||||
0
|
||||
}
|
||||
"list" => {
|
||||
cmd_list(cfg)
|
||||
0
|
||||
}
|
||||
"remove" => {
|
||||
cmd_remove(cfg, arg("name"))
|
||||
0
|
||||
}
|
||||
"env" => {
|
||||
cmd_env(cfg)
|
||||
0
|
||||
}
|
||||
"run" => cmd_run(cfg, run_tail.unwrap())
|
||||
_ => raise Failure("unknown command \{name}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn main {
|
||||
let code = run_cli() catch {
|
||||
e => {
|
||||
eprintln("mnix: error: \{e}")
|
||||
1
|
||||
}
|
||||
}
|
||||
if code != 0 {
|
||||
@env.exit(code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"experiments/moon-nix/narinfo",
|
||||
"experiments/moon-nix/cache",
|
||||
"experiments/moon-nix/closure",
|
||||
"experiments/moon-nix/nar",
|
||||
"experiments/moon-nix/installer",
|
||||
"experiments/moon-nix/profile",
|
||||
"experiments/moon-nix/resolve",
|
||||
"moonbitlang/core/argparse",
|
||||
"moonbitlang/core/env",
|
||||
"moonbitlang/core/encoding/utf8",
|
||||
"moonbitlang/async",
|
||||
"moonbitlang/async/fs",
|
||||
"moonbitlang/async/process",
|
||||
"lin2077-zeming/moonxz/lib" @xz,
|
||||
}
|
||||
|
||||
supported_targets = "+native"
|
||||
|
||||
pkgtype(kind: "executable")
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon-nix/cli"
|
||||
|
||||
// Values
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,18 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon-nix/closure"
|
||||
|
||||
import {
|
||||
"experiments/moon-nix/narinfo",
|
||||
"experiments/moon-nix/store",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub async fn compute(Array[String], async (String) -> @narinfo.NarInfo? raise @store.NixError) -> Array[@narinfo.NarInfo] raise @store.NixError
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,76 @@
|
||||
///|
|
||||
/// True if something (even a dangling symlink) exists at `path`.
|
||||
pub async fn lexists(path : String) -> Bool noraise {
|
||||
try {
|
||||
ignore(@fs.kind(path, follow_symlink=false))
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
async fn write_node(path : String, node : @nar.Node) -> Unit {
|
||||
match node {
|
||||
File(executable~, contents~) =>
|
||||
@fs.write_file(
|
||||
path,
|
||||
contents,
|
||||
create_mode=CreateNew,
|
||||
permission=if executable { 0o555 } else { 0o444 },
|
||||
)
|
||||
Symlink(target~) => @fs.symlink(target~, path)
|
||||
Directory(entries~) => {
|
||||
@fs.mkdir(path, permission=0o755)
|
||||
for e in entries {
|
||||
let (name, child) = e
|
||||
write_node("\{path}/\{name}", child)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Unpack a parsed NAR as `<store_dir>/<base>` atomically: everything is
|
||||
/// written to a private temp directory inside the store dir (same
|
||||
/// filesystem) and then `rename(2)`d into place. Returns true if the path
|
||||
/// was newly installed, false if it was already present (left untouched).
|
||||
pub async fn install_node(
|
||||
store_dir : String,
|
||||
base : String,
|
||||
node : @nar.Node,
|
||||
) -> Bool raise @store.NixError {
|
||||
// Validate the base name so we never write outside the store dir.
|
||||
ignore(@store.StorePath::parse_base(base, store_dir~))
|
||||
let target = "\{store_dir}/\{base}"
|
||||
if lexists(target) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
@fs.mkdir(store_dir, permission=0o755, recursive=true, allow_exist=true)
|
||||
let tmp = "\{store_dir}/.tmp-install-\{base}"
|
||||
if lexists(tmp) {
|
||||
remove_tree(tmp)
|
||||
}
|
||||
write_node(tmp, node)
|
||||
@fs.rename(tmp, target)
|
||||
true
|
||||
} catch {
|
||||
e => raise Io("installing \{target}: \{e}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Remove a tree, fixing permissions first (store files are read-only).
|
||||
pub async fn remove_tree(path : String) -> Unit {
|
||||
match @fs.kind(path, follow_symlink=false) {
|
||||
Directory => {
|
||||
@fs.chmod(path, 0o755)
|
||||
for name in @fs.readdir(path, include_hidden=true) {
|
||||
remove_tree("\{path}/\{name}")
|
||||
}
|
||||
@fs.rmdir(path)
|
||||
}
|
||||
_ => @fs.remove(path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
///|
|
||||
async test "unpack NAR tree: contents, exec bits, symlinks, atomic rename" {
|
||||
let root = @fs.tmpdir(prefix="mnix-test-")
|
||||
let node : @nar.Node = Directory(entries=[
|
||||
(
|
||||
"bin",
|
||||
Directory(entries=[
|
||||
("run", File(executable=true, contents=b"#!/bin/sh\necho ok\n")),
|
||||
("run-link", Symlink(target="run")),
|
||||
]),
|
||||
),
|
||||
("data", File(executable=false, contents=b"hello")),
|
||||
])
|
||||
let base = "8padfyi6z9ipfq35j86krpvpvx3j3r3v-demo-1.0"
|
||||
let store = "\{root}/store"
|
||||
assert_true(install_node(store, base, node))
|
||||
let p = "\{store}/\{base}"
|
||||
assert_true(@fs.can_execute("\{p}/bin/run"))
|
||||
assert_true(!@fs.can_execute("\{p}/data"))
|
||||
assert_eq(@fs.read_file("\{p}/data").text(), "hello")
|
||||
assert_true(@fs.kind("\{p}/bin/run-link", follow_symlink=false) is SymLink)
|
||||
assert_eq(@fs.read_file("\{p}/bin/run-link").text(), "#!/bin/sh\necho ok\n")
|
||||
// second install is a no-op
|
||||
assert_true(!install_node(store, base, node))
|
||||
// no temp leftovers
|
||||
assert_eq(@fs.readdir(store, include_hidden=true), [base])
|
||||
remove_tree(root)
|
||||
}
|
||||
|
||||
///|
|
||||
async test "invalid base names are rejected before touching disk" {
|
||||
let root = @fs.tmpdir(prefix="mnix-test-")
|
||||
let mut failed = false
|
||||
try install_node("\{root}/store", "../evil", Directory(entries=[])) catch {
|
||||
_ => failed = true
|
||||
} noraise {
|
||||
_ => ()
|
||||
}
|
||||
assert_true(failed)
|
||||
assert_true(!lexists("\{root}/store"))
|
||||
remove_tree(root)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"experiments/moon-nix/nar",
|
||||
"moonbitlang/async/fs",
|
||||
}
|
||||
|
||||
import {
|
||||
"moonbitlang/async",
|
||||
} for "wbtest"
|
||||
@@ -0,0 +1,22 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon-nix/installer"
|
||||
|
||||
import {
|
||||
"experiments/moon-nix/nar",
|
||||
"experiments/moon-nix/store",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub async fn install_node(String, String, @nar.Node) -> Bool raise @store.NixError
|
||||
|
||||
pub async fn lexists(String) -> Bool noraise
|
||||
|
||||
pub async fn remove_tree(String) -> Unit
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"experiments/moon-nix/installer",
|
||||
"moonbitlang/async/fs",
|
||||
"moonbitlang/core/encoding/utf8",
|
||||
}
|
||||
|
||||
import {
|
||||
"moonbitlang/async",
|
||||
} for "wbtest"
|
||||
@@ -0,0 +1,35 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon-nix/profile"
|
||||
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn find_conflict(Array[Entry], String, Array[String]) -> (String, String)?
|
||||
|
||||
pub fn parse_manifest(String) -> Array[Entry] raise @store.NixError
|
||||
|
||||
pub fn serialize_manifest(Array[Entry]) -> String
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct Entry {
|
||||
name : String
|
||||
path : String
|
||||
bins : Array[String]
|
||||
}
|
||||
|
||||
pub(all) struct Profile {
|
||||
dir : String
|
||||
}
|
||||
pub async fn Profile::add(Self, String, String) -> Entry raise @store.NixError
|
||||
pub async fn Profile::list(Self) -> Array[Entry] raise @store.NixError
|
||||
pub async fn Profile::remove(Self, String) -> Entry raise @store.NixError
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,175 @@
|
||||
///|
|
||||
/// One installed package in a profile.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct Entry {
|
||||
name : String // user-facing name (e.g. "hello")
|
||||
path : String // full store path as installed (under the chosen store dir)
|
||||
bins : Array[String] // executables linked into <profile>/bin
|
||||
}
|
||||
|
||||
///|
|
||||
/// Manifest format: one line per entry, tab separated:
|
||||
/// name \t store-path \t comma-separated-bin-names
|
||||
pub fn parse_manifest(text : String) -> Array[Entry] raise @store.NixError {
|
||||
let out : Array[Entry] = []
|
||||
for line in text.split("\n") {
|
||||
if line.length() == 0 {
|
||||
continue
|
||||
}
|
||||
let parts = line.split("\t").map(fn(s) { s.to_owned() }).collect()
|
||||
if parts.length() != 3 {
|
||||
raise Parse("profile manifest: malformed line '\{line}'")
|
||||
}
|
||||
let bins = if parts[2].length() == 0 {
|
||||
[]
|
||||
} else {
|
||||
parts[2].split(",").map(fn(s) { s.to_owned() }).collect()
|
||||
}
|
||||
out.push({ name: parts[0], path: parts[1], bins, })
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn serialize_manifest(entries : Array[Entry]) -> String {
|
||||
let sb = StringBuilder()
|
||||
for e in entries {
|
||||
sb.write_string("\{e.name}\t\{e.path}\t\{e.bins.join(",")}\n")
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Which other entry (if any) already owns one of `bins`?
|
||||
pub fn find_conflict(
|
||||
entries : Array[Entry],
|
||||
name : String,
|
||||
bins : Array[String],
|
||||
) -> (String, String)? {
|
||||
for e in entries {
|
||||
if e.name == name {
|
||||
continue
|
||||
}
|
||||
for b in bins {
|
||||
if e.bins.contains(b) {
|
||||
return Some((e.name, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
pub(all) struct Profile {
|
||||
dir : String
|
||||
}
|
||||
|
||||
///|
|
||||
async fn Profile::read(self : Profile) -> Array[Entry] raise @store.NixError {
|
||||
let mf = "\{self.dir}/manifest"
|
||||
if !@installer.lexists(mf) {
|
||||
return []
|
||||
}
|
||||
let text = @utf8.decode(@fs.read_file(mf).binary()) catch {
|
||||
e => raise Io("reading \{mf}: \{e}")
|
||||
}
|
||||
parse_manifest(text)
|
||||
}
|
||||
|
||||
///|
|
||||
pub async fn Profile::list(
|
||||
self : Profile,
|
||||
) -> Array[Entry] raise @store.NixError {
|
||||
self.read()
|
||||
}
|
||||
|
||||
///|
|
||||
async fn Profile::write(
|
||||
self : Profile,
|
||||
entries : Array[Entry],
|
||||
) -> Unit raise @store.NixError {
|
||||
try {
|
||||
@fs.mkdir(self.dir, recursive=true, allow_exist=true)
|
||||
@fs.write_file(
|
||||
"\{self.dir}/manifest.tmp",
|
||||
serialize_manifest(entries),
|
||||
create_mode=CreateOrTruncate,
|
||||
)
|
||||
@fs.rename("\{self.dir}/manifest.tmp", "\{self.dir}/manifest", replace=true)
|
||||
} catch {
|
||||
e => raise Io("writing profile manifest: \{e}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Link `<store path>/bin/*` into `<profile>/bin`. Re-adding the same name
|
||||
/// replaces its previous links; a clash with another package's binary fails.
|
||||
pub async fn Profile::add(
|
||||
self : Profile,
|
||||
name : String,
|
||||
path : String,
|
||||
) -> Entry raise @store.NixError {
|
||||
let bindir = "\{path}/bin"
|
||||
if !@installer.lexists(bindir) {
|
||||
raise Io("\{path} has no bin/ directory; nothing to link")
|
||||
}
|
||||
let bins = @fs.readdir(bindir, sort=true) catch {
|
||||
e => raise Io("reading \{bindir}: \{e}")
|
||||
}
|
||||
if bins.length() == 0 {
|
||||
raise Io("\{bindir} is empty; nothing to link")
|
||||
}
|
||||
let entries = self.read()
|
||||
match find_conflict(entries, name, bins) {
|
||||
Some((owner, b)) =>
|
||||
raise Io(
|
||||
"binary '\{b}' is already provided by '\{owner}' in this profile",
|
||||
)
|
||||
None => ()
|
||||
}
|
||||
let entry : Entry = { name, path, bins, }
|
||||
try {
|
||||
@fs.mkdir("\{self.dir}/bin", recursive=true, allow_exist=true)
|
||||
// drop old links of the same name that the new version no longer has
|
||||
for e in entries {
|
||||
if e.name == name {
|
||||
for b in e.bins {
|
||||
@fs.remove("\{self.dir}/bin/\{b}", allow_missing=true)
|
||||
}
|
||||
}
|
||||
}
|
||||
for b in bins {
|
||||
@fs.symlink(
|
||||
target="\{bindir}/\{b}",
|
||||
"\{self.dir}/bin/\{b}",
|
||||
force_symlink=true,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
e => raise Io("linking binaries into \{self.dir}/bin: \{e}")
|
||||
}
|
||||
let rest = entries.filter(fn(e) { e.name != name })
|
||||
rest.push(entry)
|
||||
self.write(rest)
|
||||
entry
|
||||
}
|
||||
|
||||
///|
|
||||
pub async fn Profile::remove(
|
||||
self : Profile,
|
||||
name : String,
|
||||
) -> Entry raise @store.NixError {
|
||||
let entries = self.read()
|
||||
guard entries.iter().find_first(fn(e) { e.name == name }) is Some(entry) else {
|
||||
raise Io("'\{name}' is not installed in this profile")
|
||||
}
|
||||
try {
|
||||
for b in entry.bins {
|
||||
@fs.remove("\{self.dir}/bin/\{b}", allow_missing=true)
|
||||
}
|
||||
} catch {
|
||||
e => raise Io("removing links: \{e}")
|
||||
}
|
||||
self.write(entries.filter(fn(e) { e.name != name }))
|
||||
entry
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
///|
|
||||
test "manifest roundtrip" {
|
||||
let es : Array[Entry] = [
|
||||
{ name: "hello", path: "/s/aaa-hello-2.8", bins: ["hello"], },
|
||||
{ name: "coreutils", path: "/s/bbb-coreutils-9", bins: ["ls", "cat"], },
|
||||
]
|
||||
assert_eq(parse_manifest(serialize_manifest(es)), es)
|
||||
assert_true(@store.raises(() => parse_manifest("only\ttwo\n")))
|
||||
}
|
||||
|
||||
///|
|
||||
test "conflict detection" {
|
||||
let es : Array[Entry] = [{ name: "a", path: "/p", bins: ["x", "y"], }]
|
||||
assert_eq(find_conflict(es, "b", ["y"]), Some(("a", "y")))
|
||||
assert_eq(find_conflict(es, "a", ["y"]), None) // upgrade of same name is fine
|
||||
assert_eq(find_conflict(es, "b", ["z"]), None)
|
||||
}
|
||||
|
||||
///|
|
||||
async test "add / list / remove with real symlinks" {
|
||||
let root = @fs.tmpdir(prefix="mnix-prof-")
|
||||
let pkg = "\{root}/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-demo-1"
|
||||
@fs.mkdir("\{pkg}/bin", recursive=true)
|
||||
@fs.write_file("\{pkg}/bin/demo", "#!/bin/sh\n", permission=0o755)
|
||||
let p : Profile = { dir: "\{root}/profile", }
|
||||
let e = p.add("demo", pkg)
|
||||
assert_eq(e.bins, ["demo"])
|
||||
assert_true(
|
||||
@fs.kind("\{root}/profile/bin/demo", follow_symlink=false) is SymLink,
|
||||
)
|
||||
assert_eq(p.list().length(), 1)
|
||||
// re-add is idempotent
|
||||
ignore(p.add("demo", pkg))
|
||||
assert_eq(p.list().length(), 1)
|
||||
// conflicting package
|
||||
let pkg2 = "\{root}/store/9padfyi6z9ipfq35j86krpvpvx3j3r3v-other-1"
|
||||
@fs.mkdir("\{pkg2}/bin", recursive=true)
|
||||
@fs.write_file("\{pkg2}/bin/demo", "x", permission=0o755)
|
||||
let mut failed = false
|
||||
try p.add("other", pkg2) catch {
|
||||
_ => failed = true
|
||||
} noraise {
|
||||
_ => ()
|
||||
}
|
||||
assert_true(failed)
|
||||
ignore(p.remove("demo"))
|
||||
assert_eq(p.list().length(), 0)
|
||||
assert_true(!@installer.lexists("\{root}/profile/bin/demo"))
|
||||
@installer.remove_tree(root)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"moonbitlang/core/json",
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Generated using `moon info`, DON'T EDIT IT
|
||||
package "experiments/moon-nix/resolve"
|
||||
|
||||
import {
|
||||
"experiments/moon-nix/store",
|
||||
"moonbitlang/core/debug",
|
||||
}
|
||||
|
||||
// Values
|
||||
pub fn parse_hydra_build(String) -> (String, String) raise @store.NixError
|
||||
|
||||
pub fn parse_store_paths(String) -> Array[@store.StorePath] raise @store.NixError
|
||||
|
||||
pub fn search(Array[@store.StorePath], String) -> Array[(String, Int32)]
|
||||
|
||||
// Errors
|
||||
|
||||
// Types and methods
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub(all) struct Channel {
|
||||
name : String
|
||||
project : String
|
||||
jobset : String
|
||||
job_prefix : String
|
||||
releases_url : String
|
||||
}
|
||||
pub fn Channel::job_url(Self, String, String) -> String raise @store.NixError
|
||||
pub fn Channel::parse(String) -> Self raise @store.NixError
|
||||
|
||||
// Type aliases
|
||||
|
||||
// Traits
|
||||
@@ -0,0 +1,183 @@
|
||||
///|
|
||||
/// Where to look up a package attribute on Hydra for a given channel.
|
||||
#derive(Eq, Debug)
|
||||
pub(all) struct Channel {
|
||||
name : String
|
||||
project : String
|
||||
jobset : String
|
||||
job_prefix : String // "" for nixpkgs/trunk, "nixpkgs." for nixos release jobsets
|
||||
releases_url : String // channel base URL for store-paths.xz
|
||||
}
|
||||
|
||||
///|
|
||||
/// Map a channel name to a Hydra jobset.
|
||||
/// nixos-unstable / nixpkgs-unstable / unstable -> hydra nixpkgs/trunk
|
||||
/// nixos-YY.MM -> hydra nixos/release-YY.MM
|
||||
pub fn Channel::parse(name : String) -> Channel raise @store.NixError {
|
||||
if name == "nixos-unstable" ||
|
||||
name == "nixpkgs-unstable" ||
|
||||
name == "unstable" {
|
||||
return {
|
||||
name,
|
||||
project: "nixpkgs",
|
||||
jobset: "trunk",
|
||||
job_prefix: "",
|
||||
releases_url: "https://channels.nixos.org/\{name}",
|
||||
}
|
||||
}
|
||||
if name.has_prefix("nixos-") {
|
||||
let ver = name[6:].to_owned()
|
||||
let ok = ver.length() == 5 &&
|
||||
ver[2:3].to_owned() == "." &&
|
||||
ver.to_array().iter().all(fn(c) { c == '.' || (c >= '0' && c <= '9') })
|
||||
if ok {
|
||||
return {
|
||||
name,
|
||||
project: "nixos",
|
||||
jobset: "release-\{ver}",
|
||||
job_prefix: "nixpkgs.",
|
||||
releases_url: "https://channels.nixos.org/\{name}",
|
||||
}
|
||||
}
|
||||
}
|
||||
raise Parse(
|
||||
"unknown channel '\{name}' (expected nixos-unstable, nixpkgs-unstable or nixos-YY.MM)",
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Hydra URL returning the JSON of the latest successful build of `attr`.
|
||||
pub fn Channel::job_url(
|
||||
self : Channel,
|
||||
attr : String,
|
||||
system : String,
|
||||
) -> String raise @store.NixError {
|
||||
if attr.length() == 0 {
|
||||
raise Parse("empty package attribute")
|
||||
}
|
||||
for c in attr {
|
||||
let ok = (c >= 'a' && c <= 'z') ||
|
||||
(c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') ||
|
||||
c == '_' ||
|
||||
c == '-' ||
|
||||
c == '.' ||
|
||||
c == '+'
|
||||
if !ok {
|
||||
raise Parse("invalid character '\{c}' in package attribute '\{attr}'")
|
||||
}
|
||||
}
|
||||
"https://hydra.nixos.org/job/\{self.project}/\{self.jobset}/\{self.job_prefix}\{attr}.\{system}/latest-finished"
|
||||
}
|
||||
|
||||
///|
|
||||
/// Extract `(store path, nixname)` of the `out` output from Hydra's build JSON.
|
||||
pub fn parse_hydra_build(
|
||||
text : String,
|
||||
) -> (String, String) raise @store.NixError {
|
||||
let j = @json.parse(text) catch {
|
||||
_ => raise Parse("Hydra response is not valid JSON")
|
||||
}
|
||||
guard j is Object(top) else { raise Parse("Hydra response: expected object") }
|
||||
if top.get("error") is Some(e) {
|
||||
raise Parse("Hydra error: \{e.stringify()}")
|
||||
}
|
||||
if top.get("finished") is Some(f) && f.stringify() != "1" {
|
||||
raise Verify("Hydra build not finished")
|
||||
}
|
||||
if top.get("buildstatus") is Some(s) && s.stringify() != "0" {
|
||||
raise Verify(
|
||||
"Hydra build was not successful (buildstatus \{s.stringify()})",
|
||||
)
|
||||
}
|
||||
guard top.get("buildoutputs") is Some(Object(outs)) else {
|
||||
raise Parse("Hydra response: missing buildoutputs")
|
||||
}
|
||||
guard outs.get("out") is Some(Object(out)) else {
|
||||
raise Parse("Hydra response: no 'out' output")
|
||||
}
|
||||
guard out.get("path") is Some(String(path)) else {
|
||||
raise Parse("Hydra response: no path for 'out'")
|
||||
}
|
||||
let name = match top.get("nixname") {
|
||||
Some(String(n)) => n
|
||||
_ => ""
|
||||
}
|
||||
ignore(@store.StorePath::parse(path))
|
||||
(path, name)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Parse the text of `store-paths.xz` (one store path per line).
|
||||
pub fn parse_store_paths(
|
||||
text : String,
|
||||
) -> Array[@store.StorePath] raise @store.NixError {
|
||||
let out : Array[@store.StorePath] = []
|
||||
for line in text.split("\n") {
|
||||
if line.length() == 0 {
|
||||
continue
|
||||
}
|
||||
out.push(@store.StorePath::parse(line.to_owned()))
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
/// Substring search over `name-version` strings of the channel's store paths.
|
||||
/// Returns distinct names sorted by (exact match first, then length, then
|
||||
/// alphabetical) with the number of distinct store paths for that name (the
|
||||
/// same name appears several times because the channel covers all platforms).
|
||||
pub fn search(
|
||||
paths : Array[@store.StorePath],
|
||||
query : String,
|
||||
) -> Array[(String, Int32)] {
|
||||
let q = query.to_lower()
|
||||
let counts : Map[String, Int32] = Map([])
|
||||
for p in paths {
|
||||
if p.name.to_lower().contains(q) {
|
||||
counts[p.name] = counts.get_or_default(p.name, 0) + 1
|
||||
}
|
||||
}
|
||||
let res : Array[(String, Int32)] = []
|
||||
for k, v in counts {
|
||||
res.push((k, v))
|
||||
}
|
||||
res.sort_by(fn(a, b) {
|
||||
let ka = rank(a.0, q)
|
||||
let kb = rank(b.0, q)
|
||||
if ka != kb {
|
||||
ka - kb
|
||||
} else if a.0.length() != b.0.length() {
|
||||
a.0.length() - b.0.length()
|
||||
} else {
|
||||
a.0.compare(b.0)
|
||||
}
|
||||
})
|
||||
res
|
||||
}
|
||||
|
||||
///|
|
||||
/// 0 = pname equals query, 1 = starts with query, 2 = elsewhere.
|
||||
fn rank(name : String, q : String) -> Int32 {
|
||||
let l = name.to_lower()
|
||||
// pname = up to the first '-' followed by a digit
|
||||
let chars = l.to_array()
|
||||
let mut cut = chars.length()
|
||||
for i in 0..<chars.length() {
|
||||
if chars[i] == '-' && i + 1 < chars.length() {
|
||||
let n = chars[i + 1]
|
||||
if n >= '0' && n <= '9' {
|
||||
cut = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
let pname = l[0:cut].to_owned()
|
||||
if pname == q {
|
||||
0
|
||||
} else if l.has_prefix(q) {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
///|
|
||||
test "channel mapping" {
|
||||
let c = Channel::parse("nixos-unstable")
|
||||
inspect(
|
||||
c.job_url("hello", "x86_64-linux"),
|
||||
content="https://hydra.nixos.org/job/nixpkgs/trunk/hello.x86_64-linux/latest-finished",
|
||||
)
|
||||
let r = Channel::parse("nixos-25.05")
|
||||
inspect(
|
||||
r.job_url("hello", "x86_64-linux"),
|
||||
content="https://hydra.nixos.org/job/nixos/release-25.05/nixpkgs.hello.x86_64-linux/latest-finished",
|
||||
)
|
||||
assert_true(@store.raises(() => Channel::parse("bogus")))
|
||||
assert_true(@store.raises(() => c.job_url("a/b", "x86_64-linux")))
|
||||
}
|
||||
|
||||
///|
|
||||
test "parse hydra build json (real response shape)" {
|
||||
let text =
|
||||
#|{"system":"x86_64-linux","finished":1,"buildstatus":0,"nixname":"hello-2.12.3","buildoutputs":{"out":{"path":"/nix/store/dcg4mi1h810kl0q5skk995b8nb2idg1g-hello-2.12.3"}}}
|
||||
let (p, n) = parse_hydra_build(text)
|
||||
inspect(p, content="/nix/store/dcg4mi1h810kl0q5skk995b8nb2idg1g-hello-2.12.3")
|
||||
inspect(n, content="hello-2.12.3")
|
||||
assert_true(
|
||||
@store.raises(() => {
|
||||
parse_hydra_build("{\"error\":\"There is no successful build\"}")
|
||||
}),
|
||||
)
|
||||
assert_true(@store.raises(() => parse_hydra_build("not json")))
|
||||
assert_true(
|
||||
@store.raises(() => {
|
||||
parse_hydra_build(
|
||||
"{\"finished\":1,\"buildstatus\":1,\"buildoutputs\":{}}",
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
///|
|
||||
test "search ranks exact pname first" {
|
||||
let paths = parse_store_paths(
|
||||
(
|
||||
#|/nix/store/8padfyi6z9ipfq35j86krpvpvx3j3r3v-hello-2.8.4
|
||||
#|/nix/store/2w75rgswbbfgj1910mw7w5lz0cf6rxfr-hello-1.0.0.2
|
||||
#|/nix/store/2w75rgswbbfgj1910mw7w5lz0cf6rxfr-hello-1.0.0.2
|
||||
#|/nix/store/266xlfadj5g19isr0ygn0nz9jbgmvhrd-akku-retropikzel-hello-1.2.3
|
||||
#|/nix/store/76bbldfx3g88jxaqjakksgc5mvl1c3kb-ripgrep-15.2.0
|
||||
),
|
||||
)
|
||||
let r = search(paths, "hello")
|
||||
assert_eq(r.length(), 3)
|
||||
assert_eq(r[0].0.has_prefix("hello-"), true)
|
||||
assert_eq(r[2].0, "akku-retropikzel-hello-1.2.3")
|
||||
assert_eq(search(paths, "HELLO").length(), 3)
|
||||
assert_eq(search(paths, "zzz").length(), 0)
|
||||
}
|
||||
Reference in new issue
Block a user