prek 0.3.11

A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use itertools::{Either, Itertools};
use path_clean::PathClean;
use prek_consts::env_vars::EnvVars;
use prek_identify::{TagSet, tags_from_path};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use rustc_hash::FxHashSet;
use tracing::{debug, error, instrument};

use crate::config::{FilePattern, Stage};
use crate::git::GIT_ROOT;
use crate::hook::Hook;
use crate::workspace::Project;
use crate::{fs, git, warn_user};

/// Filter filenames by include/exclude patterns.
pub(crate) struct FilenameFilter<'a> {
    include: Option<&'a FilePattern>,
    exclude: Option<&'a FilePattern>,
}

impl<'a> FilenameFilter<'a> {
    pub(crate) fn new(include: Option<&'a FilePattern>, exclude: Option<&'a FilePattern>) -> Self {
        Self { include, exclude }
    }

    pub(crate) fn filter(&self, filename: &Path) -> bool {
        let Some(filename) = filename.to_str() else {
            return false;
        };
        if let Some(pattern) = &self.include {
            if !pattern.is_match(filename) {
                return false;
            }
        }
        if let Some(pattern) = &self.exclude {
            if pattern.is_match(filename) {
                return false;
            }
        }
        true
    }
}

/// Filter files by tags.
pub(crate) struct FileTagFilter<'a> {
    all: Option<&'a TagSet>,
    any: Option<&'a TagSet>,
    exclude: Option<&'a TagSet>,
}

impl<'a> FileTagFilter<'a> {
    fn new(
        types: Option<&'a TagSet>,
        types_or: Option<&'a TagSet>,
        exclude_types: Option<&'a TagSet>,
    ) -> Self {
        Self {
            all: types,
            any: types_or,
            exclude: exclude_types,
        }
    }

    pub(crate) fn filter(&self, file_types: &TagSet) -> bool {
        if self.all.is_some_and(|s| !s.is_subset(file_types)) {
            return false;
        }
        if self
            .any
            .is_some_and(|s| !s.is_empty() && s.is_disjoint(file_types))
        {
            return false;
        }
        if self.exclude.is_some_and(|s| !s.is_disjoint(file_types)) {
            return false;
        }
        true
    }
}

pub(crate) struct FileFilter<'a> {
    filenames: Vec<&'a Path>,
    filename_prefix: PathBuf,
}

impl<'a> FileFilter<'a> {
    /// Create a `FileFilter` for a project by filtering the input filenames with the project's relative path and include/exclude patterns.
    /// `filenames` are paths relative to the workspace root.
    #[instrument(level = "trace", skip_all, fields(project = %project))]
    pub(crate) fn for_project<I>(
        filenames: I,
        project: &Project,
        mut consumed_files: Option<&mut FxHashSet<&'a Path>>,
    ) -> Self
    where
        I: Iterator<Item = &'a PathBuf> + Send,
    {
        let filter = FilenameFilter::new(
            project.config().files.as_ref(),
            project.config().exclude.as_ref(),
        );
        let relative_path = project.relative_path();
        let orphan = project.config().orphan.unwrap_or(false);

        // The order of below filters matters.
        // If this is an orphan project, we must mark all files in its directory as consumed
        // *before* applying the project's include/exclude patterns. This ensures that even
        // files excluded by this project are still considered "owned" by it and hidden
        // from parent projects.
        let filenames = filenames
            .map(PathBuf::as_path)
            // Collect files that are inside the hook project directory.
            .filter(|filename| filename.starts_with(relative_path))
            // Skip files that have already been consumed by subprojects.
            .filter(|filename| {
                if let Some(consumed_files) = consumed_files.as_mut() {
                    if orphan {
                        return consumed_files.insert(filename);
                    }
                    !consumed_files.contains(filename)
                } else {
                    true
                }
            })
            // Strip the project-relative prefix before applying project-level include/exclude patterns.
            .filter(|filename| {
                let relative = filename
                    .strip_prefix(relative_path)
                    .expect("Filename should start with project relative path");
                filter.filter(relative)
            })
            .collect::<Vec<_>>();

        Self {
            filenames,
            filename_prefix: relative_path.to_path_buf(),
        }
    }

