leetctl 0.3.0

LeetCode command-line interface in Rust, with curated problem sets and filtered random picking.
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Leetcode data models
use super::schemas::{problems, reviews, tags};
use crate::helper::HTML;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use serde_json::Number;

/// Tag model
#[derive(Clone, Insertable, Queryable, Serialize, Debug)]
#[diesel(table_name = tags)]
pub struct Tag {
    pub tag: String,
    pub refs: String,
}

/// One problem's place in the spaced-repetition deck.
///
/// Keyed on the frontend id — the number `leetctl pick <id>` takes — because that is the id every
/// command and both frontends already speak. `VerifyResult::accepted_problem_id` returns the
/// *internal* id instead, so the auto-grade path has to translate before it writes here.
#[derive(Clone, Copy, Insertable, Queryable, Serialize, Debug, PartialEq)]
#[diesel(table_name = reviews)]
pub struct ReviewCard {
    pub fid: i32,
    pub ease: f32,
    pub interval_days: i32,
    pub repetitions: i32,
    pub lapses: i32,
    pub due_day: crate::srs::Day,
    pub last_day: crate::srs::Day,
}

impl ReviewCard {
    /// The card `schedule` describes, landing `interval_days` after `today`.
    ///
    /// A freshly enrolled problem passes `Schedule::default()`, whose interval is zero — it is due
    /// the moment it enters the deck, which is the point of enrolling it.
    pub fn new(fid: i32, schedule: crate::srs::Schedule, today: crate::srs::Day) -> Self {
        ReviewCard {
            fid,
            ease: schedule.ease,
            interval_days: schedule.interval_days,
            repetitions: schedule.repetitions,
            lapses: schedule.lapses,
            due_day: today + schedule.interval_days,
            last_day: today,
        }
    }

    /// What the scheduler needs, without the calendar.
    pub fn schedule(&self) -> crate::srs::Schedule {
        crate::srs::Schedule {
            ease: self.ease,
            interval_days: self.interval_days,
            repetitions: self.repetitions,
            lapses: self.lapses,
        }
    }

    pub fn is_due(&self, today: crate::srs::Day) -> bool {
        self.due_day <= today
    }

    /// `today`, `in 4d`, `2d late`.
    pub fn due_label(&self, today: crate::srs::Day) -> String {
        crate::srs::due_label(self.due_day, today)
    }
}

/// Problem model
#[derive(AsChangeset, Clone, Identifiable, Insertable, Queryable, Serialize, Debug)]
#[diesel(table_name = problems)]
pub struct Problem {
    pub category: String,
    pub fid: i32,
    pub id: i32,
    pub level: i32,
    pub locked: bool,
    pub name: String,
    pub percent: f32,
    pub slug: String,
    pub starred: bool,
    pub status: String,
    pub desc: String,
}

impl Problem {
    fn display_level(&self) -> &str {
        crate::helper::Difficulty::from_level(self.level).map_or("Unknown", |d| d.as_str())
    }

    /// The "problem is being fetched" line the commands print before a description fetch.
    ///
    /// Lives here rather than in `Cache::get_question` because the cache layer must not print —
    /// a `println!` there would land on top of the TUI's alternate screen.
    pub fn banner(&self) -> String {
        let ids = match self.level {
            1 => self.fid.to_string().green(),
            2 => self.fid.to_string().yellow(),
            3 => self.fid.to_string().red(),
            _ => self.fid.to_string().dimmed(),
        };

        format!(
            "\n[{}] {} {}\n\n",
            ids,
            self.name.bold().underline(),
            "is on the run...".dimmed()
        )
    }

    pub fn desc_comment(&self, conf: &Config) -> String {
        let mut res = String::new();
        let comment_leading = &conf.code.comment_leading;
        res += format!("{} Category: {}\n", comment_leading, self.category).as_str();
        res += format!("{} Level: {}\n", comment_leading, self.display_level(),).as_str();
        res += format!("{} Percent: {}%\n\n", comment_leading, self.percent).as_str();

        res + "\n"
    }
}

/// A problem with only the fields a test cares about set, and plausible defaults elsewhere.
/// Internal id mirrors the frontend id, which keeps tag joins (`squash`) easy to reason about.
#[cfg(test)]
pub(crate) fn fixture(fid: i32, level: i32, name: &str) -> Problem {
    Problem {
        category: "algorithms".into(),
        fid,
        id: fid,
        level,
        locked: false,
        name: name.into(),
        percent: 50.0,
        slug: name.to_lowercase().replace(' ', "-"),
        starred: false,
        status: String::new(),
        desc: String::new(),
    }
}

