sizelint 0.1.4

Lint your working tree based on file size
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
599
600
601
use sizelint::discovery::FileDiscovery;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

struct TestGitRepo {
    _tmp: TempDir,
    root: PathBuf,
}

impl TestGitRepo {
    fn new() -> Self {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();

        Self::git(&root, &["init"]);
        Self::git(&root, &["config", "user.email", "test@test.com"]);
        Self::git(&root, &["config", "user.name", "Test"]);

        // Initial commit on default branch
        std::fs::write(root.join("init.txt"), "init").unwrap();
        Self::git(&root, &["add", "."]);
        Self::git(&root, &["commit", "-m", "init"]);

        TestGitRepo { _tmp: tmp, root }
    }

    fn git(cwd: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    fn default_branch(&self) -> String {
        Self::git(&self.root, &["branch", "--show-current"])
    }

    fn write_file(&self, name: &str, content: &str) {
        let path = self.root.join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }
}

fn file_names(files: &[PathBuf]) -> Vec<String> {
    let mut names: Vec<String> = files
        .iter()
        .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
        .collect();
    names.sort();
    names
}

#[test]
fn test_git_diff_discovers_changed_files_via_merge_base() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    // Create a feature branch with new files
    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);
    repo.write_file("feature.rs", "fn feature() {}");
    repo.write_file("src/helper.rs", "fn helper() {}");
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add feature files"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let files = discovery.discover_git_diff_files(&base).unwrap();

    let names = file_names(&files);
    assert!(names.contains(&"feature.rs".to_string()));
    assert!(names.contains(&"helper.rs".to_string()));
    assert!(!names.contains(&"init.txt".to_string()));
}

#[test]
fn test_git_diff_two_dot_range() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);
    repo.write_file("new.rs", "fn new() {}");
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "new file"]);

    let range = format!("{base}..feature");
    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let files = discovery.discover_git_diff_files(&range).unwrap();

    let names = file_names(&files);
    assert_eq!(names, vec!["new.rs"]);
}

#[test]
fn test_git_diff_empty_range_returns_zero_files() {
    let repo = TestGitRepo::new();

    // Diff HEAD against itself: no changes
    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let files = discovery.discover_git_diff_files("HEAD..HEAD").unwrap();

    assert!(files.is_empty());
}

#[test]
fn test_git_diff_config_excludes_filter_results() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);
    repo.write_file("src/main.rs", "fn main() {}");
    repo.write_file("build/output.bin", "binary data");
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "mixed files"]);

    let discovery = FileDiscovery::new(&repo.root, &["*.bin".to_string()]).unwrap();
    let files = discovery.discover_git_diff_files(&base).unwrap();

    let names = file_names(&files);
    assert!(names.contains(&"main.rs".to_string()));
    assert!(!names.contains(&"output.bin".to_string()));
}

#[test]
fn test_git_diff_error_when_not_in_git_repo() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();

    // No git init — not a repo
    let discovery = FileDiscovery::new(root, &[]).unwrap();
    let result = discovery.discover_git_diff_files("main");

    assert!(result.is_err());
}

// History blob tests

fn write_large_file(repo: &TestGitRepo, name: &str, size: usize) {
    let content = "x".repeat(size);
    repo.write_file(name, &content);
}

#[test]
fn test_history_blob_large_file_added_then_deleted() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add a large file
    write_large_file(&repo, "data/dump.sql", 1024);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add dump"]);

    // Delete it
    std::fs::remove_file(repo.root.join("data/dump.sql")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "remove dump"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    // The add commit introduced a 1024-byte blob
    let dump_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("data/dump.sql"))
        .collect();
    assert_eq!(dump_blobs.len(), 1);
    assert_eq!(dump_blobs[0].size, 1024);
    assert!(!dump_blobs[0].commit.is_empty());
}

