blockwatch 0.5.3

Language agnostic linter that keeps your code and documentation in sync and valid
Documentation
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
413
414
415
416
417
418
use crate::repo_path::RepoPath;
use anyhow::{Context, anyhow};
use globset::GlobSet;
use ignore::WalkBuilder;
use std::path::{Path, PathBuf};

/// Directory names a version control system keeps its own state in.
///
/// A superset of the markers that identify a repository root.
// <block name="vcs-metadata-directories">
const VCS_METADATA_DIRECTORY_NAMES: [&str; 4] = [".git", ".hg", ".jj", ".svn"];
// </block>

/// Every read the program performs, behind a trait.
///
/// `Send + Sync` so an `Arc<Fs>` can be shared into validator threads (std::thread and Tokio).
pub trait FileSystem: Send + Sync {
    /// Reads the entire contents of a file into a string.
    fn read_to_string(&self, path: &Path) -> anyhow::Result<String>;

    /// Whether a readable file exists at `path` inside the repository.
    fn exists(&self, path: &Path) -> bool;

    /// Walks the directory tree rooted at the file system's root path, returning an iterator over the paths of all files.
    fn walk(&self) -> impl Iterator<Item = anyhow::Result<RepoPath>>;
}

/// Checks whether a path should be allowed or ignored when parsing blocks from files.
pub trait PathChecker {
    /// Whether the given `path` should be explicitly allowed.
    fn should_allow(&self, path: &Path) -> bool;

    /// Whether the given `path` should be explicitly ignored.
    fn should_ignore(&self, path: &Path) -> bool;
}

/// The real filesystem, confined to one VCS repository.
///
/// Block attributes name other files (`affects="docs/cli.md:intro"`, `check-lua="scripts/x.lua"`),
/// and those names come from the files being linted. Routing every read through this type means a
/// crafted attribute cannot make the linter read outside the repository.
pub struct FileSystemImpl {
    /// The repository root, canonicalized so that containment checks compare like with like.
    root_path: PathBuf,
}

impl FileSystemImpl {
    /// Creates a reader confined to `root_path`, which must name an existing directory.
    ///
    /// The root is canonicalized here so every later resolution can compare against it directly.
    pub fn new(root_path: &Path) -> anyhow::Result<Self> {
        let root_path = std::fs::canonicalize(root_path).with_context(|| {
            format!(
                "failed to canonicalize repository root: {}",
                root_path.display()
            )
        })?;
        Ok(Self { root_path })
    }

    /// Resolves `path` against the repository root and guarantees the result stays inside it.
    ///
    /// Relative paths are joined to `root_path`; absolute paths are used as-is. Both the candidate
    /// and the root are canonicalized (resolving symlinks and `..`), and the canonical candidate
    /// must remain within the canonical root. This confines every read to the repository, rejecting
    /// `..` traversal, absolute escapes, and symlinks that resolve outside the root — so callers
    /// (e.g. the `check-lua` script path or a cross-file validator's target) get containment for
    /// free without re-implementing the check.
    fn resolve_within_root(&self, path: &Path) -> anyhow::Result<PathBuf> {
        let candidate = if path.is_absolute() {
            path.to_path_buf()
        } else {
            self.root_path.join(path)
        };
        let canonical = std::fs::canonicalize(&candidate)
            .with_context(|| format!("failed to canonicalize path \"{}\"", path.display()))?;
        if !canonical.starts_with(&self.root_path) {
            return Err(anyhow!(
                "path \"{}\" resolves to \"{}\" which is outside the repository root \"{}\"",
                path.display(),
                canonical.display(),
                self.root_path.display(),
            ));
        }
        Ok(canonical)
    }
}

impl FileSystem for FileSystemImpl {
    fn read_to_string(&self, path: &Path) -> anyhow::Result<String> {
        let resolved = self.resolve_within_root(path)?;
        std::fs::read_to_string(&resolved)
            .with_context(|| format!("Failed to read file \"{}\"", path.display()))
    }

    fn exists(&self, path: &Path) -> bool {
        // `resolve_within_root` fails for a missing path as well as for one escaping the root;
        // both mean "not a file this run may read".
        self.resolve_within_root(path)
            .is_ok_and(|resolved| resolved.is_file())
    }

    fn walk(&self) -> impl Iterator<Item = anyhow::Result<RepoPath>> {
        // Clone root_path for the closure.
        let root_path = self.root_path.clone();
        WalkBuilder::new(&self.root_path)
            // Hidden files should not be ignored as e.g. `.github` directory should be scanned.
            .hidden(false)
            .filter_entry(|entry| {
                !entry
                    .file_name()
                    .to_str()
                    .is_some_and(|name| VCS_METADATA_DIRECTORY_NAMES.contains(&name))
            })
            .build()
            .filter_map(move |entry| match entry {
                Ok(entry) => {
                    let path = entry.path();
                    if path.is_dir() {
                        return None;
                    }
                    // Relative to the root. A name that is not valid UTF-8 cannot be written in a
                    // glob or a block reference, so it is skipped rather than failing the run.
                    let relative_path = path.strip_prefix(&root_path).unwrap_or(path);
                    RepoPath::from_relative(relative_path).ok().map(Ok)
                }
                Err(err) => Some(Err(anyhow::Error::from(err))),
            })
    }
}

