rustloclib 0.15.3

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
//! Table-ready data structures for LOC output.
//!
//! This module provides `LOCTable`, a presentation-ready data structure
//! that can be directly consumed by templates or serialized to JSON.
//!
//! The data flow is:
//! 1. Raw Data (CountResult, DiffResult)
//! 2. QuerySet (filtered, aggregated, sorted)
//! 3. LOCTable (formatted strings for display)
//!
//! LOCTable is a pure presentation layer - it only formats data, no filtering
//! or sorting logic. All computation happens in the QuerySet layer.

use serde::{Deserialize, Serialize};

use crate::data::diff::LocsDiff;
use crate::data::stats::Locs;
use crate::query::options::Aggregation;
use crate::query::queryset::{CountQuerySet, DiffQuerySet};

/// A single row in the table (data row or footer).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableRow {
    /// Row label (file path, crate name, "Total (N files)", etc.)
    pub label: String,
    /// Values for each category column (as strings, ready for display)
    pub values: Vec<String>,
}

/// Table-ready LOC data.
///
/// This is the final data structure before presentation. Templates
/// iterate over headers/rows/footer and apply formatting - no computation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LOCTable {
    /// Optional title (e.g., "Diff: HEAD~5 → HEAD")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Column headers: [label_header, line_type1, line_type2, ..., Total]
    pub headers: Vec<String>,
    /// Data rows
    pub rows: Vec<TableRow>,
    /// Summary/footer row
    pub footer: TableRow,
    /// Optional non-Rust changes summary (e.g., "Non-Rust changes: +10/-5/5 net")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub non_rust_summary: Option<String>,
    /// Optional legend text below the table (e.g., "+added / -removed / net")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub legend: Option<String>,
}

impl LOCTable {
    /// Create a LOCTable from a CountQuerySet.
    ///
    /// The QuerySet already contains filtered, aggregated, and sorted data.
    /// This method just formats it into displayable strings.
    pub fn from_count_queryset(qs: &CountQuerySet) -> Self {
        let headers = build_headers(&qs.aggregation, &qs.line_types);
        let rows: Vec<TableRow> = qs
            .items
            .iter()
            .map(|item| TableRow {
                label: item.label.clone(),
                values: format_locs(&item.stats, &qs.line_types),
            })
            .collect();
        let footer = TableRow {
            label: build_footer_label(
                &qs.aggregation,
                rows.len(),
                qs.total_items,
                qs.file_count,
                qs.top_applied,
            ),
            values: format_locs(&qs.total, &qs.line_types),
        };

        LOCTable {
            title: None,
            headers,
            rows,
            footer,
            non_rust_summary: None,
            legend: None,
        }
    }

    /// Create a LOCTable from a DiffQuerySet.
    ///
    /// The QuerySet already contains filtered, aggregated, and sorted data.
    /// This method just formats it into displayable strings with diff notation.
    pub fn from_diff_queryset(qs: &DiffQuerySet) -> Self {
        let headers = build_headers(&qs.aggregation, &qs.line_types);
        let rows: Vec<TableRow> = qs
            .items
            .iter()
            .map(|item| TableRow {
                label: item.label.clone(),
                values: format_locs_diff(&item.stats, &qs.line_types),
            })
            .collect();
        let footer = TableRow {
            label: build_footer_label(
                &qs.aggregation,
                rows.len(),
                qs.total_items,
                qs.file_count,
                qs.top_applied,
            ),
            values: format_locs_diff(&qs.total, &qs.line_types),
        };
        let title = Some(format!("Diff: {}{}", qs.from_commit, qs.to_commit));

        let non_rust_summary = if qs.non_rust_added > 0 || qs.non_rust_removed > 0 {
            let nr_net = qs.non_rust_added as i64 - qs.non_rust_removed as i64;
            Some(format!(
                    "Non-Rust changes: [additions]+{}[/additions] / [deletions]-{}[/deletions] / {} net",
                    qs.non_rust_added, qs.non_rust_removed, nr_net
                ))
        } else {
            None
        };

        LOCTable {
            title,
            headers,
            rows,
            footer,
            non_rust_summary,
            legend: Some("(+added / -removed / net)".to_string()),
        }
    }
}

