initial commit

This commit is contained in:
raf 2025-07-21 23:56:50 +03:00
commit a4d6b9e203
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
8 changed files with 709 additions and 0 deletions

2
.cargo/config.toml Normal file
View file

@ -0,0 +1,2 @@
[alias]
xtask = "run --package xtask --"

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target/
bin/

296
Cargo.lock generated Normal file
View file

@ -0,0 +1,296 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "0.6.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "clap"
version = "4.5.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "eh"
version = "0.1.0"
dependencies = [
"clap",
"regex",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]]
name = "memchr"
version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]]
name = "once_cell_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
[[package]]
name = "proc-macro2"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "xtask"
version = "0.1.0"
dependencies = [
"clap",
]

16
Cargo.toml Normal file
View file

@ -0,0 +1,16 @@
[workspace]
members = ["eh", "xtask"]
resolver = "3"
[workspace.package]
authors = [ "NotAShelf <raf@notashelf.dev>"]
description = "Ergonomic Nix CLI helper"
edition = "2024"
license = "MPL-2.0"
readme = true
rust-version = "1.85"
version = "0.1.0"
[workspace.dependencies]
clap = { version = "4.5", features = ["derive"] }
regex = "1.0"

11
eh/Cargo.toml Normal file
View file

@ -0,0 +1,11 @@
[package]
name = "eh"
description.workspace = true
version.workspace = true
edition.workspace = true
authors.workspace = true
rust-version.workspace = true
[dependencies]
clap.workspace = true
regex.workspace = true

251
eh/src/main.rs Normal file
View file

@ -0,0 +1,251 @@
use clap::Parser;
use regex::Regex;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::process::{Command as StdCommand, Stdio};
#[derive(Parser)]
#[command(name = "nix-helper")]
#[command(about = "Smart Nix helper utility")]
struct Cli {
#[arg(trailing_var_arg = true)]
args: Vec<String>,
}
fn main() {
let path = env::args().next();
let app_name = path
.as_ref()
.and_then(|p| Path::new(p).file_name())
.and_then(|name| name.to_str())
.unwrap_or("nix-helper");
let cli = Cli::parse();
match app_name {
"nr" => handle_nix_run(&cli.args),
"ns" => handle_nix_shell(&cli.args),
"nb" => handle_nix_build(&cli.args),
_ => {
eprintln!("Unknown command: {app_name}");
std::process::exit(1);
}
}
}
fn handle_nix_run(args: &[String]) {
run_nix_cmd("run", args);
}
fn handle_nix_shell(args: &[String]) {
run_nix_cmd("shell", args);
}
fn handle_nix_build(args: &[String]) {
run_nix_cmd("build", args);
}
fn run_nix_cmd(subcommand: &str, args: &[String]) {
let mut cmd = StdCommand::new("nix");
cmd.arg(subcommand);
if !args.iter().any(|arg| arg == "--no-build-output") {
cmd.arg("--print-build-logs");
}
cmd.args(args);
cmd.stderr(Stdio::piped());
cmd.stdout(Stdio::inherit());
let mut child = cmd.spawn().expect("Failed to start nix command");
let stderr = child.stderr.take().unwrap();
let stderr_handle = std::thread::spawn(move || {
let mut buffer = Vec::new();
std::io::copy(&mut std::io::BufReader::new(stderr), &mut buffer).unwrap();
buffer
});
let exit_status = child.wait().expect("Failed to wait for nix command");
let stderr_output = stderr_handle.join().unwrap();
let stderr_str = String::from_utf8_lossy(&stderr_output);
if !exit_status.success() {
if !should_retry_nix_error(&stderr_str) {
io::stderr().write_all(&stderr_output).unwrap();
}
handle_nix_error(subcommand, args, &stderr_str);
}
}
fn handle_nix_error(subcommand: &str, args: &[String], stderr: &str) {
if let Some(new_hash) = extract_hash_from_error(stderr) {
if fix_hash_in_files(&new_hash) {
println!("Fixed hash mismatch, retrying...");
retry_nix_command(subcommand, args);
return;
}
}
if stderr.contains("unfree") && stderr.contains("refusing") {
println!("Unfree package detected, retrying with NIXPKGS_ALLOW_UNFREE=1...");
retry_nix_command_with_env(subcommand, args, "NIXPKGS_ALLOW_UNFREE", "1");
return;
}
if stderr.contains("insecure") && stderr.contains("refusing") {
println!("Insecure package detected, retrying with NIXPKGS_ALLOW_INSECURE=1...");
retry_nix_command_with_env(subcommand, args, "NIXPKGS_ALLOW_INSECURE", "1");
return;
}
if stderr.contains("broken") && stderr.contains("refusing") {
println!("Broken package detected, retrying with NIXPKGS_ALLOW_BROKEN=1...");
retry_nix_command_with_env(subcommand, args, "NIXPKGS_ALLOW_BROKEN", "1");
return;
}
io::stderr().write_all(stderr.as_bytes()).unwrap();
std::process::exit(1);
}
fn extract_hash_from_error(stderr: &str) -> Option<String> {
let patterns = [
r"got:\s+([a-zA-Z0-9+/=]+)",
r"actual:\s+([a-zA-Z0-9+/=]+)",
r"have:\s+([a-zA-Z0-9+/=]+)",
];
for pattern in &patterns {
if let Ok(re) = Regex::new(pattern) {
if let Some(captures) = re.captures(stderr) {
if let Some(hash) = captures.get(1) {
return Some(hash.as_str().to_string());
}
}
}
}
None
}
fn fix_hash_in_files(new_hash: &str) -> bool {
let nix_files = find_nix_files();
let mut fixed = false;
for file_path in nix_files {
if fix_hash_in_file(&file_path, new_hash) {
println!("Updated hash in {file_path}");
fixed = true;
}
}
fixed
}
fn find_nix_files() -> Vec<String> {
let mut files = Vec::new();
let candidates = [
"default.nix",
"package.nix",
"shell.nix",
"flake.nix",
"nix/default.nix",
"nix/package.nix",
"nix/site.nix",
];
for candidate in &candidates {
if Path::new(candidate).exists() {
files.push((*candidate).to_string());
}
}
if let Ok(entries) = fs::read_dir(".") {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if std::path::Path::new(name)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("nix"))
&& !files.contains(&name.to_string())
{
files.push(name.to_string());
}
}
}
}
files
}
fn fix_hash_in_file(file_path: &str, new_hash: &str) -> bool {
if let Ok(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}""#),
),
];
for (pattern, replacement) in &patterns {
if let Ok(re) = Regex::new(pattern) {
if re.is_match(&content) {
let new_content = re.replace_all(&content, replacement);
if fs::write(file_path, new_content.as_ref()).is_ok() {
return true;
}
}
}
}
}
false
}
fn retry_nix_command(subcommand: &str, args: &[String]) {
let mut cmd = StdCommand::new("nix");
cmd.arg(subcommand);
if !args.iter().any(|arg| arg == "--no-build-output") {
cmd.arg("--print-build-logs");
}
cmd.args(args);
let exit_status = cmd.status().expect("Failed to retry nix command");
std::process::exit(exit_status.code().unwrap_or(1));
}
fn retry_nix_command_with_env(subcommand: &str, args: &[String], env_key: &str, env_value: &str) {
let mut cmd = StdCommand::new("nix");
cmd.env(env_key, env_value);
cmd.arg(subcommand);
// Add --impure for env var to take effect
cmd.arg("--impure");
if !args.iter().any(|arg| arg == "--no-build-output") {
cmd.arg("--print-build-logs");
}
cmd.args(args);
let exit_status = cmd.status().expect("Failed to retry nix command");
std::process::exit(exit_status.code().unwrap_or(1));
}
fn should_retry_nix_error(stderr: &str) -> bool {
if extract_hash_from_error(stderr).is_some() {
return true;
}
(stderr.contains("unfree") && stderr.contains("refusing"))
|| (stderr.contains("insecure") && stderr.contains("refusing"))
|| (stderr.contains("broken") && stderr.contains("refusing"))
}

