diffler-core 0.20.0

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Which bucket a changed file belongs to, from its path alone. Rule order
//! matters: Generated outranks Tests so a generated fixture reads as noise,
//! and Build outranks Config so `Cargo.toml` reads as a manifest.

use std::path::Path;

use crate::syntax::registry::REGISTRY;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Kind {
    Source,
    Tests,
    Docs,
    Config,
    Build,
    Generated,
    Assets,
    Other,
}

impl Kind {
    /// Sidebar display order.
    pub const ALL: [Self; 8] = [
        Self::Source,
        Self::Tests,
        Self::Docs,
        Self::Config,
        Self::Build,
        Self::Generated,
        Self::Assets,
        Self::Other,
    ];

    pub fn label(self) -> &'static str {
        match self {
            Self::Source => "Source",
            Self::Tests => "Tests",
            Self::Docs => "Docs",
            Self::Config => "Config",
            Self::Build => "Build & CI",
            Self::Generated => "Generated",
            Self::Assets => "Assets",
            Self::Other => "Other",
        }
    }
}

/// The reader's globs, then git's `linguist-*` attributes, then the built-in
/// table.
#[derive(Debug, Clone, Default)]
pub struct Rules {
    overrides: Vec<(Kind, Vec<String>)>,
}

impl Rules {
    pub fn new(overrides: Vec<(Kind, Vec<String>)>) -> Self {
        Self { overrides }
    }

    /// `declared` is what git's `linguist-*` attributes say.
    pub fn kind(&self, path: &str, declared: Option<Kind>) -> Kind {
        for (kind, patterns) in &self.overrides {
            if patterns.iter().any(|pattern| glob_match(pattern, path)) {
                return *kind;
            }
        }
        declared.unwrap_or_else(|| classify(path))
    }
}

/// The bucket the `linguist-*` git attributes declare. Vendored code counts
/// as Generated.
pub fn declared(attr: impl Fn(&str) -> bool) -> Option<Kind> {
    if attr("linguist-generated") || attr("linguist-vendored") {
        Some(Kind::Generated)
    } else if attr("linguist-documentation") {
        Some(Kind::Docs)
    } else {
        None
    }
}

/// The built-in table: first match wins.
pub fn classify(path: &str) -> Kind {
    let lower = path.to_ascii_lowercase();
    let name = basename(&lower);
    let ext = extension(name);
    if generated(&lower, name, ext) {
        Kind::Generated
    } else if tests(&lower, name, ext, basename(path)) {
        Kind::Tests
    } else if build(&lower, name, ext) {
        Kind::Build
    } else if docs(&lower, name, ext) {
        Kind::Docs
    } else if config(name, ext) {
        Kind::Config
    } else if ASSET_EXTENSIONS.contains(&ext) {
        Kind::Assets
    } else if source(path, ext) {
        Kind::Source
    } else {
        Kind::Other
    }
}

fn basename(path: &str) -> &str {
    path.rsplit('/').next().unwrap_or(path)
}

/// Extension without the dot; `.gitignore` has none.
fn extension(name: &str) -> &str {
    Path::new(name)
        .extension()
        .and_then(std::ffi::OsStr::to_str)
        .unwrap_or_default()
}

fn segments(path: &str) -> impl Iterator<Item = &str> {
    path.split('/')
}

fn has_segment(path: &str, wanted: &[&str]) -> bool {
    segments(path).any(|segment| wanted.contains(&segment))
}

const GENERATED_DIRS: &[&str] = &[
    "node_modules",
    "vendor",
    "third_party",
    "bower_components",
    "pods",
    "godeps",
    "__generated__",
    "__pycache__",
    "generated",
    "dist",
    "target",
    "htmlcov",
    ".sqlx",
    ".yarn",
    ".terraform",
];

const GENERATED_SUFFIXES: &[&str] = &[
    ".min.js",
    ".min.css",
    ".pb.go",
    ".pb.cc",
    ".pb.h",
    "_pb2.py",
    "_pb2_grpc.py",
    "_generated.go",
    ".generated.cs",
    ".designer.cs",
    ".g.dart",
    ".freezed.dart",
    ".snap",
    ".map",
];

const GENERATED_FILES: &[&str] = &[
    "go.sum",
    "package.resolved",
    "npm-shrinkwrap.json",
    "packages.lock.json",
];

fn lockfile(name: &str, ext: &str) -> bool {
    matches!(ext, "lock" | "lockb") || name.contains("-lock.") || name.contains(".lock.")
}

fn generated(path: &str, name: &str, ext: &str) -> bool {
    has_segment(path, GENERATED_DIRS)
        || lockfile(name, ext)
        || GENERATED_FILES.contains(&name)
        || GENERATED_SUFFIXES
            .iter()
            .any(|suffix| name.ends_with(suffix))
}