#[test]
fn test_history_blob_file_still_at_head() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add file and keep it
    repo.write_file("src/keep.rs", "fn keep() {}");
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add keep"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    // Per-commit walk reports all blobs regardless of HEAD state
    let keep_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("src/keep.rs"))
        .collect();
    assert_eq!(keep_blobs.len(), 1);
}

#[test]
fn test_history_blob_small_file_no_violation() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add a small file then delete it
    repo.write_file("tmp/notes.txt", "small content");
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add notes"]);

    std::fs::remove_file(repo.root.join("tmp/notes.txt")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "remove notes"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    let notes_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("tmp/notes.txt"))
        .collect();
    assert_eq!(notes_blobs.len(), 1);

    // Check against rules with a high threshold — no violation expected
    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("1MB".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    let violations = engine.check_history_blobs(&blobs).unwrap();
    assert!(violations.is_empty());
}

#[test]
fn test_history_blob_config_excludes_filter() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    write_large_file(&repo, "src/code.rs", 512);
    write_large_file(&repo, "vendor/big.dat", 2048);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add files"]);

    // Delete both
    std::fs::remove_file(repo.root.join("src/code.rs")).unwrap();
    std::fs::remove_file(repo.root.join("vendor/big.dat")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "remove files"]);

    let discovery = FileDiscovery::new(&repo.root, &["*.dat".to_string()]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    // Only code.rs should appear, not big.dat (excluded)
    let has_code = blobs.iter().any(|b| b.path.ends_with("src/code.rs"));
    let has_dat = blobs.iter().any(|b| b.path.ends_with("vendor/big.dat"));
    assert!(has_code);
    assert!(!has_dat);
}

#[test]
fn test_history_blob_add_delete_readd_delete() {
    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add file, commit
    write_large_file(&repo, "data.csv", 100);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add v1"]);

    // Delete, commit
    std::fs::remove_file(repo.root.join("data.csv")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "delete v1"]);

    // Re-add bigger, commit
    write_large_file(&repo, "data.csv", 500);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add v2"]);

    // Delete again, commit
    std::fs::remove_file(repo.root.join("data.csv")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "delete v2"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    // Per-commit walk finds both add commits
    let csv_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("data.csv"))
        .collect();
    assert_eq!(csv_blobs.len(), 2);
}

#[test]
fn test_history_blob_temporarily_too_large_then_shrunk() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add a large file (over 500B threshold)
    write_large_file(&repo, "data.bin", 1024);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add large"]);

    // Shrink it below threshold
    write_large_file(&repo, "data.bin", 100);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "shrink"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    // Both the large and small versions appear
    let data_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("data.bin"))
        .collect();
    assert_eq!(data_blobs.len(), 2);

    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("500B".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    let violations = engine.check_history_blobs(&blobs).unwrap();
    // The 1024-byte intermediate blob should trigger a violation
    assert_eq!(violations.len(), 1);
    assert!(violations[0].path.ends_with("data.bin"));
}

#[test]
fn test_history_blob_grew_then_deleted() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Add a large file
    write_large_file(&repo, "big.log", 2048);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add big log"]);

    // Delete it
    std::fs::remove_file(repo.root.join("big.log")).unwrap();
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "remove big log"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("1KB".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    let violations = engine.check_history_blobs(&blobs).unwrap();
    assert_eq!(violations.len(), 1);
    assert!(violations[0].path.ends_with("big.log"));
}

#[test]
fn test_history_blob_dedup_keeps_largest() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // First commit: 600B (over 500B threshold)
    write_large_file(&repo, "grow.dat", 600);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add 600"]);

    // Second commit: grow to 900B
    write_large_file(&repo, "grow.dat", 900);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "grow to 900"]);

    // Third commit: grow to 1200B
    write_large_file(&repo, "grow.dat", 1200);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "grow to 1200"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let blobs = discovery.discover_history_blobs(&base).unwrap();

    let grow_blobs: Vec<_> = blobs
        .iter()
        .filter(|b| b.path.ends_with("grow.dat"))
        .collect();
    assert_eq!(grow_blobs.len(), 3);

    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("500B".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    let violations = engine.check_history_blobs(&blobs).unwrap();
    // Dedup keeps only the largest violation per path
    assert_eq!(violations.len(), 1);
    assert!(violations[0].path.ends_with("grow.dat"));
    assert_eq!(violations[0].sort_key, 1200);
}