12
xtask/Cargo.toml Normal file
View file

@ -0,0 +1,12 @@
[package]
name = "xtask"
description.workspace = true
version.workspace = true
edition.workspace = true
authors.workspace = true
rust-version.workspace = true
publish = false
[dependencies]
clap.workspace = true

119
xtask/src/main.rs Normal file
View file

@ -0,0 +1,119 @@
use std::{
error, fs,
path::{Path, PathBuf},
process,
};
use clap::Parser;
#[derive(clap::Parser)]
struct Cli {
#[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,
/// Path to the main binary.
#[arg(long, default_value = "target/release/eh")]
main_binary: PathBuf,
},
}
#[derive(Debug, Clone, Copy)]
enum Binary {
Nr,
Ns,
Nb,
}
impl Binary {
fn name(self) -> &'static str {
match self {
Self::Nr => "nr",
Self::Ns => "ns",
Self::Nb => "nb",
}
}
}
fn main() {
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);
}
}
}
}
fn create_multicall_binaries(
bin_dir: &Path,
main_binary: &Path,
) -> Result<(), Box<dyn error::Error>> {
println!("creating multicall binaries...");
fs::create_dir_all(bin_dir)?;
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)?;
}
match fs::hard_link(main_binary, &target_path) {
Ok(()) => {
println!(
" created hardlink: {} points to {}",
target_path.display(),
main_binary.display(),
);
}
Err(e) => {
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());
}
}
}
println!("multicall binaries created successfully!");
println!("multicall binaries are in: {}", bin_dir.display());
println!();
Ok(())
}