const TEST_DIRS: &[&str] = &[
    "test",
    "tests",
    "spec",
    "specs",
    "__tests__",
    "__mocks__",
    "testdata",
    "e2e",
    "cypress",
];

/// Matched against the lowercased stem. The separator is part of the affix so
/// `latest.rs` and `protest.rs` stay source.
const TEST_AFFIXES: &[&str] = &["_test", "_tests", "_spec", "-test", ".test", ".spec"];

/// Matched against the original-case stem, since lowercasing loses the hump
/// that separates `UserTest` from `latest`.
const TEST_CAMEL_AFFIXES: &[&str] = &["Test", "Tests"];

/// `FooSpec` is a test only in scalatest; elsewhere it names an API contract
/// like `OpenApiSpec.ts`.
const SPEC_EXTENSIONS: &[&str] = &["scala", "kt", "groovy"];

fn stem<'a>(name: &'a str, ext: &str) -> &'a str {
    name.strip_suffix(ext)
        .map_or(name, |rest| rest.trim_end_matches('.'))
}

fn tests(path: &str, name: &str, ext: &str, raw_name: &str) -> bool {
    if has_segment(path, TEST_DIRS) {
        return true;
    }
    let lower_stem = stem(name, ext);
    if lower_stem == "test" || lower_stem == "conftest" || lower_stem.starts_with("test_") {
        return true;
    }
    if TEST_AFFIXES.iter().any(|affix| lower_stem.ends_with(affix)) {
        return true;
    }
    let raw_stem = stem(raw_name, extension(raw_name));
    TEST_CAMEL_AFFIXES
        .iter()
        .any(|affix| raw_stem.ends_with(affix))
        || (SPEC_EXTENSIONS.contains(&ext) && raw_stem.ends_with("Spec"))
}

const CI_DIRS: &[&str] = &[".github", ".gitlab", ".forgejo", ".gitea", ".circleci"];

const BUILD_FILES: &[&str] = &[
    "cargo.toml",
    "package.json",
    "go.mod",
    "pyproject.toml",
    "setup.py",
    "setup.cfg",
    "gemfile",
    "rakefile",
    "pom.xml",
    "build.gradle",
    "build.gradle.kts",
    "settings.gradle",
    "cmakelists.txt",
    "makefile",
    "gnumakefile",
    "justfile",
    "meson.build",
    "build",
    "build.bazel",
    "workspace",
    "mix.exs",
    "build.rs",
    "jenkinsfile",
    "flake.nix",
    "shell.nix",
    "default.nix",
    "procfile",
    "taskfile.yml",
    ".gitlab-ci.yml",
    ".travis.yml",
    "azure-pipelines.yml",
];

fn build(path: &str, name: &str, ext: &str) -> bool {
    has_segment(path, CI_DIRS)
        || BUILD_FILES.contains(&name)
        || name.starts_with("dockerfile")
        || name.starts_with("docker-compose.")
        || name.starts_with("requirements") && ext == "txt"
        || ext == "nix"
}

const DOC_DIRS: &[&str] = &["docs", "doc", "man"];

const DOC_EXTENSIONS: &[&str] = &["md", "mdx", "rst", "adoc", "org", "txt", "1"];

/// Matched only without an extension, so `src/security.rs` stays source.
pub(crate) const DOC_NAMES: &[&str] = &[
    "readme",
    "license",
    "licence",
    "copying",
    "changelog",
    "contributing",
    "authors",
    "notice",
    "security",
];

fn docs(path: &str, name: &str, ext: &str) -> bool {
    has_segment(path, DOC_DIRS)
        || DOC_EXTENSIONS.contains(&ext)
        || (ext.is_empty()
            && DOC_NAMES
                .iter()
                .any(|stem| name == *stem || name.starts_with(&format!("{stem}-"))))
}

const CONFIG_EXTENSIONS: &[&str] = &[
    "toml",
    "yaml",
    "yml",
    "json",
    "json5",
    "jsonc",
    "ini",
    "cfg",
    "conf",
    "properties",
    "env",
    "xml",
    "plist",
];

fn config(name: &str, ext: &str) -> bool {
    CONFIG_EXTENSIONS.contains(&ext) || (name.starts_with('.') && ext.is_empty())
}

const ASSET_EXTENSIONS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "svg", "ico", "webp", "avif", "bmp", "tiff", "woff", "woff2",
    "ttf", "otf", "eot", "mp3", "mp4", "wav", "ogg", "webm", "mov", "pdf", "zip", "gz", "tar",
    "bz2", "xz", "7z",
];

/// Source languages the bundled grammars lack, so they stay out of Other.
const SOURCE_EXTENSIONS: &[&str] = &[
    "kt", "kts", "pl", "pm", "r", "jl", "erl", "hrl", "clj", "cljs", "cljc", "fs", "fsi", "fsx",
    "vb", "groovy", "proto", "graphql", "gql", "vue", "astro", "scss", "sass", "less", "styl",
    "coffee", "mm", "sol", "v", "vhd", "tcl", "f90",
];

