add --hash

This commit is contained in:
figsoda 2023-01-11 20:57:42 -05:00
parent 6d07a44504
commit aeece7a065
6 changed files with 55 additions and 9 deletions

View File

@ -25,8 +25,12 @@ pub struct Opts {
#[arg(short, long, default_value_t = 0)]
pub indent: usize,
/// only output the hash
#[arg(short = 'H', long, group = "format")]
pub hash: bool,
/// output in json format
#[arg(short, long)]
#[arg(short, long, group = "format")]
pub json: bool,
/// additional arguments to pass to the fetcher

View File

@ -40,6 +40,15 @@ pub trait Fetcher<'a> {
indent: String,
) -> Result<()>;
fn fetch_hash(
&'a self,
out: &mut impl ::std::io::Write,
url: &'a Url,
rev: Option<String>,
args: Vec<(String, String)>,
args_str: Vec<(String, String)>,
) -> Result<()>;
fn fetch_json(
&'a self,
out: &mut impl Write,
@ -96,6 +105,31 @@ macro_rules! impl_fetcher {
self.write_nix(out, values, rev, hash, args, args_str, overwrites, indent)
}
fn fetch_hash(
&'a self,
out: &mut impl ::std::io::Write,
url: &'a ::url::Url,
rev: Option<String>,
args: Vec<(String, String)>,
args_str: Vec<(String, String)>,
) -> ::anyhow::Result<()> {
use anyhow::Context;
let values = &self
.get_values(url)
.with_context(|| format!("failed to parse {url}"))?;
let rev = match rev {
Some(rev) => rev,
None => self.fetch_rev(values)?,
};
let hash = self.fetch(values, &rev, &args, &args_str)?;
write!(out, "{}", hash)?;
Ok(())
}
fn fetch_json(
&'a self,
out: &mut impl ::std::io::Write,

View File

@ -140,7 +140,9 @@ fn main() -> Result<()> {
let out = &mut stdout().lock();
let args = opts.args.into_iter().tuples().collect();
let args_str = opts.args_str.into_iter().tuples().collect();
if opts.json {
if opts.hash {
fetcher.fetch_hash(out, &opts.url, opts.rev, args, args_str)
} else if opts.json {
fetcher.fetch_json(
out,
&opts.url,
@ -166,7 +168,5 @@ fn main() -> Result<()> {
overwrites,
" ".repeat(opts.indent),
)
}?;
Ok(())
}
}

1
tests/cmd/hash.stdout Normal file
View File

@ -0,0 +1 @@
sha256-jZ+cCp1THDhfHH5yMmRPjGuthOqsgcF/3OjZ61FMdA4=

1
tests/cmd/hash.toml Normal file
View File

@ -0,0 +1 @@
args = ["https://github.com/nix-community/nurl", "v0.3.0", "--hash"]

View File

@ -15,9 +15,15 @@ fn integration() {
fn verify_outputs() {
for path in glob("tests/cmd/**/*.stdout").unwrap() {
let path = path.unwrap();
let name = path.file_name().unwrap();
let name = path
.file_name()
.unwrap()
.to_str()
.unwrap()
.strip_suffix(".stdout")
.unwrap();
if name == "json.stdout" {
if matches!(name, "hash" | "json") {
eprintln!("skipping {}", path.display());
continue;
}
@ -27,9 +33,9 @@ fn verify_outputs() {
let mut expr = String::from_utf8(fs::read(&path).unwrap()).unwrap();
expr.insert_str(0, "(import <nixpkgs> { }).");
if name == "overwrite.stdout" {
if name == "overwrite" {
expr.insert_str(0, r#"let pname = "nurl"; in "#);
} else if name == "overwrite_str.stdout" {
} else if name == "overwrite_str" {
expr.insert_str(0, r#"let version = "0.3.0"; in "#);
}