dejadoc 0.5.0

Find duplicated Rust doctests and functions across a workspace
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
//! Report rendering.

use crate::{Kind, Remedy, Report};

use alloc::format;
use alloc::string::String;
use core::fmt::Write;

/// Render the report for humans.
#[must_use]
pub fn human(report: &Report, verbose: bool) -> String {
    let mut out = String::new();
    let _ = writeln!(
        &mut out,
        "{} doctests ({} unique), {} functions ({} unique), {} duplicated groups",
        report.total,
        report.unique,
        report.functions,
        report.unique_functions,
        report.groups.len()
    );
    if report.groups.is_empty() {
        return out;
    }
    out.push('\n');
    for (i, group) in report.groups.iter().enumerate() {
        let _ = match group.kind {
            Kind::Doctest => writeln!(
                &mut out,
                "[{}] {} sites, {} tokens",
                group.id,
                group.sites.len(),
                group.tokens
            ),
            Kind::Function => writeln!(
                &mut out,
                "[{}] {} functions, {} tokens, {}",
                group.id,
                group.sites.len(),
                group.tokens,
                advice(group.remedy.unwrap_or(Remedy::Delete))
            ),
        };
        let deletes = group.kind == Kind::Function
            && group.remedy.unwrap_or(Remedy::Delete) == Remedy::Delete;
        for (copy, site) in group.sites.iter().enumerate() {
            let info = if deletes && copy > 0 && site.public {
                format!("   (public API, {PUBLIC_ADVICE})")
            } else if site.info.is_empty() {
                String::new()
            } else {
                format!("   ({})", site.info.join(", "))
            };
            let _ = writeln!(
                &mut out,
                "  {}:{}  {}{}",
                site.file.as_str(),
                site.line,
                site.item,
                info
            );
            if verbose {
                for line in site.code.lines() {
                    let _ = writeln!(&mut out, "    {line}");
                }
            }
        }
        if i + 1 < report.groups.len() {
            out.push('\n');
        }
    }
    out.push('\n');
    if report.groups.iter().any(|g| g.kind == Kind::Doctest) {
        out.push_str(
            "Remove the copies listed above, or keep one on purpose with a `rust,dejadoc` fence\n",
        );
    }
    if report.groups.iter().any(|g| g.kind == Kind::Function) {
        out.push_str("Act on each function group as its advice says, or keep one on purpose with a `// dejadoc: allow` comment above it\n");
    }
    out
}

/// The advice for a copy other crates may call, which deleting would break.
const PUBLIC_ADVICE: &str = "make it call the kept copy or deprecate it";

/// The advice the human report gives a function group.
fn advice(remedy: Remedy) -> &'static str {
    match remedy {
        Remedy::Delete => "delete or update all but the first",
        Remedy::MergeCfg => "one function under the merged cfg can replace them",
        Remedy::GenericOrMacro => "a generic or a macro can share one body",
        Remedy::HelperOrMacro => "a helper or a macro can share one body",
    }
}

/// Render the report as JSON.
///
/// # Panics
///
/// `Report` is `Serialize`. Serialization failure would be a bug in this
/// crate.
#[must_use]
pub fn json(report: &Report) -> String {
    serde_json::to_string(report).expect("Report serializes to JSON")
}

