WIP: installer, profile, resolve, cli
This commit is contained in:
1 parent
988c942952
commit
b3d95bb012
20 files changed
+1274
-2
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user