static DONE: &str = " ✔";
static LOCK: &str = "🔒";
static NDONE: &str = " ✘";
static SPACE: &str = " ";
/// Display columns the problem name gets in a `leetctl list` line.
const NAME_WIDTH: usize = 60;
impl std::fmt::Display for Problem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let space_2 = SPACE.repeat(2);
        let mut lock = space_2.as_str();
        let mut done = space_2.normal();
        let mut id = "".to_string();
        let mut name = "".to_string();
        let mut level = "".normal();

        if self.locked {
            lock = LOCK
        };
        if self.status == "ac" {
            done = DONE.green().bold();
        } else if self.status == "notac" {
            done = NDONE.green().bold();
        }

        match self.fid.to_string().len() {
            1 => {
                id.push_str(&SPACE.repeat(2));
                id.push_str(&self.fid.to_string());
                id.push_str(SPACE);
            }
            2 => {
                id.push_str(SPACE);
                id.push_str(&self.fid.to_string());
                id.push_str(SPACE);
            }
            3 => {
                id.push_str(SPACE);
                id.push_str(&self.fid.to_string());
            }
            4 => {
                id.push_str(&self.fid.to_string());
            }
            _ => {
                id.push_str(&space_2);
                id.push_str(&space_2);
            }
        }

        name.push_str(&crate::helper::fit_width(&self.name, NAME_WIDTH, "..."));

        // Padded to the width of "Medium" so the columns line up.
        level = match crate::helper::Difficulty::from_level(self.level) {
            Some(d @ crate::helper::Difficulty::Easy) => format!("{:6}", d.as_str()).bright_green(),
            Some(d @ crate::helper::Difficulty::Medium) => {
                format!("{:6}", d.as_str()).bright_yellow()
            }
            Some(d @ crate::helper::Difficulty::Hard) => format!("{:6}", d.as_str()).bright_red(),
            None => level,
        };

        let mut pct = self.percent.to_string();
        if pct.len() < 5 {
            pct.push_str(&"0".repeat(5 - pct.len()));
        }
        write!(
            f,
            "  {} {} [{}] {} {} ({} %)",
            lock,
            done,
            id,
            name,
            level,
            &pct[..5]
        )
    }
}

/// desc model
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Question {
    pub content: String,
    pub stats: Stats,
    pub defs: CodeDefintion,
    pub case: String,
    pub all_cases: String,
    pub metadata: MetaData,
    pub test: bool,
    pub t_content: String,
}

impl Question {
    pub fn desc(&self) -> String {
        self.content.render()
    }

    pub fn desc_comment(&self, conf: &Config) -> String {
        let desc = self.content.render();

        let mut res = desc.lines().fold("\n".to_string(), |acc, e| {
            acc + "" + conf.code.comment_leading.as_str() + " " + e + "\n"
        });
        res += " \n";

        res
    }
}

use question::*;
/// deps of Question
mod question {
    use serde::{Deserialize, Serialize};

    /// Code samples
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct CodeDefintion(pub Vec<CodeDefintionInner>);

    /// CodeDefinition Inner struct
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct CodeDefintionInner {
        pub value: String,
        pub text: String,
        #[serde(alias = "defaultCode")]
        pub code: String,
    }

    /// Question status
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct Stats {
        #[serde(alias = "totalAccepted")]
        tac: String,
        #[serde(alias = "totalSubmission")]
        tsm: String,
        #[serde(alias = "totalAcceptedRaw")]
        tacr: i32,
        #[serde(alias = "totalSubmissionRaw")]
        tsmr: i32,
        #[serde(alias = "acRate")]
        rate: String,
    }

    /// Algorithm metadata
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct MetaData {
        pub name: Option<String>,
        pub params: Option<Vec<Param>>,
        pub r#return: Return,
    }

    /// MetaData nested fields
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct Param {
        pub name: String,
        pub r#type: String,
    }

    /// MetaData nested fields
    #[derive(Debug, Default, Serialize, Deserialize)]
    pub struct Return {
        pub r#type: String,
    }
}

