chore: tidy

This commit is contained in:
2026-01-12 18:07:52 +08:00
parent a8683e720b
commit 6cd87aa653
7 changed files with 73 additions and 67 deletions

View File

@@ -105,8 +105,11 @@ impl DowngradeContext for DowngradeCtx<'_> {
.rposition(|t| t.current_binding.is_some());
// Record dependency if both exist
if let (Some(expr_idx), Some(curr_idx)) = (expr_tracker_idx, current_tracker_idx) {
let current_binding = self.dep_tracker_stack[curr_idx].current_binding.unwrap();
if let (Some(expr_idx), Some(curr_idx)) =
(expr_tracker_idx, current_tracker_idx)
{
let current_binding =
self.dep_tracker_stack[curr_idx].current_binding.unwrap();
let owner_binding = self.dep_tracker_stack[curr_idx].owner_binding;
// If referencing from inner scope to outer scope
@@ -120,17 +123,17 @@ impl DowngradeContext for DowngradeCtx<'_> {
tracker.graph.add_edge(from_node, to_node, ());
} else if curr_idx > expr_idx {
// Cross-scope reference: use owner_binding if available
if let Some(owner) = owner_binding {
if let (Some(&from_node), Some(&to_node)) = (
if let Some(owner) = owner_binding
&& let (Some(&from_node), Some(&to_node)) = (
tracker.expr_to_node.get(&owner),
tracker.expr_to_node.get(&expr),
) {
)
{
tracker.graph.add_edge(from_node, to_node, ());
}
}
}
}
}
return Ok(self.new_expr(Ir::ExprRef(expr)));
}
@@ -273,7 +276,9 @@ impl DowngradeContext for DowngradeCtx<'_> {
}
fn get_current_binding(&self) -> Option<ExprId> {
self.dep_tracker_stack.last().and_then(|t| t.current_binding)
self.dep_tracker_stack
.last()
.and_then(|t| t.current_binding)
}
fn set_current_binding(&mut self, expr: Option<ExprId>) {

View File

@@ -121,10 +121,7 @@ impl Error {
Self::new(ErrorKind::DowngradeError(msg))
}
pub fn eval_error(msg: String, backtrace: Option<String>) -> Self {
Self::new(ErrorKind::EvalError {
msg,
backtrace
})
Self::new(ErrorKind::EvalError { msg, backtrace })
}
pub fn internal(msg: String) -> Self {
Self::new(ErrorKind::InternalError(msg))

View File

@@ -57,21 +57,17 @@ pub fn op_fetch_url(
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
let downloader = Downloader::new();
let file_name = name.unwrap_or_else(|| {
url.rsplit('/')
.next()
.unwrap_or("download")
.to_string()
});
let file_name =
name.unwrap_or_else(|| url.rsplit('/').next().unwrap_or("download").to_string());
if let Some(ref hash) = expected_hash {
if let Some(cached) = cache.get_url(&url, hash) {
if let Some(ref hash) = expected_hash
&& let Some(cached) = cache.get_url(&url, hash)
{
return Ok(FetchUrlResult {
store_path: cached.to_string_lossy().to_string(),
hash: hash.clone(),
});
}
}
let data = downloader
.download(&url)
@@ -111,11 +107,6 @@ pub fn op_fetch_tarball(
let dir_name = name.unwrap_or_else(|| "source".to_string());
let is_nar_hash = expected_hash
.as_ref()
.map(|h| h.starts_with("sha256-"))
.unwrap_or(false);
if let Some(ref hash) = expected_hash {
let normalized = normalize_hash(hash);
if let Some(cached) = cache.get_tarball(&url, &normalized) {
@@ -134,17 +125,16 @@ pub fn op_fetch_tarball(
let extracted_path = archive::extract_archive(&data, &temp_dir.path().to_path_buf())
.map_err(|e| NixError::from(e.to_string()))?;
let nar_hash = nar::compute_nar_hash(&extracted_path)
.map_err(|e| NixError::from(e.to_string()))?;
let nar_hash =
nar::compute_nar_hash(&extracted_path).map_err(|e| NixError::from(e.to_string()))?;
if let Some(ref expected) = expected_hash {
let normalized_expected = normalize_hash(expected);
let hash_to_compare = if is_nar_hash { &nar_hash } else { &nar_hash };
if *hash_to_compare != normalized_expected {
if nar_hash != normalized_expected {
return Err(NixError::from(format!(
"hash mismatch for '{}': expected {}, got {}",
url, normalized_expected, hash_to_compare
url, normalized_expected, nar_hash
)));
}
}
@@ -173,7 +163,16 @@ pub fn op_fetch_git(
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
let dir_name = name.unwrap_or_else(|| "source".to_string());
git::fetch_git(&cache, &url, git_ref.as_deref(), rev.as_deref(), shallow, submodules, all_refs, &dir_name)
git::fetch_git(
&cache,
&url,
git_ref.as_deref(),
rev.as_deref(),
shallow,
submodules,
all_refs,
&dir_name,
)
.map_err(|e| NixError::from(e.to_string()))
}
@@ -187,18 +186,16 @@ pub fn op_fetch_hg(
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
let dir_name = name.unwrap_or_else(|| "source".to_string());
hg::fetch_hg(&cache, &url, rev.as_deref(), &dir_name)
.map_err(|e| NixError::from(e.to_string()))
hg::fetch_hg(&cache, &url, rev.as_deref(), &dir_name).map_err(|e| NixError::from(e.to_string()))
}
fn normalize_hash(hash: &str) -> String {
if hash.starts_with("sha256-") {
if let Some(b64) = hash.strip_prefix("sha256-") {
if let Ok(bytes) = base64_decode(b64) {
if hash.starts_with("sha256-")
&& let Some(b64) = hash.strip_prefix("sha256-")
&& let Ok(bytes) = base64_decode(b64)
{
return hex::encode(bytes);
}
}
}
hash.to_string()
}
@@ -212,7 +209,9 @@ fn base64_decode(input: &str) -> Result<Vec<u8>, String> {
let mut bits = 0;
for c in input.bytes() {
let value = ALPHABET.iter().position(|&x| x == c)
let value = ALPHABET
.iter()
.position(|&x| x == c)
.ok_or_else(|| format!("Invalid base64 character: {}", c as char))?;
buffer = (buffer << 6) | (value as u32);

View File

@@ -1,6 +1,6 @@
use std::fs::{self, File};
use std::io::Cursor;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use flate2::read::GzDecoder;
@@ -48,7 +48,7 @@ impl ArchiveFormat {
}
}
pub fn extract_archive(data: &[u8], dest: &PathBuf) -> Result<PathBuf, ArchiveError> {
pub fn extract_archive(data: &[u8], dest: &Path) -> Result<PathBuf, ArchiveError> {
let format = ArchiveFormat::detect("", data);
let temp_dir = dest.join("_extract_temp");
@@ -65,34 +65,34 @@ pub fn extract_archive(data: &[u8], dest: &PathBuf) -> Result<PathBuf, ArchiveEr
strip_single_toplevel(&temp_dir, dest)
}
fn extract_tar_gz(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
fn extract_tar_gz(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
let decoder = GzDecoder::new(Cursor::new(data));
let mut archive = tar::Archive::new(decoder);
archive.unpack(dest)?;
Ok(())
}
fn extract_tar_xz(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
fn extract_tar_xz(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
let decoder = xz2::read::XzDecoder::new(Cursor::new(data));
let mut archive = tar::Archive::new(decoder);
archive.unpack(dest)?;
Ok(())
}
fn extract_tar_bz2(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
fn extract_tar_bz2(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
let decoder = bzip2::read::BzDecoder::new(Cursor::new(data));
let mut archive = tar::Archive::new(decoder);
archive.unpack(dest)?;
Ok(())
}
fn extract_tar(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
fn extract_tar(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
let mut archive = tar::Archive::new(Cursor::new(data));
archive.unpack(dest)?;
Ok(())
}
fn extract_zip(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
fn extract_zip(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
let cursor = Cursor::new(data);
let mut archive = zip::ZipArchive::new(cursor)?;
@@ -122,7 +122,7 @@ fn extract_zip(data: &[u8], dest: &PathBuf) -> Result<(), ArchiveError> {
Ok(())
}
fn strip_single_toplevel(temp_dir: &PathBuf, dest: &PathBuf) -> Result<PathBuf, ArchiveError> {
fn strip_single_toplevel(temp_dir: &Path, dest: &Path) -> Result<PathBuf, ArchiveError> {
let entries: Vec<_> = fs::read_dir(temp_dir)?
.filter_map(|e| e.ok())
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
@@ -131,7 +131,7 @@ fn strip_single_toplevel(temp_dir: &PathBuf, dest: &PathBuf) -> Result<PathBuf,
let source_dir = if entries.len() == 1 && entries[0].file_type()?.is_dir() {
entries[0].path()
} else {
temp_dir.clone()
temp_dir.to_path_buf()
};
let final_dest = dest.join("content");
@@ -149,7 +149,7 @@ fn strip_single_toplevel(temp_dir: &PathBuf, dest: &PathBuf) -> Result<PathBuf,
Ok(final_dest)
}
fn copy_dir_recursive(src: &PathBuf, dst: &PathBuf) -> Result<(), std::io::Error> {
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), std::io::Error> {
fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? {
@@ -194,7 +194,9 @@ impl std::fmt::Display for ArchiveError {
match self {
ArchiveError::IoError(e) => write!(f, "I/O error: {}", e),
ArchiveError::ZipError(e) => write!(f, "ZIP error: {}", e),
ArchiveError::UnsupportedFormat(fmt) => write!(f, "Unsupported archive format: {}", fmt),
ArchiveError::UnsupportedFormat(fmt) => {
write!(f, "Unsupported archive format: {}", fmt)
}
}
}
}

View File

@@ -97,7 +97,8 @@ impl FetcherCache {
return None;
}
let meta: CacheMetadata = serde_json::from_str(&fs::read_to_string(&meta_path).ok()?).ok()?;
let meta: CacheMetadata =
serde_json::from_str(&fs::read_to_string(&meta_path).ok()?).ok()?;
if meta.hash == expected_hash {
Some(data_path)
@@ -166,7 +167,8 @@ impl FetcherCache {
return None;
}
let meta: CacheMetadata = serde_json::from_str(&fs::read_to_string(&meta_path).ok()?).ok()?;
let meta: CacheMetadata =
serde_json::from_str(&fs::read_to_string(&meta_path).ok()?).ok()?;
if meta.hash == expected_hash {
Some(self.make_store_path(&meta.hash, &meta.name))

View File

@@ -2,8 +2,8 @@ use std::fs;
use std::path::PathBuf;
use std::process::Command;
use super::cache::FetcherCache;
use super::FetchGitResult;
use super::cache::FetcherCache;
pub fn fetch_git(
cache: &FetcherCache,
@@ -72,10 +72,7 @@ fn fetch_repo(repo: &PathBuf, all_refs: bool) -> Result<(), GitError> {
args.push("--all");
}
let output = Command::new("git")
.args(args)
.current_dir(repo)
.output()?;
let output = Command::new("git").args(args).current_dir(repo).output()?;
if !output.status.success() {
return Err(GitError::CommandFailed {
@@ -87,7 +84,11 @@ fn fetch_repo(repo: &PathBuf, all_refs: bool) -> Result<(), GitError> {
Ok(())
}
fn resolve_rev(repo: &PathBuf, git_ref: Option<&str>, rev: Option<&str>) -> Result<String, GitError> {
fn resolve_rev(
repo: &PathBuf,
git_ref: Option<&str>,
rev: Option<&str>,
) -> Result<String, GitError> {
if let Some(rev) = rev {
return Ok(rev.to_string());
}
@@ -263,7 +264,7 @@ fn days_to_ymd(days: u64) -> (u64, u64, u64) {
}
fn is_leap_year(y: u64) -> bool {
(y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)
(y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400)
}
trait Pipe: Sized {

View File

@@ -2,8 +2,8 @@ use std::fs;
use std::path::PathBuf;
use std::process::Command;
use super::cache::FetcherCache;
use super::FetchHgResult;
use super::cache::FetcherCache;
pub fn fetch_hg(
cache: &FetcherCache,