Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ async-compression = { version = "0.4.18", features = ["gzip", "xz", "tokio"] }
async_zip = { git = "https://github.com/astral-sh/rs-async-zip", rev = "c909fda63fcafe4af496a07bfda28a5aae97e58d", features = ["deflate", "tokio"] }
axoupdater = { version = "0.9.0", default-features = false, features = ["github_releases"], optional = true }
bstr = { version = "1.11.0" }
camino = { version = "1.1.9", features = ["serde1"] }
clap = { version = "4.5.16", features = ["derive", "env", "string", "wrap_help"] }
clap_complete = { version = "4.5.37", features = ["unstable-dynamic"] }
constants = { workspace = true }
Expand All @@ -71,7 +72,6 @@ levenshtein = { version = "1.0.5" }
liblzma = { version = "*", features = ["static"] }
memchr = { version = "2.7.5" }
owo-colors = { version = "4.1.0" }
path-clean = { version = "1.0.1" }
quick-xml = { version = "0.38" }
rand = { version = "0.9.0" }
rayon = { version = "1.10.0" }
Expand Down
27 changes: 14 additions & 13 deletions src/builtin/meta_hooks.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::io::Write;
use std::path::Path;

use anyhow::Result;
use camino::Utf8Path;
use fancy_regex::Regex;
use itertools::Itertools;