#[test]
fn test_cross_phase_dedup_keeps_larger_history_blob() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Commit 1: large file (over 500B threshold)
    write_large_file(&repo, "bloat.bin", 2000);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add large"]);

    // Commit 2: shrink but still over threshold
    write_large_file(&repo, "bloat.bin", 600);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "shrink"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let live_files = discovery.discover_git_diff_files(&base).unwrap();

    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("500B".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    // Phase 1: check live files (600B at HEAD)
    let mut violations = engine.check_files(&live_files).unwrap();
    let phase1_count = violations.len();
    assert_eq!(phase1_count, 1);

    // Phase 2: history walk finds the 2000B intermediate blob
    let blobs = discovery.discover_history_blobs(&base).unwrap();
    let blob_violations = engine.check_history_blobs(&blobs).unwrap();
    violations.extend(blob_violations);

    // Before dedup: Phase 1 (600B) + Phase 2 (2000B) = 2 violations for same path
    assert!(violations.len() > 1);

    // Cross-phase dedup: keep largest per path
    let mut best: std::collections::HashMap<std::path::PathBuf, sizelint::rules::Violation> =
        std::collections::HashMap::new();
    for v in violations {
        best.entry(v.path.clone())
            .and_modify(|existing| {
                if v.sort_key > existing.sort_key {
                    *existing = v.clone();
                }
            })
            .or_insert(v);
    }
    let violations: Vec<_> = best.into_values().collect();

    assert_eq!(violations.len(), 1);
    // The 2000B history blob wins over the 600B HEAD version
    assert_eq!(violations[0].sort_key, 2000);
}

#[test]
fn test_cross_phase_dedup_no_duplicate_when_unchanged() {
    use sizelint::config::RuleDefinition;
    use sizelint::rules::ConfigurableRule;
    use sizelint::rules::RuleEngine;

    let repo = TestGitRepo::new();
    let base = repo.default_branch();

    TestGitRepo::git(&repo.root, &["checkout", "-b", "feature"]);

    // Single commit: file stays at HEAD
    write_large_file(&repo, "big.dat", 800);
    TestGitRepo::git(&repo.root, &["add", "."]);
    TestGitRepo::git(&repo.root, &["commit", "-m", "add big"]);

    let discovery = FileDiscovery::new(&repo.root, &[]).unwrap();
    let live_files = discovery.discover_git_diff_files(&base).unwrap();

    let mut engine = RuleEngine::new();
    let rule = ConfigurableRule::new(
        "default".to_string(),
        RuleDefinition {
            enabled: true,
            description: "test".to_string(),
            priority: 100,
            max_size: Some("500B".to_string()),
            ..Default::default()
        },
    )
    .unwrap();
    engine.add_rule(rule);

    // Phase 1
    let mut violations = engine.check_files(&live_files).unwrap();
    assert_eq!(violations.len(), 1);

    // Phase 2
    let blobs = discovery.discover_history_blobs(&base).unwrap();
    let blob_violations = engine.check_history_blobs(&blobs).unwrap();
    violations.extend(blob_violations);

    // Both phases fire for the same file at the same size
    assert_eq!(violations.len(), 2);

    // After dedup: only 1 violation
    let mut best: std::collections::HashMap<std::path::PathBuf, sizelint::rules::Violation> =
        std::collections::HashMap::new();
    for v in violations {
        best.entry(v.path.clone())
            .and_modify(|existing| {
                if v.sort_key > existing.sort_key {
                    *existing = v.clone();
                }
            })
            .or_insert(v);
    }
    let violations: Vec<_> = best.into_values().collect();

    assert_eq!(violations.len(), 1);
    assert_eq!(violations[0].sort_key, 800);
}