rustloclib 0.13.1

Rust-aware LOC counter that separates production code from tests — even in the same file
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! High-level LOC counting API.
//!
//! This module provides the main entry points for counting lines of code
//! in Rust projects, with support for workspace filtering and glob patterns.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::error::RustlocError;
use crate::query::options::{Aggregation, LineTypes};
use crate::source::filter::{discover_files, discover_files_in_dirs, FilterConfig};
use crate::source::workspace::{CrateInfo, WorkspaceInfo};
use crate::Result;

use super::stats::{CrateStats, FileStats, Locs, ModuleStats};
use super::visitor::gather_stats_for_path;

/// Options for counting LOC.
#[derive(Debug, Clone)]
pub struct CountOptions {
    /// Filter by crate names (empty = all crates)
    pub crate_filter: Vec<String>,
    /// File filter configuration
    pub file_filter: FilterConfig,
    /// Aggregation level for results
    pub aggregation: Aggregation,
    /// Which line types to include in results
    pub line_types: LineTypes,
}

impl Default for CountOptions {
    fn default() -> Self {
        Self {
            crate_filter: Vec::new(),
            file_filter: FilterConfig::new(),
            aggregation: Aggregation::Total,
            line_types: LineTypes::default(),
        }
    }
}

impl CountOptions {
    /// Create new default options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter to specific crates.
    pub fn crates(mut self, names: Vec<String>) -> Self {
        self.crate_filter = names;
        self
    }

    /// Set file filter.
    pub fn filter(mut self, filter: FilterConfig) -> Self {
        self.file_filter = filter;
        self
    }

    /// Set aggregation level.
    pub fn aggregation(mut self, level: Aggregation) -> Self {
        self.aggregation = level;
        self
    }

    /// Set which line types to include.
    pub fn line_types(mut self, types: LineTypes) -> Self {
        self.line_types = types;
        self
    }
}

/// Result of counting LOC in a workspace or directory.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct CountResult {
    /// Root path of the workspace or directory analyzed
    pub root: PathBuf,
    /// Total number of files analyzed
    pub file_count: usize,
    /// Aggregated statistics across all files
    pub total: Locs,
    /// Per-crate statistics (if workspace)
    pub crates: Vec<CrateStats>,
    /// Per-file statistics (if requested)
    pub files: Vec<FileStats>,
    /// Per-module statistics (if requested)
    pub modules: Vec<ModuleStats>,
}

impl CountResult {
    /// Create a new empty result.
    pub fn new() -> Self {
        Self::default()
    }

    /// Return a filtered copy with only the specified line types included.
    pub fn filter(&self, types: LineTypes) -> Self {
        Self {
            root: self.root.clone(),
            file_count: self.file_count,
            total: self.total.filter(types),
            crates: self.crates.iter().map(|c| c.filter(types)).collect(),
            files: self.files.iter().map(|f| f.filter(types)).collect(),
            modules: self.modules.iter().map(|m| m.filter(types)).collect(),
        }
    }
}

/// Count LOC in a Cargo workspace.
///
/// This is the main entry point for analyzing a Rust project. It:
/// 1. Discovers the workspace structure
/// 2. Optionally filters to specific crates
/// 3. Applies glob filters to files
/// 4. Parses all matching files and aggregates statistics
///
/// # Example
///
/// ```rust
/// use rustloclib::{count_workspace, CountOptions, FilterConfig};
/// use std::fs;
/// use tempfile::tempdir;
///
/// let dir = tempdir().unwrap();
/// fs::write(dir.path().join("Cargo.toml"), r#"
/// [package]
/// name = "my-lib"
/// version = "0.1.0"
/// edition = "2021"
/// "#).unwrap();
/// fs::create_dir(dir.path().join("src")).unwrap();
/// fs::write(dir.path().join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
///
/// // Count all crates in the workspace
/// let result = count_workspace(dir.path(), CountOptions::new()).unwrap();
/// assert_eq!(result.crates.len(), 0); // Total aggregation doesn't include crate breakdown
/// assert!(result.total.code >= 1);
///
/// // Exclude test files with filter
/// let filter = FilterConfig::new().exclude("**/tests/**").unwrap();
/// let result = count_workspace(dir.path(), CountOptions::new().filter(filter)).unwrap();
/// ```
pub fn count_workspace(path: impl AsRef<Path>, options: CountOptions) -> Result<CountResult> {
    let workspace = WorkspaceInfo::discover(path)?;

    // Filter crates if specified
    let crates: Vec<&CrateInfo> = if options.crate_filter.is_empty() {
        workspace.crates.iter().collect()
    } else {
        let names: Vec<&str> = options.crate_filter.iter().map(|s| s.as_str()).collect();
        workspace
            .crates
            .iter()
            .filter(|c| names.contains(&c.name.as_str()))
            .collect()
    };

    let mut result = CountResult::new();
    result.root = workspace.root.clone();

    // Determine what to include based on aggregation level
    let include_files = matches!(options.aggregation, Aggregation::ByFile);
    let include_modules = matches!(options.aggregation, Aggregation::ByModule);
    let include_crates = matches!(
        options.aggregation,
        Aggregation::ByCrate | Aggregation::ByModule | Aggregation::ByFile
    );

    for crate_info in &crates {
        let crate_stats = count_crate(crate_info, &options)?;
        result.total += crate_stats.stats;
        result.file_count += crate_stats.files.len();

        if include_files {
            result.files.extend(crate_stats.files.clone());
        }

        // Compute module stats per-crate if requested
        if include_modules {
            let crate_modules = aggregate_modules(&crate_stats.files, &crate_info.name, crate_info);
            result.modules.extend(crate_modules);
        }

        if include_crates {
            result.crates.push(crate_stats);
        }
    }

    // Sort modules by name for consistent output
    if include_modules {
        result.modules.sort_by(|a, b| a.name.cmp(&b.name));
    }

    // Apply line type filter
    Ok(result.filter(options.line_types))
}