/// Render the report as GitHub workflow annotations, one per copy to
/// remove. They need no token, so a fork pull request still shows them
/// anchored in the diff.
#[must_use]
pub fn annotations(report: &Report, no_fail: bool) -> String {
    let level = if no_fail { "warning" } else { "error" };
    let mut out = String::new();
    for group in &report.groups {
        let Some((kept, copies)) = group.sites.split_first() else {
            continue;
        };
        for copy in copies {
            let (file, line, item, kept_item, kept_file, kept_line, id) = (
                escape_property(copy.file.as_str()),
                copy.line,
                escape(&copy.item),
                escape(&kept.item),
                escape(kept.file.as_str()),
                kept.line,
                &group.id,
            );
            let _ = match group.kind {
                Kind::Doctest => writeln!(
                    &mut out,
                    "::{level} file={file},line={line},title=dejadoc::{item} duplicates the doctest of {kept_item} at {kept_file}:{kept_line}, group {id}"
                ),
                Kind::Function => match group.remedy.unwrap_or(Remedy::Delete) {
                    Remedy::Delete if copy.public => writeln!(
                        &mut out,
                        "::{level} file={file},line={line},title=dejadoc::{item} repeats {kept_item} at {kept_file}:{kept_line} and is public API, {PUBLIC_ADVICE}, group {id}"
                    ),
                    Remedy::Delete => writeln!(
                        &mut out,
                        "::{level} file={file},line={line},title=dejadoc::{item} duplicates the function {kept_item} at {kept_file}:{kept_line}, group {id}"
                    ),
                    Remedy::MergeCfg => writeln!(
                        &mut out,
                        "::{level} file={file},line={line},title=dejadoc::{item} repeats {kept_item} at {kept_file}:{kept_line} under another cfg, one function under both cfgs can replace them, group {id}"
                    ),
                    Remedy::GenericOrMacro => writeln!(
                        &mut out,
                        "::{level} file={file},line={line},title=dejadoc::{item} repeats {kept_item} at {kept_file}:{kept_line} on another type, a generic or a macro can share it, group {id}"
                    ),
                    Remedy::HelperOrMacro => writeln!(
                        &mut out,
                        "::{level} file={file},line={line},title=dejadoc::{item} repeats {kept_item} at {kept_file}:{kept_line} and can't be deleted, a helper or a macro can share it, group {id}"
                    ),
                },
            };
        }
    }
    out
}

