dev-prune 1.23.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Handler for `dev-prune history`.
//
// `devp stats` says 27 GiB across 10 passes. This says which passes, what each one was
// asked to do, and what it took — the question anyone asks straight after reading the
// total, and the one the tool could not answer until 1.17.0 because only the totals were
// ever kept.
//
// The output is deliberately two commands rather than one long one. A pass that cleared
// forty repositories has hundreds of directories in it, and a report that prints them all
// by default is a report nobody reads: the list is one line per pass, and the detail is
// asked for by number. `--export` exists for the case where the answer genuinely is
// "all of it" — a file is a better place for that than a scrollback buffer.

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

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;

use crate::config::{PrunedDir, Registry};
use crate::constants::PRUNE_LOG_STARTS_AT;
use crate::history::{self, Pass};
use crate::output;

/// How many passes the compact list shows without `--limit` or `--all`.
const PASSES_SHOWN: usize = 20;

/// How many directories one pass's detail prints to a terminal before it stops.
///
/// Only to a terminal. A redirect or a pipe has somewhere to put the rest, and silently
/// truncating what someone asked to be written to a file would be the worse failure.
const DETAIL_DIRS_SHOWN: usize = 200;

/// Options for the `history` command, from the CLI.
pub struct HistoryArgs {
    /// Show one pass in full. 1 is the most recent.
    pub pass: Option<usize>,
    /// How many passes the list shows.
    pub limit: Option<usize>,
    /// Show every recorded pass.
    pub all: bool,
    /// Emit the whole log as one JSON document.
    pub json: bool,
    /// Write the JSON document to a file. `Some(None)` means the default location.
    pub export: Option<Option<PathBuf>>,
    /// Show leaderboard high scores.
    pub scores: bool,
}

/// Run the `history` command.
pub fn run(args: &HistoryArgs) -> Result<()> {
    let registry = Registry::load()?;
    let passes = history::merged(history::load()?, &registry);

    if args.scores {
        return print_scores(&passes, args.json);
    }

    // Checked once, before anything branches on the output mode: `--pass 40 --json` on
    // a machine with ten passes is the same question with no answer as `--pass 40`, and
    // an empty `passes` array would read as "that pass deleted nothing".
    if let Some(n) = args.pass {
        check_pass_number(&passes, n)?;
    }

    if let Some(destination) = &args.export {
        return export(&passes, args.pass, destination.as_deref());
    }

    if args.json {
        return crate::json::emit(&crate::json::history_document(&passes, args.pass));
    }

    match args.pass {
        Some(n) => print_one_pass(&passes, n),
        None => {
            print_pass_list(&passes, args);
            Ok(())
        }
    }
}

/// One single-cleanup record: bytes, when, and the repository's name where it is known.
type SingleCleanup = (u64, DateTime<Utc>, Option<String>);
/// One whole-pass record: bytes and when.
type TotalRun = (u64, DateTime<Utc>);

/// The two leaderboards behind `devp scores`: the most one repository gave back in a
/// single pass, and the most one whole pass gave back.
///
/// A `Summary` pass without a directory list only yields a single-cleanup record when
/// it touched exactly one repository, because that is the only case where the pass
/// total and the per-repository figure are the same number. Guessing a split for the
/// others would put invented records on the board.
fn collect_scores(passes: &[Pass]) -> (Vec<SingleCleanup>, Vec<TotalRun>) {
    let mut single_cleanups: Vec<(u64, DateTime<Utc>, Option<String>)> = Vec::new();
    for pass in passes {
        match pass {
            Pass::Detailed(record) => {
                let mut per_repo: std::collections::HashMap<PathBuf, u64> =
                    std::collections::HashMap::new();
                for d in &record.dirs {
                    *per_repo.entry(d.repo_path.clone()).or_insert(0) += d.size_freed;
                }
                for (repo, bytes) in per_repo {
                    if bytes > 0 {
                        let name = repo.file_name().map(|f| f.to_string_lossy().to_string());
                        single_cleanups.push((bytes, record.at, name));
                    }
                }
            }
            Pass::Summary {
                at,
                bytes_freed,
                repos_touched,
                dirs,
                ..
            } => {
                if let Some(dirs) = dirs {
                    let mut per_repo: std::collections::HashMap<PathBuf, u64> =
                        std::collections::HashMap::new();
                    for d in dirs {
                        *per_repo.entry(d.repo_path.clone()).or_insert(0) += d.size_freed;
                    }
                    for (repo, bytes) in per_repo {
                        if bytes > 0 {
                            let name = repo.file_name().map(|f| f.to_string_lossy().to_string());
                            single_cleanups.push((bytes, *at, name));
                        }
                    }
                } else if *repos_touched == 1 && *bytes_freed > 0 {
                    single_cleanups.push((*bytes_freed, *at, None));
                }
            }
        }
    }
    single_cleanups.sort_by_key(|entry| std::cmp::Reverse(entry.0));

    let mut total_runs: Vec<(u64, DateTime<Utc>)> = passes
        .iter()
        .filter(|p| p.bytes_freed() > 0)
        .map(|p| (p.bytes_freed(), p.at()))
        .collect();
    total_runs.sort_by_key(|entry| std::cmp::Reverse(entry.0));

    (single_cleanups, total_runs)
}

