cargo-port 0.1.3

A TUI for inspecting and managing Rust projects
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
use std::collections::HashMap;
use std::fs;
use std::ops::Range;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;

use tokei::CodeStats;
use tokei::Config;
use tokei::Language;
use tokei::LanguageType;
use tokei::Report;

use crate::project::LangEntry;

const CODE_LABEL: &str = "code";
const UNIT_TESTS_LABEL: &str = "unit tests";
const INTEGRATION_TESTS_LABEL: &str = "integration tests";
const EXAMPLES_LABEL: &str = "examples";
const BENCHES_LABEL: &str = "benches";

#[derive(Default)]
pub(super) struct RustBreakdownCache {
    unit_totals: HashMap<PathBuf, Option<LineTotals>>,
}

impl RustBreakdownCache {
    fn unit_totals_for_file(
        &mut self,
        path: &Path,
        totals: LineTotals,
        config: &Config,
    ) -> Option<LineTotals> {
        if let Some(cached) = self.unit_totals.get(path) {
            return *cached;
        }
        let unit = unit_totals_for_file(path, totals, config);
        self.unit_totals.insert(path.to_path_buf(), unit);
        unit
    }
}

pub(super) fn child_entries(
    root: &Path,
    language: &Language,
    config: &Config,
    cache: &mut RustBreakdownCache,
) -> Vec<LangEntry> {
    let mut buckets = RustBuckets::default();
    for report in &language.reports {
        let totals = LineTotals::from_report(report);
        match rust_file_bucket(root, report.name.as_path()) {
            RustBucket::Code => {
                add_code_file_with_unit_split(&mut buckets, report, totals, config, cache);
            },
            bucket => buckets.add_file(bucket, totals),
        }
    }
    buckets.entries()
}

fn add_code_file_with_unit_split(
    buckets: &mut RustBuckets,
    report: &Report,
    totals: LineTotals,
    config: &Config,
    cache: &mut RustBreakdownCache,
) {
    let Some(unit) = cache.unit_totals_for_file(report.name.as_path(), totals, config) else {
        buckets.add_file(RustBucket::Code, totals);
        return;
    };

    let code = totals.without(unit);
    buckets.add_file(RustBucket::UnitTests, unit);
    if !code.is_empty() {
        buckets.add_file(RustBucket::Code, code);
    }
}

fn unit_totals_for_file(path: &Path, totals: LineTotals, config: &Config) -> Option<LineTotals> {
    let source = fs::read_to_string(path).ok()?;
    let ranges = cfg_test_item_ranges(&source);
    if ranges.is_empty() {
        return None;
    }
    let unit = ranges
        .iter()
        .map(|range| {
            LineTotals::from_code_stats(
                &LanguageType::Rust.parse_from_str(&source[range.clone()], config),
            )
        })
        .fold(LineTotals::default(), |mut acc, totals| {
            acc.add(totals);
            acc
        })
        .capped_by(totals);
    (!unit.is_empty()).then_some(unit)
}

fn rust_file_bucket(root: &Path, path: &Path) -> RustBucket {
    let relative = path.strip_prefix(root).unwrap_or(path);
    let components = normal_components(relative);
    if components.iter().any(|part| *part == "examples") {
        RustBucket::Examples
    } else if components.iter().any(|part| *part == "benches") {
        RustBucket::Benches
    } else if is_src_unit_test_path(&components) {
        RustBucket::UnitTests
    } else if components.iter().any(|part| *part == "tests") {
        RustBucket::IntegrationTests
    } else {
        RustBucket::Code
    }
}

fn normal_components(path: &Path) -> Vec<String> {
    path.components()
        .filter_map(|component| match component {
            Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            Component::Prefix(_)
            | Component::RootDir
            | Component::CurDir
            | Component::ParentDir => None,
        })
        .collect()
}

