Skip to content

Commit

Permalink
tests.nixpkgs-check-by-name: .context -> .with_context
Browse files Browse the repository at this point in the history
Avoids allocation in the non-error case
  • Loading branch information
infinisil committed Jan 9, 2024
1 parent 4cd2e64 commit a1db0cd
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 31 deletions.
26 changes: 15 additions & 11 deletions pkgs/test/nixpkgs-check-by-name/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,22 @@ pub fn check_values(
) -> validation::Result<ratchet::Nixpkgs> {
// Write the list of packages we need to check into a temporary JSON file.
// This can then get read by the Nix evaluation.
let attrs_file = NamedTempFile::new().context("Failed to create a temporary file")?;
let attrs_file = NamedTempFile::new().with_context(|| "Failed to create a temporary file")?;
// We need to canonicalise this path because if it's a symlink (which can be the case on
// Darwin), Nix would need to read both the symlink and the target path, therefore need 2
// NIX_PATH entries for restrict-eval. But if we resolve the symlinks then only one predictable
// entry is needed.
let attrs_file_path = attrs_file.path().canonicalize()?;

serde_json::to_writer(&attrs_file, &package_names).context(format!(
"Failed to serialise the package names to the temporary path {}",
attrs_file_path.display()
))?;
serde_json::to_writer(&attrs_file, &package_names).with_context(|| {
format!(
"Failed to serialise the package names to the temporary path {}",
attrs_file_path.display()
)
})?;

let expr_path = std::env::var("NIX_CHECK_BY_NAME_EXPR_PATH")
.context("Could not get environment variable NIX_CHECK_BY_NAME_EXPR_PATH")?;
.with_context(|| "Could not get environment variable NIX_CHECK_BY_NAME_EXPR_PATH")?;
// With restrict-eval, only paths in NIX_PATH can be accessed, so we explicitly specify the
// ones needed needed
let mut command = process::Command::new("nix-instantiate");
Expand Down Expand Up @@ -112,17 +114,19 @@ pub fn check_values(

let result = command
.output()
.context(format!("Failed to run command {command:?}"))?;
.with_context(|| format!("Failed to run command {command:?}"))?;

if !result.status.success() {
anyhow::bail!("Failed to run command {command:?}");
}
// Parse the resulting JSON value
let attributes: Vec<(String, ByNameAttribute)> = serde_json::from_slice(&result.stdout)
.context(format!(
"Failed to deserialise {}",
String::from_utf8_lossy(&result.stdout)
))?;
.with_context(|| {
format!(
"Failed to deserialise {}",
String::from_utf8_lossy(&result.stdout)
)
})?;

let check_result = validation::sequence(attributes.into_iter().map(
|(attribute_name, attribute_value)| {
Expand Down
12 changes: 7 additions & 5 deletions pkgs/test/nixpkgs-check-by-name/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,12 @@ pub fn check_nixpkgs<W: io::Write>(
error_writer: &mut W,
) -> validation::Result<ratchet::Nixpkgs> {
Ok({
let nixpkgs_path = nixpkgs_path.canonicalize().context(format!(
"Nixpkgs path {} could not be resolved",
nixpkgs_path.display()
))?;
let nixpkgs_path = nixpkgs_path.canonicalize().with_context(|| {
format!(
"Nixpkgs path {} could not be resolved",
nixpkgs_path.display()
)
})?;

if !nixpkgs_path.join(utils::BASE_SUBPATH).exists() {
writeln!(
Expand Down Expand Up @@ -237,7 +239,7 @@ mod tests {
let writer = temp_env::with_var("NO_COLOR", Some("1"), || -> anyhow::Result<_> {
let mut writer = vec![];
process(base_nixpkgs, &path, &[&extra_nix_path], &mut writer)
.context(format!("Failed test case {name}"))?;
.with_context(|| format!("Failed test case {name}"))?;
Ok(writer)
})?;

Expand Down
29 changes: 16 additions & 13 deletions pkgs/test/nixpkgs-check-by-name/src/references.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ pub fn check_references(
) -> validation::Result<()> {
// The empty argument here is the subpath under the package directory to check
// An empty one means the package directory itself
check_path(relative_package_dir, absolute_package_dir, Path::new("")).context(format!(
"While checking the references in package directory {}",
relative_package_dir.display()
))
check_path(relative_package_dir, absolute_package_dir, Path::new("")).with_context(|| {
format!(
"While checking the references in package directory {}",
relative_package_dir.display()
)
})
}

/// Checks for a specific path to not have references outside
Expand Down Expand Up @@ -62,16 +64,18 @@ fn check_path(
.map(|entry| {
let entry_subpath = subpath.join(entry.file_name());
check_path(relative_package_dir, absolute_package_dir, &entry_subpath)
.context(format!("Error while recursing into {}", subpath.display()))
.with_context(|| {
format!("Error while recursing into {}", subpath.display())
})
})
.collect_vec()?,
)
} else if path.is_file() {
// Only check Nix files
if let Some(ext) = path.extension() {
if ext == OsStr::new("nix") {
check_nix_file(relative_package_dir, absolute_package_dir, subpath).context(
format!("Error while checking Nix file {}", subpath.display()),
check_nix_file(relative_package_dir, absolute_package_dir, subpath).with_context(
|| format!("Error while checking Nix file {}", subpath.display()),
)?
} else {
Success(())
Expand All @@ -93,13 +97,12 @@ fn check_nix_file(
subpath: &Path,
) -> validation::Result<()> {
let path = absolute_package_dir.join(subpath);
let parent_dir = path.parent().context(format!(
"Could not get parent of path {}",
subpath.display()
))?;
let parent_dir = path
.parent()
.with_context(|| format!("Could not get parent of path {}", subpath.display()))?;

let contents =
read_to_string(&path).context(format!("Could not read file {}", subpath.display()))?;
let contents = read_to_string(&path)
.with_context(|| format!("Could not read file {}", subpath.display()))?;

let root = Root::parse(&contents);
if let Some(error) = root.errors().first() {
Expand Down
4 changes: 2 additions & 2 deletions pkgs/test/nixpkgs-check-by-name/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ pub const PACKAGE_NIX_FILENAME: &str = "package.nix";
pub fn read_dir_sorted(base_dir: &Path) -> anyhow::Result<Vec<fs::DirEntry>> {
let listing = base_dir
.read_dir()
.context(format!("Could not list directory {}", base_dir.display()))?;
.with_context(|| format!("Could not list directory {}", base_dir.display()))?;
let mut shard_entries = listing
.collect::<io::Result<Vec<_>>>()
.context(format!("Could not list directory {}", base_dir.display()))?;
.with_context(|| format!("Could not list directory {}", base_dir.display()))?;
shard_entries.sort_by_key(|entry| entry.file_name());
Ok(shard_entries)
}
Expand Down

0 comments on commit a1db0cd

Please sign in to comment.