/// A workflow command message, with the characters that would end it
/// percent encoded.
fn escape(text: &str) -> String {
    text.replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

/// A workflow command property value, which a `,` or `:` would also end.
fn escape_property(text: &str) -> String {
    escape(text).replace(':', "%3A").replace(',', "%2C")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DocTest, Group, Remedy};
    use alloc::string::ToString;
    use alloc::vec;
    use alloc::vec::Vec;

    fn site(file: &str, line: u32, item: &str, code: &str, info: &[&str]) -> DocTest {
        DocTest {
            file: file.to_string(),
            line,
            end: None,
            item: item.to_string(),
            info: info.iter().map(ToString::to_string).collect(),
            code: code.to_string(),
            allow: false,
            self_type: None,
            public: false,
        }
    }

    fn report() -> Report {
        Report {
            total: 34,
            unique: 12,
            functions: 0,
            unique_functions: 0,
            groups: vec![Group {
                kind: crate::Kind::Doctest,
                remedy: None,
                id: "ab12cd34".into(),
                hash: "ab12cd34".into(),
                unparsed: false,
                tokens: 5,
                sites: vec![
                    site("src/a.rs", 14, "m::a", "fn f() {}", &["no_run"]),
                    site("src/b.rs", 97, "m::b", "fn f() {}", &[]),
                ],
            }],
        }
    }

    #[test]
    fn human_summary_only_when_clean() {
        let report = Report {
            total: 3,
            unique: 3,
            functions: 0,
            unique_functions: 0,
            groups: Vec::new(),
        };
        assert_eq!(
            human(&report, false),
            "3 doctests (3 unique), 0 functions (0 unique), 0 duplicated groups\n"
        );
    }

    #[test]
    fn human_group_section_without_code() {
        assert_eq!(
            human(&report(), false),
            "34 doctests (12 unique), 0 functions (0 unique), 1 duplicated groups\n\n[ab12cd34] 2 sites, 5 tokens\n  src/a.rs:14  m::a   (no_run)\n  src/b.rs:97  m::b\n\nRemove the copies listed above, or keep one on purpose with a `rust,dejadoc` fence\n"
        );
    }

    #[test]
    fn human_verbose_prints_code_indented() {
        let out = human(&report(), true);
        assert!(out.contains("\n    fn f() {}\n"), "got: {out:?}");
        assert_eq!(out.matches("fn f() {}").count(), 2);
    }

    #[test]
    fn json_shape() {
        let value: serde_json::Value = serde_json::from_str(&json(&report())).unwrap();
        assert_eq!(value["total"], 34);
        assert_eq!(value["unique"], 12);
        let group = &value["groups"][0];
        // serde_json values order keys alphabetically; pin the exact sets.
        assert_eq!(
            group.as_object().unwrap().keys().collect::<Vec<_>>(),
            vec!["hash", "id", "kind", "sites", "tokens", "unparsed"]
        );
        assert_eq!(group["id"], "ab12cd34");
        assert_eq!(group["kind"], "doctest");
        assert_eq!(group["tokens"], 5);
        assert_eq!(group["unparsed"], false);
        assert_eq!(group["sites"].as_array().unwrap().len(), 2);
        let first = &group["sites"][0];
        assert_eq!(
            first.as_object().unwrap().keys().collect::<Vec<_>>(),
            vec!["code", "end", "file", "info", "item", "line"]
        );
        assert_eq!(first["file"], "src/a.rs");
        assert_eq!(first["line"], 14);
        assert_eq!(first["end"], serde_json::Value::Null);
        assert_eq!(first["item"], "m::a");
        assert_eq!(first["info"][0], "no_run");
    }

    #[test]
    fn human_multiple_groups_separated_by_blank_line() {
        let report = Report {
            total: 4,
            unique: 2,
            functions: 0,
            unique_functions: 0,
            groups: vec![
                Group {
                    kind: crate::Kind::Doctest,
                    remedy: None,
                    id: "ab12cd34".into(),
                    hash: "ab12cd34".into(),
                    unparsed: false,
                    tokens: 5,
                    sites: vec![
                        site("src/a.rs", 14, "m::a", "fn f() {}", &[]),
                        site("src/b.rs", 97, "m::b", "fn f() {}", &[]),
                    ],
                },
                Group {
                    kind: crate::Kind::Doctest,
                    remedy: None,
                    id: "ef56gh78".into(),
                    hash: "ef56gh78".into(),
                    unparsed: false,
                    tokens: 3,
                    sites: vec![site("src/c.rs", 5, "n::c", "fn g() {}", &[])],
                },
            ],
        };
        assert_eq!(
            human(&report, false),
            "4 doctests (2 unique), 0 functions (0 unique), 2 duplicated groups\n\n[ab12cd34] 2 sites, 5 tokens\n  src/a.rs:14  m::a\n  src/b.rs:97  m::b\n\n[ef56gh78] 1 sites, 3 tokens\n  src/c.rs:5  n::c\n\nRemove the copies listed above, or keep one on purpose with a `rust,dejadoc` fence\n"
        );
    }

    /// A report holding one function group of two copies with `remedy`.
    fn function_report(remedy: Remedy) -> Report {
        Report {
            total: 0,
            unique: 0,
            functions: 7,
            unique_functions: 6,
            groups: vec![Group {
                kind: crate::Kind::Function,
                id: "cd34ef56".into(),
                hash: "cd34ef56".into(),
                unparsed: false,
                tokens: 40,
                remedy: Some(remedy),
                sites: vec![
                    site("src/a.rs", 3, "m::A::run", "fn run() {}", &[]),
                    site("src/a.rs", 9, "m::B::run", "fn run() {}", &[]),
                ],
            }],
        }
    }

    #[test]
    fn human_gives_each_function_group_its_advice() {
        let head = "0 doctests (0 unique), 7 functions (6 unique), 1 duplicated groups\n\n[cd34ef56] 2 functions, 40 tokens, ";
        let tail = "\n  src/a.rs:3  m::A::run\n  src/a.rs:9  m::B::run\n\nAct on each function group as its advice says, or keep one on purpose with a `// dejadoc: allow` comment above it\n";
        for (remedy, advice) in [
            (Remedy::Delete, "delete or update all but the first"),
            (
                Remedy::MergeCfg,
                "one function under the merged cfg can replace them",
            ),
            (
                Remedy::GenericOrMacro,
                "a generic or a macro can share one body",
            ),
            (
                Remedy::HelperOrMacro,
                "a helper or a macro can share one body",
            ),
        ] {
            assert_eq!(
                human(&function_report(remedy), false),
                format!("{head}{advice}{tail}")
            );
        }
    }

    #[test]
    fn a_public_copy_is_called_or_deprecated_never_deleted() {
        let mut report = function_report(Remedy::Delete);
        report.groups[0].sites[1].public = true;
        assert_eq!(
            annotations(&report, false),
            "::error file=src/a.rs,line=9,title=dejadoc::m::B::run repeats m::A::run at src/a.rs:3 and is public API, make it call the kept copy or deprecate it, group cd34ef56\n"
        );
        assert!(human(&report, false).contains(
            "  src/a.rs:9  m::B::run   (public API, make it call the kept copy or deprecate it)\n"
        ));
        // The kept copy being public changes nothing, and nor does a copy that isn't deleted.
        let mut report = function_report(Remedy::Delete);
        report.groups[0].sites[0].public = true;
        assert!(annotations(&report, false).contains("duplicates the function m::A::run"));
        assert!(!human(&report, false).contains("public API"));
        let mut report = function_report(Remedy::GenericOrMacro);
        report.groups[0].sites[1].public = true;
        assert!(!human(&report, false).contains("public API"));
        assert!(annotations(&report, false).contains("on another type"));
    }

    #[test]
    fn function_annotations_follow_the_remedy() {
        let head = "::error file=src/a.rs,line=9,title=dejadoc::m::B::run ";
        for (remedy, body) in [
            (
                Remedy::Delete,
                "duplicates the function m::A::run at src/a.rs:3",
            ),
            (
                Remedy::MergeCfg,
                "repeats m::A::run at src/a.rs:3 under another cfg, one function under both cfgs can replace them",
            ),
            (
                Remedy::GenericOrMacro,
                "repeats m::A::run at src/a.rs:3 on another type, a generic or a macro can share it",
            ),
            (
                Remedy::HelperOrMacro,
                "repeats m::A::run at src/a.rs:3 and can't be deleted, a helper or a macro can share it",
            ),
        ] {
            assert_eq!(
                annotations(&function_report(remedy), false),
                format!("{head}{body}, group cd34ef56\n")
            );
        }
    }

    #[test]
    fn annotations_mark_every_copy_but_the_first() {
        let out = annotations(&report(), false);
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines.len(), 1);
        assert_eq!(
            lines[0],
            "::error file=src/b.rs,line=97,title=dejadoc::m::b duplicates the doctest of m::a at src/a.rs:14, group ab12cd34"
        );
    }

    #[test]
    fn annotations_warn_when_the_run_cannot_fail() {
        let out = annotations(&report(), true);
        assert!(out.starts_with("::warning file=src/b.rs,line=97,"), "{out}");
    }

    #[test]
    fn annotations_are_empty_without_duplicates() {
        let clean = Report {
            total: 3,
            unique: 3,
            functions: 0,
            unique_functions: 0,
            groups: Vec::new(),
        };
        assert_eq!(annotations(&clean, false), "");
    }

    #[test]
    fn annotations_skip_a_group_without_sites() {
        let mut empty = report();
        empty.groups[0].sites.clear();
        assert_eq!(annotations(&empty, false), "");
    }

    #[test]
    fn annotations_mark_every_later_site_of_a_larger_group() {
        let mut three = report();
        three.groups[0]
            .sites
            .push(site("src/c.rs", 3, "m::c", "fn f() {}", &[]));
        let out = annotations(&three, false);
        assert_eq!(out.lines().count(), 2);
        assert!(out.contains("file=src/c.rs,line=3,"), "{out}");
        assert!(
            out.lines().all(|l| l.contains("of m::a at src/a.rs:14")),
            "{out}"
        );
    }

    #[test]
    fn annotations_escape_the_message() {
        let mut odd = report();
        odd.groups[0].sites[0].item = "m::a%weird".into();
        let out = annotations(&odd, false);
        assert!(out.contains("of m::a%25weird at"), "{out}");
    }

    #[test]
    fn annotations_escape_the_file_property() {
        let mut odd = report();
        odd.groups[0].sites[1].file = "src/a,b:c%.rs".into();
        let out = annotations(&odd, false);
        assert!(
            out.starts_with("::error file=src/a%2Cb%3Ac%25.rs,line=97,"),
            "{out}"
        );
    }
}