fn is_src_unit_test_path(components: &[String]) -> bool {
    let has_src_tests_dir = components.iter().enumerate().any(|(index, part)| {
        part == "tests"
            && components[..index]
                .iter()
                .any(|candidate| candidate == "src")
    });
    let is_tests_file = components.last().is_some_and(|file| file == "tests.rs")
        && components.iter().any(|part| part == "src");
    has_src_tests_dir || is_tests_file
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RustBucket {
    Code,
    UnitTests,
    IntegrationTests,
    Examples,
    Benches,
}

impl RustBucket {
    const ORDERED: [Self; 5] = [
        Self::Code,
        Self::UnitTests,
        Self::IntegrationTests,
        Self::Examples,
        Self::Benches,
    ];

    const fn label(self) -> &'static str {
        match self {
            Self::Code => CODE_LABEL,
            Self::UnitTests => UNIT_TESTS_LABEL,
            Self::IntegrationTests => INTEGRATION_TESTS_LABEL,
            Self::Examples => EXAMPLES_LABEL,
            Self::Benches => BENCHES_LABEL,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct LineTotals {
    code:     usize,
    comments: usize,
    blanks:   usize,
}

impl LineTotals {
    fn from_report(report: &Report) -> Self { Self::from_code_stats(&report.stats) }

    fn from_code_stats(stats: &CodeStats) -> Self {
        let stats = stats.summarise();
        Self {
            code:     stats.code,
            comments: stats.comments,
            blanks:   stats.blanks,
        }
    }

    const fn is_empty(self) -> bool { self.code == 0 && self.comments == 0 && self.blanks == 0 }

    const fn add(&mut self, other: Self) {
        self.code += other.code;
        self.comments += other.comments;
        self.blanks += other.blanks;
    }

    const fn capped_by(self, max: Self) -> Self {
        Self {
            code:     if self.code > max.code {
                max.code
            } else {
                self.code
            },
            comments: if self.comments > max.comments {
                max.comments
            } else {
                self.comments
            },
            blanks:   if self.blanks > max.blanks {
                max.blanks
            } else {
                self.blanks
            },
        }
    }

    const fn without(self, other: Self) -> Self {
        Self {
            code:     self.code.saturating_sub(other.code),
            comments: self.comments.saturating_sub(other.comments),
            blanks:   self.blanks.saturating_sub(other.blanks),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct BucketTotals {
    files: usize,
    lines: LineTotals,
}

impl BucketTotals {
    const fn is_empty(self) -> bool { self.files == 0 && self.lines.is_empty() }

    const fn add_file(&mut self, totals: LineTotals) {
        if totals.is_empty() {
            return;
        }
        self.files += 1;
        self.lines.add(totals);
    }

    fn entry(self, label: &'static str) -> Option<LangEntry> {
        (!self.is_empty()).then(|| LangEntry {
            language: label.to_string(),
            files:    self.files,
            code:     self.lines.code,
            comments: self.lines.comments,
            blanks:   self.lines.blanks,
            children: Vec::new(),
        })
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct RustBuckets {
    code:        BucketTotals,
    unit:        BucketTotals,
    integration: BucketTotals,
    examples:    BucketTotals,
    benches:     BucketTotals,
}

impl RustBuckets {
    const fn add_file(&mut self, bucket: RustBucket, totals: LineTotals) {
        self.bucket_mut(bucket).add_file(totals);
    }

    const fn bucket_mut(&mut self, bucket: RustBucket) -> &mut BucketTotals {
        match bucket {
            RustBucket::Code => &mut self.code,
            RustBucket::UnitTests => &mut self.unit,
            RustBucket::IntegrationTests => &mut self.integration,
            RustBucket::Examples => &mut self.examples,
            RustBucket::Benches => &mut self.benches,
        }
    }

    const fn bucket(self, bucket: RustBucket) -> BucketTotals {
        match bucket {
            RustBucket::Code => self.code,
            RustBucket::UnitTests => self.unit,
            RustBucket::IntegrationTests => self.integration,
            RustBucket::Examples => self.examples,
            RustBucket::Benches => self.benches,
        }
    }

    fn entries(self) -> Vec<LangEntry> {
        RustBucket::ORDERED
            .into_iter()
            .filter_map(|bucket| self.bucket(bucket).entry(bucket.label()))
            .collect()
    }
}

fn cfg_test_item_ranges(source: &str) -> Vec<Range<usize>> {
    let mut ranges = Vec::new();
    let mut offset = 0;
    for line in source.split_inclusive('\n') {
        if is_cfg_test_attr(line.trim_start()) {
            let search_start = offset + line.len();
            if let Some(end) = cfg_test_item_end(source, search_start) {
                ranges.push(offset..end);
            }
        }
        offset += line.len();
    }
    merge_ranges(ranges)
}

fn is_cfg_test_attr(trimmed: &str) -> bool {
    let Some(after_open) = trimmed.strip_prefix("#[") else {
        return false;
    };
    let Some(end) = after_open.find(']') else {
        return false;
    };
    let compact = after_open[..end]
        .chars()
        .filter(|ch| !ch.is_whitespace())
        .collect::<String>();
    let Some(inner) = compact
        .strip_prefix("cfg(")
        .and_then(|value| value.strip_suffix(')'))
    else {
        return false;
    };
    inner
        .split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
        .any(|token| token == "test")
}

fn cfg_test_item_end(source: &str, search_start: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let mut index = search_start;
    while index < bytes.len() {
        if starts_with(bytes, index, b"//") {
            index = skip_line_comment(bytes, index);
            continue;
        }
        if starts_with(bytes, index, b"/*") {
            index = skip_block_comment(bytes, index);
            continue;
        }
        if let Some(hash_count) = raw_string_hash_count(bytes, index) {
            index = skip_raw_string(bytes, index, hash_count);
            continue;
        }
        match bytes[index] {
            b'"' => index = skip_quoted_string(bytes, index),
            b'\'' => {
                index = char_literal_end(bytes, index).unwrap_or(index + 1);
            },
            b'{' => return matching_brace_end(source, index),
            b';' => return Some(index + 1),
            _ => index += 1,
        }
    }
    None
}

fn merge_ranges(mut ranges: Vec<Range<usize>>) -> Vec<Range<usize>> {
    ranges.sort_by_key(|range| range.start);
    let mut merged: Vec<Range<usize>> = Vec::new();
    for range in ranges {
        if let Some(last) = merged.last_mut()
            && range.start <= last.end
        {
            last.end = last.end.max(range.end);
            continue;
        }
        merged.push(range);
    }
    merged
}

fn matching_brace_end(source: &str, open: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let mut index = open;
    let mut depth = 0usize;
    while index < bytes.len() {
        if starts_with(bytes, index, b"//") {
            index = skip_line_comment(bytes, index);
            continue;
        }
        if starts_with(bytes, index, b"/*") {
            index = skip_block_comment(bytes, index);
            continue;
        }
        if let Some(hash_count) = raw_string_hash_count(bytes, index) {
            index = skip_raw_string(bytes, index, hash_count);
            continue;
        }
        match bytes[index] {
            b'"' => index = skip_quoted_string(bytes, index),
            b'\'' => {
                index = char_literal_end(bytes, index).unwrap_or(index + 1);
            },
            b'{' => {
                depth += 1;
                index += 1;
            },
            b'}' => {
                depth = depth.saturating_sub(1);
                index += 1;
                if depth == 0 {
                    return Some(index);
                }
            },
            _ => index += 1,
        }
    }
    None
}

fn starts_with(bytes: &[u8], index: usize, pattern: &[u8]) -> bool {
    bytes
        .get(index..index + pattern.len())
        .is_some_and(|candidate| candidate == pattern)
}

fn skip_line_comment(bytes: &[u8], mut index: usize) -> usize {
    while index < bytes.len() && bytes[index] != b'\n' {
        index += 1;
    }
    index
}

fn skip_block_comment(bytes: &[u8], mut index: usize) -> usize {
    let mut depth = 1usize;
    index += 2;
    while index < bytes.len() {
        if starts_with(bytes, index, b"/*") {
            depth += 1;
            index += 2;
        } else if starts_with(bytes, index, b"*/") {
            depth = depth.saturating_sub(1);
            index += 2;
            if depth == 0 {
                return index;
            }
        } else {
            index += 1;
        }
    }
    index
}

fn raw_string_hash_count(bytes: &[u8], index: usize) -> Option<usize> {
    if bytes.get(index) != Some(&b'r') {
        return None;
    }
    let mut cursor = index + 1;
    while bytes.get(cursor) == Some(&b'#') {
        cursor += 1;
    }
    (bytes.get(cursor) == Some(&b'"')).then_some(cursor - index - 1)
}

fn skip_raw_string(bytes: &[u8], index: usize, hash_count: usize) -> usize {
    let mut cursor = index + hash_count + 2;
    while cursor < bytes.len() {
        if bytes[cursor] == b'"' {
            let hash_start = cursor + 1;
            let hash_end = hash_start + hash_count;
            if bytes
                .get(hash_start..hash_end)
                .is_some_and(|hashes| hashes.iter().all(|byte| *byte == b'#'))
            {
                return hash_end;
            }
        }
        cursor += 1;
    }
    cursor
}

fn skip_quoted_string(bytes: &[u8], mut index: usize) -> usize {
    index += 1;
    while index < bytes.len() {
        match bytes[index] {
            b'\\' => index += 2,
            b'"' => return index + 1,
            _ => index += 1,
        }
    }
    index
}

fn char_literal_end(bytes: &[u8], index: usize) -> Option<usize> {
    let mut cursor = index + 1;
    while cursor < bytes.len() && cursor <= index + 6 && bytes[cursor] != b'\n' {
        match bytes[cursor] {
            b'\\' => cursor += 2,
            b'\'' => return Some(cursor + 1),
            _ => cursor += 1,
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use std::error::Error;
    use std::fs;
    use std::io;
    use std::path::Path;

    use super::BENCHES_LABEL;
    use super::CODE_LABEL;
    use super::EXAMPLES_LABEL;
    use super::INTEGRATION_TESTS_LABEL;
    use super::UNIT_TESTS_LABEL;
    use crate::project::LangEntry;
    use crate::project::LanguageStats;
    use crate::scan::language_stats;

    type TestResult = Result<(), Box<dyn Error>>;

    fn write_file(root: &Path, relative: &str, contents: &str) -> io::Result<()> {
        let path = root.join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, contents)
    }

    fn rust_entry(stats: &LanguageStats) -> io::Result<&LangEntry> {
        stats
            .entries
            .iter()
            .find(|entry| entry.language == "Rust")
            .ok_or_else(|| io::Error::other("missing Rust entry"))
    }

    fn child_entry<'a>(entry: &'a LangEntry, label: &str) -> io::Result<&'a LangEntry> {
        entry
            .children
            .iter()
            .find(|child| child.language == label)
            .ok_or_else(|| io::Error::other(format!("missing `{label}` child")))
    }

    #[test]
    fn rust_breakdown_uses_requested_child_labels() -> TestResult {
        let dir = tempfile::tempdir()?;
        write_file(dir.path(), "src/lib.rs", "pub fn code() {}\n")?;
        write_file(dir.path(), "src/tests.rs", "#[test]\nfn unit_file() {}\n")?;
        write_file(
            dir.path(),
            "tests/integration.rs",
            "#[test]\nfn integration() {}\n",
        )?;
        write_file(dir.path(), "examples/demo.rs", "fn main() {}\n")?;
        write_file(dir.path(), "benches/bench.rs", "fn main() {}\n")?;

        let stats = language_stats::collect_language_stats_single(dir.path());
        let rust = rust_entry(&stats)?;
        let labels = rust
            .children
            .iter()
            .map(|entry| entry.language.as_str())
            .collect::<Vec<_>>();

        assert_eq!(
            labels,
            vec![
                CODE_LABEL,
                UNIT_TESTS_LABEL,
                INTEGRATION_TESTS_LABEL,
                EXAMPLES_LABEL,
                BENCHES_LABEL,
            ]
        );
        assert_rust_children_add_to_parent(rust);
        Ok(())
    }

    #[test]
    fn inline_cfg_test_module_moves_loc_to_unit_tests() -> TestResult {
        let dir = tempfile::tempdir()?;
        write_file(
            dir.path(),
            "src/lib.rs",
            "\
pub fn production() -> usize {
    1
}

#[cfg(test)]
mod tests {
    #[test]
    fn unit() {
        let text = \"{still text}\";
        assert_eq!(text.len(), 12);
    }
}
",
        )?;

        let stats = language_stats::collect_language_stats_single(dir.path());
        let rust = rust_entry(&stats)?;
        let code = child_entry(rust, CODE_LABEL)?;
        let unit = child_entry(rust, UNIT_TESTS_LABEL)?;

        assert!(code.code > 0);
        assert!(unit.code > 0);
        assert_rust_children_add_to_parent(rust);
        Ok(())
    }

    fn assert_rust_children_add_to_parent(rust: &LangEntry) {
        let code: usize = rust.children.iter().map(|entry| entry.code).sum();
        let comments: usize = rust.children.iter().map(|entry| entry.comments).sum();
        let blanks: usize = rust.children.iter().map(|entry| entry.blanks).sum();
        assert_eq!(code, rust.code);
        assert_eq!(comments, rust.comments);
        assert_eq!(blanks, rust.blanks);
    }
}