/// Compute the module name for a file path relative to a source root.
///
/// Returns the directory-level module name so that all files within
/// a directory aggregate under a single module entry.
///
/// Module naming rules:
/// - `lib.rs`, `main.rs`, `mod.rs` in root → "" (root module)
/// - `foo.rs` in root → "foo"
/// - `foo/mod.rs` → "foo"
/// - `foo/bar.rs` → "foo" (aggregates with other files in foo/)
/// - `foo/sub/baz.rs` → "foo::sub"
/// - New-style: `foo.rs` + `foo/bar.rs` both → "foo"
pub fn compute_module_name(file_path: &Path, src_root: &Path) -> String {
    let relative = file_path.strip_prefix(src_root).unwrap_or(file_path);

    let mut components: Vec<&str> = relative
        .components()
        .filter_map(|c| c.as_os_str().to_str())
        .collect();

    if components.is_empty() {
        return String::new();
    }

    // Get the filename
    let filename = components.pop().unwrap_or("");
    let stem = filename.strip_suffix(".rs").unwrap_or(filename);

    // Special case: root module files
    if components.is_empty() && (stem == "lib" || stem == "main" || stem == "mod") {
        return String::new();
    }

    // mod.rs belongs to parent module
    if stem == "mod" {
        return components.join("::");
    }

    // Files inside a directory belong to that directory's module.
    // e.g., data/counter.rs → "data", data/sub/foo.rs → "data::sub"
    // Root-level files (like error.rs or data.rs) are their own module.
    // This means data.rs (new-style module entry) naturally aggregates
    // with files in data/ since both map to "data".
    if !components.is_empty() {
        components.join("::")
    } else {
        stem.to_string()
    }
}

/// Aggregate file stats into modules for a specific crate.
fn aggregate_modules(
    files: &[FileStats],
    crate_name: &str,
    crate_info: &CrateInfo,
) -> Vec<ModuleStats> {
    let mut module_map: HashMap<String, ModuleStats> = HashMap::new();

    for file in files {
        // Find the appropriate src root for this file
        let src_root = crate_info
            .src_dirs
            .iter()
            .find(|dir| file.path.starts_with(dir))
            .map(|p| p.as_path())
            .unwrap_or(&crate_info.root);

        let local_module = compute_module_name(&file.path, src_root);

        // Prefix with crate name for multi-crate workspaces
        let full_module_name = if local_module.is_empty() {
            crate_name.to_string()
        } else {
            format!("{}::{}", crate_name, local_module)
        };

        let module = module_map
            .entry(full_module_name.clone())
            .or_insert_with(|| ModuleStats::new(full_module_name));

        module.add_file(file.path.clone(), file.stats);
    }

    module_map.into_values().collect()
}

/// Count LOC in a single crate.
fn count_crate(crate_info: &CrateInfo, options: &CountOptions) -> Result<CrateStats> {
    let dirs: Vec<&Path> = crate_info.all_dirs();
    let files = discover_files_in_dirs(&dirs, &options.file_filter)?;

    let mut crate_stats = CrateStats::new(crate_info.name.clone(), crate_info.root.clone());

    for file_path in files {
        let stats = gather_stats_for_path(&file_path)?;
        let file_stats = FileStats::new(file_path, stats);
        crate_stats.add_file(file_stats);
    }

    Ok(crate_stats)
}

