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
//! Query set: processed data ready for table rendering.
//!
//! A QuerySet sits between raw counting/diff results and the final table output.
//! It represents data that has been:
//! - Aggregated to the requested level (crate, module, file)
//! - Filtered to include only requested line types
//! - Sorted according to the ordering preference
//!
//! The data pipeline is:
//! 1. Raw Data (CountResult, DiffResult)
//! 2. QuerySet (filtered, aggregated, sorted)
//! 3. LOCTable (formatted strings for display)

use serde::{Deserialize, Serialize};

use std::collections::HashMap;

use crate::data::counter::{compute_module_name, CountResult};
use crate::data::diff::{DiffResult, LocsDiff};
use crate::data::stats::Locs;

use super::options::{Aggregation, LineTypes, OrderBy, OrderDirection, Ordering};

/// A single item in a query set (one row of data before string formatting).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryItem<T> {
    /// Row label (file path, crate name, module name, etc.)
    pub label: String,
    /// Statistics for this item
    pub stats: T,
}

/// Query set for count results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CountQuerySet {
    /// Aggregation level used
    pub aggregation: Aggregation,
    /// Line types included
    pub line_types: LineTypes,
    /// Data rows (filtered and sorted)
    pub items: Vec<QueryItem<Locs>>,
    /// Total across all items
    pub total: Locs,
    /// Number of files analyzed
    pub file_count: usize,
}

/// Query set for diff results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffQuerySet {
    /// Aggregation level used
    pub aggregation: Aggregation,
    /// Line types included
    pub line_types: LineTypes,
    /// Data rows (filtered and sorted)
    pub items: Vec<QueryItem<LocsDiff>>,
    /// Total diff across all items
    pub total: LocsDiff,
    /// Number of files changed
    pub file_count: usize,
    /// Source commit
    pub from_commit: String,
    /// Target commit
    pub to_commit: String,
    /// Lines added in non-Rust files
    #[serde(default)]
    pub non_rust_added: u64,
    /// Lines removed in non-Rust files
    #[serde(default)]
    pub non_rust_removed: u64,
}

impl CountQuerySet {
    /// Create a QuerySet from a CountResult.
    ///
    /// Applies aggregation level, line type filters, and ordering.
    pub fn from_result(
        result: &CountResult,
        aggregation: Aggregation,
        line_types: LineTypes,
        ordering: Ordering,
    ) -> Self {
        let items = build_count_items(result, &aggregation, &line_types, &ordering);
        let total = result.total.filter(line_types);

        CountQuerySet {
            aggregation,
            line_types,
            items,
            total,
            file_count: result.file_count,
        }
    }
}

/// Compute a relative path label for a file.
/// Returns the path relative to the workspace root, falling back to the full path if strip fails.
fn relative_path_label(path: &std::path::Path, root: &std::path::Path) -> String {
    path.strip_prefix(root)
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|_| path.to_string_lossy().to_string())
}

impl DiffQuerySet {
    /// Create a QuerySet from a DiffResult.
    ///
    /// Applies aggregation level, line type filters, and ordering.
    pub fn from_result(
        result: &DiffResult,
        aggregation: Aggregation,
        line_types: LineTypes,
        ordering: Ordering,
    ) -> Self {
        let items = build_diff_items(result, &aggregation, &line_types, &ordering);
        let total = result.total.filter(line_types);

        DiffQuerySet {
            aggregation,
            line_types,
            items,
            total,
            file_count: result.files.len(),
            from_commit: result.from_commit.clone(),
            to_commit: result.to_commit.clone(),
            non_rust_added: result.non_rust_added,
            non_rust_removed: result.non_rust_removed,
        }
    }
}

/// Compute filtered total for a Locs struct.
fn locs_filtered_total(locs: &Locs, line_types: &LineTypes) -> u64 {
    let mut total = 0;
    if line_types.code {
        total += locs.code;
    }
    if line_types.tests {
        total += locs.tests;
    }
    if line_types.examples {
        total += locs.examples;
    }
    if line_types.docs {
        total += locs.docs;
    }
    if line_types.comments {
        total += locs.comments;
    }
    if line_types.blanks {
        total += locs.blanks;
    }
    total
}