/// Line types configuration for header building.
/// This is a local copy of the fields we need to avoid circular imports.
struct LineTypesView {
    code: bool,
    tests: bool,
    examples: bool,
    docs: bool,
    comments: bool,
    blanks: bool,
    total: bool,
}

impl From<&crate::query::options::LineTypes> for LineTypesView {
    fn from(lt: &crate::query::options::LineTypes) -> Self {
        LineTypesView {
            code: lt.code,
            tests: lt.tests,
            examples: lt.examples,
            docs: lt.docs,
            comments: lt.comments,
            blanks: lt.blanks,
            total: lt.total,
        }
    }
}

/// Build footer label based on aggregation level.
///
/// `displayed` is the number of rows actually shown after any user-driven
/// reduction. `total` is the pre-reduction row count. When they differ the
/// label makes the gap explicit so the reader can see that the totals row
/// reflects more data than what's visible.
///
/// `top_applied` distinguishes the two reduction paths so the wording is
/// honest: "top X of Y" for `--top` (a sorted slice), plain "X of Y" for
/// filter-eliminated rows. Both can apply at once, in which case the
/// "top" wording dominates because the visible rows ARE the top of what
/// passed the filter.
///
/// `total < displayed` is logically impossible (reductions only shrink
/// the row set), but a deserialized queryset from a payload that pre-dates
/// the `total_items` field will arrive with `total = 0`. The `.max` clamp
/// keeps the footer correct for that case rather than rendering nonsense
/// like "Total (0 crates)" alongside two visible rows.
fn build_footer_label(
    aggregation: &Aggregation,
    displayed: usize,
    total: usize,
    file_count: usize,
    top_applied: bool,
) -> String {
    let unit = match aggregation {
        Aggregation::Total => return format!("Total ({} files)", file_count),
        Aggregation::ByCrate => "crates",
        Aggregation::ByModule => "modules",
        Aggregation::ByFile => "files",
    };
    let total = total.max(displayed);
    if displayed == total {
        format!("Total ({} {})", total, unit)
    } else if top_applied {
        format!("Total (top {} of {} {})", displayed, total, unit)
    } else {
        format!("Total ({} of {} {})", displayed, total, unit)
    }
}

/// Build column headers based on aggregation level and enabled line types.
fn build_headers(
    aggregation: &Aggregation,
    line_types: &crate::query::options::LineTypes,
) -> Vec<String> {
    let label_header = match aggregation {
        Aggregation::Total => "Name".to_string(),
        Aggregation::ByCrate => "Crate".to_string(),
        Aggregation::ByModule => "Module".to_string(),
        Aggregation::ByFile => "File".to_string(),
    };

    let lt = LineTypesView::from(line_types);
    let mut headers = vec![label_header];

    if lt.code {
        headers.push("Code".to_string());
    }
    if lt.tests {
        headers.push("Tests".to_string());
    }
    if lt.examples {
        headers.push("Examples".to_string());
    }
    if lt.docs {
        headers.push("Docs".to_string());
    }
    if lt.comments {
        headers.push("Comments".to_string());
    }
    if lt.blanks {
        headers.push("Blanks".to_string());
    }
    if lt.total {
        headers.push("Total".to_string());
    }

    headers
}