/// run_code Result
#[derive(Debug, Deserialize)]
pub struct RunCode {
    #[serde(default)]
    pub interpret_id: String,
    #[serde(default)]
    pub test_case: String,
    #[serde(default)]
    pub submission_id: i64,
}

use super::parser::ssr;
use crate::cache::Run;

/// verify result model
#[derive(Default, Debug, Deserialize)]
pub struct VerifyResult {
    pub state: String,
    #[serde(skip)]
    pub name: String,
    #[serde(skip)]
    pub data_input: String,
    #[serde(skip)]
    pub result_type: Run,
    // #[serde(default)]
    // lang: String,
    #[serde(default)]
    pretty_lang: String,
    // #[serde(default)]
    // submission_id: String,
    // #[serde(default)]
    // run_success: bool,
    #[serde(default)]
    correct_answer: bool,
    #[serde(default, deserialize_with = "ssr")]
    code_answer: Vec<String>,
    #[serde(default, deserialize_with = "ssr")]
    code_output: Vec<String>,
    #[serde(default, deserialize_with = "ssr")]
    expected_output: Vec<String>,
    #[serde(default, deserialize_with = "ssr")]
    std_output: Vec<String>,

    // flatten
    // #[serde(flatten, default)]
    // info: VerifyInfo,
    #[serde(flatten, default)]
    status: VerifyStatus,
    #[serde(flatten, default)]
    analyse: Analyse,
    #[serde(flatten, default)]
    expected: Expected,
    #[serde(flatten, default)]
    error: CompileError,
    #[serde(flatten, default)]
    submit: Submit,
}

impl VerifyResult {
    /// A submission LeetCode accepted: status 10 plus the per-case comparison string it only
    /// sends for a finished submission.
    pub fn is_accepted(&self) -> bool {
        self.status.status_code == 10
            && matches!(self.result_type, Run::Submit)
            && !self.submit.compare_result.is_empty()
    }

    /// Internal problem id of an accepted submission, for marking the cached row solved.
    /// `None` for anything that was not accepted; an error only if LeetCode sent a
    /// `question_id` that is not an integer.
    pub fn accepted_problem_id(&self) -> std::result::Result<Option<i32>, std::num::ParseIntError> {
        if !self.is_accepted() {
            return Ok(None);
        }

        self.submit.question_id.parse().map(Some)
    }

    /// Internal problem id of a submission the judge finished, accepted or not — what the review
    /// deck grades on.
    ///
    /// `compare_result` is the per-case comparison string, and LeetCode sends it only once cases
    /// have actually run. Gating on it keeps a test run out (it never carries one) and also keeps
    /// a compile error out, which is a failure to build rather than a failure to recall.
    pub fn submitted_problem_id(
        &self,
    ) -> std::result::Result<Option<i32>, std::num::ParseIntError> {
        if !matches!(self.result_type, Run::Submit) || self.submit.compare_result.is_empty() {
            return Ok(None);
        }

        self.submit.question_id.parse().map(Some)
    }
}

