sniffy 1.0.0

A blazingly fast source code lines counter with git history analysis, supporting 33+ languages
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
//! Directory walking and file discovery.
//!
//! This module implements recursive directory traversal,
//! respecting .gitignore patterns and skip rules.

use ignore::WalkBuilder;
use std::path::{Path, PathBuf};

/// Directory walker that respects .gitignore and other ignore files.
pub struct DirectoryWalker {
    paths: Vec<PathBuf>,
    hidden: bool,
}

/// Check if a file should be skipped based on common patterns.
///
/// This function filters out:
/// - Common dependency directories (node_modules, target, etc.)
/// - Build output directories (build, dist, etc.)
/// - Version control directories (.git, .svn, etc.)
/// - Python cache directories (__pycache__, .venv, venv)
/// - Minified files (*.min.js, *.min.css)
/// - Lock files (package-lock.json, Cargo.lock, etc.)
fn should_skip_file(path: &Path) -> bool {
    // Skip directories by checking path components
    for component in path.components() {
        if let Some(component_str) = component.as_os_str().to_str() {
            match component_str {
                // Dependency directories
                "node_modules" | "vendor" | "bower_components" => return true,
                // Build output directories
                "target" | "build" | "dist" | "out" | ".next" => return true,
                // Version control directories
                ".git" | ".svn" | ".hg" => return true,
                // Python virtual environments and cache
                ".venv" | "venv" | "__pycache__" | ".pytest_cache" => return true,
                // IDE and editor directories
                ".idea" | ".vscode" | ".vs" => return true,
                // OS-specific directories
                ".DS_Store" => return true,
                _ => {}
            }
        }
    }

    // Skip specific file patterns
    if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
        // Minified files
        if file_name.ends_with(".min.js") || file_name.ends_with(".min.css") {
            return true;
        }

        // Lock files
        match file_name {
            "package-lock.json" | "yarn.lock" | "pnpm-lock.yaml" | "Cargo.lock"
            | "Gemfile.lock" | "poetry.lock" | "composer.lock" | "go.sum" => return true,
            _ => {}
        }
    }

    false
}