fn source(path: &str, ext: &str) -> bool {
    SOURCE_EXTENSIONS.contains(&ext) || REGISTRY.for_path(path).is_some()
}

/// Gitignore-flavoured glob: `*` and `?` stay inside one segment, `**` spans
/// any number, a pattern with no `/` matches the basename at any depth, a
/// leading `/` anchors, and a trailing `/` names a subtree.
pub(crate) fn glob_match(pattern: &str, path: &str) -> bool {
    let pattern = pattern.trim_start_matches("./");
    if let Some(dir) = pattern.strip_suffix('/') {
        return glob_match(&format!("{dir}/**"), path);
    }
    let anchored = pattern.starts_with('/');
    let pattern = pattern.trim_start_matches('/');
    if anchored || pattern.contains('/') {
        let pattern: Vec<&str> = segments(pattern).collect();
        let path: Vec<&str> = segments(path).collect();
        match_segments(&pattern, &path)
    } else {
        match_segment(pattern, basename(path))
    }
}

fn match_segments(pattern: &[&str], path: &[&str]) -> bool {
    let Some((head, rest)) = pattern.split_first() else {
        return path.is_empty();
    };
    if *head == "**" {
        return (0..=path.len()).any(|skip| {
            path.get(skip..)
                .is_some_and(|tail| match_segments(rest, tail))
        });
    }
    match path.split_first() {
        Some((segment, tail)) if match_segment(head, segment) => match_segments(rest, tail),
        _ => false,
    }
}

