chroot-realpath: Add error context (#410360)

authored by Will Fancher and committed by GitHub 37ba5e55 6caf586c

+23 -11
+10 -1
pkgs/by-name/ch/chroot-realpath/src/Cargo.lock
··· 1 1 # This file is automatically @generated by Cargo. 2 2 # It is not intended for manual editing. 3 - version = 3 3 + version = 4 4 + 5 + [[package]] 6 + name = "anyhow" 7 + version = "1.0.98" 8 + source = "registry+https://github.com/rust-lang/crates.io-index" 9 + checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" 4 10 5 11 [[package]] 6 12 name = "chroot-realpath" 7 13 version = "0.1.0" 14 + dependencies = [ 15 + "anyhow", 16 + ]
+1
pkgs/by-name/ch/chroot-realpath/src/Cargo.toml
··· 4 4 edition = "2021" 5 5 6 6 [dependencies] 7 + anyhow = "1.0.98" 7 8 8 9 [profile.release] 9 10 opt-level = "z"
+12 -10
pkgs/by-name/ch/chroot-realpath/src/src/main.rs
··· 1 1 use std::env; 2 - use std::io::{stdout, Error, ErrorKind, Write}; 2 + use std::io::{stdout, Write}; 3 3 use std::os::unix::ffi::OsStrExt; 4 4 use std::os::unix::fs; 5 5 6 - fn main() -> std::io::Result<()> { 6 + use anyhow::{bail, Context, Result}; 7 + 8 + fn main() -> Result<()> { 7 9 let args: Vec<String> = env::args().collect(); 8 10 9 11 if args.len() != 3 { 10 - return Err(Error::new( 11 - ErrorKind::InvalidInput, 12 - format!("Usage: {} <chroot> <path>", args[0]), 13 - )); 12 + bail!("Usage: {} <chroot> <path>", args[0]); 14 13 } 15 14 16 - fs::chroot(&args[1])?; 17 - std::env::set_current_dir("/")?; 15 + fs::chroot(&args[1]).context("Failed to chroot")?; 16 + std::env::set_current_dir("/").context("Failed to change directory")?; 18 17 19 - let path = std::fs::canonicalize(&args[2])?; 18 + let path = std::fs::canonicalize(&args[2]) 19 + .with_context(|| format!("Failed to canonicalize {}", args[2]))?; 20 20 21 - stdout().write_all(path.into_os_string().as_bytes())?; 21 + stdout() 22 + .write_all(path.into_os_string().as_bytes()) 23 + .context("Failed to write output")?; 22 24 23 25 Ok(()) 24 26 }