/// Checks whether a path should be allowed or ignored.
pub struct PathCheckerImpl {
    glob_set: GlobSet,
    ignored_glob_set: GlobSet,
}

impl PathCheckerImpl {
    /// Builds a checker from the compiled globs of the positional file filters and of `--ignore`.
    ///
    /// An empty `glob_set` matches nothing, so callers treat "no filters given" as "every file" on
    /// their own rather than relying on this type.
    pub fn new(glob_set: GlobSet, ignored_glob_set: GlobSet) -> Self {
        Self {
            glob_set,
            ignored_glob_set,
        }
    }
}

impl PathChecker for PathCheckerImpl {
    fn should_allow(&self, path: &Path) -> bool {
        self.glob_set.is_match(path)
    }

    fn should_ignore(&self, path: &Path) -> bool {
        self.ignored_glob_set.is_match(path)
    }
}

#[cfg(test)]
mod file_system_impl_tests {
    use crate::fs::{FileSystem, FileSystemImpl};
    use std::path::{Path, PathBuf};

    /// Writes `content` to `name` inside a fresh temp dir that doubles as the repository root.
    /// Returns the held temp dir (kept alive for the test) and the file's absolute path.
    fn root_with_file(name: &str, content: &str) -> (tempfile::TempDir, PathBuf) {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join(name);
        std::fs::write(&path, content).unwrap();
        (root, path)
    }

    /// Writes `content` to `relative_path` below `root`, creating the intermediate directories.
    fn write_file(root: &Path, relative_path: &str, content: &str) {
        let path = root.join(relative_path);
        std::fs::create_dir_all(path.parent().expect("a file path has a parent")).unwrap();
        std::fs::write(&path, content).unwrap();
    }

    /// The paths [`FileSystem::walk`] yields, relative to the root and sorted for comparison.
    fn walked_paths(file_system: &FileSystemImpl) -> anyhow::Result<Vec<String>> {
        let mut paths = file_system
            .walk()
            .map(|path| path.map(|path| path.as_str().to_owned()))
            .collect::<anyhow::Result<Vec<_>>>()?;
        paths.sort();
        Ok(paths)
    }