/// The document emitted by `devp scores --json` and `devp history --scores --json`.
///
/// The command key is spelled the way flag variants are everywhere else in the JSON
/// contract (`status --drift`, `caches clear`): by the flag, on the command that owns
/// the data.
fn scores_document(
    single_cleanups: &[(u64, DateTime<Utc>, Option<String>)],
    total_runs: &[(u64, DateTime<Utc>)],
) -> serde_json::Value {
    use serde_json::json;
    let medals = ["Gold", "Silver", "Bronze"];
    let medals_emojis = ["🥇", "🥈", "🥉"];

    let single_cleanup_json: Vec<serde_json::Value> = single_cleanups
        .iter()
        .take(3)
        .enumerate()
        .map(|(i, (bytes, date, repo))| {
            json!({
                "rank": i + 1,
                "medal": medals[i],
                "emoji": medals_emojis[i],
                "bytes": bytes,
                "formatted_bytes": output::format_bytes(*bytes),
                "date": date.format("%Y-%m-%d").to_string(),
                "repo": repo,
            })
        })
        .collect();

    let total_run_json: Vec<serde_json::Value> = total_runs
        .iter()
        .take(3)
        .enumerate()
        .map(|(i, (bytes, date))| {
            json!({
                "rank": i + 1,
                "medal": medals[i],
                "emoji": medals_emojis[i],
                "bytes": bytes,
                "formatted_bytes": output::format_bytes(*bytes),
                "date": date.format("%Y-%m-%d").to_string(),
            })
        })
        .collect();

    json!({
        "schema": crate::json::SCHEMA_VERSION,
        "version": crate::constants::VERSION,
        "command": "history --scores",
        "single_cleanup": single_cleanup_json,
        "total_run": total_run_json,
    })
}

/// High-scores leaderboard: the best single cleanup and the best total run on record.
pub fn print_scores(passes: &[Pass], json: bool) -> Result<()> {
    let (single_cleanups, total_runs) = collect_scores(passes);

    if json {
        return crate::json::emit(&scores_document(&single_cleanups, &total_runs));
    }

    if single_cleanups.is_empty() && total_runs.is_empty() {
        output::print_header("High Scores Leaderboard");
        output::print_info(
            "No prune passes recorded yet. Run `devp run` to earn your first cleanup badge!",
        );
        return Ok(());
    }

    println!();
    println!("   {}", "──── ★ SINGLE CLEANUP ★ ────".cyan().bold());
    if single_cleanups.is_empty() {
        println!("     {}", "No single repository records yet".dimmed());
    } else {
        for (i, (bytes, date, repo)) in single_cleanups.iter().take(3).enumerate() {
            match i {
                0 => println!("     {}", "🥇 Gold".yellow().bold()),
                1 => println!("     {}", "🥈 Silver".white().bold()),
                _ => println!("     {}", "🥉 Bronze".bright_yellow().bold()),
            }
            let repo_tag = repo
                .as_ref()
                .map(|r| format!(" ({})", r).cyan().to_string())
                .unwrap_or_default();
            println!(
                "         {} · {}{}",
                output::format_bytes(*bytes).green().bold(),
                date.format("%Y-%m-%d").to_string().dimmed(),
                repo_tag
            );
            println!("   {}", "────────────────────────────".dimmed());
        }
    }

    println!();
    println!("   {}", "──── ★    TOTAL RUN   ★ ────".cyan().bold());
    if total_runs.is_empty() {
        println!("     {}", "No total run records yet".dimmed());
    } else {
        for (i, (bytes, date)) in total_runs.iter().take(3).enumerate() {
            match i {
                0 => println!("     {}", "🥇 Gold".yellow().bold()),
                1 => println!("     {}", "🥈 Silver".white().bold()),
                _ => println!("     {}", "🥉 Bronze".bright_yellow().bold()),
            }
            println!(
                "         {} · {}",
                output::format_bytes(*bytes).green().bold(),
                date.format("%Y-%m-%d").to_string().dimmed()
            );
            println!("   {}", "────────────────────────────".dimmed());
        }
    }
    println!();

    Ok(())
}