    pub(crate) fn len(&self) -> usize {
        self.filenames.len()
    }

    /// Filter filenames by type tags for a specific hook.
    pub(crate) fn by_type(
        &self,
        types: Option<&TagSet>,
        types_or: Option<&TagSet>,
        exclude_types: Option<&TagSet>,
    ) -> Vec<&Path> {
        let filter = FileTagFilter::new(types, types_or, exclude_types);
        let filenames: Vec<_> = self
            .filenames
            .par_iter()
            .filter(|filename| match tags_from_path(filename) {
                Ok(tags) => filter.filter(&tags),
                Err(err) => {
                    error!(filename = ?filename.display(), error = %err, "Failed to get tags");
                    false
                }
            })
            .copied()
            .collect();

        filenames
    }

    /// Filter filenames by file patterns and tags for a specific hook.
    #[instrument(level = "trace", skip_all, fields(hook = ?hook.id))]
    pub(crate) fn for_hook(&self, hook: &Hook) -> Vec<&Path> {
        // Filter by hook `files` and `exclude` patterns.
        let filter = FilenameFilter::new(hook.files.as_ref(), hook.exclude.as_ref());

        let filenames = self.filenames.par_iter().filter(|filename| {
            // Strip the project-relative prefix before applying hook-level include/exclude patterns.
            if let Ok(relative) = filename.strip_prefix(&self.filename_prefix) {
                filter.filter(relative)
            } else {
                false
            }
        });

        // Filter by hook `types`, `types_or` and `exclude_types`.
        let filter = FileTagFilter::new(
            Some(&hook.types),
            Some(&hook.types_or),
            Some(&hook.exclude_types),
        );
        let filenames = filenames.filter(|filename| match tags_from_path(filename) {
            Ok(tags) => filter.filter(&tags),
            Err(err) => {
                error!(filename = ?filename.display(), error = %err, "Failed to get tags");
                false
            }
        });

        // Strip the prefix to get relative paths.
        let filenames: Vec<_> = filenames
            .map(|p| {
                p.strip_prefix(&self.filename_prefix)
                    .expect("Filename should start with project relative path")
            })
            .collect();

        filenames
    }
}

#[derive(Default)]
pub(crate) struct CollectOptions {
    pub(crate) hook_stage: Stage,
    pub(crate) from_ref: Option<String>,
    pub(crate) to_ref: Option<String>,
    pub(crate) all_files: bool,
    pub(crate) files: Vec<String>,
    pub(crate) directories: Vec<String>,
    pub(crate) commit_msg_filename: Option<String>,
}

impl CollectOptions {
    pub(crate) fn all_files() -> Self {
        Self {
            all_files: true,
            ..Default::default()
        }
    }
}

/// Get all filenames to run hooks on.
/// Returns a list of file paths relative to the workspace root.
#[instrument(level = "trace", skip_all)]
pub(crate) async fn collect_files(root: &Path, opts: CollectOptions) -> Result<Vec<PathBuf>> {
    let CollectOptions {
        hook_stage,
        from_ref,
        to_ref,
        all_files,
        files,
        directories,
        commit_msg_filename,
    } = opts;

    let git_root = GIT_ROOT.as_ref()?;

    // The workspace root relative to the git root.
    let relative_root = root.strip_prefix(git_root).with_context(|| {
        format!(
            "Workspace root `{}` is not under git root `{}`",
            root.display(),
            git_root.display()
        )
    })?;

    let filenames = collect_files_from_args(
        git_root,
        root,
        hook_stage,
        from_ref,
        to_ref,
        all_files,
        files,
        directories,
        commit_msg_filename,
    )
    .await?;

    // Convert filenames to be relative to the workspace root.
    let mut filenames = filenames
        .into_iter()
        .filter_map(|filename| {
            // Only keep files under the workspace root.
            filename
                .strip_prefix(relative_root)
                .map(|p| fs::normalize_path(p.to_path_buf()))
                .ok()
        })
        .collect::<Vec<_>>();

    // Sort filenames if in tests to make the order consistent.
    if EnvVars::is_set(EnvVars::PREK_INTERNAL__SORT_FILENAMES) {
        filenames.sort_unstable();
    }

    Ok(filenames)
}