/// Wildcard match within one segment, backtracking on `*` so `a*b*c` behaves.
fn match_segment(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    let (mut p, mut t) = (0usize, 0usize);
    let (mut star, mut retry) = (None, 0usize);
    while t < text.len() {
        match pattern.get(p) {
            Some('*') => {
                star = Some(p);
                retry = t;
                p += 1;
            }
            Some('?') => {
                p += 1;
                t += 1;
            }
            Some(c) if Some(c) == text.get(t) => {
                p += 1;
                t += 1;
            }
            _ => match star {
                Some(at) => {
                    p = at + 1;
                    retry += 1;
                    t = retry;
                }
                None => return false,
            },
        }
    }
    pattern
        .get(p..)
        .is_none_or(|rest| rest.iter().all(|c| *c == '*'))
}

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

    #[track_caller]
    fn assert_kind(path: &str, expected: Kind) {
        assert_eq!(classify(path), expected, "{path}");
    }

    #[test]
    fn code_lands_in_source() {
        assert_kind("crates/diffler/src/ui/diff.rs", Kind::Source);
        assert_kind("app/main.py", Kind::Source);
        assert_kind("web/src/App.tsx", Kind::Source);
        assert_kind("cmd/server/main.go", Kind::Source);
        assert_kind("android/Main.kt", Kind::Source);
        assert_kind("api/schema.proto", Kind::Source);
        assert_kind("web/styles/app.scss", Kind::Source);
    }

    #[test]
    fn every_language_convention_for_a_test_is_recognised() {
        for path in [
            "tests/e2e/test_status.py",
            "src/foo_test.go",
            "src/foo_test.rs",
            "web/src/App.test.tsx",
            "web/src/App.spec.ts",
            "src/UserTest.java",
            "src/UserTests.cs",
            "spec/models/user_spec.rb",
            "test/support/helper.ex",
            "testdata/golden.json",
            "conftest.py",
            "cypress/e2e/login.cy.js",
        ] {
            assert_kind(path, Kind::Tests);
        }
    }

    #[test]
    fn a_word_that_ends_in_test_is_not_a_test() {
        assert_kind("src/latest.rs", Kind::Source);
        assert_kind("src/protest.rs", Kind::Source);
        assert_kind("src/contests.rs", Kind::Source);
        assert_kind("src/manifest.rs", Kind::Source);
        assert_kind("web/src/OpenApiSpec.ts", Kind::Source);
        assert_kind("src/main/scala/UserSpec.scala", Kind::Tests);
    }

    #[test]
    fn a_source_file_named_like_a_doc_stays_source() {
        assert_kind("src/security.rs", Kind::Source);
        assert_kind("app/models/license.rb", Kind::Source);
        assert_kind("pkg/changelog.go", Kind::Source);
        assert_kind("LICENSE-MIT", Kind::Docs);
        assert_kind("AUTHORS", Kind::Docs);
    }

    #[test]
    fn generated_output_and_lockfiles_are_one_bucket() {
        for path in [
            "Cargo.lock",
            "pnpm-lock.yaml",
            "go.sum",
            "node_modules/left-pad/index.js",
            "vendor/github.com/pkg/errors/errors.go",
            "api/service.pb.go",
            "api/service_pb2.py",
            "web/dist/bundle.min.js",
            "crates/diffler/src/ui/snapshots/a_pane.snap",
            "target/debug/build.rs",
        ] {
            assert_kind(path, Kind::Generated);
        }
    }

    #[test]
    fn generated_outranks_tests_so_a_snapshot_is_not_a_test() {
        assert_kind("tests/snapshots/render.snap", Kind::Generated);
        assert_kind("tests/fixtures/node_modules/dep/index.js", Kind::Generated);
    }

    #[test]
    fn manifests_and_pipelines_are_build() {
        for path in [
            "Cargo.toml",
            "package.json",
            "go.mod",
            "pyproject.toml",
            "Makefile",
            "justfile",
            "Dockerfile",
            "docker-compose.yml",
            ".github/workflows/ci.yml",
            ".forgejo/workflows/ci.yml",
            ".gitlab-ci.yml",
            "flake.nix",
            "requirements.txt",
            "crates/diffler/build.rs",
        ] {
            assert_kind(path, Kind::Build);
        }
    }

    #[test]
    fn prose_is_docs_wherever_it_sits() {
        assert_kind("README.md", Kind::Docs);
        assert_kind("LICENSE", Kind::Docs);
        assert_kind("CHANGELOG.md", Kind::Docs);
        assert_kind("docs/config.example.toml", Kind::Docs);
        assert_kind("notes/design.rst", Kind::Docs);
    }

    #[test]
    fn settings_are_config_and_binaries_are_assets() {
        assert_kind(".diffler/config.toml", Kind::Config);
        assert_kind(".gitignore", Kind::Config);
        assert_kind("tsconfig.json", Kind::Config);
        assert_kind("assets/demo.gif", Kind::Assets);
        assert_kind("showcase/img/theme.png", Kind::Assets);
    }

    #[test]
    fn an_unreadable_extension_falls_through_to_other() {
        assert_kind("data/model.bin", Kind::Other);
        assert_kind("weird", Kind::Other);
    }

    #[test]
    fn a_reader_glob_outranks_the_table_and_the_repo() {
        let rules = Rules::new(vec![
            (Kind::Tests, vec!["e2e/**".to_owned()]),
            (
                Kind::Docs,
                vec!["notes/**".to_owned(), "*_note.rs".to_owned()],
            ),
        ]);
        assert_eq!(rules.kind("e2e/harness.rs", None), Kind::Tests);
        assert_eq!(rules.kind("notes/plan.rs", None), Kind::Docs);
        assert_eq!(rules.kind("src/a_note.rs", None), Kind::Docs);
        assert_eq!(rules.kind("src/lib.rs", None), Kind::Source);
        assert_eq!(
            rules.kind("e2e/harness.rs", Some(Kind::Generated)),
            Kind::Tests,
            "the reader's own globs win over the repo's attributes"
        );
    }

    #[test]
    fn the_repo_attributes_outrank_the_table() {
        let rules = Rules::default();
        assert_eq!(
            rules.kind("src/lib.rs", Some(Kind::Generated)),
            Kind::Generated
        );
        assert_eq!(rules.kind("src/lib.rs", None), Kind::Source);
    }

    #[test]
    fn globs_respect_segment_boundaries() {
        assert!(glob_match("src/*.rs", "src/lib.rs"));
        assert!(!glob_match("src/*.rs", "src/app/lib.rs"));
        assert!(glob_match("src/**/*.rs", "src/app/diff/lib.rs"));
        assert!(glob_match("src/**", "src/a/b/c.rs"));
        assert!(glob_match("src/**", "src"));
        assert!(glob_match("*.rs", "deep/nested/lib.rs"));
        assert!(!glob_match("*.rs", "deep/lib.rsx"));
        assert!(glob_match("a*b*c.rs", "axxbyyc.rs"));
        assert!(!glob_match("a*b*c.rs", "axxbyy.rs"));
        assert!(glob_match("t?st.rs", "test.rs"));
        assert!(!glob_match("t?st.rs", "toast.rs"), "? is exactly one char");
    }

    #[test]
    fn globs_honour_the_shapes_a_gitignore_reader_writes() {
        assert!(glob_match("/a.rs", "a.rs"));
        assert!(
            !glob_match("/a.rs", "src/a.rs"),
            "a leading / anchors at the root"
        );
        assert!(glob_match("/src/**", "src/lib.rs"), "leading slash anchors");
        assert!(glob_match("/src/*.rs", "src/lib.rs"));
        assert!(
            glob_match("src/", "src/a/b.rs"),
            "trailing slash is a subtree"
        );
        assert!(!glob_match("src/", "srcx/a.rs"));
        assert!(glob_match("**/fixtures/**", "crates/x/fixtures/a.json"));
    }
}