impl DirectoryWalker {
    /// Create a new DirectoryWalker for the given path.
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        Self {
            paths: vec![path.as_ref().to_path_buf()],
            hidden: false,
        }
    }

    /// Set whether to include hidden files and directories.
    pub fn hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Walk the directory and yield all file paths.
    pub fn walk(&self) -> impl Iterator<Item = PathBuf> {
        let mut builder = WalkBuilder::new(&self.paths[0]);

        // Configure walker
        builder.hidden(!self.hidden);
        builder.git_ignore(true);
        builder.git_global(true);
        builder.git_exclude(true);

        // Add additional paths if any
        for path in &self.paths[1..] {
            builder.add(path);
        }

        builder
            .build()
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.file_type().map(|ft| ft.is_file()).unwrap_or(false))
            .map(|entry| entry.into_path())
            .filter(|path| !should_skip_file(path))
    }
}

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

    #[test]
    fn test_directory_walker_new() {
        let temp_dir = TempDir::new().unwrap();
        let walker = DirectoryWalker::new(temp_dir.path());
        assert!(!walker.hidden);
    }

    #[test]
    fn test_directory_walker_hidden() {
        let temp_dir = TempDir::new().unwrap();
        let walker = DirectoryWalker::new(temp_dir.path()).hidden(true);
        assert!(walker.hidden);
    }

    #[test]
    fn test_walk_files() {
        let temp_dir = TempDir::new().unwrap();

        // Create some test files
        let file1 = temp_dir.path().join("test1.rs");
        let file2 = temp_dir.path().join("test2.rs");
        fs::File::create(&file1).unwrap();
        fs::File::create(&file2).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_walk_respects_gitignore() {
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repository (required for .gitignore to work)
        std::process::Command::new("git")
            .args(&["init"])
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to initialize git repo");

        // Create .gitignore and flush it
        let gitignore_path = temp_dir.path().join(".gitignore");
        let mut gitignore = fs::File::create(&gitignore_path).unwrap();
        writeln!(gitignore, "ignored.rs").unwrap();
        gitignore.sync_all().unwrap();
        drop(gitignore); // Ensure file is closed

        // Create files
        let included = temp_dir.path().join("included.rs");
        let ignored = temp_dir.path().join("ignored.rs");
        fs::File::create(&included).unwrap();
        fs::File::create(&ignored).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Filter out .gitignore file and check for ignored.rs
        let has_included = files.iter().any(|p| p.ends_with("included.rs"));
        let has_ignored = files.iter().any(|p| p.ends_with("ignored.rs"));

        assert!(has_included, "included.rs should be present");
        assert!(!has_ignored, "ignored.rs should be excluded");
    }

    #[test]
    fn test_walk_excludes_hidden_by_default() {
        let temp_dir = TempDir::new().unwrap();

        // Create regular and hidden files
        let regular = temp_dir.path().join("regular.rs");
        let hidden = temp_dir.path().join(".hidden.rs");
        fs::File::create(&regular).unwrap();
        fs::File::create(&hidden).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should exclude hidden files by default
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("regular.rs"));
    }

    #[test]
    fn test_walk_includes_hidden_when_enabled() {
        let temp_dir = TempDir::new().unwrap();

        // Create regular and hidden files
        let regular = temp_dir.path().join("regular.rs");
        let hidden = temp_dir.path().join(".hidden.rs");
        fs::File::create(&regular).unwrap();
        fs::File::create(&hidden).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path()).hidden(true);
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should include both files
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn test_walk_excludes_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Create a subdirectory with a file
        let subdir = temp_dir.path().join("subdir");
        fs::create_dir(&subdir).unwrap();
        let file_in_subdir = subdir.join("test.rs");
        fs::File::create(&file_in_subdir).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only return files, not directories
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("test.rs"));
    }

    #[test]
    fn test_skip_node_modules() {
        let temp_dir = TempDir::new().unwrap();

        // Create node_modules directory with a file
        let node_modules = temp_dir.path().join("node_modules");
        fs::create_dir(&node_modules).unwrap();
        let file_in_node_modules = node_modules.join("package.js");
        fs::File::create(&file_in_node_modules).unwrap();

        // Create a regular file
        let regular_file = temp_dir.path().join("app.js");
        fs::File::create(&regular_file).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find the regular file, not the one in node_modules
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("app.js"));
    }

    #[test]
    fn test_skip_target_directory() {
        let temp_dir = TempDir::new().unwrap();

        // Create target directory with a file
        let target = temp_dir.path().join("target");
        fs::create_dir(&target).unwrap();
        let file_in_target = target.join("binary");
        fs::File::create(&file_in_target).unwrap();

        // Create a regular file
        let regular_file = temp_dir.path().join("main.rs");
        fs::File::create(&regular_file).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find the regular file
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("main.rs"));
    }

    #[test]
    fn test_skip_build_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Create multiple build directories
        let build = temp_dir.path().join("build");
        let dist = temp_dir.path().join("dist");
        fs::create_dir(&build).unwrap();
        fs::create_dir(&dist).unwrap();

        fs::File::create(build.join("output.js")).unwrap();
        fs::File::create(dist.join("bundle.js")).unwrap();

        // Create a regular file
        let regular_file = temp_dir.path().join("source.js");
        fs::File::create(&regular_file).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find the regular file
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("source.js"));
    }

    #[test]
    fn test_skip_minified_files() {
        let temp_dir = TempDir::new().unwrap();

        // Create minified files
        fs::File::create(temp_dir.path().join("app.min.js")).unwrap();
        fs::File::create(temp_dir.path().join("style.min.css")).unwrap();

        // Create regular files
        fs::File::create(temp_dir.path().join("app.js")).unwrap();
        fs::File::create(temp_dir.path().join("style.css")).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find non-minified files
        assert_eq!(files.len(), 2);
        assert!(files.iter().any(|p| p.ends_with("app.js")));
        assert!(files.iter().any(|p| p.ends_with("style.css")));
        assert!(!files.iter().any(|p| p.ends_with("app.min.js")));
        assert!(!files.iter().any(|p| p.ends_with("style.min.css")));
    }

    #[test]
    fn test_skip_lock_files() {
        let temp_dir = TempDir::new().unwrap();

        // Create various lock files
        fs::File::create(temp_dir.path().join("package-lock.json")).unwrap();
        fs::File::create(temp_dir.path().join("Cargo.lock")).unwrap();
        fs::File::create(temp_dir.path().join("yarn.lock")).unwrap();
        fs::File::create(temp_dir.path().join("Gemfile.lock")).unwrap();

        // Create regular files
        fs::File::create(temp_dir.path().join("package.json")).unwrap();
        fs::File::create(temp_dir.path().join("Cargo.toml")).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find non-lock files
        assert_eq!(files.len(), 2);
        assert!(files.iter().any(|p| p.ends_with("package.json")));
        assert!(files.iter().any(|p| p.ends_with("Cargo.toml")));
        assert!(!files
            .iter()
            .any(|p| p.file_name().unwrap().to_str().unwrap().contains("lock")));
    }

    #[test]
    fn test_skip_python_venv() {
        let temp_dir = TempDir::new().unwrap();

        // Create virtual environment directories
        let venv = temp_dir.path().join("venv");
        let dot_venv = temp_dir.path().join(".venv");
        let pycache = temp_dir.path().join("__pycache__");

        fs::create_dir(&venv).unwrap();
        fs::create_dir(&dot_venv).unwrap();
        fs::create_dir(&pycache).unwrap();

        fs::File::create(venv.join("activate")).unwrap();
        fs::File::create(dot_venv.join("lib.py")).unwrap();
        fs::File::create(pycache.join("module.pyc")).unwrap();

        // Create regular Python file
        fs::File::create(temp_dir.path().join("main.py")).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find the regular Python file
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("main.py"));
    }

    #[test]
    fn test_skip_ide_directories() {
        let temp_dir = TempDir::new().unwrap();

        // Create IDE directories
        let vscode = temp_dir.path().join(".vscode");
        let idea = temp_dir.path().join(".idea");

        fs::create_dir(&vscode).unwrap();
        fs::create_dir(&idea).unwrap();

        fs::File::create(vscode.join("settings.json")).unwrap();
        fs::File::create(idea.join("workspace.xml")).unwrap();

        // Create regular file
        fs::File::create(temp_dir.path().join("code.rs")).unwrap();

        let walker = DirectoryWalker::new(temp_dir.path());
        let files: Vec<PathBuf> = walker.walk().collect();

        // Should only find the regular file
        assert_eq!(files.len(), 1);
        assert!(files[0].ends_with("code.rs"));
    }

    #[test]
    fn test_should_skip_file_function() {
        // Test dependency directories
        assert!(should_skip_file(Path::new(
            "/project/node_modules/package/index.js"
        )));
        assert!(should_skip_file(Path::new("/project/vendor/lib.rb")));

        // Test build directories
        assert!(should_skip_file(Path::new(
            "/project/target/release/binary"
        )));
        assert!(should_skip_file(Path::new("/project/build/output.js")));
        assert!(should_skip_file(Path::new("/project/dist/bundle.js")));

        // Test version control
        assert!(should_skip_file(Path::new("/project/.git/config")));
        assert!(should_skip_file(Path::new("/project/.svn/entries")));

        // Test Python
        assert!(should_skip_file(Path::new("/project/venv/lib/python.py")));
        assert!(should_skip_file(Path::new("/project/.venv/activate")));
        assert!(should_skip_file(Path::new(
            "/project/__pycache__/module.pyc"
        )));

        // Test minified files
        assert!(should_skip_file(Path::new("/project/app.min.js")));
        assert!(should_skip_file(Path::new("/project/style.min.css")));

        // Test lock files
        assert!(should_skip_file(Path::new("/project/package-lock.json")));
        assert!(should_skip_file(Path::new("/project/Cargo.lock")));
        assert!(should_skip_file(Path::new("/project/yarn.lock")));

        // Test that regular files are NOT skipped
        assert!(!should_skip_file(Path::new("/project/src/main.rs")));
        assert!(!should_skip_file(Path::new("/project/app.js")));
        assert!(!should_skip_file(Path::new("/project/style.css")));
        assert!(!should_skip_file(Path::new("/project/Cargo.toml")));
    }
}