impl std::fmt::Display for VerifyResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ca = match &self.code_answer.len() {
            1 => self.code_answer[0].to_string(),
            _ => self.code_answer.join("↩ "),
        };

        let eca = match &self.expected.expected_code_answer.len() {
            1 => self.expected.expected_code_answer[0].to_string(),
            _ => self.expected.expected_code_answer.join("↩ "),
        };

        debug!("{:#?}", self);

        match &self.status.status_code {
            10 => {
                if matches!(self.result_type, Run::Test) && self.correct_answer {
                    // Pass Tests
                    write!(
                        f,
                        "\n{}{}{}\n{}{}{}{}{}{}\n",
                        self.status.status_msg.green().bold(),
                        "Runtime: ".before_spaces(7).dimmed(),
                        self.status.status_runtime.dimmed(),
                        "\nYour input:".after_spaces(4),
                        self.data_input.replace('\n', "↩ "),
                        "\nOutput:".after_spaces(8),
                        ca,
                        "\nExpected:".after_spaces(6),
                        eca,
                    )?
                } else if matches!(self.result_type, Run::Submit)
                    && !self.submit.compare_result.is_empty()
                {
                    // only Submit execute this branch
                    // Submit Successfully
                    // TODO: result should be all 1;
                    let rp = if let Some(n) = &self.analyse.runtime_percentile {
                        if n.is_f64() {
                            n.as_f64().unwrap_or(0.0) as i64
                        } else {
                            n.as_i64().unwrap_or(0)
                        }
                    } else {
                        0
                    };

                    let mp = if let Some(n) = &self.analyse.memory_percentile {
                        if n.is_f64() {
                            n.as_f64().unwrap_or(0.0) as i64
                        } else {
                            n.as_i64().unwrap_or(0)
                        }
                    } else {
                        0
                    };

                    write!(
                        f,
                        "\n{}{}{}\
                         , faster than \
                         {}{}\
                         of \
                         {} \
                         online submissions for \
                         {}.\n\n\
                         {}{}\
                         , less than \
                         {}{}\
                         of \
                         {} {}.\n\n",
                        "Success\n\n".green().bold(),
                        "Runtime: ".dimmed(),
                        self.status.status_runtime.bold(),
                        rp.to_string().bold(),
                        "% ".bold(),
                        self.pretty_lang,
                        self.name,
                        "Memory Usage: ".dimmed(),
                        self.status.status_memory.bold(),
                        mp.to_string().bold(),
                        "% ".bold(),
                        self.pretty_lang,
                        self.name,
                    )?
                } else {
                    // Wrong Answer during testing
                    write!(
                        f,
                        "\n{}{}{}\n{}{}{}{}{}{}\n",
                        "Wrong Answer".red().bold(),
                        "   Runtime: ".dimmed(),
                        self.status.status_runtime.dimmed(),
                        "\nYour input:".after_spaces(4),
                        self.data_input.replace('\n', "↩ "),
                        "\nOutput:".after_spaces(8),
                        ca,
                        "\nExpected:".after_spaces(6),
                        eca,
                    )?
                }
            }
            // Failed some tests during submission
            11 => write!(
                f,
                "\n{}\n\n{}{}\n{}{}\n{}{}{}{}{}{}\n",
                self.status.status_msg.red().bold(),
                "Cases passed:".after_spaces(2).green(),
                self.analyse
                    .total_correct
                    .as_ref()
                    .unwrap_or(&Number::from(0))
                    .to_string()
                    .green(),
                "Total cases:".after_spaces(3).yellow(),
                self.analyse
                    .total_testcases
                    .as_ref()
                    .unwrap_or(&Number::from(0))
                    .to_string()
                    .bold()
                    .yellow(),
                "Last case:".after_spaces(5).dimmed(),
                self.submit.last_testcase.replace('\n', "↩ ").dimmed(),
                "\nOutput:".after_spaces(8),
                first_line(&self.code_output),
                "\nExpected:".after_spaces(6),
                first_line(&self.expected_output),
            )?,
            // Memory Exceeded
            12 => write!(
                f,
                "\n{}\n\n{}{}\n",
                self.status.status_msg.yellow().bold(),
                "Last case:".after_spaces(5).dimmed(),
                self.data_input.replace('\n', "↩ "),
            )?,
            // Output Timeout Exceeded
            //
            // TODO: 13 and 14 might have some different,
            // if anybody reach this, welcome to fix this!
            13 | 14 => write!(f, "\n{}\n", self.status.status_msg.yellow().bold(),)?,
            // Runtime error
            15 => write!(
                f,
                "\n{}\n{}\n'",
                self.status.status_msg.red().bold(),
                self.status.runtime_error
            )?,
            // Compile Error
            20 => write!(
                f,
                "\n{}:\n\n{}\n",
                self.status.status_msg.red().bold(),
                self.error.full_compile_error.dimmed()
            )?,
            _ => write!(
                f,
                "{}{}{}{}{}{}{}{}",
                "\nUnknown Error...\n".red().bold(),
                "\nBingo! Welcome to fix this! Pull your request at ".yellow(),
                "https://github.com/siansiansu/leetctl/pulls"
                    .dimmed()
                    .underline(),
                ", and this file is located at ".yellow(),
                "leetctl/src/cache/models.rs".dimmed().underline(),
                " waiting for you! Yep, line ".yellow(),
                "385".dimmed().underline(),
                ".\n".yellow(),
            )?,
        };

        match &self.result_type {
            Run::Test => {
                if !self.code_output.is_empty() {
                    write!(
                        f,
                        "{}{}",
                        "Stdout:".after_spaces(8).purple(),
                        self.code_output.join(&"\n".after_spaces(15))
                    )
                } else {
                    write!(f, "")
                }
            }
            _ => {
                if !self.std_output.is_empty() {
                    write!(
                        f,
                        "{}{}",
                        "Stdout:".after_spaces(8).purple(),
                        self.std_output[0].replace('\n', &"\n".after_spaces(15))
                    )
                } else {
                    write!(f, "")
                }
            }
        }
    }
}

