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
use crate::error::{Result, SizelintError};
use crate::git::GitRepo;
use globset::{Glob, GlobSet, GlobSetBuilder};
use ignore::WalkBuilder;
use rayon::prelude::*;
use std::path::{Path, PathBuf};
use tracing::{Level, debug, span};

const DEFAULT_FILES_CAPACITY: usize = 1024;
const DEFAULT_DIR_CAPACITY: usize = 512;

pub struct FileDiscovery {
    root: PathBuf,
    git_repo: Option<GitRepo>,
    excludes: GlobSet,
}

impl FileDiscovery {
    pub fn new<P: AsRef<Path>>(root: P, exclude_patterns: &[String]) -> Result<Self> {
        let root = root.as_ref().to_path_buf();

        let git_repo = GitRepo::discover(&root).ok();

        let mut builder = GlobSetBuilder::new();
        for pattern in exclude_patterns {
            let glob = Glob::new(pattern)
                .map_err(|e| SizelintError::config_invalid_pattern(pattern.clone(), e))?;
            builder.add(glob);
        }
        let excludes = builder.build().map_err(|e| {
            SizelintError::config_invalid(
                "exclude_patterns".to_string(),
                "globset_builder".to_string(),
                format!("Failed to build exclude patterns: {e}"),
            )
        })?;

        Ok(FileDiscovery {
            root,
            git_repo,
            excludes,
        })
    }

    fn create_walker(&self, root: &Path, respect_gitignore: bool) -> WalkBuilder {
        let mut builder = WalkBuilder::new(root);
        builder
            .hidden(false)
            .git_ignore(respect_gitignore)
            .git_global(respect_gitignore)
            .git_exclude(respect_gitignore)
            .threads(rayon::current_num_threads());
        builder
    }

    fn walk_parallel(&self, walker: ignore::WalkParallel, capacity: usize) -> Result<Vec<PathBuf>> {
        let files = std::sync::Mutex::new(Vec::with_capacity(capacity));

        walker.run(|| {
            let files = &files;
            let excludes = &self.excludes;

            Box::new(move |entry| {
                match entry {
                    Ok(entry) if entry.file_type().is_some_and(|ft| ft.is_file()) => {
                        let path = entry.path();

                        // Skip files inside .git directory
                        // This is needed, because we walk hidden files
                        // hidden(false) by default
                        if path.components().any(|c| c.as_os_str() == ".git") {
                            return ignore::WalkState::Continue;
                        }

                        if !excludes.is_match(path) {
                            files.lock().unwrap().push(path.to_path_buf());
                        }
                    }
                    Err(_) => return ignore::WalkState::Quit,
                    _ => {}
                }
                ignore::WalkState::Continue
            })
        });

        let files = files.into_inner().unwrap();
        Ok(files)
    }

    pub fn discover_files(&self, respect_gitignore: bool) -> Result<Vec<PathBuf>> {
        let _span = span!(
            Level::DEBUG,
            "discover_files",
            respect_gitignore = respect_gitignore
        )
        .entered();

        let builder = self.create_walker(&self.root, respect_gitignore);
        let walker = builder.build_parallel();
        let files = self.walk_parallel(walker, DEFAULT_FILES_CAPACITY)?;

        debug!("Discovered {} files", files.len());
        Ok(files)
    }

    pub fn discover_staged_files(&self) -> Result<Vec<PathBuf>> {
        match &self.git_repo {
            Some(git_repo) => {
                let staged_files = git_repo.get_staged_files()?;
                Ok(self.filter_files(staged_files))
            }
            None => Err(crate::git::GitError::RepoNotFound {
                path: self.root.clone(),
            }
            .into()),
        }
    }

    pub fn discover_working_tree_files(&self) -> Result<Vec<PathBuf>> {
        match &self.git_repo {
            Some(git_repo) => {
                let working_files = git_repo.get_working_tree_files()?;
                Ok(self.filter_files(working_files))
            }
            None => Err(crate::git::GitError::RepoNotFound {
                path: self.root.clone(),
            }
            .into()),
        }
    }