    #[test]
    fn walk_yields_files_inside_hidden_directories() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        write_file(root.path(), ".github/workflows/ci.yml", "name: CI");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(walked_paths(&file_system)?, [".github/workflows/ci.yml"]);
        Ok(())
    }

    #[test]
    fn walk_yields_hidden_files() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        write_file(root.path(), ".eslintrc.yml", "root: true");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(walked_paths(&file_system)?, [".eslintrc.yml"]);
        Ok(())
    }

    #[test]
    fn walk_skips_version_control_metadata_directories() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        for marker in [".git", ".hg", ".jj", ".svn"] {
            write_file(root.path(), &format!("{marker}/config.yml"), "internal");
        }
        write_file(root.path(), "src/main.yml", "name: app");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(walked_paths(&file_system)?, ["src/main.yml"]);
        Ok(())
    }

    #[test]
    fn walk_skips_version_control_metadata_directories_below_the_root() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        write_file(root.path(), "vendor/dep/.git/config.yml", "internal");
        write_file(root.path(), "vendor/dep/main.yml", "name: dep");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(walked_paths(&file_system)?, ["vendor/dep/main.yml"]);
        Ok(())
    }

    #[test]
    fn read_to_string_reads_relative_path_inside_root() -> anyhow::Result<()> {
        let (root, _path) = root_with_file("a.txt", "hello");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(file_system.read_to_string(Path::new("a.txt"))?, "hello");
        Ok(())
    }

    #[test]
    fn read_to_string_reads_absolute_path_inside_root() -> anyhow::Result<()> {
        let (root, abs_path) = root_with_file("a.txt", "hello");
        let file_system = FileSystemImpl::new(root.path())?;

        assert_eq!(file_system.read_to_string(&abs_path)?, "hello");
        Ok(())
    }

    #[test]
    fn read_to_string_rejects_absolute_path_outside_root() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        // A file that exists and is readable, but lives outside the repository root.
        let (_outside_root, outside) = root_with_file("secret.txt", "secret");
        let file_system = FileSystemImpl::new(root.path())?;

        let err = file_system.read_to_string(&outside).unwrap_err();

        assert!(
            format!("{err:#}").contains("outside the repository root"),
            "unexpected error: {err:#}"
        );
        Ok(())
    }

    #[test]
    fn read_to_string_rejects_relative_path_escaping_root() -> anyhow::Result<()> {
        let parent = tempfile::tempdir()?;
        std::fs::write(parent.path().join("evil.txt"), "evil")?;
        let root = parent.path().join("repo");
        std::fs::create_dir(&root)?;
        let file_system = FileSystemImpl::new(&root)?;

        let err = file_system
            .read_to_string(Path::new("../evil.txt"))
            .unwrap_err();

        assert!(
            format!("{err:#}").contains("outside the repository root"),
            "unexpected error: {err:#}"
        );
        Ok(())
    }

    #[test]
    fn read_to_string_rejects_missing_path() -> anyhow::Result<()> {
        let root = tempfile::tempdir()?;
        let file_system = FileSystemImpl::new(root.path())?;

        let err = file_system
            .read_to_string(Path::new("does_not_exist.txt"))
            .unwrap_err();

        assert!(
            format!("{err:#}").contains("failed to canonicalize path"),
            "unexpected error: {err:#}"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn read_to_string_rejects_symlink_escaping_root() -> anyhow::Result<()> {
        let parent = tempfile::tempdir()?;
        std::fs::write(parent.path().join("secret.txt"), "secret")?;
        let root = parent.path().join("repo");
        std::fs::create_dir(&root)?;
        std::os::unix::fs::symlink(parent.path().join("secret.txt"), root.join("link.txt"))?;
        let file_system = FileSystemImpl::new(&root)?;

        let err = file_system
            .read_to_string(Path::new("link.txt"))
            .unwrap_err();

        assert!(
            format!("{err:#}").contains("outside the repository root"),
            "unexpected error: {err:#}"
        );
        Ok(())
    }
}

/// In-memory stand-ins for [`FileSystem`] and [`PathChecker`], so unit tests can describe a source
/// tree as a map of strings instead of creating temporary directories.
#[cfg(test)]
pub mod test_utils {
    use crate::fs::{FileSystem, PathChecker};
    use crate::repo_path::RepoPath;
    use globset::GlobSet;
    use std::collections::{HashMap, HashSet};
    use std::path::Path;

    /// A source tree held in memory, keyed by path exactly as it is spelled by the caller.
    ///
    /// Unlike [`super::FileSystemImpl`] it enforces no root confinement, so tests that care about
    /// containment must exercise the real implementation.
    pub(crate) struct FakeFileSystem {
        files: HashMap<String, String>,
    }

    impl FakeFileSystem {
        /// Creates a fake tree from a path -> contents map.
        pub(crate) fn new(files: HashMap<String, String>) -> Self {
            Self { files }
        }
    }

    impl FileSystem for FakeFileSystem {
        fn read_to_string(&self, path: &Path) -> anyhow::Result<String> {
            // Mirror a real filesystem: a missing file is an error, not a panic. This lets
            // validators' read-failure paths be exercised with the fake.
            self.files
                .get(&path.display().to_string())
                .cloned()
                .ok_or_else(|| anyhow::anyhow!("File {} not found", path.display()))
        }

        fn exists(&self, path: &Path) -> bool {
            self.files.contains_key(&path.display().to_string())
        }

        fn walk(&self) -> impl Iterator<Item = anyhow::Result<RepoPath>> {
            self.files.keys().map(|path| RepoPath::from_reference(path))
        }
    }

    /// A path filter for tests: an explicit deny list, so a file can be excluded without writing
    /// glob patterns, plus an optional allow-list of globs for the tests that are about globbing.
    pub(crate) struct FakePathChecker {
        /// The globs a path must match to be allowed. `None` allows every path, which is what most
        /// tests want; `Some` mirrors the real checker, whose empty glob set matches nothing.
        allowed_globs: Option<GlobSet>,
        ignored_paths: HashSet<String>,
    }

    impl FakePathChecker {
        /// Allows every path except those listed.
        pub(crate) fn with_ignored_paths(ignored_paths: HashSet<String>) -> Self {
            Self {
                allowed_globs: None,
                ignored_paths,
            }
        }

        /// Allows every path — the default for tests that are not about filtering.
        pub(crate) fn allow_all() -> Self {
            Self::with_ignored_paths(HashSet::new())
        }

        /// Allows only the paths matching `glob`.
        pub(crate) fn allow_only(glob: &str) -> Self {
            let glob_set = GlobSet::builder()
                .add(globset::Glob::new(glob).expect("malformed test glob"))
                .build()
                .expect("failed to build test glob set");
            Self {
                allowed_globs: Some(glob_set),
                ignored_paths: HashSet::new(),
            }
        }
    }

    impl PathChecker for FakePathChecker {
        fn should_allow(&self, path: &Path) -> bool {
            self.allowed_globs
                .as_ref()
                .is_none_or(|globs| globs.is_match(path))
        }

        fn should_ignore(&self, path: &Path) -> bool {
            self.ignored_paths.contains(&path.display().to_string())
        }
    }
}