use crate::Config;
use verify::*;

mod verify {
    use super::super::parser::ssr;
    use serde::Deserialize;
    use serde_json::Number;

    #[derive(Debug, Default, Deserialize)]
    pub struct Submit {
        #[serde(default)]
        pub question_id: String,
        #[serde(default)]
        pub last_testcase: String,
        #[serde(default)]
        pub compare_result: String,
    }

    // #[derive(Debug, Default, Deserialize)]
    // pub struct VerifyInfo {
    //     #[serde(default)]
    //     memory: i64,
    //     #[serde(default)]
    //     elapsed_time: i64,
    //     #[serde(default)]
    //     task_finish_time: i64,
    // }

    #[derive(Debug, Default, Deserialize)]
    pub struct Analyse {
        #[serde(default)]
        pub total_correct: Option<Number>,
        #[serde(default)]
        pub total_testcases: Option<Number>,
        #[serde(default)]
        pub runtime_percentile: Option<Number>,
        #[serde(default)]
        pub memory_percentile: Option<Number>,
    }

    #[derive(Debug, Default, Deserialize)]
    pub struct VerifyStatus {
        #[serde(default)]
        pub status_code: i32,
        #[serde(default)]
        pub status_msg: String,
        #[serde(default)]
        pub status_memory: String,
        #[serde(default)]
        pub status_runtime: String,
        #[serde(default)]
        pub runtime_error: String,
    }

    #[derive(Debug, Default, Deserialize)]
    pub struct CompileError {
        // #[serde(default)]
        // compile_error: String,
        #[serde(default)]
        pub full_compile_error: String,
    }

    #[derive(Debug, Default, Deserialize)]
    pub struct Expected {
        // #[serde(default)]
        // expected_status_code: i32,
        // #[serde(default)]
        // expected_lang: String,
        // #[serde(default)]
        // expected_run_success: bool,
        // #[serde(default)]
        // expected_status_runtime: String,
        // #[serde(default)]
        // expected_memory: i64,
        // #[serde(default, deserialize_with = "ssr")]
        // expected_code_output: Vec<String>,
        // #[serde(default)]
        // expected_elapsed_time: i64,
        // #[serde(default)]
        // expected_task_finish_time: i64,
        #[serde(default, deserialize_with = "ssr")]
        pub expected_code_answer: Vec<String>,
    }
}

/// Formatter for str
/// The first line of an output list, or nothing.
///
/// LeetCode leaves `code_output` empty and omits `expected_output` entirely on a submission, so
/// indexing these panicked — while formatting, which the TUI does mid-render.
fn first_line(lines: &[String]) -> &str {
    lines.first().map(String::as_str).unwrap_or("")
}

trait Formatter {
    fn after_spaces(&self, spaces: usize) -> String;
    fn before_spaces(&self, spaces: usize) -> String;
}

impl Formatter for str {
    fn after_spaces(&self, spaces: usize) -> String {
        let mut r = String::new();
        r.push_str(self);
        r.push_str(&" ".repeat(spaces));
        r
    }

    fn before_spaces(&self, spaces: usize) -> String {
        let mut r = String::new();
        r.push_str(&" ".repeat(spaces));
        r.push_str(self);
        r
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The one shape a submission response needs for the accepted path: status 10, a compare
    /// string, and the internal problem id. `result_type` is `#[serde(skip)]` and defaults to
    /// `Run::Submit`, which is what a real submit carries.
    fn accepted_submission() -> VerifyResult {
        serde_json::from_str(
            r#"{
                "state": "SUCCESS",
                "status_code": 10,
                "status_msg": "Accepted",
                "status_runtime": "4 ms",
                "status_memory": "2.1 MB",
                "runtime_percentile": 91.5,
                "memory_percentile": 47.0,
                "compare_result": "111",
                "question_id": "704",
                "pretty_lang": "Rust"
            }"#,
        )
        .expect("accepted submission fixture should deserialize")
    }

