///| /// A parsed `.narinfo` file as served by a Nix binary cache. #derive(Eq, Debug) pub(all) struct NarInfo { store_path : String // full path, e.g. /nix/store/-hello-2.8.4 url : String // relative to the cache, e.g. nar/.nar.xz compression : String // none | xz | zstd | bzip2 ... file_hash : String // sha256: of the compressed file file_size : Int64 nar_hash : String // sha256: of the uncompressed NAR nar_size : Int64 references : Array[String] // base names (-), may include self deriver : String? // base name of the .drv sigs : Array[String] // name:base64 ca : String? } ///| fn parse_i64(key : String, v : String) -> Int64 raise @store.NixError { @string.parse_int64(v) catch { _ => raise Parse("narinfo: bad integer for \{key}: '\{v}'") } } ///| /// Parse the text of a narinfo file. Required keys: StorePath, URL, /// NarHash, NarSize. `References` is optional (omitted when empty). `Compression` defaults to "bzip2" when /// absent (per the Nix spec); unsupported values fail at decompression time. /// Duplicate keys (except `Sig`, which may repeat) and malformed lines are /// errors. pub fn NarInfo::parse(text : String) -> NarInfo raise @store.NixError { let seen : Map[String, String] = Map([]) let sigs : Array[String] = [] for line in text.split("\n") { let line = line.trim_end(chars="\r").to_owned() if line.length() == 0 { continue } // "Key: value", or "Key:" alone when the value is empty (e.g. no references) let (key, value) = if line.find(": ") is Some(i) { (line[0:i].to_owned(), line[i + 2:].to_owned()) } else if line.has_suffix(":") { (line[0:line.length() - 1].to_owned(), "") } else { raise Parse("narinfo: malformed line (no ': '): \{line}") } if key == "Sig" { sigs.push(value) continue } if seen.contains(key) { raise Parse("narinfo: duplicate key \{key}") } seen[key] = value } fn req(k : String) -> String raise @store.NixError { match seen.get(k) { Some(v) => v None => raise Parse("narinfo: missing required key \{k}") } } let store_path = req("StorePath") // Validate the path shape loudly. ignore(@store.StorePath::parse(store_path)) let file_hash = match seen.get("FileHash") { Some(v) => v None => "" } let file_size = match seen.get("FileSize") { Some(v) => parse_i64("FileSize", v) None => 0L } let references = match seen.get("References") { Some(v) => v .split(" ") .filter(fn(s) { s.length() > 0 }) .map(fn(s) { s.to_owned() }) .collect() // cache.nixos.org omits the line entirely when there are no references None => [] } for r in references { ignore(@store.StorePath::parse_base(r)) } { store_path, url: req("URL"), compression: match seen.get("Compression") { Some(c) => c None => "bzip2" }, file_hash, file_size, nar_hash: req("NarHash"), nar_size: parse_i64("NarSize", req("NarSize")), references, deriver: seen.get("Deriver"), sigs, ca: seen.get("CA"), } }