/// Count LOC in a directory (non-workspace mode).
///
/// Use this when you want to count files in a directory without
/// Cargo workspace awareness.
///
/// # Example
///
/// ```rust
/// use rustloclib::{count_directory, FilterConfig};
/// use std::fs;
/// use tempfile::tempdir;
///
/// let dir = tempdir().unwrap();
/// let src = dir.path().join("src");
/// fs::create_dir(&src).unwrap();
/// fs::write(src.join("lib.rs"), "pub fn hello() {}\n").unwrap();
/// fs::write(src.join("util.rs"), "pub fn util() {\n    // helper\n}\n").unwrap();
///
/// let filter = FilterConfig::new();
/// let result = count_directory(&src, &filter).unwrap();
/// assert_eq!(result.files.len(), 2);
/// ```
pub fn count_directory(path: impl AsRef<Path>, filter: &FilterConfig) -> Result<CountResult> {
    let path = path.as_ref();

    if !path.exists() {
        return Err(RustlocError::PathNotFound(path.to_path_buf()));
    }

    let files = discover_files(path, filter)?;

    let mut result = CountResult::new();
    result.root = path.to_path_buf();

    for file_path in files {
        let stats = gather_stats_for_path(&file_path)?;
        result.total += stats;
        result.file_count += 1;
        result.files.push(FileStats::new(file_path, stats));
    }

    Ok(result)
}