    #[test]
    fn banner_names_the_problem_and_reads_as_in_flight() {
        let rendered = fixture(704, 1, "Binary Search").banner();

        assert!(
            rendered.contains("704"),
            "banner should carry the frontend id"
        );
        assert!(rendered.contains("Binary Search"));
        assert!(rendered.contains("is on the run..."));
    }

    #[test]
    fn is_accepted_only_for_a_finished_submission() {
        assert!(accepted_submission().is_accepted());

        // A test run reaches status 10 too; only a submission carries `compare_result`.
        let mut passing_test = accepted_submission();
        passing_test.result_type = Run::Test;
        assert!(!passing_test.is_accepted());

        let mut wrong_answer = accepted_submission();
        wrong_answer.status.status_code = 11;
        assert!(!wrong_answer.is_accepted());

        assert!(!VerifyResult::default().is_accepted());
    }

    #[test]
    fn accepted_problem_id_is_the_internal_id() {
        assert_eq!(accepted_submission().accepted_problem_id(), Ok(Some(704)));
        assert_eq!(VerifyResult::default().accepted_problem_id(), Ok(None));

        let mut unparseable = accepted_submission();
        unparseable.submit.question_id = "seven-oh-four".to_string();
        assert!(unparseable.accepted_problem_id().is_err());
    }

    #[test]
    fn submitted_problem_id_covers_rejected_submissions_too() {
        // What the deck grades `good`.
        assert_eq!(accepted_submission().submitted_problem_id(), Ok(Some(704)));

        // What it grades `again`: the judge ran the cases and some failed.
        let mut wrong_answer = accepted_submission();
        wrong_answer.status.status_code = 11;
        assert_eq!(wrong_answer.submitted_problem_id(), Ok(Some(704)));

        // A test run never grades anything — it carries no `compare_result`.
        let mut passing_test = accepted_submission();
        passing_test.result_type = Run::Test;
        passing_test.submit.compare_result = String::new();
        assert_eq!(passing_test.submitted_problem_id(), Ok(None));

        // Neither does a compile error: nothing ran, so nothing was recalled or forgotten.
        let mut compile_error = accepted_submission();
        compile_error.status.status_code = 20;
        compile_error.submit.compare_result = String::new();
        assert_eq!(compile_error.submitted_problem_id(), Ok(None));
    }

    /// Regression guard: formatting an accepted submission used to open the sqlite cache and write
    /// `update_after_ac` from inside `fmt`, panicking through `expect` when that failed. Rendering
    /// must be pure — the TUI formats results while drawing.
    #[test]
    fn display_of_an_accepted_submission_only_formats() {
        let rendered = accepted_submission().to_string();

        assert!(rendered.contains("Success"));
        assert!(rendered.contains("4 ms"), "runtime should be reported");
        assert!(
            rendered.contains("91%"),
            "runtime percentile is truncated to a whole percent"
        );
        assert!(rendered.contains("2.1 MB"));
    }

    /// Regression guard: a submission that fails some cases carries an empty `code_output` and no
    /// `expected_output` at all, and formatting used to index straight into both. `leetctl exec`
    /// panicked on it, and the TUI formats results while drawing.
    #[test]
    fn display_of_a_partly_failed_submission_does_not_panic() {
        let result: VerifyResult = serde_json::from_str(
            r#"{"status_code": 11, "lang": "rust", "run_success": true, "status_runtime": "4 ms", "memory": 2716000, "question_id": "203", "elapsed_time": 0, "compare_result": "11111111111111111111111111011", "code_output": "", "std_output": "", "last_testcase": "[1, 2, 3]", "task_finish_time": 1578590021187, "total_correct": 28, "total_testcases": 29, "runtime_percentile": 76.9231, "status_memory": "2.7 MB", "memory_percentile": 100, "pretty_lang": "Rust", "submission_id": "292701790", "status_msg": "Failed", "state": "SUCCESS"}"#,
        )
        .expect("failed-submission fixture should deserialize");

        let rendered = result.to_string();

        assert!(rendered.contains("Failed"), "{rendered}");
        assert!(rendered.contains("28"), "cases passed missing:\n{rendered}");
        assert!(rendered.contains("29"), "total cases missing:\n{rendered}");
        assert!(
            rendered.contains("[1, 2, 3]"),
            "failing case missing:\n{rendered}"
        );
        assert!(!result.is_accepted());
    }
}