chore: use nightly rustfmt rules

Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: Ia3745c82c92a78e8326d2e0e446f20d66a6a6964
This commit is contained in:
raf 2025-11-14 21:47:33 +03:00
commit c3321858c4
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
11 changed files with 912 additions and 799 deletions

View file

@ -1 +1,27 @@
condense_wildcard_suffixes = true
doc_comment_code_block_width = 80
edition = "2024" # Keep in sync with Cargo.toml.
enum_discrim_align_threshold = 60
force_explicit_abi = false
force_multiline_blocks = true
format_code_in_doc_comments = true
format_macro_matchers = true
format_strings = true
group_imports = "StdExternalCrate"
hex_literal_case = "Upper"
imports_granularity = "Crate"
imports_layout = "HorizontalVertical"
inline_attribute_width = 60
match_block_trailing_comma = true
max_width = 80
newline_style = "Unix"
normalize_comments = true
normalize_doc_attributes = true
overflow_delimited_expr = true
struct_field_align_threshold = 60
tab_spaces = 2
unstable_features = true
use_field_init_shorthand = true
use_try_shorthand = true
wrap_comments = true

View file

@ -1,11 +1,18 @@
use crate::error::Result;
use crate::util::{HashExtractor, NixErrorClassifier, NixFileFixer, handle_nix_with_retry};
use crate::{
error::Result,
util::{
HashExtractor,
NixErrorClassifier,
NixFileFixer,
handle_nix_with_retry,
},
};
pub fn handle_nix_build(
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
) -> Result<i32> {
handle_nix_with_retry("build", args, hash_extractor, fixer, classifier, false)
handle_nix_with_retry("build", args, hash_extractor, fixer, classifier, false)
}

View file