/// Count LOC in a single file.
///
/// # Example
///
/// ```rust
/// use rustloclib::count_file;
/// use std::fs;
/// use tempfile::tempdir;
///
/// let dir = tempdir().unwrap();
/// let file_path = dir.path().join("main.rs");
/// fs::write(&file_path, "fn main() {\n    println!(\"Hello\");\n}\n").unwrap();
///
/// let stats = count_file(&file_path).unwrap();
/// assert_eq!(stats.code, 3);
/// ```
pub fn count_file(path: impl AsRef<Path>) -> Result<Locs> {
    gather_stats_for_path(path)
}

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

    fn create_rust_file(path: &Path, content: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, content).unwrap();
    }

    fn create_simple_project(root: &Path) {
        // Cargo.toml
        fs::write(
            root.join("Cargo.toml"),
            r#"[package]
name = "test-project"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();

        // src/main.rs
        create_rust_file(
            &root.join("src/main.rs"),
            r#"fn main() {
    println!("Hello");
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_main() {
        assert!(true);
    }
}
"#,
        );

        // src/lib.rs
        create_rust_file(
            &root.join("src/lib.rs"),
            r#"//! Library documentation

/// A public function
pub fn hello() {
    println!("Hello from lib");
}
"#,
        );
    }

    fn create_workspace(root: &Path) {
        // Workspace Cargo.toml
        fs::write(
            root.join("Cargo.toml"),
            r#"[workspace]
members = ["crate-a", "crate-b"]
"#,
        )
        .unwrap();

        // crate-a
        fs::create_dir_all(root.join("crate-a/src")).unwrap();
        fs::write(
            root.join("crate-a/Cargo.toml"),
            r#"[package]
name = "crate-a"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        create_rust_file(
            &root.join("crate-a/src/lib.rs"),
            r#"pub fn a() {
    println!("A");
}
"#,
        );

        // crate-b
        fs::create_dir_all(root.join("crate-b/src")).unwrap();
        fs::write(
            root.join("crate-b/Cargo.toml"),
            r#"[package]
name = "crate-b"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        create_rust_file(
            &root.join("crate-b/src/lib.rs"),
            r#"pub fn b() {
    println!("B");
}

// A comment
"#,
        );
    }

    #[test]
    fn test_count_directory() {
        let temp = tempdir().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();

        create_rust_file(
            &src.join("main.rs"),
            r#"fn main() {
    println!("Hello");
}
"#,
        );

        let filter = FilterConfig::new();
        let result = count_directory(&src, &filter).unwrap();

        assert_eq!(result.files.len(), 1);
        assert_eq!(result.total.code, 3);
    }

    #[test]
    fn test_count_file() {
        let temp = tempdir().unwrap();
        let file = temp.path().join("test.rs");

        create_rust_file(
            &file,
            r#"/// Doc comment
fn foo() {
    // Regular comment
    let x = 1;
}
"#,
        );

        let stats = count_file(&file).unwrap();

        assert_eq!(stats.docs, 1);
        assert_eq!(stats.code, 3); // fn, let, }
        assert_eq!(stats.comments, 1);
    }

    #[test]
    fn test_count_workspace() {
        let temp = tempdir().unwrap();
        create_workspace(temp.path());

        let result = count_workspace(
            temp.path(),
            CountOptions::new().aggregation(Aggregation::ByCrate),
        )
        .unwrap();

        assert_eq!(result.crates.len(), 2);
    }

    #[test]
    fn test_count_workspace_filtered() {
        let temp = tempdir().unwrap();
        create_workspace(temp.path());

        let options = CountOptions::new()
            .crates(vec!["crate-a".to_string()])
            .aggregation(Aggregation::ByCrate);
        let result = count_workspace(temp.path(), options).unwrap();

        assert_eq!(result.crates.len(), 1);
        assert_eq!(result.crates[0].name, "crate-a");
    }

    #[test]
    fn test_count_workspace_with_file_stats() {
        let temp = tempdir().unwrap();
        create_workspace(temp.path());

        let options = CountOptions::new().aggregation(Aggregation::ByFile);
        let result = count_workspace(temp.path(), options).unwrap();

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

    #[test]
    fn test_count_mixed_code_and_tests() {
        let temp = tempdir().unwrap();
        create_simple_project(temp.path());

        let result = count_workspace(temp.path(), CountOptions::new()).unwrap();

        // main.rs has 3 production code lines + test block
        // lib.rs has doc comment + code
        assert!(result.total.code > 0);
        assert!(result.total.tests > 0);
        assert!(result.total.docs > 0);
    }

    #[test]
    fn test_compute_module_name_root_files() {
        let src = Path::new("/project/src");
        assert_eq!(
            compute_module_name(Path::new("/project/src/lib.rs"), src),
            ""
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/main.rs"), src),
            ""
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/error.rs"), src),
            "error"
        );
    }

    #[test]
    fn test_compute_module_name_directory_aggregation() {
        let src = Path::new("/project/src");
        // All files in data/ aggregate to "data"
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/mod.rs"), src),
            "data"
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/counter.rs"), src),
            "data"
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/stats.rs"), src),
            "data"
        );
    }

    #[test]
    fn test_compute_module_name_nested_directories() {
        let src = Path::new("/project/src");
        // Nested directories get their own module
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/sub/foo.rs"), src),
            "data::sub"
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/sub/mod.rs"), src),
            "data::sub"
        );
    }

    #[test]
    fn test_compute_module_name_new_style_module() {
        let src = Path::new("/project/src");
        // New-style: data.rs (sibling to data/) maps to "data"
        // just like files inside data/ — they aggregate together
        assert_eq!(
            compute_module_name(Path::new("/project/src/data.rs"), src),
            "data"
        );
        assert_eq!(
            compute_module_name(Path::new("/project/src/data/counter.rs"), src),
            "data"
        );
    }

    #[test]
    fn test_module_aggregation_groups_files_by_directory() {
        let temp = tempdir().unwrap();
        let root = temp.path();

        // Create a project with multiple modules
        fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"test-proj\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();

        create_rust_file(&root.join("src/lib.rs"), "pub mod data;\npub mod utils;\n");
        create_rust_file(
            &root.join("src/data/mod.rs"),
            "pub mod counter;\npub mod stats;\n",
        );
        create_rust_file(&root.join("src/data/counter.rs"), "pub fn count() {}\n");
        create_rust_file(&root.join("src/data/stats.rs"), "pub fn stats() {}\n");
        create_rust_file(&root.join("src/utils.rs"), "pub fn helper() {}\n");

        let options = CountOptions::new().aggregation(Aggregation::ByModule);
        let result = count_workspace(root, options).unwrap();

        let module_names: Vec<&str> = result.modules.iter().map(|m| m.name.as_str()).collect();

        // data/mod.rs, data/counter.rs, data/stats.rs all aggregate under "test-proj::data"
        assert!(module_names.contains(&"test-proj::data"));
        // utils.rs is a root-level module
        assert!(module_names.contains(&"test-proj::utils"));
        // lib.rs maps to the crate root
        assert!(module_names.contains(&"test-proj"));
        // Should NOT have per-file entries
        assert!(!module_names.contains(&"test-proj::data::counter"));
        assert!(!module_names.contains(&"test-proj::data::stats"));
    }
}