/// Get sort key for Locs based on OrderBy.
fn count_sort_key(locs: &Locs, order_by: &OrderBy, line_types: &LineTypes) -> u64 {
    match order_by {
        OrderBy::Label => 0, // Label sorting handled separately
        OrderBy::Code => locs.code,
        OrderBy::Tests => locs.tests,
        OrderBy::Examples => locs.examples,
        OrderBy::Docs => locs.docs,
        OrderBy::Comments => locs.comments,
        OrderBy::Blanks => locs.blanks,
        OrderBy::Total => locs_filtered_total(locs, line_types),
    }
}

/// Build query items from CountResult based on aggregation level.
fn build_count_items(
    result: &CountResult,
    aggregation: &Aggregation,
    line_types: &LineTypes,
    ordering: &Ordering,
) -> Vec<QueryItem<Locs>> {
    let mut items: Vec<(String, Locs)> = match aggregation {
        Aggregation::Total => return vec![],
        Aggregation::ByCrate => result
            .crates
            .iter()
            .map(|c| (c.name.clone(), c.stats.filter(*line_types)))
            .collect(),
        Aggregation::ByModule => result
            .modules
            .iter()
            .map(|m| {
                let label = if m.name.is_empty() {
                    "(root)".to_string()
                } else {
                    m.name.clone()
                };
                (label, m.stats.filter(*line_types))
            })
            .collect(),
        Aggregation::ByFile => result
            .files
            .iter()
            .map(|f| {
                (
                    relative_path_label(&f.path, &result.root),
                    f.stats.filter(*line_types),
                )
            })
            .collect(),
    };

    // Sort based on ordering
    match ordering.by {
        OrderBy::Label => {
            items.sort_by(|a, b| a.0.cmp(&b.0));
        }
        _ => {
            items.sort_by(|a, b| {
                let key_a = count_sort_key(&a.1, &ordering.by, line_types);
                let key_b = count_sort_key(&b.1, &ordering.by, line_types);
                key_a.cmp(&key_b)
            });
        }
    }

    // Reverse if descending
    if ordering.direction == OrderDirection::Descending {
        items.reverse();
    }

    // Map to QueryItems
    items
        .into_iter()
        .map(|(label, stats)| QueryItem { label, stats })
        .collect()
}

/// Compute filtered total for a LocsDiff struct.
fn locs_diff_filtered_total(diff: &LocsDiff, line_types: &LineTypes) -> (u64, u64) {
    let added = locs_filtered_total(&diff.added, line_types);
    let removed = locs_filtered_total(&diff.removed, line_types);
    (added, removed)
}

/// Get sort key for LocsDiff based on OrderBy (uses net change).
fn diff_sort_key(diff: &LocsDiff, order_by: &OrderBy, line_types: &LineTypes) -> i64 {
    match order_by {
        OrderBy::Label => 0, // Label sorting handled separately
        OrderBy::Code => diff.net_code(),
        OrderBy::Tests => diff.net_tests(),
        OrderBy::Examples => diff.net_examples(),
        OrderBy::Docs => diff.net_docs(),
        OrderBy::Comments => diff.net_comments(),
        OrderBy::Blanks => diff.net_blanks(),
        OrderBy::Total => {
            let (a, r) = locs_diff_filtered_total(diff, line_types);
            a as i64 - r as i64
        }
    }
}

