| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `.gitignore` and `.braidignore` rules, as the walk over a working copy |
| 5 | //! meets them. |
| 6 | //! |
| 7 | //! Each directory may hold either file, with git's pattern syntax. Rules in a |
| 8 | //! deeper directory win over rules above it, and within one directory |
| 9 | //! `.braidignore` wins over `.gitignore`. As in git, a file under an ignored |
| 10 | //! directory cannot be brought back by a later `!` rule, since the walk does |
| 11 | //! not go into ignored directories. Tracked files are never ignored: the |
| 12 | //! walk checks them whatever the rules say. |
| 13 | //! |
| 14 | //! The walk reads a directory's entries once, and opens an ignore file only |
| 15 | //! where the listing has one. The rules in force in a directory have a |
| 16 | //! digest, of the ignore files read for it and above it, so that a scan can |
| 17 | //! tell whether they are the ones an earlier scan had. |
| 18 | |
| 19 | use std::io::Read; |
| 20 | use std::sync::Arc; |
| 21 | |
| 22 | use cap_std::fs::Dir; |
| 23 | use ignore::Match; |
| 24 | use ignore::gitignore::{Gitignore, GitignoreBuilder}; |
| 25 | |
| 26 | use braid_format::{IdHasher, Kind}; |
| 27 | |
| 28 | use crate::fsprobe::FileSystem; |
| 29 | use crate::paths::os_name; |
| 30 | use crate::safe::open_file; |
| 31 | |
| 32 | /// Ignore files read in each directory, highest precedence first. |
| 33 | const FILES: [&str; 2] = [".braidignore", ".gitignore"]; |
| 34 | |
| 35 | /// The rules of one directory, and those of the directories above it. |
| 36 | #[derive(Debug)] |
| 37 | pub(crate) struct Rules { |
| 38 | /// The directory's path in the working copy; empty for the root. |
| 39 | dir: Vec<u8>, |
| 40 | /// Its matchers, highest precedence first. |
| 41 | matchers: Vec<Gitignore>, |
| 42 | parent: Option<Arc<Rules>>, |
| 43 | /// The digest of the ignore files these rules come from, and of their |
| 44 | /// parent's. |
| 45 | digest: u64, |
| 46 | } |
| 47 | |
| 48 | /// The rules in force in a directory. |
| 49 | pub(crate) type Chain = Option<Arc<Rules>>; |
| 50 | |
| 51 | /// The digest of the rules in force: 0 for none. |
| 52 | pub(crate) fn digest(chain: &Chain) -> u64 { |
| 53 | chain.as_ref().map_or(0, |rules| rules.digest) |
| 54 | } |
| 55 | |
| 56 | /// A directory's ignore files, as named in its listing, in the order of |
| 57 | /// [`FILES`]. |
| 58 | pub(crate) type IgnoreFiles<'n> = [Option<&'n [u8]>; 2]; |
| 59 | |
| 60 | /// The ignore files among `names`, the entries of one directory: each |
| 61 | /// entry that `fs` takes for `.braidignore` or `.gitignore`, as it would |
| 62 | /// find it by that name. |
| 63 | pub(crate) fn ignore_files<'n>( |
| 64 | fs: FileSystem, |
| 65 | names: impl Iterator<Item = &'n [u8]>, |
| 66 | ) -> IgnoreFiles<'n> { |
| 67 | let mut found: IgnoreFiles<'n> = [None; 2]; |
| 68 | for name in names { |
| 69 | // Folding maps ASCII letters to ASCII letters and changes no length |
| 70 | // here, so only a dot name of the same length can be one of them. |
| 71 | for (slot, wanted) in found.iter_mut().zip(FILES) { |
| 72 | if slot.is_none() |
| 73 | && name.len() == wanted.len() |
| 74 | && name.first() == Some(&b'.') |
| 75 | && fs.fold(name) == fs.fold(wanted.as_bytes()) |
| 76 | { |
| 77 | *slot = Some(name); |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | found |
| 82 | } |
| 83 | |
| 84 | /// Which ignore files there are, one bit each, in the order of [`FILES`]. |
| 85 | pub(crate) fn bits(files: &IgnoreFiles<'_>) -> u8 { |
| 86 | u8::from(files[0].is_some()) | u8::from(files[1].is_some()) << 1 |
| 87 | } |
| 88 | |
| 89 | /// The ignore files that [`bits`] says there are, by their own names: the |
| 90 | /// file system finds each by that name as it found it before. |
| 91 | pub(crate) fn from_bits(bits: u8) -> IgnoreFiles<'static> { |
| 92 | let named = |index: usize| (bits >> index & 1 != 0).then_some(FILES[index].as_bytes()); |
| 93 | [named(0), named(1)] |
| 94 | } |
| 95 | |
| 96 | /// The rules in force inside `dir`, whose path is `path`: those of its |
| 97 | /// ignore files `files` (see [`ignore_files`]) on top of `parent`. Ignore |
| 98 | /// files that are symlinks, unreadable, or not UTF-8 lines are skipped. |
| 99 | pub(crate) fn enter(dir: &Dir, path: &[u8], parent: &Chain, files: &IgnoreFiles<'_>) -> Chain { |
| 100 | let mut matchers = Vec::new(); |
| 101 | let mut hasher = IdHasher::new(Kind::Derived); |
| 102 | hasher.update(&digest(parent).to_le_bytes()); |
| 103 | for (index, name) in files.iter().enumerate() { |
| 104 | let Some(os) = name.and_then(os_name) else { |
| 105 | continue; |
| 106 | }; |
| 107 | let Ok(mut file) = open_file(dir, os) else { |
| 108 | continue; |
| 109 | }; |
| 110 | let mut text = Vec::new(); |
| 111 | if file.read_to_end(&mut text).is_err() { |
| 112 | continue; |
| 113 | } |
| 114 | hasher.update(&[index as u8]); |
| 115 | hasher.update(&(text.len() as u64).to_le_bytes()); |
| 116 | hasher.update(&text); |
| 117 | let mut builder = GitignoreBuilder::new("."); |
| 118 | for line in text.split(|byte| *byte == b'\n') { |
| 119 | if let Ok(line) = std::str::from_utf8(line) { |
| 120 | // A pattern that does not parse is left out, as git does. |
| 121 | let _ = builder.add_line(None, line.trim_end_matches('\r')); |
| 122 | } |
| 123 | } |
| 124 | if let Ok(matcher) = builder.build() |
| 125 | && !matcher.is_empty() |
| 126 | { |
| 127 | matchers.push(matcher); |
| 128 | } |
| 129 | } |
| 130 | if matchers.is_empty() { |
| 131 | return parent.clone(); |
| 132 | } |
| 133 | let id = hasher.finalize(); |
| 134 | let mut digest = [0u8; 8]; |
| 135 | digest.copy_from_slice(&id.as_bytes()[..8]); |
| 136 | Some(Arc::new(Rules { |
| 137 | dir: path.to_vec(), |
| 138 | matchers, |
| 139 | parent: parent.clone(), |
| 140 | digest: u64::from_le_bytes(digest), |
| 141 | })) |
| 142 | } |
| 143 | |
| 144 | /// Whether the rules ignore `path`, a directory if `is_dir`. |
| 145 | pub(crate) fn is_ignored(chain: &Chain, path: &[u8], is_dir: bool) -> bool { |
| 146 | let mut rules = chain.as_deref(); |
| 147 | while let Some(current) = rules { |
| 148 | let skip = if current.dir.is_empty() { |
| 149 | 0 |
| 150 | } else { |
| 151 | current.dir.len() + 1 |
| 152 | }; |
| 153 | if let Some(relative) = path.get(skip..).and_then(os_name) { |
| 154 | for matcher in ¤t.matchers { |
| 155 | match matcher.matched(relative, is_dir) { |
| 156 | Match::Ignore(_) => return true, |
| 157 | Match::Whitelist(_) => return false, |
| 158 | Match::None => {} |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | rules = current.parent.as_deref(); |
| 163 | } |
| 164 | false |
| 165 | } |
| 166 | |
| 167 | #[cfg(test)] |
| 168 | mod tests { |
| 169 | use super::*; |
| 170 | |
| 171 | fn dir(path: &std::path::Path) -> Dir { |
| 172 | Dir::open_ambient_dir(path, cap_std::ambient_authority()).unwrap() |
| 173 | } |
| 174 | |
| 175 | const BOTH: IgnoreFiles<'static> = [Some(b".braidignore"), Some(b".gitignore")]; |
| 176 | const GIT: IgnoreFiles<'static> = [None, Some(b".gitignore")]; |
| 177 | |
| 178 | #[test] |
| 179 | fn rules_nest_and_negate() { |
| 180 | let temp = tempfile::tempdir().unwrap(); |
| 181 | std::fs::write(temp.path().join(".gitignore"), "*.log\nbuild/\n/top.txt\n").unwrap(); |
| 182 | std::fs::create_dir(temp.path().join("sub")).unwrap(); |
| 183 | std::fs::write(temp.path().join("sub/.gitignore"), "!keep.log\n").unwrap(); |
| 184 | std::fs::write(temp.path().join("sub/.braidignore"), "secret\n").unwrap(); |
| 185 | |
| 186 | let root = enter(&dir(temp.path()), b"", &None, &GIT); |
| 187 | assert!(is_ignored(&root, b"a.log", false)); |
| 188 | assert!(is_ignored(&root, b"build", true)); |
| 189 | assert!(!is_ignored(&root, b"build", false)); |
| 190 | assert!(is_ignored(&root, b"top.txt", false)); |
| 191 | assert!(!is_ignored(&root, b"sub/top.txt", false)); |
| 192 | assert!(!is_ignored(&root, b"a.txt", false)); |
| 193 | |
| 194 | let sub = enter(&dir(&temp.path().join("sub")), b"sub", &root, &BOTH); |
| 195 | assert!(is_ignored(&sub, b"sub/x.log", false)); |
| 196 | assert!(!is_ignored(&sub, b"sub/keep.log", false)); |
| 197 | assert!(is_ignored(&sub, b"sub/secret", false)); |
| 198 | // Directories without ignore files share their parent's rules. |
| 199 | std::fs::create_dir(temp.path().join("plain")).unwrap(); |
| 200 | let plain = enter( |
| 201 | &dir(&temp.path().join("plain")), |
| 202 | b"plain", |
| 203 | &root, |
| 204 | &[None, None], |
| 205 | ); |
| 206 | assert!(Arc::ptr_eq(plain.as_ref().unwrap(), root.as_ref().unwrap())); |
| 207 | |
| 208 | // The digest follows the files' content, and the rules above. |
| 209 | assert_eq!(digest(&None), 0); |
| 210 | assert_ne!(digest(&root), digest(&sub)); |
| 211 | let again = enter(&dir(temp.path()), b"", &None, &GIT); |
| 212 | assert_eq!(digest(&again), digest(&root)); |
| 213 | std::fs::write(temp.path().join(".gitignore"), "*.log\n").unwrap(); |
| 214 | let edited = enter(&dir(temp.path()), b"", &None, &GIT); |
| 215 | assert_ne!(digest(&edited), digest(&root)); |
| 216 | let below = enter(&dir(&temp.path().join("sub")), b"sub", &edited, &BOTH); |
| 217 | assert_ne!(digest(&below), digest(&sub)); |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn ignore_files_are_found_in_the_listing() { |
| 222 | let exact = FileSystem::default(); |
| 223 | let names: [&[u8]; 4] = [b".gitignore", b"a.txt", b".braidignore", b".GITIGNORE"]; |
| 224 | assert_eq!(ignore_files(exact, names.into_iter()), BOTH); |
| 225 | let only: [&[u8]; 2] = [b"x", b".GitIgnore"]; |
| 226 | assert_eq!(ignore_files(exact, only.into_iter()), [None, None]); |
| 227 | // Where case is ignored, the file is found under any case, as an |
| 228 | // open by its name would find it. |
| 229 | assert_eq!( |
| 230 | ignore_files(FileSystem::FORGIVING, only.into_iter()), |
| 231 | [None, Some(&b".GitIgnore"[..])] |
| 232 | ); |
| 233 | for files in [BOTH, GIT, [None, None], [Some(&b".braidignore"[..]), None]] { |
| 234 | assert_eq!(from_bits(bits(&files)), files); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | #[cfg(unix)] |
| 239 | #[test] |
| 240 | fn symlinked_ignore_files_are_not_read() { |
| 241 | let temp = tempfile::tempdir().unwrap(); |
| 242 | let outside = tempfile::tempdir().unwrap(); |
| 243 | std::fs::write(outside.path().join("rules"), "*\n").unwrap(); |
| 244 | std::os::unix::fs::symlink(outside.path().join("rules"), temp.path().join(".gitignore")) |
| 245 | .unwrap(); |
| 246 | let root = enter(&dir(temp.path()), b"", &None, &GIT); |
| 247 | assert!(!is_ignored(&root, b"anything", false)); |
| 248 | } |
| 249 | } |