/// Exit 2 for a pass number nobody has.
fn check_pass_number(passes: &[Pass], number: usize) -> Result<()> {
    if number == 0 || number > passes.len() {
        return Err(anyhow::Error::new(crate::UsageError(format!(
            "There is no pass #{number}. {} recorded; `devp history` lists them, newest first.",
            passes.len()
        ))));
    }
    Ok(())
}

/// One line per pass, newest first.
fn print_pass_list(passes: &[Pass], args: &HistoryArgs) {
    output::print_header("Prune passes");

    if passes.is_empty() {
        output::print_info(
            "Nothing recorded yet — `devp run --dry-run` shows what a pass would do.",
        );
        return;
    }

    let shown = if args.all {
        passes.len()
    } else {
        args.limit.unwrap_or(PASSES_SHOWN).min(passes.len())
    };

    for (index, pass) in passes.iter().take(shown).enumerate() {
        let number = index + 1;
        let (started_by, note) = match pass {
            Pass::Detailed(record) => (record.trigger.label().to_string(), String::new()),
            // Not "unknown": the pass is not mysterious, the format was younger than it.
            Pass::Summary { .. } => ("—".to_string(), " (totals only)".to_string()),
        };
        // Padded before colouring: a width applied to a string carrying ANSI escapes
        // counts the escapes as width and the column drifts.
        println!(
            "  {}  {}   {}   {:<10} {} {}, {} {}{}",
            format!("#{number}").dimmed(),
            pass.at().format("%Y-%m-%d %H:%M"),
            format!("{:>10}", output::format_bytes(pass.bytes_freed())).green(),
            started_by,
            pass.dirs_removed(),
            output::plural(pass.dirs_removed(), "directory", "directories"),
            pass.repos_touched(),
            output::plural(pass.repos_touched(), "repository", "repositories"),
            note.dimmed(),
        );
    }

    if shown < passes.len() {
        output::print_info(&format!(
            "{} passes recorded; showing the most recent {shown}. `--all` for every one.",
            passes.len()
        ));
    }

    if passes.iter().any(|p| matches!(p, Pass::Summary { .. })) {
        output::print_dimmed(&format!(
            "  Passes marked \"totals only\" ran before {PRUNE_LOG_STARTS_AT}, which is where \
             the per-directory log starts."
        ));
    }

    output::print_info("What one pass deleted:  devp history --pass 1");
    output::print_info("All of it, as a file:   devp history --export");
}

/// One pass in full.
fn print_one_pass(passes: &[Pass], number: usize) -> Result<()> {
    check_pass_number(passes, number)?;
    let pass = &passes[number - 1];

    output::print_header(&format!("Pass #{number}"));
    output::print_info(&format!(
        "When         {} ({})",
        pass.at().format("%Y-%m-%d %H:%M UTC"),
        describe_age(pass.at()),
    ));

    match pass {
        Pass::Detailed(record) => {
            output::print_info(&format!("Started by   {}", record.trigger.label()));
            output::print_info(&format!("Command      {}", record.command_line()));
            if !record.version.is_empty() {
                output::print_info(&format!("Version      dev-prune {}", record.version));
            }
        }
        Pass::Summary { .. } => {
            output::print_info(&format!(
                "Started by   not recorded — this pass predates {PRUNE_LOG_STARTS_AT}"
            ));
        }
    }

    output::print_info(&format!(
        "Freed        {} from {} {} in {} {}",
        output::format_bytes_styled(pass.bytes_freed()),
        pass.dirs_removed(),
        output::plural(pass.dirs_removed(), "directory", "directories"),
        pass.repos_touched(),
        output::plural(pass.repos_touched(), "repository", "repositories"),
    ));

    let Some(dirs) = pass.dirs() else {
        output::print_header("Directories");
        output::print_info(&format!(
            "Not recorded. Only the totals above were kept before {PRUNE_LOG_STARTS_AT}; every \
             pass from that release on carries its full list."
        ));
        return Ok(());
    };

    print_directories(dirs, number);
    Ok(())
}