Expand All @@ -22,7 +22,7 @@ use crate::workspace::Project;
pub(crate) async fn check_hooks_apply(
store: &Store,
hook: &Hook,
filenames: &[&Path],
filenames: &[&Utf8Path],
) -> Result<(i32, Vec<u8>)> {
let relative_path = hook.project().relative_path();
// Collect all files in the project
Expand Down Expand Up @@ -64,7 +64,7 @@ pub(crate) async fn check_hooks_apply(

// Returns true if the exclude pattern matches any files matching the include pattern.
fn excludes_any(
files: &[impl AsRef<Path>],
files: &[impl AsRef<Utf8Path>],
include: Option<&Regex>,
exclude: Option<&Regex>,
) -> bool {
Expand All @@ -73,9 +73,7 @@ fn excludes_any(
}

files.iter().any(|f| {
let Some(f) = f.as_ref().to_str() else {
return false; // Skip files that cannot be converted to a string
};
let f = f.as_ref().as_str();

if let Some(re) = &include {
if !re.is_match(f).unwrap_or(false) {
Expand All @@ -94,7 +92,7 @@ fn excludes_any(
/// Ensures that exclude directives apply to any file in the repository.
pub(crate) async fn check_useless_excludes(
hook: &Hook,
filenames: &[&Path],
filenames: &[&Utf8Path],
) -> Result<(i32, Vec<u8>)> {
let relative_path = hook.project().relative_path();
let input = collect_files(hook.work_dir(), CollectOptions::all_files()).await?;
Expand Down Expand Up @@ -154,12 +152,12 @@ pub(crate) async fn check_useless_excludes(
}

/// Prints all arguments passed to the hook. Useful for debugging.
pub fn identity(_hook: &Hook, filenames: &[&Path]) -> (i32, Vec<u8>) {
pub fn identity(_hook: &Hook, filenames: &[&Utf8Path]) -> (i32, Vec<u8>) {
(
0,
filenames
.iter()
.map(|f| f.to_string_lossy())
.map(ToString::to_string)
.join("\n")
.into_bytes(),
)
Expand All @@ -172,9 +170,9 @@ mod tests {
#[test]
fn test_excludes_any() {
let files = vec![
Path::new("file1.txt"),
Path::new("file2.txt"),
Path::new("file3.txt"),
Utf8Path::new("file1.txt"),
Utf8Path::new("file2.txt"),
Utf8Path::new("file3.txt"),
];
assert!(excludes_any(
&files,
Expand All @@ -188,7 +186,10 @@ mod tests {
));
assert!(excludes_any(&files, None, None));

let files = vec![Path::new("html/file1.html"), Path::new("html/file2.html")];
let files = vec![
Utf8Path::new("html/file1.html"),
Utf8Path::new("html/file2.html"),
];
assert!(excludes_any(
&files,
None,
Expand Down
6 changes: 3 additions & 3 deletions src/builtin/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::Path;
use camino::Utf8Path;
use std::str::FromStr;
use std::sync::LazyLock;

Expand Down Expand Up @@ -33,7 +33,7 @@ pub fn check_fast_path(hook: &Hook) -> bool {
pub async fn run_fast_path(
store: &Store,
hook: &Hook,
filenames: &[&Path],
filenames: &[&Utf8Path],
) -> anyhow::Result<(i32, Vec<u8>)> {
match hook.repo() {
Repo::Meta { .. } => run_meta_hook(store, hook, filenames).await,
Expand All @@ -50,7 +50,7 @@ pub async fn run_fast_path(
async fn run_meta_hook(
store: &Store,
hook: &Hook,
filenames: &[&Path],
filenames: &[&Utf8Path],
) -> anyhow::Result<(i32, Vec<u8>)> {
match hook.id.as_str() {
"check-hooks-apply" => meta_hooks::check_hooks_apply(store, hook, filenames).await,
Expand Down
12 changes: 5 additions & 7 deletions src/builtin/pre_commit_hooks/check_added_large_files.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::path::{Path, PathBuf};

use camino::{Utf8Path, Utf8PathBuf};
use clap::Parser;
use futures::StreamExt;
use rustc_hash::FxHashSet;
Expand All @@ -10,11 +9,11 @@ use crate::run::CONCURRENCY;

enum FileFilter {
NoFilter,
Files(FxHashSet<PathBuf>),
Files(FxHashSet<Utf8PathBuf>),
}

impl FileFilter {
fn contains(&self, path: &Path) -> bool {
fn contains(&self, path: &Utf8Path) -> bool {
match self {
FileFilter::NoFilter => true,
FileFilter::Files(files) => files.contains(path),
Expand All @@ -35,7 +34,7 @@ struct Args {

pub(crate) async fn check_added_large_files(
hook: &Hook,
filenames: &[&Path],
filenames: &[&Utf8Path],
) -> anyhow::Result<(i32, Vec<u8>)> {
let args = Args::try_parse_from(hook.entry.resolve(None)?.iter().chain(&hook.args))?;

Expand Down Expand Up @@ -64,8 +63,7 @@ pub(crate) async fn check_added_large_files(
if size > args.max_kb {
anyhow::Ok(Some(format!(
"{} ({size} KB) exceeds {} KB\n",
filename.display(),
args.max_kb
filename, args.max_kb
)))
} else {
anyhow::Ok(None)
Expand Down
29 changes: 15 additions & 14 deletions src/builtin/pre_commit_hooks/check_json.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::Path;
use camino::Utf8Path;

use anyhow::Result;
use futures::StreamExt;
Expand All @@ -18,7 +18,7 @@ enum JsonValue {
Null,
}

pub(crate) async fn check_json(hook: &Hook, filenames: &[&Path]) -> Result<(i32, Vec<u8>)> {
pub(crate) async fn check_json(hook: &Hook, filenames: &[&Utf8Path]) -> Result<(i32, Vec<u8>)> {
let mut tasks = futures::stream::iter(filenames)
.map(async |filename| check_file(hook.project().relative_path(), filename).await)
.buffered(*CONCURRENCY);
Expand All @@ -35,7 +35,7 @@ pub(crate) async fn check_json(hook: &Hook, filenames: &[&Path]) -> Result<(i32,
Ok((code, output))
}

async fn check_file(file_base: &Path, filename: &Path) -> Result<(i32, Vec<u8>)> {
async fn check_file(file_base: &Utf8Path, filename: &Utf8Path) -> Result<(i32, Vec<u8>)> {
let file_path = file_base.join(filename);
let content = fs_err::tokio::read(file_path).await?;
if content.is_empty() {
Expand All @@ -53,7 +53,7 @@ async fn check_file(file_base: &Path, filename: &Path) -> Result<(i32, Vec<u8>)>
Ok((0, Vec::new()))
}
Err(e) => {
let error_message = format!("{}: Failed to json decode ({e})\n", filename.display());
let error_message = format!("{filename}: Failed to json decode ({e})\n");
Ok((1, error_message.into_bytes()))
}
}
Expand Down Expand Up @@ -151,25 +151,26 @@ impl<'de> Deserialize<'de> for JsonValue {
#[cfg(test)]
mod tests {
use super::*;
use std::path::{Path, PathBuf};
use crate::path::IntoUtf8PathBuf;
use camino::{Utf8Path, Utf8PathBuf};
use tempfile::tempdir;

async fn create_test_file(
dir: &tempfile::TempDir,
name: &str,
content: &[u8],
) -> Result<PathBuf> {
) -> Result<Utf8PathBuf> {
let file_path = dir.path().join(name);
fs_err::tokio::write(&file_path, content).await?;
Ok(file_path)
Ok(file_path.into_utf8_path_buf())
}

#[tokio::test]
async fn test_valid_json() -> Result<()> {
let dir = tempdir()?;
let content = br#"{"key1": "value1", "key2": "value2"}"#;
let file_path = create_test_file(&dir, "valid.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 0);
assert!(output.is_empty());

Expand All @@ -181,7 +182,7 @@ mod tests {
let dir = tempdir()?;
let content = br#"{"key1": "value1", "key2": "value2""#;
let file_path = create_test_file(&dir, "invalid.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 1);
assert!(!output.is_empty());

Expand All @@ -193,7 +194,7 @@ mod tests {
let dir = tempdir()?;
let content = br#"{"key1": "value1", "key1": "value2"}"#;
let file_path = create_test_file(&dir, "duplicate.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 1);
assert!(!output.is_empty());

Expand All @@ -205,7 +206,7 @@ mod tests {
let dir = tempdir()?;
let content = b"";
let file_path = create_test_file(&dir, "empty.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 0);
assert!(output.is_empty());

Expand All @@ -217,7 +218,7 @@ mod tests {
let dir = tempdir()?;
let content = br#"[{"key1": "value1"}, {"key2": "value2"}]"#;
let file_path = create_test_file(&dir, "valid_array.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 0);
assert!(output.is_empty());

Expand All @@ -229,7 +230,7 @@ mod tests {
let dir = tempdir()?;
let content = br#"{"key1": "value1", "key2": {"nested_key": 1, "nested_key": 2}}"#;
let file_path = create_test_file(&dir, "nested_duplicate.json", content).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 1);
assert!(!output.is_empty());

Expand All @@ -246,7 +247,7 @@ mod tests {
}

let file_path = create_test_file(&dir, "deeply_nested.json", json.as_bytes()).await?;
let (code, output) = check_file(Path::new(""), &file_path).await?;
let (code, output) = check_file(Utf8Path::new(""), &file_path).await?;
assert_eq!(code, 0);
assert!(output.is_empty());

Expand Down
Loading
Loading