chroot-realpath: Add error context

This commit is contained in:
Will Fancher 2025-05-23 16:15:31 -04:00
parent 2795c506fe
commit ceabb2059d
3 changed files with 23 additions and 11 deletions

View file

@ -1,7 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "anyhow"
version = "1.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
[[package]]
name = "chroot-realpath"
version = "0.1.0"
dependencies = [
"anyhow",
]

View file

@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1.0.98"
[profile.release]
opt-level = "z"

View file

@ -1,24 +1,26 @@
use std::env;
use std::io::{stdout, Error, ErrorKind, Write};
use std::io::{stdout, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs;
fn main() -> std::io::Result<()> {
use anyhow::{bail, Context, Result};
fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("Usage: {} <chroot> <path>", args[0]),
));
bail!("Usage: {} <chroot> <path>", args[0]);
}
fs::chroot(&args[1])?;
std::env::set_current_dir("/")?;
fs::chroot(&args[1]).context("Failed to chroot")?;
std::env::set_current_dir("/").context("Failed to change directory")?;
let path = std::fs::canonicalize(&args[2])?;
let path = std::fs::canonicalize(&args[2])
.with_context(|| format!("Failed to canonicalize {}", args[2]))?;
stdout().write_all(path.into_os_string().as_bytes())?;
stdout()
.write_all(path.into_os_string().as_bytes())
.context("Failed to write output")?;
Ok(())
}