/// Format Locs values as strings for display.
fn format_locs(locs: &Locs, line_types: &crate::query::options::LineTypes) -> Vec<String> {
    let lt = LineTypesView::from(line_types);
    let mut values = Vec::new();

    if lt.code {
        values.push(locs.code.to_string());
    }
    if lt.tests {
        values.push(locs.tests.to_string());
    }
    if lt.examples {
        values.push(locs.examples.to_string());
    }
    if lt.docs {
        values.push(locs.docs.to_string());
    }
    if lt.comments {
        values.push(locs.comments.to_string());
    }
    if lt.blanks {
        values.push(locs.blanks.to_string());
    }
    if lt.total {
        // Use the precomputed all field
        values.push(locs.total.to_string());
    }

    values
}

/// Format a diff value as "+added/-removed/net" with standout style tags.
fn format_diff_value(added: u64, removed: u64) -> String {
    let net = added as i64 - removed as i64;
    format!(
        "[additions]+{}[/additions]/[deletions]-{}[/deletions]/{}",
        added, removed, net
    )
}

/// Format LocsDiff values as strings for display.
fn format_locs_diff(diff: &LocsDiff, line_types: &crate::query::options::LineTypes) -> Vec<String> {
    let lt = LineTypesView::from(line_types);
    let mut values = Vec::new();

    if lt.code {
        values.push(format_diff_value(diff.added.code, diff.removed.code));
    }
    if lt.tests {
        values.push(format_diff_value(diff.added.tests, diff.removed.tests));
    }
    if lt.examples {
        values.push(format_diff_value(
            diff.added.examples,
            diff.removed.examples,
        ));
    }
    if lt.docs {
        values.push(format_diff_value(diff.added.docs, diff.removed.docs));
    }
    if lt.comments {
        values.push(format_diff_value(
            diff.added.comments,
            diff.removed.comments,
        ));
    }
    if lt.blanks {
        values.push(format_diff_value(diff.added.blanks, diff.removed.blanks));
    }
    if lt.total {
        // Use the precomputed all fields
        values.push(format_diff_value(diff.added.total, diff.removed.total));
    }

    values
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::counter::CountResult;
    use crate::data::stats::CrateStats;
    use crate::query::options::{LineTypes, Ordering};
    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_headers_by_crate() {
        let headers = build_headers(&Aggregation::ByCrate, &LineTypes::everything());
        assert_eq!(headers[0], "Crate");
        assert_eq!(headers[1], "Code");
        assert_eq!(headers[2], "Tests");
        assert_eq!(headers[3], "Examples");
        assert_eq!(headers[4], "Docs");
        assert_eq!(headers[5], "Comments");
        assert_eq!(headers[6], "Blanks");
        assert_eq!(headers[7], "Total");
    }

    #[test]
    fn test_headers_filtered_line_types() {
        let line_types = LineTypes::new().with_code();
        let headers = build_headers(&Aggregation::ByFile, &line_types);
        assert_eq!(headers.len(), 3); // File, Code, All
        assert_eq!(headers[0], "File");
        assert_eq!(headers[1], "Code");
        assert_eq!(headers[2], "Total");
    }

    #[test]
    fn test_format_locs() {
        let locs = sample_locs(100, 50);
        let values = format_locs(&locs, &LineTypes::everything());
        assert_eq!(values[0], "100"); // Code
        assert_eq!(values[1], "50"); // Tests
        assert_eq!(values[2], "0"); // Examples
        assert_eq!(values[3], "0"); // Docs
        assert_eq!(values[4], "0"); // Comments
        assert_eq!(values[5], "0"); // Blanks
        assert_eq!(values[6], "150"); // All
    }

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

        assert!(table.title.is_none());
        assert_eq!(table.headers[0], "Crate");
        assert_eq!(table.rows.len(), 2);
        // Default ordering is by label ascending: alpha before beta
        assert_eq!(table.rows[0].label, "alpha");
        assert_eq!(table.rows[1].label, "beta");
        assert_eq!(table.footer.label, "Total (2 crates)");
    }

    #[test]
    fn test_footer_label_marks_truncation_when_top_applied() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::default(),
        )
        .top(1);
        let table = LOCTable::from_count_queryset(&qs);

        assert_eq!(table.rows.len(), 1);
        assert_eq!(table.footer.label, "Total (top 1 of 2 crates)");
    }

    #[test]
    fn test_footer_label_filter_only_uses_plain_x_of_y() {
        // When rows are reduced by a filter (not by --top), the footer
        // says "X of Y" without the "top" qualifier, because the visible
        // rows aren't sorted-and-sliced — they're just the ones that
        // passed the predicate.
        use crate::query::options::{Field, Op, Predicate};

        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::default(),
        )
        .filter(&[Predicate::new(Field::Code, Op::Gte, 100)]);
        let table = LOCTable::from_count_queryset(&qs);

        assert_eq!(table.rows.len(), 1);
        assert_eq!(table.footer.label, "Total (1 of 2 crates)");
    }

    #[test]
    fn test_footer_label_filter_then_top_uses_top_wording() {
        use crate::query::options::{Field, Op, Predicate};

        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::default(),
        )
        .filter(&[Predicate::new(Field::Code, Op::Gte, 50)])
        .top(1);
        let table = LOCTable::from_count_queryset(&qs);

        // Both filter (kept 2) and top (kept 1) ran; "top" wording wins
        // because the visible row IS the top of what passed the filter.
        assert_eq!(table.rows.len(), 1);
        assert_eq!(table.footer.label, "Total (top 1 of 2 crates)");
    }

    #[test]
    fn test_footer_label_clamps_when_total_items_missing() {
        // A queryset deserialized from a payload that predates `total_items`
        // arrives with `total_items = 0`. The footer must still show the
        // correct row count rather than "Total (0 crates)".
        let result = sample_count_result();
        let mut qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::default(),
        );
        qs.total_items = 0; // simulate stale payload
        let table = LOCTable::from_count_queryset(&qs);

        assert_eq!(table.rows.len(), 2);
        assert_eq!(table.footer.label, "Total (2 crates)");
    }

    #[test]
    fn test_ordering_by_label_ascending() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::by_label(),
        );
        let table = LOCTable::from_count_queryset(&qs);

        assert_eq!(table.rows[0].label, "alpha");
        assert_eq!(table.rows[1].label, "beta");
    }

    #[test]
    fn test_ordering_by_label_descending() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::by_label().descending(),
        );
        let table = LOCTable::from_count_queryset(&qs);

        assert_eq!(table.rows[0].label, "beta");
        assert_eq!(table.rows[1].label, "alpha");
    }

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

        // beta has 150 code, alpha has 50
        assert_eq!(table.rows[0].label, "beta");
        assert_eq!(table.rows[0].values[0], "150");
        assert_eq!(table.rows[1].label, "alpha");
        assert_eq!(table.rows[1].values[0], "50");
    }

    #[test]
    fn test_ordering_by_code_ascending() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::by_code().ascending(),
        );
        let table = LOCTable::from_count_queryset(&qs);

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

    #[test]
    fn test_ordering_by_total_descending() {
        let result = sample_count_result();
        let qs = CountQuerySet::from_result(
            &result,
            Aggregation::ByCrate,
            LineTypes::everything(),
            Ordering::by_total(),
        );
        let table = LOCTable::from_count_queryset(&qs);

        // beta has 225 total, alpha has 75
        assert_eq!(table.rows[0].label, "beta");
        assert_eq!(table.rows[1].label, "alpha");
    }

    #[test]
    fn test_format_diff_value() {
        assert_eq!(
            format_diff_value(10, 5),
            "[additions]+10[/additions]/[deletions]-5[/deletions]/5"
        );
        assert_eq!(
            format_diff_value(5, 10),
            "[additions]+5[/additions]/[deletions]-10[/deletions]/-5"
        );
        assert_eq!(
            format_diff_value(0, 0),
            "[additions]+0[/additions]/[deletions]-0[/deletions]/0"
        );
    }
}