/// The directory list, grouped under the repository each one belonged to.
fn print_directories(dirs: &[PrunedDir], number: usize) {
    use std::io::IsTerminal;

    output::print_header("Directories");

    let mut grouped: Vec<(&PathBuf, Vec<&PrunedDir>)> = Vec::new();
    for dir in dirs {
        match grouped.iter_mut().find(|(repo, _)| *repo == &dir.repo_path) {
            Some((_, entries)) => entries.push(dir),
            None => grouped.push((&dir.repo_path, vec![dir])),
        }
    }
    grouped.sort_by_key(|(_, entries)| {
        std::cmp::Reverse(entries.iter().map(|d| d.size_freed).sum::<u64>())
    });

    // Only a terminal has a scrollback to overflow. Redirected or piped, the caller has
    // asked for the whole thing and has somewhere to put it.
    let budget = if std::io::stdout().is_terminal() {
        DETAIL_DIRS_SHOWN
    } else {
        usize::MAX
    };
    let mut printed = 0usize;

    for (repo, entries) in &grouped {
        if printed >= budget {
            break;
        }
        println!("  {}", output::styled_path(repo));
        for dir in entries {
            if printed >= budget {
                break;
            }
            println!(
                "    {}   {}   {}",
                format!("{:>10}", output::format_bytes(dir.size_freed)).green(),
                output::pad_display(&dir.bloat_dir, 32),
                output::styled_adapter(&dir.adapter),
            );
            printed += 1;
        }
    }

    if printed < dirs.len() {
        output::print_info(&format!(
            "{} more not shown. `devp history --pass {number} --json` or `devp history --export` \
             has all {}.",
            dirs.len() - printed,
            dirs.len(),
        ));
    }
}

/// Write the whole log to a file, and say where it went.
fn export(passes: &[Pass], only: Option<usize>, destination: Option<&Path>) -> Result<()> {
    let path = resolve_export_path(destination)?;
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create {}", parent.display()))?;
    }
    let document = crate::json::history_document(passes, only);
    let contents =
        serde_json::to_string_pretty(&document).context("Failed to serialize history")?;
    std::fs::write(&path, &contents)
        .with_context(|| format!("Failed to write {}", path.display()))?;

    let written = if only.is_some() { 1 } else { passes.len() };
    output::print_success(&format!(
        "{written} {} written to {}",
        output::plural(written, "pass", "passes"),
        output::clean_path(&path),
    ));
    Ok(())
}

/// Where `--export` writes.
///
/// A bare `--export` goes to the documents folder, which is the one directory every
/// desktop has and nothing else writes to on its own. An argument that is an existing
/// directory gets the same filename inside it, because `--export .` meaning "overwrite
/// the current directory" is not what anyone types it for.
pub fn resolve_export_path(destination: Option<&Path>) -> Result<PathBuf> {
    let name = format!("dev-prune-history-{}.json", Utc::now().format("%Y-%m-%d"));
    match destination {
        Some(path) if path.is_dir() => Ok(path.join(name)),
        Some(path) => Ok(path.to_path_buf()),
        None => {
            let base = dirs::document_dir()
                .or_else(dirs::home_dir)
                .context("Could not find a documents or home directory to export into. Pass a path: `devp history --export <FILE>`")?;
            Ok(base.join(name))
        }
    }
}

