Skip to content

Commit

Permalink
rework ldns command matching to use file-stem and give errors
Browse files Browse the repository at this point in the history
  • Loading branch information
tertsdiepraam committed Nov 22, 2024
1 parent bfbf492 commit 178468c
Showing 1 changed file with 44 additions and 8 deletions.
52 changes: 44 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,55 @@ pub fn try_ldns_compatibility<I: IntoIterator<Item = OsString>>(
let mut args_iter = args.into_iter();
let binary_path = args_iter.next().ok_or("Missing binary name")?;

let binary_name = Path::new(&binary_path)
let binary_name = extract_binary_name(Path::new(&binary_path))?;

// We only branch on the binary name for the ldns utilities. The rest we
// just handle as regular dnst.
let Some(binary_name) = binary_name.strip_prefix("ldns-") else {
return Ok(None);
};

let res = match binary_name {
"key2ds" => Key2ds::parse_ldns_args(args_iter),
"nsec3-hash" => Nsec3Hash::parse_ldns_args(args_iter),
_ => return Err(format!("Unrecognized ldns command 'ldns-{binary_name}'").into()),
};

Ok(Some(res?))
}

/// Get the binary name from a [`Path`].
///
/// The binary name is the file name without any extensions. It is similar
/// to the unstable `Path::file_stem`.
///
/// ```rust
/// use dnst::extract_binary_name;
/// use std::path::Path;
///
/// let bin = extract_binary_name(Path::new("foo/ldns-xxx")).unwrap();
/// assert_eq!(bin, "ldns-xxx");
///
/// let bin = extract_binary_name(Path::new("foo/ldns-xxx.real")).unwrap();
/// assert_eq!(bin, "ldns-xxx");
///
/// let bin = extract_binary_name(Path::new("./ldns-xxx.exe")).unwrap();
/// assert_eq!(bin, "ldns-xxx");
///
/// let bin = extract_binary_name(Path::new("ldns-xxx")).unwrap();
/// assert_eq!(bin, "ldns-xxx");
/// ```
pub fn extract_binary_name(path: &Path) -> Result<&str, Error> {
let filename = path
.file_name()
.ok_or("Missing binary file name")?
.to_str()
.ok_or("Binary file name is not valid unicode")?;

let res = match binary_name {
"ldns-key2ds" => Key2ds::parse_ldns_args(args_iter),
"ldns-nsec3-hash" => Nsec3Hash::parse_ldns_args(args_iter),
_ => return Ok(None),
};

res.map(Some)
match filename.split_once('.') {
Some((binary, _)) => Ok(binary),
None => Ok(filename),
}
}

fn parse_args(env: impl Env) -> Result<Args, Error> {
Expand Down

0 comments on commit 178468c

Please sign in to comment.