fn adjust_relative_path(path: &str, new_cwd: &Path) -> Result<PathBuf, std::io::Error> {
    let absolute = std::path::absolute(path)?.clean();
    fs::relative_to(absolute, new_cwd)
}

/// Collect files to run hooks on.
/// Returns a list of file paths relative to the git root.
#[allow(clippy::too_many_arguments)]
async fn collect_files_from_args(
    git_root: &Path,
    workspace_root: &Path,
    hook_stage: Stage,
    from_ref: Option<String>,
    to_ref: Option<String>,
    all_files: bool,
    files: Vec<String>,
    directories: Vec<String>,
    commit_msg_filename: Option<String>,
) -> Result<Vec<PathBuf>> {
    if !hook_stage.operate_on_files() {
        return Ok(vec![]);
    }

    if hook_stage == Stage::PrepareCommitMsg || hook_stage == Stage::CommitMsg {
        let path = commit_msg_filename.expect("commit_msg_filename should be set");
        let path = adjust_relative_path(&path, git_root)?;
        return Ok(vec![path]);
    }

    if let (Some(from_ref), Some(to_ref)) = (from_ref, to_ref) {
        let files = git::get_changed_files(&from_ref, &to_ref, workspace_root).await?;
        debug!(
            "Files changed between {} and {}: {}",
            from_ref,
            to_ref,
            files.len()
        );
        return Ok(files);
    }

    if !files.is_empty() || !directories.is_empty() {
        // By default, `pre-commit` add `types: [file]` for all hooks,
        // so `pre-commit` will ignore user provided directories.
        // We do the same here for compatibility.
        // For `types: [directory]`, `pre-commit` passes the directory names to the hook directly.
        let (exists, non_exists): (FxHashSet<_>, Vec<_>) =
            files.into_iter().partition_map(|filename| {
                if std::fs::exists(&filename).unwrap_or(false) {
                    Either::Left(filename)
                } else {
                    Either::Right(filename)
                }
            });
        if !non_exists.is_empty() {
            if non_exists.len() == 1 {
                warn_user!(
                    "This file does not exist and will be ignored: `{}`",
                    non_exists[0]
                );
            } else {
                warn_user!(
                    "These files do not exist and will be ignored: `{}`",
                    non_exists.join(", ")
                );
            }
        }

        let mut exists = exists
            .into_iter()
            .map(|filename| adjust_relative_path(&filename, git_root).map(fs::normalize_path))
            .collect::<Result<FxHashSet<_>, _>>()?;

        for dir in directories {
            let dir = adjust_relative_path(&dir, git_root)?;
            let dir_files = git::ls_files(git_root, &dir).await?;
            for file in dir_files {
                let file = fs::normalize_path(file);
                exists.insert(file);
            }
        }

        debug!("Files passed as arguments: {}", exists.len());
        return Ok(exists.into_iter().collect());
    }

    if all_files {
        let files = git::ls_files(git_root, workspace_root).await?;
        debug!("All files in the workspace: {}", files.len());
        return Ok(files);
    }

    if git::is_in_merge_conflict().await? {
        let files = git::get_conflicted_files(workspace_root).await?;
        debug!("Conflicted files: {}", files.len());
        return Ok(files);
    }

    let files = git::get_staged_files(workspace_root).await?;
    debug!("Staged files: {}", files.len());

    Ok(files)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GlobPatterns;

    fn glob_pattern(pattern: &str) -> FilePattern {
        FilePattern::Glob(GlobPatterns::new(vec![pattern.to_string()]).unwrap())
    }

    #[test]
    fn filename_filter_supports_glob_include_and_exclude() {
        let include = glob_pattern("src/**/*.rs");
        let exclude = glob_pattern("src/**/ignored.rs");
        let filter = FilenameFilter::new(Some(&include), Some(&exclude));

        assert!(filter.filter(Path::new("src/lib/main.rs")));
        assert!(!filter.filter(Path::new("src/lib/ignored.rs")));
        assert!(!filter.filter(Path::new("tests/main.rs")));
    }
}