/// "3 days ago", in the coarsest unit that is not a lie.
fn describe_age(at: DateTime<Utc>) -> String {
    let elapsed = Utc::now().signed_duration_since(at);
    let days = elapsed.num_days();
    if days >= 1 {
        return format!(
            "{days} {} ago",
            output::plural(days as usize, "day", "days")
        );
    }
    let hours = elapsed.num_hours();
    if hours >= 1 {
        return format!(
            "{hours} {} ago",
            output::plural(hours as usize, "hour", "hours")
        );
    }
    let minutes = elapsed.num_minutes().max(0);
    format!(
        "{minutes} {} ago",
        output::plural(minutes as usize, "minute", "minutes")
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::history::{PassRecord, Trigger};
    use tempfile::TempDir;

    fn pass(at: DateTime<Utc>) -> Pass {
        Pass::Detailed(PassRecord {
            at,
            trigger: Trigger::Manual,
            argv: vec!["run".to_string()],
            version: "1.17.0".to_string(),
            dirs: vec![PrunedDir {
                repo_path: PathBuf::from("/a"),
                bloat_dir: "node_modules".to_string(),
                adapter: "npm".to_string(),
                size_freed: 100,
                runtime: None,
            }],
        })
    }

    #[test]
    fn a_pass_number_nobody_has_is_a_usage_error_not_an_empty_report() {
        let passes = vec![pass(Utc::now())];
        for n in [0usize, 2, 99] {
            let err = print_one_pass(&passes, n).unwrap_err();
            assert!(
                err.downcast_ref::<crate::UsageError>().is_some(),
                "--pass {n} should exit 2"
            );
        }
    }

    #[test]
    fn asking_for_a_pass_on_an_empty_log_is_a_usage_error() {
        let err = print_one_pass(&[], 1).unwrap_err();
        assert!(err.downcast_ref::<crate::UsageError>().is_some());
    }

    #[test]
    fn exporting_into_a_directory_keeps_the_generated_filename() {
        // `devp history --export .` must not try to overwrite the directory itself.
        let tmp = TempDir::new().unwrap();
        let path = resolve_export_path(Some(tmp.path())).unwrap();
        assert_eq!(path.parent().unwrap(), tmp.path());
        assert!(
            path.file_name()
                .unwrap()
                .to_string_lossy()
                .starts_with("dev-prune-history-")
        );
    }

    #[test]
    fn exporting_to_a_named_file_uses_exactly_that_name() {
        let tmp = TempDir::new().unwrap();
        let target = tmp.path().join("mine.json");
        assert_eq!(resolve_export_path(Some(&target)).unwrap(), target);
    }

    #[test]
    fn an_export_writes_a_document_that_parses() {
        let tmp = TempDir::new().unwrap();
        let target = tmp.path().join("nested").join("history.json");
        export(&[pass(Utc::now())], None, Some(&target)).unwrap();
        let raw = std::fs::read_to_string(&target).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap();
        assert_eq!(parsed["command"], "history");
        assert_eq!(parsed["passes"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn an_empty_log_still_prints_a_scores_report() {
        assert!(print_scores(&[], false).is_ok());
        assert!(print_scores(&[], true).is_ok());
        let doc = scores_document(&[], &[]);
        assert_eq!(doc["command"], "history --scores");
        assert_eq!(doc["single_cleanup"].as_array().unwrap().len(), 0);
        assert_eq!(doc["total_run"].as_array().unwrap().len(), 0);
    }

    #[test]
    fn scores_rank_the_biggest_cleanup_and_the_biggest_run_first() {
        let p1 = Pass::Detailed(PassRecord {
            at: Utc::now(),
            trigger: crate::history::Trigger::Manual,
            argv: vec![],
            version: "1.23.0".to_string(),
            dirs: vec![
                PrunedDir {
                    repo_path: PathBuf::from("/repo1"),
                    bloat_dir: "node_modules".to_string(),
                    adapter: "npm".to_string(),
                    size_freed: 1000,
                    runtime: None,
                },
                PrunedDir {
                    repo_path: PathBuf::from("/repo2"),
                    bloat_dir: "target".to_string(),
                    adapter: "cargo".to_string(),
                    size_freed: 5000,
                    runtime: None,
                },
            ],
        });
        // A totals-only pass that touched one repository is a single-cleanup record
        // too: the pass total and the per-repository figure are the same number.
        let p2 = Pass::Summary {
            at: Utc::now(),
            bytes_freed: 10000,
            dirs_removed: 1,
            repos_touched: 1,
            dirs: None,
        };
        let (singles, totals) = collect_scores(&[p1, p2]);

        let single_bytes: Vec<u64> = singles.iter().map(|s| s.0).collect();
        assert_eq!(single_bytes, vec![10000, 5000, 1000]);
        assert_eq!(singles[1].2.as_deref(), Some("repo2"));
        assert_eq!(singles[0].2, None, "a totals-only pass names no repository");

        let total_bytes: Vec<u64> = totals.iter().map(|t| t.0).collect();
        assert_eq!(total_bytes, vec![10000, 6000]);

        let doc = scores_document(&singles, &totals);
        assert_eq!(doc["command"], "history --scores");
        assert_eq!(doc["schema"], crate::json::SCHEMA_VERSION);
        assert_eq!(doc["single_cleanup"][0]["rank"], 1);
        assert_eq!(doc["single_cleanup"][0]["bytes"], 10000);
        assert_eq!(doc["single_cleanup"][0]["medal"], "Gold");
        assert_eq!(doc["total_run"][1]["bytes"], 6000);
    }
}