/// Build query items from DiffResult based on aggregation level.
fn build_diff_items(
    result: &DiffResult,
    aggregation: &Aggregation,
    line_types: &LineTypes,
    ordering: &Ordering,
) -> Vec<QueryItem<LocsDiff>> {
    let mut items: Vec<(String, LocsDiff)> = match aggregation {
        Aggregation::Total => return vec![],
        Aggregation::ByCrate => result
            .crates
            .iter()
            .map(|c| (c.name.clone(), c.diff.filter(*line_types)))
            .collect(),
        Aggregation::ByModule => {
            let mut module_map: HashMap<String, LocsDiff> = HashMap::new();
            for crate_diff in &result.crates {
                let src_root = crate_diff.path.join("src");
                let effective_root = if src_root.exists() {
                    src_root
                } else {
                    crate_diff.path.clone()
                };
                for file in &crate_diff.files {
                    let abs_path = if file.path.is_absolute() {
                        file.path.clone()
                    } else {
                        result.root.join(&file.path)
                    };
                    let local_module = compute_module_name(&abs_path, &effective_root);
                    let full_name = if local_module.is_empty() {
                        crate_diff.name.clone()
                    } else {
                        format!("{}::{}", crate_diff.name, local_module)
                    };
                    let entry = module_map.entry(full_name).or_default();
                    *entry += file.diff.filter(*line_types);
                }
            }
            module_map.into_iter().collect()
        }
        Aggregation::ByFile => result
            .files
            .iter()
            .map(|f| {
                (
                    f.path.to_string_lossy().to_string(),
                    f.diff.filter(*line_types),
                )
            })
            .collect(),
    };

    // Sort based on ordering
    match ordering.by {
        OrderBy::Label => {
            items.sort_by(|a, b| a.0.cmp(&b.0));
        }
        _ => {
            items.sort_by(|a, b| {
                let key_a = diff_sort_key(&a.1, &ordering.by, line_types);
                let key_b = diff_sort_key(&b.1, &ordering.by, line_types);
                key_a.cmp(&key_b)
            });
        }
    }

    // Reverse if descending
    if ordering.direction == OrderDirection::Descending {
        items.reverse();
    }

    // Map to QueryItems
    items
        .into_iter()
        .map(|(label, stats)| QueryItem { label, stats })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::stats::CrateStats;
    use std::path::PathBuf;

    fn sample_locs(code: u64, tests: u64) -> Locs {
        Locs {
            code,
            tests,
            examples: 0,
            docs: 0,
            comments: 0,
            blanks: 0,
            total: code + tests,
        }
    }

    fn sample_count_result() -> CountResult {
        CountResult {
            root: PathBuf::from("/workspace"),
            file_count: 4,
            total: sample_locs(200, 100),
            crates: vec![
                CrateStats {
                    name: "alpha".to_string(),
                    path: PathBuf::from("/alpha"),
                    stats: sample_locs(50, 25),
                    files: vec![],
                },
                CrateStats {
                    name: "beta".to_string(),
                    path: PathBuf::from("/beta"),
                    stats: sample_locs(150, 75),
                    files: vec![],
                },
            ],
            files: vec![],
            modules: vec![],
        }
    }

    #[test]
    fn test_count_queryset_by_crate() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::default(),
        );

        assert_eq!(qs.items.len(), 2);
        assert_eq!(qs.file_count, 4);
        // Default ordering is by label ascending
        assert_eq!(qs.items[0].label, "alpha");
        assert_eq!(qs.items[1].label, "beta");
    }

    #[test]
    fn test_count_queryset_ordering_by_code() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::by_code(), // Descending by default
        );

        // beta has 150 code, alpha has 50
        assert_eq!(qs.items[0].label, "beta");
        assert_eq!(qs.items[0].stats.code, 150);
        assert_eq!(qs.items[1].label, "alpha");
        assert_eq!(qs.items[1].stats.code, 50);
    }

    #[test]
    fn test_count_queryset_total_aggregation() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::Total,
            LineTypes::everything(),
            Ordering::default(),
        );

        // Total aggregation returns no items (just uses total)
        assert_eq!(qs.items.len(), 0);
        assert_eq!(qs.total.code, 200);
        assert_eq!(qs.total.tests, 100);
    }

    #[test]
    fn test_count_queryset_filtered_line_types() {
        let result = sample_count_result();
        let line_types = LineTypes::new().with_code();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            line_types,
            Ordering::default(),
        );

        // Stats should be filtered
        assert_eq!(qs.items[0].stats.code, 50);
        assert_eq!(qs.items[0].stats.tests, 0); // Filtered out
    }

    #[test]
    fn test_count_queryset_by_file_relative_paths() {
        use crate::data::stats::FileStats;

        let result = CountResult {
            root: PathBuf::from("/workspace"),
            file_count: 2,
            total: sample_locs(100, 50),
            crates: vec![],
            files: vec![
                FileStats::new(PathBuf::from("/workspace/src/main.rs"), sample_locs(50, 25)),
                FileStats::new(
                    PathBuf::from("/workspace/crate-a/src/lib.rs"),
                    sample_locs(50, 25),
                ),
            ],
            modules: vec![],
        };

        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByFile,
            LineTypes::everything(),
            Ordering::default(),
        );

        // Labels should be relative to workspace root
        assert_eq!(qs.items.len(), 2);
        assert!(qs.items.iter().any(|item| item.label == "src/main.rs"));
        assert!(qs
            .items
            .iter()
            .any(|item| item.label == "crate-a/src/lib.rs"));
    }
}