Skip to main content

gix_dir/walk/
mod.rs

1use std::{collections::BTreeSet, path::PathBuf, sync::atomic::AtomicBool};
2
3use bstr::{BStr, BString};
4
5use crate::{EntryRef, entry};
6
7/// A type returned by the [`Delegate::emit()`] as passed to [`walk()`](function::walk()).
8///
9/// Use [`std::ops::ControlFlow::Continue`] to continue the traversal as normal.
10/// Use [`std::ops::ControlFlow::Break`] to exit the traversal.
11pub type Action = std::ops::ControlFlow<()>;
12
13/// Ready-made delegate implementations.
14pub mod delegate {
15    use crate::{Entry, EntryRef, entry, walk, walk::Action};
16
17    type Entries = Vec<(Entry, Option<entry::Status>)>;
18
19    /// A [`Delegate`](walk::Delegate) implementation that collects all `entries` along with their directory status, if present.
20    ///
21    /// Note that this allocates for each entry.
22    #[derive(Default)]
23    pub struct Collect {
24        /// All collected entries, in any order.
25        pub unorded_entries: Entries,
26    }
27
28    impl Collect {
29        /// Return the list of entries that were emitted, sorted ascending by their repository-relative tree path.
30        pub fn into_entries_by_path(mut self) -> Entries {
31            self.unorded_entries.sort_by(|a, b| a.0.rela_path.cmp(&b.0.rela_path));
32            self.unorded_entries
33        }
34    }
35
36    impl walk::Delegate for Collect {
37        fn emit(&mut self, entry: EntryRef<'_>, dir_status: Option<entry::Status>) -> Action {
38            self.unorded_entries.push((entry.to_owned(), dir_status));
39            std::ops::ControlFlow::Continue(())
40        }
41    }
42}
43
44/// A way for the caller to control the traversal based on provided data.
45pub trait Delegate {
46    /// Called for each observed `entry` *inside* a directory, or the directory itself if the traversal is configured
47    /// to simplify the result (i.e. if every file in a directory is ignored, emit the containing directory instead
48    /// of each file), or if the root of the traversal passes through a directory that can't be traversed.
49    ///
50    /// It will also be called if the `root` in [`walk()`](crate::walk()) itself is matching a particular status,
51    /// even if it is a file.
52    ///
53    /// Note that tracked entries will only be emitted if [`Options::emit_tracked`] is `true`.
54    /// Further, not all pruned entries will be observable as they might be pruned so early that the kind of
55    /// item isn't yet known. Pruned entries are also only emitted if [`Options::emit_pruned`] is `true`.
56    ///
57    /// `collapsed_directory_status` is `Some(dir_status)` if this entry was part of a directory with the given
58    /// `dir_status` that wasn't the same as the one of `entry` and if [Options::emit_collapsed] was
59    /// [CollapsedEntriesEmissionMode::OnStatusMismatch]. It will also be `Some(dir_status)` if that option
60    /// was [CollapsedEntriesEmissionMode::All].
61    fn emit(&mut self, entry: EntryRef<'_>, collapsed_directory_status: Option<entry::Status>) -> Action;
62
63    /// Return `true` if the given entry can be recursed into. Will only be called if the entry is a physical directory.
64    /// The base implementation will act like Git does by default in `git status` or `git clean`.
65    ///
66    /// Use `for_deletion` to specify if the seen entries should ultimately be deleted, which may affect the decision
67    /// of whether to resource or not.
68    ///
69    /// If `worktree_root_is_repository` is `true`, then this status is part of the root of an iteration, and the corresponding
70    /// worktree root is a repository itself. This typically happens for submodules. In this case, recursion rules are relaxed
71    /// to allow traversing submodule worktrees.
72    ///
73    /// Note that this method will see all directories, even though not all of them may end up being [emitted](Self::emit()).
74    /// If this method returns `false`, the `entry` will always be emitted.
75    fn can_recurse(
76        &mut self,
77        entry: EntryRef<'_>,
78        for_deletion: Option<ForDeletionMode>,
79        worktree_root_is_repository: bool,
80    ) -> bool {
81        entry.status.can_recurse(
82            entry.disk_kind,
83            entry.pathspec_match,
84            for_deletion,
85            worktree_root_is_repository,
86        )
87    }
88}
89
90/// The way entries are emitted using the [Delegate].
91///
92/// The choice here controls if entries are emitted immediately, or have to be held back.
93#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
94pub enum EmissionMode {
95    /// Emit each entry as it matches exactly, without doing any kind of simplification.
96    ///
97    /// Emissions in this mode are happening as they occur, without any buffering or ordering.
98    #[default]
99    Matching,
100    /// Emit only a containing directory if all of its entries are of the same type.
101    ///
102    /// Note that doing so is more expensive as it requires us to keep track of all entries in the directory structure
103    /// until it's clear what to finally emit.
104    ///
105    /// Also note that empty *untracked* directories aren't empitted, also if these are nested (and empty)
106    CollapseDirectory,
107}
108
109/// The way entries that are contained in collapsed directories are emitted using the [Delegate].
110#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
111pub enum CollapsedEntriesEmissionMode {
112    /// Emit only entries if their status does not match the one of the parent directory that is
113    /// going to be collapsed.
114    ///
115    /// E.g. if a directory is determined to be untracked, and the entries in question are ignored,
116    /// they will be emitted.
117    ///
118    /// Entries that have the same status will essentially be 'merged' into the collapsing directory
119    /// and won't be observable anymore.
120    #[default]
121    OnStatusMismatch,
122    /// Emit all entries inside of a collapsed directory to make them observable.
123    All,
124}
125
126/// When the walk is for deletion, assure that we don't collapse directories that have precious files in
127/// them, and otherwise assure that no entries are observable that shouldn't be deleted.
128#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
129pub enum ForDeletionMode {
130    /// We will stop traversing into ignored directories which may save a lot of time, but also may include nested repositories
131    /// which might end up being deleted.
132    #[default]
133    IgnoredDirectoriesCanHideNestedRepositories,
134    /// Instead of skipping over ignored directories entirely, we will dive in and find ignored non-bare repositories
135    /// so these are emitted separately and prevent collapsing. These are assumed to be a directory with `.git` inside.
136    /// Only relevant when ignored entries are emitted.
137    FindNonBareRepositoriesInIgnoredDirectories,
138    /// This is a more expensive form of the above variant as it finds all repositories, bare or non-bare.
139    FindRepositoriesInIgnoredDirectories,
140}
141
142/// Options for use in [`walk()`](function::walk()) function.
143#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
144pub struct Options<'a> {
145    /// If `true`, the filesystem will store paths as decomposed unicode, i.e. `รค` becomes `"a\u{308}"`, which means that
146    /// we have to turn these forms back from decomposed to precomposed unicode before storing it in the index or generally
147    /// using it. This also applies to input received from the command-line, so callers may have to be aware of this and
148    /// perform conversions accordingly.
149    /// If `false`, no conversions will be performed.
150    pub precompose_unicode: bool,
151    /// If true, the filesystem ignores the case of input, which makes `A` the same file as `a`.
152    /// This is also called case-folding.
153    /// Note that [pathspecs](Context::pathspec) must also be using the same defaults, which makes them match case-insensitive
154    /// automatically.
155    pub ignore_case: bool,
156    /// If `true`, we will stop figuring out if any directory that is a candidate for recursion is also a nested repository,
157    /// which saves time but leads to recurse into it. If `false`, nested repositories will not be traversed.
158    pub recurse_repositories: bool,
159    /// If `true`, entries that are pruned and whose [Kind](crate::entry::Kind) is known will be emitted.
160    pub emit_pruned: bool,
161    /// If `Some(mode)`, entries that are ignored will be emitted according to the given `mode`.
162    /// If `None`, ignored entries will not be emitted at all.
163    pub emit_ignored: Option<EmissionMode>,
164    /// When the walk is for deletion, this must be `Some(_)` to assure we don't collapse directories that have precious files in
165    /// them, and otherwise assure that no entries are observable that shouldn't be deleted.
166    /// If `None`, precious files are treated like expendable files, which is usually what you want when displaying them
167    /// for addition to the repository, and the collapse of folders can be more generous in relation to ignored files.
168    pub for_deletion: Option<ForDeletionMode>,
169    /// If `true`, we will not only find non-bare repositories in untracked directories, but also bare ones.
170    ///
171    /// Note that this is very costly, but without it, bare repositories will appear like untracked directories when collapsed,
172    /// and they will be recursed into.
173    pub classify_untracked_bare_repositories: bool,
174    /// If `true`, we will also emit entries for tracked items. Otherwise these will remain 'hidden', even if a pathspec directly
175    /// refers to it.
176    pub emit_tracked: bool,
177    /// Controls the way untracked files are emitted. By default, this is happening immediately and without any simplification.
178    pub emit_untracked: EmissionMode,
179    /// If `true`, emit empty directories as well. Note that a directory also counts as empty if it has any amount or depth of nested
180    /// subdirectories, as long as none of them includes a file.
181    /// Thus, this makes leaf-level empty directories visible, as those don't have any content.
182    pub emit_empty_directories: bool,
183    /// If `None`, no entries inside of collapsed directories are emitted. Otherwise, act as specified by `Some(mode)`.
184    pub emit_collapsed: Option<CollapsedEntriesEmissionMode>,
185    /// This is a `libgit2` compatibility flag, and if enabled, symlinks that point to directories will be considered a directory
186    /// when checking for exclusion.
187    ///
188    /// This is relevant if `src2` points to `src`, and is excluded with `src2/`. If `false`, `src2` will not be excluded,
189    /// if `true` it will be excluded as the symlink is considered a directory.
190    ///
191    /// In other words, for Git compatibility this flag should be `false`, the default, for `git2` compatibility it should be `true`.
192    pub symlinks_to_directories_are_ignored_like_directories: bool,
193    /// A set of all git worktree checkouts that are located within the main worktree directory.
194    ///
195    /// They will automatically be detected as 'tracked', but without providing index information (as there is no actual index entry).
196    /// Note that the unicode composition must match the `precompose_unicode` field so that paths will match verbatim.
197    pub worktree_relative_worktree_dirs: Option<&'a BTreeSet<BString>>,
198}
199
200/// All information that is required to perform a dirwalk, and classify paths properly.
201pub struct Context<'a> {
202    /// If not `None`, it will be checked before entering any directory to trigger early interruption.
203    ///
204    /// If this flag is `true` at any point in the iteration, it will abort with an error.
205    pub should_interrupt: Option<&'a AtomicBool>,
206    /// The `git_dir` of the parent repository, after a call to [`gix_path::realpath()`].
207    ///
208    /// It's used to help us differentiate our own `.git` directory from nested unrelated repositories,
209    /// which is needed if `core.worktree` is used to nest the `.git` directory deeper within.
210    pub git_dir_realpath: &'a std::path::Path,
211    /// The current working directory as returned by `gix_fs::current_dir()` to assure it respects `core.precomposeUnicode`.
212    /// It's used to produce the realpath of the git-dir of a repository candidate to assure it's not our own repository.
213    ///
214    /// It is also used to assure that when the walk is for deletion, that the current working dir will not be collapsed.
215    pub current_dir: &'a std::path::Path,
216    /// The index to quickly understand if a file or directory is tracked or not.
217    ///
218    /// ### Important
219    ///
220    /// The index must have been validated so that each entry that is considered up-to-date will have the [gix_index::entry::Flags::UPTODATE] flag
221    /// set. Otherwise the index entry is not considered and a disk-access may occur which is costly.
222    pub index: &'a gix_index::State,
223    /// A utility to lookup index entries faster, and deal with ignore-case handling.
224    ///
225    /// Must be set if `ignore_case` is `true`, or else some entries won't be found if their case is different.
226    ///
227    /// ### Deviation
228    ///
229    /// Git uses a name-based hash (for looking up entries, not directories) even when operating
230    /// in case-sensitive mode. It does, however, skip the directory hash creation (for looking
231    /// up directories) unless `core.ignoreCase` is enabled.
232    ///
233    /// We only use the hashmap when available and when [`ignore_case`](Options::ignore_case) is enabled in the options.
234    pub ignore_case_index_lookup: Option<&'a gix_index::AccelerateLookup<'a>>,
235    /// A pathspec to use as filter - we only traverse into directories if it matches.
236    /// Note that the `ignore_case` setting it uses should match our [Options::ignore_case].
237    /// If no such filtering is desired, pass an empty `pathspec` which will match everything.
238    pub pathspec: &'a mut gix_pathspec::Search,
239    /// The `attributes` callback for use in [gix_pathspec::Search::pattern_matching_relative_path()], which happens when
240    /// pathspecs use attributes for filtering.
241    /// If `pathspec` isn't empty, this function may be called if pathspecs perform attribute lookups.
242    pub pathspec_attributes: &'a mut dyn FnMut(
243        &BStr,
244        gix_pathspec::attributes::glob::pattern::Case,
245        bool,
246        &mut gix_pathspec::attributes::search::Outcome,
247    ) -> bool,
248    /// A way to query the `.gitignore` files to see if a directory or file is ignored.
249    /// Set to `None` to not perform any work on checking for ignored, which turns previously ignored files into untracked ones, a useful
250    /// operation when trying to add ignored files to a repository.
251    pub excludes: Option<&'a mut gix_worktree::Stack>,
252    /// Access to the object database for use with `excludes` - it's possible to access `.gitignore` files in the index if configured.
253    pub objects: &'a dyn gix_object::Find,
254    /// If not `None`, override the traversal root that is computed and use this one instead.
255    ///
256    /// This can be useful if the traversal root may be a file, in which case the traversal will
257    /// still be returning possibly matching root entries.
258    ///
259    /// ### Panics
260    ///
261    /// If the `traversal_root` is not in the `worktree_root` passed to [walk()](crate::walk()).
262    pub explicit_traversal_root: Option<&'a std::path::Path>,
263}
264
265/// Additional information collected as outcome of [`walk()`](function::walk()).
266#[derive(Default, Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
267pub struct Outcome {
268    /// The amount of calls to read the directory contents.
269    pub read_dir_calls: u32,
270    /// The amount of returned entries provided to the callback. This number can be lower than `seen_entries`.
271    pub returned_entries: usize,
272    /// The amount of entries, prior to pathspecs filtering them out or otherwise excluding them.
273    pub seen_entries: u32,
274}
275
276/// The error returned by [`walk()`](function::walk()).
277#[derive(Debug, thiserror::Error)]
278#[expect(missing_docs)]
279pub enum Error {
280    #[error("Interrupted")]
281    Interrupted,
282    #[error("Worktree root at '{}' is not a directory", root.display())]
283    WorktreeRootIsFile { root: PathBuf },
284    #[error("Traversal root '{}' contains relative path components and could not be normalized", root.display())]
285    NormalizeRoot { root: PathBuf },
286    #[error("A symlink was found at component {component_index} of traversal root '{}' as seen from worktree root '{}'", root.display(), worktree_root.display())]
287    SymlinkInRoot {
288        root: PathBuf,
289        worktree_root: PathBuf,
290        /// This index starts at 0, with 0 being the first component.
291        component_index: usize,
292    },
293    #[error("Failed to update the excludes stack to see if a path is excluded")]
294    ExcludesAccess(std::io::Error),
295    #[error("Failed to read the directory at '{}'", path.display())]
296    ReadDir { path: PathBuf, source: std::io::Error },
297    #[error("Could not obtain directory entry in root of '{}'", parent_directory.display())]
298    DirEntry {
299        parent_directory: PathBuf,
300        source: std::io::Error,
301    },
302    #[error("Could not obtain filetype of directory entry '{}'", path.display())]
303    DirEntryFileType { path: PathBuf, source: std::io::Error },
304    #[error("Could not obtain symlink metadata on '{}'", path.display())]
305    SymlinkMetadata { path: PathBuf, source: std::io::Error },
306}
307
308mod classify;
309pub(crate) mod function;
310mod readdir;