    pub fn discover_git_diff_files(&self, range: &str) -> Result<Vec<PathBuf>> {
        match &self.git_repo {
            Some(git_repo) => {
                let diff_files = git_repo.get_diff_files(range)?;
                Ok(self.filter_files(diff_files))
            }
            None => Err(crate::git::GitError::RepoNotFound {
                path: self.root.clone(),
            }
            .into()),
        }
    }

    pub fn discover_history_blobs(&self, range: &str) -> Result<Vec<crate::git::HistoryBlob>> {
        match &self.git_repo {
            Some(git_repo) => {
                let blobs = git_repo.walk_history_blobs(range)?;
                Ok(blobs
                    .into_iter()
                    .filter(|blob| {
                        let path = Path::new(&blob.path);
                        !self.excludes.is_match(path)
                    })
                    .collect())
            }
            None => Err(crate::git::GitError::RepoNotFound {
                path: self.root.clone(),
            }
            .into()),
        }
    }

    pub fn discover_specific_paths(&self, paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();

        for path in paths {
            if path.is_file() {
                if !self.excludes.is_match(path) {
                    files.push(path.clone());
                }
            } else if path.is_dir() {
                let dir_files = self.discover_files_in_directory(path)?;
                files.extend(dir_files);
            }
        }

        Ok(files)
    }

    fn discover_files_in_directory(&self, dir: &Path) -> Result<Vec<PathBuf>> {
        let builder = self.create_walker(dir, true);
        let walker = builder.build_parallel();
        self.walk_parallel(walker, DEFAULT_DIR_CAPACITY)
    }

    fn filter_files(&self, files: Vec<PathBuf>) -> Vec<PathBuf> {
        files
            .into_par_iter()
            .filter(|path| !self.excludes.is_match(path))
            .collect()
    }

    pub fn is_in_git_repo(&self) -> bool {
        self.git_repo.is_some()
    }