@ -1,24 +1,27 @@
use std::{
collections::VecDeque,
io::{self, Read, Write},
process::{Command, ExitStatus, Output, Stdio},
};
use crate::error::{EhError, Result};
use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::process::{Command, ExitStatus, Output, Stdio};
/// Trait for log interception and output handling.
pub trait LogInterceptor: Send {
fn on_stderr(&mut self, chunk: &[u8]);
fn on_stdout(&mut self, chunk: &[u8]);
fn on_stderr(&mut self, chunk: &[u8]);
fn on_stdout(&mut self, chunk: &[u8]);
}
/// Default log interceptor that just writes to stdio.
pub struct StdIoInterceptor;
impl LogInterceptor for StdIoInterceptor {
fn on_stderr(&mut self, chunk: &[u8]) {
let _ = io::stderr().write_all(chunk);
}
fn on_stdout(&mut self, chunk: &[u8]) {
let _ = io::stdout().write_all(chunk);
}
fn on_stderr(&mut self, chunk: &[u8]) {
let _ = io::stderr().write_all(chunk);
}
fn on_stdout(&mut self, chunk: &[u8]) {
let _ = io::stdout().write_all(chunk);
}
}
/// Default buffer size for reading command output
@ -26,167 +29,179 @@ const DEFAULT_BUFFER_SIZE: usize = 4096;
/// Builder and executor for Nix commands.
pub struct NixCommand {
subcommand: String,
args: Vec<String>,
env: Vec<(String, String)>,
impure: bool,
print_build_logs: bool,
interactive: bool,
subcommand: String,
args: Vec<String>,
env: Vec<(String, String)>,
impure: bool,
print_build_logs: bool,
interactive: bool,
}
impl NixCommand {
pub fn new<S: Into<String>>(subcommand: S) -> Self {
Self {
subcommand: subcommand.into(),
args: Vec::new(),
env: Vec::new(),
impure: false,
print_build_logs: true,
interactive: false,
}
pub fn new<S: Into<String>>(subcommand: S) -> Self {
Self {
subcommand: subcommand.into(),
args: Vec::new(),
env: Vec::new(),
impure: false,
print_build_logs: true,
interactive: false,
}
}
pub fn arg<S: Into<String>>(mut self, arg: S) -> Self {
self.args.push(arg.into());
self
}
pub fn arg<S: Into<String>>(mut self, arg: S) -> Self {
self.args.push(arg.into());
self
}
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.args.extend(args.into_iter().map(Into::into));
self
}
pub fn env<K: Into<String>, V: Into<String>>(
mut self,
key: K,
value: V,
) -> Self {
self.env.push((key.into(), value.into()));
self
}
#[must_use]
pub const fn impure(mut self, yes: bool) -> Self {
self.impure = yes;
self
}
#[must_use]
pub const fn interactive(mut self, yes: bool) -> Self {
self.interactive = yes;
self
}
#[must_use]
pub const fn print_build_logs(mut self, yes: bool) -> Self {
self.print_build_logs = yes;
self
}
/// Run the command, streaming output to the provided interceptor.
pub fn run_with_logs<I: LogInterceptor + 'static>(
&self,
mut interceptor: I,
) -> Result<ExitStatus> {
let mut cmd = Command::new("nix");
cmd.arg(&self.subcommand);
if self.print_build_logs
&& !self.args.iter().any(|a| a == "--no-build-output")
{
self.args.extend(args.into_iter().map(Into::into));
self
cmd.arg("--print-build-logs");
}
if self.impure {
cmd.arg("--impure");
}
for (k, v) in &self.env {
cmd.env(k, v);
}
cmd.args(&self.args);
if self.interactive {
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
cmd.stdin(Stdio::inherit());
return Ok(cmd.status()?);
}
pub fn env<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
self.env.push((key.into(), value.into()));
self
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
let mut child = cmd.spawn()?;
let child_stdout = child.stdout.take().ok_or_else(|| {
EhError::CommandFailed {
command: format!("nix {}", self.subcommand),
}
})?;
let child_stderr = child.stderr.take().ok_or_else(|| {
EhError::CommandFailed {
command: format!("nix {}", self.subcommand),
}
})?;
let mut stdout = child_stdout;
let mut stderr = child_stderr;
let mut out_buf = [0u8; DEFAULT_BUFFER_SIZE];
let mut err_buf = [0u8; DEFAULT_BUFFER_SIZE];
let mut out_queue = VecDeque::new();
let mut err_queue = VecDeque::new();
loop {
let mut did_something = false;
match stdout.read(&mut out_buf) {
Ok(0) => {},
Ok(n) => {
interceptor.on_stdout(&out_buf[..n]);
out_queue.push_back(Vec::from(&out_buf[..n]));
did_something = true;
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {},
Err(e) => return Err(EhError::Io(e)),
}
match stderr.read(&mut err_buf) {
Ok(0) => {},
Ok(n) => {
interceptor.on_stderr(&err_buf[..n]);
err_queue.push_back(Vec::from(&err_buf[..n]));
did_something = true;
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {},
Err(e) => return Err(EhError::Io(e)),
}
if !did_something && child.try_wait()?.is_some() {
break;
}
}
#[must_use]
pub const fn impure(mut self, yes: bool) -> Self {
self.impure = yes;
self
let status = child.wait()?;
Ok(status)
}
/// Run the command and capture all output.
pub fn output(&self) -> Result<Output> {
let mut cmd = Command::new("nix");
cmd.arg(&self.subcommand);
if self.print_build_logs
&& !self.args.iter().any(|a| a == "--no-build-output")
{
cmd.arg("--print-build-logs");
}
if self.impure {
cmd.arg("--impure");
}
for (k, v) in &self.env {
cmd.env(k, v);
}
cmd.args(&self.args);
if self.interactive {
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
cmd.stdin(Stdio::inherit());
} else {
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
}
#[must_use]
pub const fn interactive(mut self, yes: bool) -> Self {
self.interactive = yes;
self
}
#[must_use]
pub const fn print_build_logs(mut self, yes: bool) -> Self {
self.print_build_logs = yes;
self
}
/// Run the command, streaming output to the provided interceptor.
pub fn run_with_logs<I: LogInterceptor + 'static>(
&self,
mut interceptor: I,
) -> Result<ExitStatus> {
let mut cmd = Command::new("nix");
cmd.arg(&self.subcommand);
if self.print_build_logs && !self.args.iter().any(|a| a == "--no-build-output") {
cmd.arg("--print-build-logs");
}
if self.impure {
cmd.arg("--impure");
}
for (k, v) in &self.env {
cmd.env(k, v);
}
cmd.args(&self.args);
if self.interactive {
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
cmd.stdin(Stdio::inherit());
return Ok(cmd.status()?);
}
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
let mut child = cmd.spawn()?;
let child_stdout = child.stdout.take().ok_or_else(|| EhError::CommandFailed {
command: format!("nix {}", self.subcommand),
})?;
let child_stderr = child.stderr.take().ok_or_else(|| EhError::CommandFailed {
command: format!("nix {}", self.subcommand),
})?;
let mut stdout = child_stdout;
let mut stderr = child_stderr;
let mut out_buf = [0u8; DEFAULT_BUFFER_SIZE];
let mut err_buf = [0u8; DEFAULT_BUFFER_SIZE];
let mut out_queue = VecDeque::new();
let mut err_queue = VecDeque::new();
loop {
let mut did_something = false;
match stdout.read(&mut out_buf) {
Ok(0) => {}
Ok(n) => {
interceptor.on_stdout(&out_buf[..n]);
out_queue.push_back(Vec::from(&out_buf[..n]));
did_something = true;
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
Err(e) => return Err(EhError::Io(e)),
}
match stderr.read(&mut err_buf) {
Ok(0) => {}
Ok(n) => {
interceptor.on_stderr(&err_buf[..n]);
err_queue.push_back(Vec::from(&err_buf[..n]));
did_something = true;
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
Err(e) => return Err(EhError::Io(e)),
}
if !did_something && child.try_wait()?.is_some() {
break;
}
}
let status = child.wait()?;
Ok(status)
}
/// Run the command and capture all output.
pub fn output(&self) -> Result<Output> {
let mut cmd = Command::new("nix");
cmd.arg(&self.subcommand);
if self.print_build_logs && !self.args.iter().any(|a| a == "--no-build-output") {
cmd.arg("--print-build-logs");
}
if self.impure {
cmd.arg("--impure");
}
for (k, v) in &self.env {
cmd.env(k, v);
}
cmd.args(&self.args);
if self.interactive {
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
cmd.stdin(Stdio::inherit());
} else {
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
}
Ok(cmd.output()?)
}
Ok(cmd.output()?)
}
}

View file

@ -2,44 +2,44 @@ use thiserror::Error;
#[derive(Error, Debug)]
pub enum EhError {
#[error("Nix command failed: {0}")]
NixCommandFailed(String),
#[error("Nix command failed: {0}")]
NixCommandFailed(String),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Regex error: {0}")]
Regex(#[from] regex::Error),
#[error("Regex error: {0}")]
Regex(#[from] regex::Error),
#[error("UTF-8 conversion error: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("UTF-8 conversion error: {0}")]
Utf8(#[from] std::string::FromUtf8Error),
#[error("Hash extraction failed")]
HashExtractionFailed,
#[error("Hash extraction failed")]
HashExtractionFailed,
#[error("No Nix files found")]
NoNixFilesFound,
#[error("No Nix files found")]
NoNixFilesFound,
#[error("Failed to fix hash in file: {path}")]
HashFixFailed { path: String },
#[error("Failed to fix hash in file: {path}")]
HashFixFailed { path: String },
#[error("Process exited with code: {code}")]
ProcessExit { code: i32 },
#[error("Process exited with code: {code}")]
ProcessExit { code: i32 },
#[error("Command execution failed: {command}")]
CommandFailed { command: String },
#[error("Command execution failed: {command}")]
CommandFailed { command: String },
}
pub type Result<T> = std::result::Result<T, EhError>;
impl EhError {
#[must_use]
pub const fn exit_code(&self) -> i32 {
match self {
Self::ProcessExit { code } => *code,
Self::NixCommandFailed(_) => 1,
Self::CommandFailed { .. } => 1,
_ => 1,
}
#[must_use]
pub const fn exit_code(&self) -> i32 {
match self {
Self::ProcessExit { code } => *code,
Self::NixCommandFailed(_) => 1,
Self::CommandFailed { .. } => 1,
_ => 1,
}
}
}

View file

@ -13,25 +13,25 @@ pub use error::{EhError, Result};
#[command(about = "Ergonomic Nix helper", long_about = None)]
#[command(version)]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Subcommand)]
pub enum Command {
/// Run a Nix derivation
Run {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
/// Enter a Nix shell
Shell {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
/// Build a Nix derivation
Build {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
/// Run a Nix derivation
Run {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
/// Enter a Nix shell
Shell {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
/// Build a Nix derivation
Build {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
},
}

View file

@ -1,7 +1,7 @@
use std::{env, path::Path};
use eh::{Cli, Command, CommandFactory, Parser};
use error::Result;
use std::env;
use std::path::Path;
mod build;
mod command;
@ -11,91 +11,100 @@ mod shell;
mod util;
fn main() {
let format = tracing_subscriber::fmt::format()
let format = tracing_subscriber::fmt::format()
.with_level(true) // don't include levels in formatted output
.with_target(true) // don't include targets
.with_thread_ids(false) // include the thread ID of the current thread
.with_thread_names(false) // include the name of the current thread
.compact(); // use the `Compact` formatting style.
tracing_subscriber::fmt().event_format(format).init();
tracing_subscriber::fmt().event_format(format).init();
let result = run_app();
let result = run_app();
match result {
Ok(code) => std::process::exit(code),
Err(e) => {
eprintln!("Error: {e}");
std::process::exit(e.exit_code());
}
}
match result {
Ok(code) => std::process::exit(code),
Err(e) => {
eprintln!("Error: {e}");
std::process::exit(e.exit_code());
},
}
}
// Design partially taken from Stash
fn dispatch_multicall(app_name: &str, args: std::env::Args) -> Option<Result<i32>> {
let rest: Vec<String> = args.collect();
let hash_extractor = util::RegexHashExtractor;
let fixer = util::DefaultNixFileFixer;
let classifier = util::DefaultNixErrorClassifier;
fn dispatch_multicall(
app_name: &str,
args: std::env::Args,
) -> Option<Result<i32>> {
let rest: Vec<String> = args.collect();
let hash_extractor = util::RegexHashExtractor;
let fixer = util::DefaultNixFileFixer;
let classifier = util::DefaultNixErrorClassifier;
match app_name {
"nr" => Some(run::handle_nix_run(
&rest,
&hash_extractor,
&fixer,
&classifier,
)),
"ns" => Some(shell::handle_nix_shell(
&rest,
&hash_extractor,
&fixer,
&classifier,
)),
"nb" => Some(build::handle_nix_build(
&rest,
&hash_extractor,
&fixer,
&classifier,
)),
_ => None,
}
match app_name {
"nr" => {
Some(run::handle_nix_run(
&rest,
&hash_extractor,
&fixer,
&classifier,
))
},
"ns" => {
Some(shell::handle_nix_shell(
&rest,
&hash_extractor,
&fixer,
&classifier,
))
},
"nb" => {
Some(build::handle_nix_build(
&rest,
&hash_extractor,
&fixer,
&classifier,
))
},
_ => None,
}
}
fn run_app() -> Result<i32> {
let mut args = env::args();
let bin = args.next().unwrap_or_else(|| "eh".to_string());
let app_name = Path::new(&bin)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("eh");
let mut args = env::args();
let bin = args.next().unwrap_or_else(|| "eh".to_string());
let app_name = Path::new(&bin)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("eh");
// If invoked as nr/ns/nb, dispatch directly and exit
if let Some(result) = dispatch_multicall(app_name, args) {
return result;
}
// If invoked as nr/ns/nb, dispatch directly and exit
if let Some(result) = dispatch_multicall(app_name, args) {
return result;
}
let cli = Cli::parse();
let cli = Cli::parse();
let hash_extractor = util::RegexHashExtractor;
let fixer = util::DefaultNixFileFixer;
let classifier = util::DefaultNixErrorClassifier;
let hash_extractor = util::RegexHashExtractor;
let fixer = util::DefaultNixFileFixer;
let classifier = util::DefaultNixErrorClassifier;
match cli.command {
Some(Command::Run { args }) => {
run::handle_nix_run(&args, &hash_extractor, &fixer, &classifier)
}
match cli.command {
Some(Command::Run { args }) => {
run::handle_nix_run(&args, &hash_extractor, &fixer, &classifier)
},
Some(Command::Shell { args }) => {
shell::handle_nix_shell(&args, &hash_extractor, &fixer, &classifier)
}
Some(Command::Shell { args }) => {
shell::handle_nix_shell(&args, &hash_extractor, &fixer, &classifier)
},
Some(Command::Build { args }) => {
build::handle_nix_build(&args, &hash_extractor, &fixer, &classifier)
}
Some(Command::Build { args }) => {
build::handle_nix_build(&args, &hash_extractor, &fixer, &classifier)
},
_ => {
Cli::command().print_help()?;
println!();
Ok(0)
}
}
_ => {
Cli::command().print_help()?;
println!();
Ok(0)
},
}
}

View file

@ -1,11 +1,18 @@
use crate::error::Result;
use crate::util::{HashExtractor, NixErrorClassifier, NixFileFixer, handle_nix_with_retry};
use crate::{
error::Result,
util::{
HashExtractor,
NixErrorClassifier,
NixFileFixer,
handle_nix_with_retry,
},
};
pub fn handle_nix_run(
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
) -> Result<i32> {
handle_nix_with_retry("run", args, hash_extractor, fixer, classifier, true)
handle_nix_with_retry("run", args, hash_extractor, fixer, classifier, true)
}

View file

@ -1,11 +1,18 @@
use crate::error::Result;
use crate::util::{HashExtractor, NixErrorClassifier, NixFileFixer, handle_nix_with_retry};
use crate::{
error::Result,
util::{
HashExtractor,
NixErrorClassifier,
NixFileFixer,
handle_nix_with_retry,
},
};
pub fn handle_nix_shell(
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
) -> Result<i32> {
handle_nix_with_retry("shell", args, hash_extractor, fixer, classifier, true)
handle_nix_with_retry("shell", args, hash_extractor, fixer, classifier, true)
}

View file

@ -1,293 +1,314 @@
use crate::command::{NixCommand, StdIoInterceptor};
use crate::error::{EhError, Result};
use std::{
fs,
io::Write,
path::{Path, PathBuf},
};
use regex::Regex;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use tracing::{info, warn};
use walkdir::WalkDir;
use yansi::Paint;
use crate::{
command::{NixCommand, StdIoInterceptor},
error::{EhError, Result},
};
pub trait HashExtractor {
fn extract_hash(&self, stderr: &str) -> Option<String>;
fn extract_hash(&self, stderr: &str) -> Option<String>;
}
pub struct RegexHashExtractor;
impl HashExtractor for RegexHashExtractor {
fn extract_hash(&self, stderr: &str) -> Option<String> {
let patterns = [
r"got:\s+(sha256-[a-zA-Z0-9+/=]+)",
r"actual:\s+(sha256-[a-zA-Z0-9+/=]+)",
r"have:\s+(sha256-[a-zA-Z0-9+/=]+)",
];
for pattern in &patterns {
if let Ok(re) = Regex::new(pattern)
&& let Some(captures) = re.captures(stderr)
&& let Some(hash) = captures.get(1)
{
return Some(hash.as_str().to_string());
}
}
None
fn extract_hash(&self, stderr: &str) -> Option<String> {
let patterns = [
r"got:\s+(sha256-[a-zA-Z0-9+/=]+)",
r"actual:\s+(sha256-[a-zA-Z0-9+/=]+)",
r"have:\s+(sha256-[a-zA-Z0-9+/=]+)",
];
for pattern in &patterns {
if let Ok(re) = Regex::new(pattern)
&& let Some(captures) = re.captures(stderr)
&& let Some(hash) = captures.get(1)
{
return Some(hash.as_str().to_string());
}
}
None
}
}
pub trait NixFileFixer {
fn fix_hash_in_files(&self, new_hash: &str) -> Result<bool>;
fn find_nix_files(&self) -> Result<Vec<PathBuf>>;
fn fix_hash_in_file(&self, file_path: &Path, new_hash: &str) -> Result<bool>;
fn fix_hash_in_files(&self, new_hash: &str) -> Result<bool>;
fn find_nix_files(&self) -> Result<Vec<PathBuf>>;
fn fix_hash_in_file(&self, file_path: &Path, new_hash: &str) -> Result<bool>;
}
pub struct DefaultNixFileFixer;
impl NixFileFixer for DefaultNixFileFixer {
fn fix_hash_in_files(&self, new_hash: &str) -> Result<bool> {
let nix_files = self.find_nix_files()?;
let mut fixed = false;
for file_path in nix_files {
if self.fix_hash_in_file(&file_path, new_hash)? {
println!("Updated hash in {}", file_path.display());
fixed = true;
}
}
Ok(fixed)
fn fix_hash_in_files(&self, new_hash: &str) -> Result<bool> {
let nix_files = self.find_nix_files()?;
let mut fixed = false;
for file_path in nix_files {
if self.fix_hash_in_file(&file_path, new_hash)? {
println!("Updated hash in {}", file_path.display());
fixed = true;
}
}
Ok(fixed)
}
fn find_nix_files(&self) -> Result<Vec<PathBuf>> {
let files: Vec<PathBuf> = WalkDir::new(".")
.into_iter()
.filter_map(|entry| entry.ok())
.filter(|entry| {
entry.file_type().is_file()
&& entry
.path()
.extension()
.map(|ext| ext.eq_ignore_ascii_case("nix"))
.unwrap_or(false)
})
.map(|entry| entry.path().to_path_buf())
.collect();
fn find_nix_files(&self) -> Result<Vec<PathBuf>> {
let files: Vec<PathBuf> = WalkDir::new(".")
.into_iter()
.filter_map(|entry| entry.ok())
.filter(|entry| {
entry.file_type().is_file()
&& entry
.path()
.extension()
.map(|ext| ext.eq_ignore_ascii_case("nix"))
.unwrap_or(false)
})
.map(|entry| entry.path().to_path_buf())
.collect();
if files.is_empty() {
return Err(EhError::NoNixFilesFound);
}
Ok(files)
if files.is_empty() {
return Err(EhError::NoNixFilesFound);
}
Ok(files)
}
fn fix_hash_in_file(&self, file_path: &Path, new_hash: &str) -> Result<bool> {
let content = fs::read_to_string(file_path)?;
let patterns = [
(r#"hash\s*=\s*"[^"]*""#, format!(r#"hash = "{new_hash}""#)),
(
r#"sha256\s*=\s*"[^"]*""#,
format!(r#"sha256 = "{new_hash}""#),
),
(
r#"outputHash\s*=\s*"[^"]*""#,
format!(r#"outputHash = "{new_hash}""#),
),
];
let mut new_content = content;
let mut replaced = false;
for (pattern, replacement) in &patterns {
let re = Regex::new(pattern)?;
if re.is_match(&new_content) {
new_content = re
.replace_all(&new_content, replacement.as_str())
.into_owned();
replaced = true;
}
}
if replaced {
fs::write(file_path, new_content).map_err(|_| EhError::HashFixFailed {
path: file_path.to_string_lossy().to_string(),
})?;
Ok(true)
} else {
Ok(false)
}
fn fix_hash_in_file(&self, file_path: &Path, new_hash: &str) -> Result<bool> {
let content = fs::read_to_string(file_path)?;
let patterns = [
(r#"hash\s*=\s*"[^"]*""#, format!(r#"hash = "{new_hash}""#)),
(
r#"sha256\s*=\s*"[^"]*""#,
format!(r#"sha256 = "{new_hash}""#),
),
(
r#"outputHash\s*=\s*"[^"]*""#,
format!(r#"outputHash = "{new_hash}""#),
),
];
let mut new_content = content;
let mut replaced = false;
for (pattern, replacement) in &patterns {
let re = Regex::new(pattern)?;
if re.is_match(&new_content) {
new_content = re
.replace_all(&new_content, replacement.as_str())
.into_owned();
replaced = true;
}
}
if replaced {
fs::write(file_path, new_content).map_err(|_| {
EhError::HashFixFailed {
path: file_path.to_string_lossy().to_string(),
}
})?;
Ok(true)
} else {
Ok(false)
}
}
}
pub trait NixErrorClassifier {
fn should_retry(&self, stderr: &str) -> bool;
fn should_retry(&self, stderr: &str) -> bool;
}
/// Pre-evaluate expression to catch errors early
fn pre_evaluate(_subcommand: &str, args: &[String]) -> Result<bool> {
// Find flake references or expressions to evaluate
// Only take the first non-flag argument (the package/expression)
let eval_arg = args.iter().find(|arg| !arg.starts_with('-'));
// Find flake references or expressions to evaluate
// Only take the first non-flag argument (the package/expression)
let eval_arg = args.iter().find(|arg| !arg.starts_with('-'));
let Some(eval_arg) = eval_arg else {
return Ok(true); // No expression to evaluate
};
let Some(eval_arg) = eval_arg else {
return Ok(true); // No expression to evaluate
};
let eval_cmd = NixCommand::new("eval").arg(eval_arg).arg("--raw");
let eval_cmd = NixCommand::new("eval").arg(eval_arg).arg("--raw");
let output = eval_cmd.output()?;
let output = eval_cmd.output()?;
if output.status.success() {
return Ok(true);
}
if output.status.success() {
return Ok(true);
}
let stderr = String::from_utf8_lossy(&output.stderr);
let stderr = String::from_utf8_lossy(&output.stderr);
// If eval fails due to unfree/insecure/broken, don't fail pre-evaluation
// Let the main command handle it with retry logic
if stderr.contains("has an unfree license")
|| stderr.contains("refusing to evaluate")
|| stderr.contains("has been marked as insecure")
|| stderr.contains("has been marked as broken")
{
return Ok(true);
}
// If eval fails due to unfree/insecure/broken, don't fail pre-evaluation
// Let the main command handle it with retry logic
if stderr.contains("has an unfree license")
|| stderr.contains("refusing to evaluate")
|| stderr.contains("has been marked as insecure")
|| stderr.contains("has been marked as broken")
{
return Ok(true);
}
// For other eval failures, fail early
Ok(false)
// For other eval failures, fail early
Ok(false)
}
/// Shared retry logic for nix commands (build/run/shell).
pub fn handle_nix_with_retry(
subcommand: &str,
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
interactive: bool,
subcommand: &str,
args: &[String],
hash_extractor: &dyn HashExtractor,
fixer: &dyn NixFileFixer,
classifier: &dyn NixErrorClassifier,
interactive: bool,
) -> Result<i32> {
// Pre-evaluate for build commands to catch errors early
if !pre_evaluate(subcommand, args)? {
return Err(EhError::NixCommandFailed(
"Expression evaluation failed".to_string(),
));
}
// Pre-evaluate for build commands to catch errors early
if !pre_evaluate(subcommand, args)? {
return Err(EhError::NixCommandFailed(
"Expression evaluation failed".to_string(),
));
}
// For run commands, try interactive first to avoid breaking terminal
if subcommand == "run" && interactive {
let mut cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.interactive(true);
for arg in args {
cmd = cmd.arg(arg);
}
let status = cmd.run_with_logs(StdIoInterceptor)?;
if status.success() {
return Ok(0);
}
// For run commands, try interactive first to avoid breaking terminal
if subcommand == "run" && interactive {
let mut cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.interactive(true);
for arg in args {
cmd = cmd.arg(arg);
}
let status = cmd.run_with_logs(StdIoInterceptor)?;
if status.success() {
return Ok(0);
}
}
// First, always capture output to check for errors that need retry
let output_cmd = NixCommand::new(subcommand)
// First, always capture output to check for errors that need retry
let output_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned());
let output = output_cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
// Check if we need to retry with special flags
if let Some(new_hash) = hash_extractor.extract_hash(&stderr) {
match fixer.fix_hash_in_files(&new_hash) {
Ok(true) => {
info!("{}", Paint::green("✔ Fixed hash mismatch, retrying..."));
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned());
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
},
Ok(false) => {
// No files were fixed, continue with normal error handling
},
Err(EhError::NoNixFilesFound) => {
warn!("No .nix files found to fix hash in");
// Continue with normal error handling
},
Err(e) => {
return Err(e);
},
}
} else if stderr.contains("hash") || stderr.contains("sha256") {
// If there's a hash-related error but we couldn't extract it, that's a
// failure
return Err(EhError::HashExtractionFailed);
}
if classifier.should_retry(&stderr) {
if stderr.contains("has an unfree license") && stderr.contains("refusing") {
warn!(
"{}",
Paint::yellow(
"⚠ Unfree package detected, retrying with NIXPKGS_ALLOW_UNFREE=1..."
)
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned());
let output = output_cmd.output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
// Check if we need to retry with special flags
if let Some(new_hash) = hash_extractor.extract_hash(&stderr) {
match fixer.fix_hash_in_files(&new_hash) {
Ok(true) => {
info!("{}", Paint::green("✔ Fixed hash mismatch, retrying..."));
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned());
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
Ok(false) => {
// No files were fixed, continue with normal error handling
}
Err(EhError::NoNixFilesFound) => {
warn!("No .nix files found to fix hash in");
// Continue with normal error handling
}
Err(e) => {
return Err(e);
}
}
} else if stderr.contains("hash") || stderr.contains("sha256") {
// If there's a hash-related error but we couldn't extract it, that's a failure
return Err(EhError::HashExtractionFailed);
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_UNFREE", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
if classifier.should_retry(&stderr) {
if stderr.contains("has an unfree license") && stderr.contains("refusing") {
warn!(
"{}",
Paint::yellow("⚠ Unfree package detected, retrying with NIXPKGS_ALLOW_UNFREE=1...")
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_UNFREE", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
if stderr.contains("has been marked as insecure") && stderr.contains("refusing") {
warn!(
"{}",
Paint::yellow(
"⚠ Insecure package detected, retrying with NIXPKGS_ALLOW_INSECURE=1..."
)
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_INSECURE", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
if stderr.contains("has been marked as broken") && stderr.contains("refusing") {
warn!(
"{}",
Paint::yellow("⚠ Broken package detected, retrying with NIXPKGS_ALLOW_BROKEN=1...")
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_BROKEN", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
if stderr.contains("has been marked as insecure")
&& stderr.contains("refusing")
{
warn!(
"{}",
Paint::yellow(
"⚠ Insecure package detected, retrying with \
NIXPKGS_ALLOW_INSECURE=1..."
)
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_INSECURE", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
// If the first attempt succeeded, we're done
if output.status.success() {
return Ok(0);
if stderr.contains("has been marked as broken")
&& stderr.contains("refusing")
{
warn!(
"{}",
Paint::yellow(
"⚠ Broken package detected, retrying with NIXPKGS_ALLOW_BROKEN=1..."
)
);
let mut retry_cmd = NixCommand::new(subcommand)
.print_build_logs(true)
.args(args.iter().cloned())
.env("NIXPKGS_ALLOW_BROKEN", "1")
.impure(true);
if interactive {
retry_cmd = retry_cmd.interactive(true);
}
let retry_status = retry_cmd.run_with_logs(StdIoInterceptor)?;
return Ok(retry_status.code().unwrap_or(1));
}
}
// Otherwise, show the error and return error
std::io::stderr()
.write_all(&output.stderr)
.map_err(EhError::Io)?;
Err(EhError::ProcessExit {
code: output.status.code().unwrap_or(1),
})
// If the first attempt succeeded, we're done
if output.status.success() {
return Ok(0);
}
// Otherwise, show the error and return error
std::io::stderr()
.write_all(&output.stderr)
.map_err(EhError::Io)?;
Err(EhError::ProcessExit {
code: output.status.code().unwrap_or(1),
})
}
pub struct DefaultNixErrorClassifier;
impl NixErrorClassifier for DefaultNixErrorClassifier {
fn should_retry(&self, stderr: &str) -> bool {
RegexHashExtractor.extract_hash(stderr).is_some()
|| (stderr.contains("has an unfree license") && stderr.contains("refusing"))
|| (stderr.contains("has been marked as insecure") && stderr.contains("refusing"))
|| (stderr.contains("has been marked as broken") && stderr.contains("refusing"))
}
fn should_retry(&self, stderr: &str) -> bool {
RegexHashExtractor.extract_hash(stderr).is_some()
|| (stderr.contains("has an unfree license")
&& stderr.contains("refusing"))
|| (stderr.contains("has been marked as insecure")
&& stderr.contains("refusing"))
|| (stderr.contains("has been marked as broken")
&& stderr.contains("refusing"))
}
}

View file

@ -1,78 +1,84 @@
use std::{fs, process::Command};
use eh::util::{
DefaultNixErrorClassifier, DefaultNixFileFixer, HashExtractor, NixErrorClassifier,
NixFileFixer, RegexHashExtractor,
DefaultNixErrorClassifier,
DefaultNixFileFixer,
HashExtractor,
NixErrorClassifier,
NixFileFixer,
RegexHashExtractor,
};
use std::fs;
use std::process::Command;
use tempfile::TempDir;
#[test]
fn test_hash_extraction_from_real_nix_errors() {
// Test hash extraction from actual Nix error messages
let extractor = RegexHashExtractor;
// Test hash extraction from actual Nix error messages
let extractor = RegexHashExtractor;
let test_cases = [
(
r#"error: hash mismatch in fixed-output derivation '/nix/store/xxx-foo.drv':
let test_cases = [
(
r#"error: hash mismatch in fixed-output derivation '/nix/store/xxx-foo.drv':
specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
got: sha256-BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="#,
Some("sha256-BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=".to_string()),
),
(
"actual: sha256-abc123def456",
Some("sha256-abc123def456".to_string()),
),
("have: sha256-xyz789", Some("sha256-xyz789".to_string())),
("no hash here", None),
];
Some("sha256-BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=".to_string()),
),
(
"actual: sha256-abc123def456",
Some("sha256-abc123def456".to_string()),
),
("have: sha256-xyz789", Some("sha256-xyz789".to_string())),
("no hash here", None),
];
for (input, expected) in test_cases {
assert_eq!(extractor.extract_hash(input), expected);
}
for (input, expected) in test_cases {
assert_eq!(extractor.extract_hash(input), expected);
}
}
#[test]
fn test_error_classification_for_retry_logic() {
// Test that the classifier correctly identifies errors that should be retried
let classifier = DefaultNixErrorClassifier;
// Test that the classifier correctly identifies errors that should be retried
let classifier = DefaultNixErrorClassifier;
// These should trigger retries
let retry_cases = [
"Package 'discord-1.0.0' has an unfree license ('unfree'), refusing to evaluate.",
"Package 'openssl-1.1.1' has been marked as insecure, refusing to evaluate.",
"Package 'broken-1.0' has been marked as broken, refusing to evaluate.",
"hash mismatch in fixed-output derivation\ngot: sha256-newhash",
];
// These should trigger retries
let retry_cases = [
"Package 'discord-1.0.0' has an unfree license ('unfree'), refusing to \
evaluate.",
"Package 'openssl-1.1.1' has been marked as insecure, refusing to \
evaluate.",
"Package 'broken-1.0' has been marked as broken, refusing to evaluate.",
"hash mismatch in fixed-output derivation\ngot: sha256-newhash",
];
for error in retry_cases {
assert!(classifier.should_retry(error), "Should retry: {}", error);
}
for error in retry_cases {
assert!(classifier.should_retry(error), "Should retry: {}", error);
}
// These should NOT trigger retries
let no_retry_cases = [
"build failed",
"random error",
"permission denied",
"network error",
];
// These should NOT trigger retries
let no_retry_cases = [
"build failed",
"random error",
"permission denied",
"network error",
];
for error in no_retry_cases {
assert!(
!classifier.should_retry(error),
"Should not retry: {}",
error
);
}
for error in no_retry_cases {
assert!(
!classifier.should_retry(error),
"Should not retry: {}",
error
);
}
}
#[test]
fn test_hash_fixing_in_nix_files() {
// Test that hash fixing actually works on real Nix files
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let fixer = DefaultNixFileFixer;
// Test that hash fixing actually works on real Nix files
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let fixer = DefaultNixFileFixer;
// Create a mock Nix file with various hash formats
let nix_content = r#"
// Create a mock Nix file with various hash formats
let nix_content = r#"
stdenv.mkDerivation {
name = "test-package";
src = fetchurl {
@ -89,131 +95,140 @@ stdenv.mkDerivation {
}
"#;
let file_path = temp_dir.path().join("test.nix");
fs::write(&file_path, nix_content).expect("Failed to write test file");
let file_path = temp_dir.path().join("test.nix");
fs::write(&file_path, nix_content).expect("Failed to write test file");
// Test hash replacement
let new_hash = "sha256-newhashabc";
let was_fixed = fixer
.fix_hash_in_file(&file_path, new_hash)
.expect("Failed to fix hash");
// Test hash replacement
let new_hash = "sha256-newhashabc";
let was_fixed = fixer
.fix_hash_in_file(&file_path, new_hash)
.expect("Failed to fix hash");
assert!(was_fixed, "File should have been modified");
assert!(was_fixed, "File should have been modified");
let updated_content = fs::read_to_string(&file_path).expect("Failed to read updated file");
let updated_content =
fs::read_to_string(&file_path).expect("Failed to read updated file");
// All hash formats should be updated
assert!(updated_content.contains(&format!(r#"hash = "{}""#, new_hash)));
assert!(updated_content.contains(&format!(r#"sha256 = "{}""#, new_hash)));
assert!(updated_content.contains(&format!(r#"outputHash = "{}""#, new_hash)));
// All hash formats should be updated
assert!(updated_content.contains(&format!(r#"hash = "{}""#, new_hash)));
assert!(updated_content.contains(&format!(r#"sha256 = "{}""#, new_hash)));
assert!(updated_content.contains(&format!(r#"outputHash = "{}""#, new_hash)));
// Old hashes should be gone
assert!(!updated_content.contains("oldhash123"));
assert!(!updated_content.contains("oldhash456"));
assert!(!updated_content.contains("oldhash789"));
// Old hashes should be gone
assert!(!updated_content.contains("oldhash123"));
assert!(!updated_content.contains("oldhash456"));
assert!(!updated_content.contains("oldhash789"));
}
#[test]
fn test_multicall_binary_dispatch() {
// Test that multicall binaries work without needing actual Nix evaluation
let commands = [("nb", "build"), ("nr", "run"), ("ns", "shell")];
// Test that multicall binaries work without needing actual Nix evaluation
let commands = [("nb", "build"), ("nr", "run"), ("ns", "shell")];
for (binary_name, _expected_command) in &commands {
// Test that the binary starts and handles invalid arguments gracefully
let output = Command::new("timeout")
.args(["5", "cargo", "run", "--bin", "eh", "--"])
.env("CARGO_BIN_NAME", binary_name)
.arg("invalid-package-ref")
.output()
.expect("Failed to execute command");
for (binary_name, _expected_command) in &commands {
// Test that the binary starts and handles invalid arguments gracefully
let output = Command::new("timeout")
.args(["5", "cargo", "run", "--bin", "eh", "--"])
.env("CARGO_BIN_NAME", binary_name)
.arg("invalid-package-ref")
.output()
.expect("Failed to execute command");
// Should fail gracefully (not panic or hang)
assert!(
output.status.code().is_some(),
"{} should exit with a code",
binary_name
);
// Should fail gracefully (not panic or hang)
assert!(
output.status.code().is_some(),
"{} should exit with a code",
binary_name
);
// Should show an error message, not crash
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Error:") || stderr.contains("error:") || stderr.contains("failed"),
"{} should show error for invalid package",
binary_name
);
}
// Should show an error message, not crash
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Error:")
|| stderr.contains("error:")
|| stderr.contains("failed"),
"{} should show error for invalid package",
binary_name
);
}
}
#[test]
fn test_invalid_expression_handling() {
// Test that invalid Nix expressions fail fast with proper error messages
let invalid_refs = [
"invalid-flake-ref",
"nonexistent-package",
"file:///nonexistent/path",
];
// Test that invalid Nix expressions fail fast with proper error messages
let invalid_refs = [
"invalid-flake-ref",
"nonexistent-package",
"file:///nonexistent/path",
];
for invalid_ref in invalid_refs {
let output = Command::new("timeout")
.args([
"10",
"cargo",
"run",
"--bin",
"eh",
"--",
"build",
invalid_ref,
])
.output()
.expect("Failed to execute command");
for invalid_ref in invalid_refs {
let output = Command::new("timeout")
.args([
"10",
"cargo",
"run",
"--bin",
"eh",
"--",
"build",
invalid_ref,
])
.output()
.expect("Failed to execute command");
// Should fail with a proper error, not hang or crash
assert!(
!output.status.success(),
"Invalid ref '{}' should fail",
invalid_ref
);
// Should fail with a proper error, not hang or crash
assert!(
!output.status.success(),
"Invalid ref '{}' should fail",
invalid_ref
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Error:") || stderr.contains("error:") || stderr.contains("failed"),
"Should show error message for invalid ref '{}': {}",
invalid_ref,
stderr
);
}
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("Error:")
|| stderr.contains("error:")
|| stderr.contains("failed"),
"Should show error message for invalid ref '{}': {}",
invalid_ref,
stderr
);
}
}
#[test]
fn test_nix_file_discovery() {
// Test that the fixer can find Nix files in a directory structure
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let fixer = DefaultNixFileFixer;
// Test that the fixer can find Nix files in a directory structure
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let fixer = DefaultNixFileFixer;
// Create directory structure with Nix files
fs::create_dir_all(temp_dir.path().join("subdir")).expect("Failed to create subdir");
// Create directory structure with Nix files
fs::create_dir_all(temp_dir.path().join("subdir"))
.expect("Failed to create subdir");
let files = [
("test.nix", "stdenv.mkDerivation { name = \"test\"; }"),
("subdir/other.nix", "pkgs.hello"),
("not-nix.txt", "not a nix file"),
("default.nix", "import ./test.nix"),
];
let files = [
("test.nix", "stdenv.mkDerivation { name = \"test\"; }"),
("subdir/other.nix", "pkgs.hello"),
("not-nix.txt", "not a nix file"),
("default.nix", "import ./test.nix"),
];
for (path, content) in files {
fs::write(temp_dir.path().join(path), content).expect("Failed to write file");
}
for (path, content) in files {
fs::write(temp_dir.path().join(path), content)
.expect("Failed to write file");
}
// Change to temp dir for file discovery
let original_dir = std::env::current_dir().expect("Failed to get current dir");
std::env::set_current_dir(temp_dir.path()).expect("Failed to change directory");
// Change to temp dir for file discovery
let original_dir =
std::env::current_dir().expect("Failed to get current dir");
std::env::set_current_dir(temp_dir.path())
.expect("Failed to change directory");
let found_files = fixer.find_nix_files().expect("Failed to find Nix files");
let found_files = fixer.find_nix_files().expect("Failed to find Nix files");
// Should find 3 .nix files (not the .txt file)
assert_eq!(found_files.len(), 3, "Should find exactly 3 .nix files");
// Should find 3 .nix files (not the .txt file)
assert_eq!(found_files.len(), 3, "Should find exactly 3 .nix files");
// Restore original directory
std::env::set_current_dir(original_dir).expect("Failed to restore directory");
// Restore original directory
std::env::set_current_dir(original_dir).expect("Failed to restore directory");
}

View file

@ -1,7 +1,8 @@
use std::{
error, fs,
path::{Path, PathBuf},
process,
error,
fs,
path::{Path, PathBuf},
process,
};
use clap::{CommandFactory, Parser};
@ -9,164 +10,169 @@ use clap_complete::{Shell, generate};
#[derive(clap::Parser)]
struct Cli {
#[clap(subcommand)]
command: Command,
#[clap(subcommand)]
command: Command,
}
#[derive(clap::Subcommand)]
enum Command {
/// Create multicall binaries (hardlinks or copies).
Multicall {
/// Directory to install multicall binaries.
#[arg(long, default_value = "bin")]
bin_dir: PathBuf,
/// Create multicall binaries (hardlinks or copies).
Multicall {
/// Directory to install multicall binaries.
#[arg(long, default_value = "bin")]
bin_dir: PathBuf,
/// Path to the main binary.
#[arg(long, default_value = "target/release/eh")]
main_binary: PathBuf,
},
/// Generate shell completion scripts
Completions {
/// Shell to generate completions for
#[arg(value_enum)]
shell: Shell,
/// Directory to output completion files
#[arg(long, default_value = "completions")]
output_dir: PathBuf,
},
/// Path to the main binary.
#[arg(long, default_value = "target/release/eh")]
main_binary: PathBuf,
},
/// Generate shell completion scripts
Completions {
/// Shell to generate completions for
#[arg(value_enum)]
shell: Shell,
/// Directory to output completion files
#[arg(long, default_value = "completions")]
output_dir: PathBuf,
},
}
#[derive(Debug, Clone, Copy)]
enum Binary {
Nr,
Ns,
Nb,
Nr,
Ns,
Nb,
}
impl Binary {
const fn name(self) -> &'static str {
match self {
Self::Nr => "nr",
Self::Ns => "ns",
Self::Nb => "nb",
}
const fn name(self) -> &'static str {
match self {
Self::Nr => "nr",
Self::Ns => "ns",
Self::Nb => "nb",
}
}
}
fn main() {
let cli = Cli::parse();
let cli = Cli::parse();
match cli.command {
Command::Multicall {
bin_dir,
main_binary,
} => {
if let Err(error) = create_multicall_binaries(&bin_dir, &main_binary) {
eprintln!("error creating multicall binaries: {error}");
process::exit(1);
}
}
Command::Completions { shell, output_dir } => {
if let Err(error) = generate_completions(shell, &output_dir) {
eprintln!("error generating completions: {error}");
process::exit(1);
}
}
}
match cli.command {
Command::Multicall {
bin_dir,
main_binary,
} => {
if let Err(error) = create_multicall_binaries(&bin_dir, &main_binary) {
eprintln!("error creating multicall binaries: {error}");
process::exit(1);
}
},
Command::Completions { shell, output_dir } => {
if let Err(error) = generate_completions(shell, &output_dir) {
eprintln!("error generating completions: {error}");
process::exit(1);
}
},
}
}
fn create_multicall_binaries(
bin_dir: &Path,
main_binary: &Path,
bin_dir: &Path,
main_binary: &Path,
) -> Result<(), Box<dyn error::Error>> {
println!("creating multicall binaries...");
println!("creating multicall binaries...");
fs::create_dir_all(bin_dir)?;
fs::create_dir_all(bin_dir)?;
if !main_binary.exists() {
return Err(format!("main binary not found at: {}", main_binary.display()).into());
if !main_binary.exists() {
return Err(
format!("main binary not found at: {}", main_binary.display()).into(),
);
}
let multicall_binaries = [Binary::Nr, Binary::Ns, Binary::Nb];
let bin_path = Path::new(bin_dir);
for binary in multicall_binaries {
let target_path = bin_path.join(binary.name());
if target_path.exists() {
fs::remove_file(&target_path)?;
}
let multicall_binaries = [Binary::Nr, Binary::Ns, Binary::Nb];
let bin_path = Path::new(bin_dir);
if let Err(e) = fs::hard_link(main_binary, &target_path) {
eprintln!(
" warning: could not create hardlink for {}: {e}",
binary.name(),
);
eprintln!(" warning: falling back to copying binary...");
for binary in multicall_binaries {
let target_path = bin_path.join(binary.name());
fs::copy(main_binary, &target_path)?;
if target_path.exists() {
fs::remove_file(&target_path)?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&target_path)?.permissions();
perms.set_mode(perms.mode() | 0o755);
fs::set_permissions(&target_path, perms)?;
}
if let Err(e) = fs::hard_link(main_binary, &target_path) {
eprintln!(
" warning: could not create hardlink for {}: {e}",
binary.name(),
);
eprintln!(" warning: falling back to copying binary...");
fs::copy(main_binary, &target_path)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&target_path)?.permissions();
perms.set_mode(perms.mode() | 0o755);
fs::set_permissions(&target_path, perms)?;
}
println!(" created copy: {}", target_path.display());
} else {
println!(
" created hardlink: {} points to {}",
target_path.display(),
main_binary.display(),
);
}
println!(" created copy: {}", target_path.display());
} else {
println!(
" created hardlink: {} points to {}",
target_path.display(),
main_binary.display(),
);
}
}
println!("multicall binaries created successfully!");
println!("multicall binaries are in: {}", bin_dir.display());
println!();
println!("multicall binaries created successfully!");
println!("multicall binaries are in: {}", bin_dir.display());
println!();
Ok(())
Ok(())
}
fn generate_completions(shell: Shell, output_dir: &Path) -> Result<(), Box<dyn error::Error>> {
println!("generating {shell} completions...");
fn generate_completions(
shell: Shell,
output_dir: &Path,
) -> Result<(), Box<dyn error::Error>> {
println!("generating {shell} completions...");
fs::create_dir_all(output_dir)?;
fs::create_dir_all(output_dir)?;
let mut cmd = eh::Cli::command();
let bin_name = "eh";
let mut cmd = eh::Cli::command();
let bin_name = "eh";
let completion_file = output_dir.join(format!("{bin_name}.{shell}"));
let mut file = fs::File::create(&completion_file)?;
let completion_file = output_dir.join(format!("{bin_name}.{shell}"));
let mut file = fs::File::create(&completion_file)?;
generate(shell, &mut cmd, bin_name, &mut file);
generate(shell, &mut cmd, bin_name, &mut file);
println!("completion file generated: {}", completion_file.display());
println!("completion file generated: {}", completion_file.display());
// Create symlinks for multicall binaries
let multicall_names = ["nb", "nr", "ns"];
for name in &multicall_names {
let symlink_path = output_dir.join(format!("{name}.{shell}"));
if symlink_path.exists() {
fs::remove_file(&symlink_path)?;
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&completion_file, &symlink_path)?;
println!("completion symlink created: {}", symlink_path.display());
}
#[cfg(not(unix))]
{
fs::copy(&completion_file, &symlink_path)?;
println!("completion copy created: {}", symlink_path.display());
}
// Create symlinks for multicall binaries
let multicall_names = ["nb", "nr", "ns"];
for name in &multicall_names {
let symlink_path = output_dir.join(format!("{name}.{shell}"));
if symlink_path.exists() {
fs::remove_file(&symlink_path)?;
}
println!("completions generated successfully!");
Ok(())
#[cfg(unix)]
{
std::os::unix::fs::symlink(&completion_file, &symlink_path)?;
println!("completion symlink created: {}", symlink_path.display());
}
#[cfg(not(unix))]
{
fs::copy(&completion_file, &symlink_path)?;
println!("completion copy created: {}", symlink_path.display());
}
}
println!("completions generated successfully!");
Ok(())
}