    pub fn git_repo(&self) -> Option<&GitRepo> {
        self.git_repo.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    struct TestRepo {
        _temp_dir: TempDir,
        root: PathBuf,
    }

    impl TestRepo {
        fn new() -> Result<Self> {
            let temp_dir = tempfile::tempdir().map_err(|e| {
                SizelintError::filesystem(
                    "create temp directory".to_string(),
                    PathBuf::from("/tmp"),
                    e,
                )
            })?;

            let root = temp_dir.path().to_path_buf();

            std::process::Command::new("git")
                .args(["init"])
                .current_dir(&root)
                .output()
                .map_err(|e| {
                    SizelintError::filesystem("execute git init".to_string(), root.clone(), e)
                })?;

            std::process::Command::new("git")
                .args(["config", "user.email", "test@example.com"])
                .current_dir(&root)
                .output()
                .map_err(|e| {
                    SizelintError::filesystem("execute git config".to_string(), root.clone(), e)
                })?;

            std::process::Command::new("git")
                .args(["config", "user.name", "Test User"])
                .current_dir(&root)
                .output()
                .map_err(|e| {
                    SizelintError::filesystem("execute git config".to_string(), root.clone(), e)
                })?;

            Ok(TestRepo {
                _temp_dir: temp_dir,
                root,
            })
        }

        fn create_file<P: AsRef<Path>>(&self, path: P, content: &str) -> Result<PathBuf> {
            let full_path = self.root.join(path);
            if let Some(parent) = full_path.parent() {
                fs::create_dir_all(parent).map_err(|e| {
                    SizelintError::filesystem(
                        "create directory".to_string(),
                        parent.to_path_buf(),
                        e,
                    )
                })?;
            }
            fs::write(&full_path, content).map_err(|e| {
                SizelintError::filesystem("write file".to_string(), full_path.clone(), e)
            })?;
            Ok(full_path)
        }

        fn create_gitignore(&self, content: &str) -> Result<()> {
            self.create_file(".gitignore", content)?;
            Ok(())
        }

        fn path(&self) -> &Path {
            &self.root
        }
    }

    #[test]
    #[ignore = "requires git binary"]
    fn test_discovers_files_without_gitignore() -> Result<()> {
        let repo = TestRepo::new()?;

        repo.create_file("file1.txt", "content1")?;
        repo.create_file("src/file2.rs", "content2")?;
        repo.create_file("docs/file3.md", "content3")?;

        let discovery = FileDiscovery::new(repo.path(), &[])?;
        let files = discovery.discover_files(true)?;

        let file_names: Vec<String> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        // Should find the files we created
        // (gitignore functionality working means git metadata is excluded)
        assert!(file_names.contains(&"file1.txt".to_string()));
        assert!(file_names.contains(&"file2.rs".to_string()));
        assert!(file_names.contains(&"file3.md".to_string()));

        // Should NOT find git metadata files
        // (.git directory should be automatically ignored)
        assert!(!file_names.iter().any(|name| name.starts_with("HEAD")));
        assert!(!file_names.iter().any(|name| name.starts_with("config")));

        Ok(())
    }

    #[test]
    #[ignore = "requires git binary"]
    fn test_respects_gitignore() -> Result<()> {
        let repo = TestRepo::new()?;

        repo.create_gitignore("*.log\nsrc/generated/\ndocs/private.md")?;
        repo.create_file("file1.txt", "content1")?;
        repo.create_file("debug.log", "log content")?;
        repo.create_file("src/main.rs", "rust code")?;
        repo.create_file("src/generated/auto.rs", "generated code")?;
        repo.create_file("docs/readme.md", "docs")?;
        repo.create_file("docs/private.md", "private docs")?;

        let discovery = FileDiscovery::new(repo.path(), &[])?;
        let files = discovery.discover_files(true)?;

        let file_names: Vec<String> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        // Should find files not in gitignore
        assert!(file_names.contains(&"file1.txt".to_string()));
        assert!(file_names.contains(&"main.rs".to_string()));
        assert!(file_names.contains(&"readme.md".to_string()));
        assert!(file_names.contains(&".gitignore".to_string()));

        // Should NOT find ignored files
        assert!(!file_names.contains(&"debug.log".to_string()));
        assert!(!file_names.contains(&"auto.rs".to_string()));
        assert!(!file_names.contains(&"private.md".to_string()));

        Ok(())
    }

    #[test]
    #[ignore = "requires git binary"]
    fn test_ignores_gitignore_when_disabled() -> Result<()> {
        let repo = TestRepo::new()?;

        repo.create_gitignore("*.log")?;

        repo.create_file("file1.txt", "content1")?;
        repo.create_file("debug.log", "log content")?;

        let discovery = FileDiscovery::new(repo.path(), &[])?;
        let files = discovery.discover_files(false)?; // respect_gitignore = false

        let file_names: Vec<String> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        // Should find ALL files when gitignore is disabled
        assert!(file_names.contains(&"file1.txt".to_string()));
        assert!(file_names.contains(&"debug.log".to_string()));
        assert!(file_names.contains(&".gitignore".to_string()));

        Ok(())
    }

    #[test]
    #[ignore = "requires git binary"]
    fn test_config_excludes_override_gitignore() -> Result<()> {
        let repo = TestRepo::new()?;

        repo.create_gitignore("src/generated/")?;

        repo.create_file("file1.txt", "content1")?;
        repo.create_file("debug.log", "log content")?;
        repo.create_file("src/main.rs", "rust code")?;

        let discovery = FileDiscovery::new(repo.path(), &["*.log".to_string()])?;
        let files = discovery.discover_files(true)?;

        let file_names: Vec<String> = files
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();

        // Should find files not excluded by config
        assert!(file_names.contains(&"file1.txt".to_string()));
        assert!(file_names.contains(&"main.rs".to_string()));
        assert!(file_names.contains(&".gitignore".to_string()));

        // Should NOT find files excluded by config
        // (even though gitignore allows them)
        assert!(!file_names.contains(&"debug.log".to_string()));

        Ok(())
    }

    #[test]
    #[ignore = "requires git binary"]
    fn test_specific_files_ignore_gitignore() -> Result<()> {
        let repo = TestRepo::new()?;

        repo.create_gitignore("*.log")?;

        let _file1 = repo.create_file("file1.txt", "content1")?;
        let log_file = repo.create_file("debug.log", "log content")?;

        let discovery = FileDiscovery::new(repo.path(), &[])?;

        let files = discovery.discover_specific_paths(&[log_file])?;
        assert_eq!(files.len(), 1);
        assert!(
            files[0]
                .file_name()
                .unwrap()
                .to_string_lossy()
                .contains("debug.log")
        );

        Ok(())
    }
}