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
// Copyright Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt::{self, Debug};
use std::iter;
use std::slice;

use git_workarea::{CommitId, GitContext, GitError, Identity, WorkAreaError};
use log::{debug, error};
use rayon::prelude::*;
use thiserror::Error;

use crate::check::{BranchCheck, Check, CheckResult, TopicCheck};
use crate::commit::{Commit, CommitError, Topic};
use crate::context::CheckGitContext;

/// Errors which can occur when running checks.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RunError {
    /// Command preparation failure.
    #[error("git error: {}", source)]
    Git {
        /// The cause of the error.
        #[from]
        source: GitError,
    },
    /// An error occurred when working with the workarea.
    #[error("git workarea error: {}", source)]
    WorkArea {
        /// The cause of the error.
        #[from]
        source: WorkAreaError,
    },
    /// An error occurred when working with a commit.
    #[error("commit error: {}", source)]
    Commit {
        /// The cause of the error.
        #[from]
        source: CommitError,
    },
    /// Failure to create a ref to refer to the checked commit.
    #[error("run check error: failed to update the {} ref: {}", base_ref, output)]
    UpdateRef {
        /// The base name of the ref.
        base_ref: CommitId,
        /// Git's output for the error.
        output: String,
    },
    /// Failure to list revisions to check.
    #[error(
        "run check error: failed to list refs from {} to {}",
        base_ref,
        new_ref
    )]
    RevList {
        /// The base ref for the topic.
        base_ref: CommitId,
        /// The head of the topic.
        new_ref: CommitId,
        /// Git's output for the error.
        output: String,
    },
}

impl RunError {
    fn update_ref(base_ref: CommitId, output: &[u8]) -> Self {
        RunError::UpdateRef {
            base_ref,
            output: String::from_utf8_lossy(output).into(),
        }
    }

    fn rev_list(base_ref: CommitId, new_ref: CommitId, output: &[u8]) -> Self {
        RunError::RevList {
            base_ref,
            new_ref,
            output: String::from_utf8_lossy(output).into(),
        }
    }
}

/// Configuration for checks to run against a repository.
#[derive(Default, Clone)]
pub struct GitCheckConfiguration<'a> {
    /// Checks to run on each commit.
    checks: Vec<&'a dyn Check>,
    /// Checks to run on the branch as a whole.
    checks_branch: Vec<&'a dyn BranchCheck>,
    /// Checks to run on the topic.
    checks_topic: Vec<&'a dyn TopicCheck>,
}

/// Results from checking a topic.
#[derive(Debug)]
pub struct TopicCheckResult {
    /// The results for each commit in the topic.
    commit_results: Vec<(CommitId, CheckResult)>,
    /// The results for the branch as a whole.
    topic_result: CheckResult,
}

impl TopicCheckResult {
    /// The results for each commit checked.
    pub fn commit_results(&self) -> slice::Iter<(CommitId, CheckResult)> {
        self.commit_results.iter()
    }

    /// The results for the topic as a whole.
    pub fn topic_result(&self) -> &CheckResult {
        &self.topic_result
    }
}

impl From<TopicCheckResult> for CheckResult {
    fn from(res: TopicCheckResult) -> Self {
        res.commit_results
            .into_iter()
            .map(|(_, result)| result)
            .chain(iter::once(res.topic_result))
            .fold(Self::new(), Self::combine)
    }
}

impl<'a> GitCheckConfiguration<'a> {
    /// Create a new check configuration.
    pub fn new() -> Self {
        GitCheckConfiguration {
            checks: Vec::new(),
            checks_branch: Vec::new(),
            checks_topic: Vec::new(),
        }
    }

    /// Add a check to be run on every commit.
    pub fn add_check(&mut self, check: &'a dyn Check) -> &mut Self {
        self.checks.push(check);

        self
    }

    /// Add a check to be once for the entire branch.
    pub fn add_branch_check(&mut self, check: &'a dyn BranchCheck) -> &mut Self {
        self.checks_branch.push(check);

        self
    }

    /// Add a check to be once for the entire topic.
    pub fn add_topic_check(&mut self, check: &'a dyn TopicCheck) -> &mut Self {
        self.checks_topic.push(check);

        self
    }

    /// Find refs that should be checked given a target branch and the topic names.
    fn list(
        &self,
        ctx: &GitContext,
        reason: &str,
        base_branch: &CommitId,
        topic: &CommitId,
    ) -> Result<Vec<CommitId>, RunError> {
        let (new_ref, base_ref) = ctx.reserve_refs(format!("check/{}", reason), topic)?;
        let update_ref = ctx
            .git()
            .arg("update-ref")
            .args(["-m", reason])
            .arg(&base_ref)
            .arg(base_branch.as_str())
            .output()
            .map_err(|err| GitError::subcommand("update-ref", err))?;
        if !update_ref.status.success() {
            return Err(RunError::update_ref(
                CommitId::new(base_ref),
                &update_ref.stderr,
            ));
        }

        let rev_list = ctx
            .git()
            .arg("rev-list")
            .arg("--reverse")
            .arg("--topo-order")
            .arg(&new_ref)
            .arg(&format!("^{}", base_ref))
            .output()
            .map_err(|err| GitError::subcommand("rev-list", err))?;
        if !rev_list.status.success() {
            return Err(RunError::rev_list(
                CommitId::new(base_ref),
                CommitId::new(new_ref),
                &rev_list.stderr,
            ));
        }
        let refs = String::from_utf8_lossy(&rev_list.stdout);

        Ok(refs.lines().map(CommitId::new).collect())
    }

    /// Run a commit check over a commit.
    fn run_check(ctx: &CheckGitContext, check: &dyn Check, commit: &Commit) -> CheckResult {
        debug!(
            target: "git-checks",
            "running check {} on commit {}",
            check.name(),
            commit.sha1,
        );

        check.check(ctx, commit).unwrap_or_else(|err| {
            error!(
                target: "git-checks",
                "check {} failed on commit {}: {:?}",
                check.name(),
                commit.sha1,
                err,
            );

            let mut res = CheckResult::new();
            res.add_alert(
                format!(
                    "failed to run the {} check on commit {}",
                    check.name(),
                    commit.sha1,
                ),
                true,
            );
            res
        })
    }

    /// Run a branch check over a commit.
    fn run_branch_check(
        ctx: &CheckGitContext,
        check: &dyn BranchCheck,
        commit: &CommitId,
    ) -> CheckResult {
        debug!(target: "git-checks", "running check {}", check.name());

        check.check(ctx, commit).unwrap_or_else(|err| {
            error!(
                target: "git-checks",
                "branch check {}: {:?}",
                check.name(),
                err,
            );

            let mut res = CheckResult::new();
            res.add_alert(
                format!("failed to run the {} branch check", check.name()),
                true,
            );
            res
        })
    }

    /// Run a topic check over a topic.
    fn run_topic_check(
        ctx: &CheckGitContext,
        check: &dyn TopicCheck,
        topic: &Topic,
    ) -> CheckResult {
        debug!(target: "git-checks", "running check {}", check.name());

        check.check(ctx, topic).unwrap_or_else(|err| {
            error!(
                target: "git-checks",
                "topic check {}: {:?}",
                check.name(),
                err,
            );

            let mut res = CheckResult::new();
            res.add_alert(
                format!("failed to run the {} topic check", check.name()),
                true,
            );
            res
        })
    }

    /// Run checks over a given topic and collect results from the checks.
    fn run_topic_impl(
        &self,
        ctx: &GitContext,
        base: &CommitId,
        refs: Vec<CommitId>,
        owner: &Identity,
    ) -> Result<TopicCheckResult, RunError> {
        let topic_result = refs.last().map_or_else(
            || Ok(CheckResult::new()) as Result<_, RunError>,
            |head_commit| {
                // Avoid setting up the workarea if there aren't any branch or topic checks.
                if self.checks_branch.is_empty() && self.checks_topic.is_empty() {
                    return Ok(CheckResult::new());
                }

                let workarea = ctx.prepare(head_commit)?;
                let check_ctx = CheckGitContext::new(workarea, owner.clone());
                let topic = Topic::new(ctx, base, head_commit)?;

                Ok(self
                    .checks_branch
                    .par_iter()
                    .map(|&check| Self::run_branch_check(&check_ctx, check, head_commit))
                    .chain(
                        self.checks_topic
                            .par_iter()
                            .map(|&check| Self::run_topic_check(&check_ctx, check, &topic)),
                    )
                    .reduce(CheckResult::new, CheckResult::combine))
            },
        )?;
        let commit_results = refs
            .into_par_iter()
            .map(|sha1| {
                self.run_commit(ctx, &sha1, owner)
                    .map(|result| (sha1, result))
            })
            .collect::<Vec<Result<_, RunError>>>()
            .into_iter()
            .collect::<Result<Vec<_>, RunError>>()?;

        Ok(TopicCheckResult {
            commit_results,
            topic_result,
        })
    }

    /// Run checks over a given commit.
    pub fn run_commit(
        &self,
        ctx: &GitContext,
        commit: &CommitId,
        owner: &Identity,
    ) -> Result<CheckResult, RunError> {
        // Avoid setting up the workarea if there aren't any per-commit checks.
        if self.checks.is_empty() {
            return Ok(CheckResult::new());
        }

        let workarea = ctx.prepare(commit)?;
        let check_ctx = CheckGitContext::new(workarea, owner.clone());

        let commit = Commit::new(ctx, commit)?;

        Ok(self
            .checks
            .par_iter()
            .map(|&check| Self::run_check(&check_ctx, check, &commit))
            .reduce(CheckResult::new, CheckResult::combine))
    }

    /// Run checks over a given topic and collect results from the checks.
    pub fn run_topic<R>(
        &self,
        ctx: &GitContext,
        reason: R,
        base_branch: &CommitId,
        topic: &CommitId,
        owner: &Identity,
    ) -> Result<TopicCheckResult, RunError>
    where
        R: AsRef<str>,
    {
        let refs = self.list(ctx, reason.as_ref(), base_branch, topic)?;
        self.run_topic_impl(ctx, base_branch, refs, owner)
    }
}

impl<'a> Debug for GitCheckConfiguration<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "GitCheckConfiguration {{ {} commit checks, {} branch checks, {} topic checks }}",
            self.checks.len(),
            self.checks_branch.len(),
            self.checks_topic.len(),
        )
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use std::path::Path;

    use git_workarea::{CommitId, GitContext, Identity};

    use crate::run::{CheckResult, GitCheckConfiguration, TopicCheckResult};

    mod checks {
        use thiserror::Error;

        use crate::impl_prelude::*;

        #[derive(Debug)]
        pub struct FailingCheck {}

        #[derive(Debug, Error)]
        #[error("the failing check did its thing")]
        struct FailingCheckError;

        impl Check for FailingCheck {
            fn name(&self) -> &str {
                "test-failing-check-commit"
            }

            fn check(
                &self,
                _: &CheckGitContext,
                _: &Commit,
            ) -> Result<CheckResult, Box<dyn Error>> {
                Err(FailingCheckError.into())
            }
        }

        impl BranchCheck for FailingCheck {
            fn name(&self) -> &str {
                "test-failing-check-branch"
            }

            fn check(
                &self,
                _: &CheckGitContext,
                _: &CommitId,
            ) -> Result<CheckResult, Box<dyn Error>> {
                Err(FailingCheckError.into())
            }
        }

        impl TopicCheck for FailingCheck {
            fn name(&self) -> &str {
                "test-failing-check-topic"
            }

            fn check(&self, _: &CheckGitContext, _: &Topic) -> Result<CheckResult, Box<dyn Error>> {
                Err(FailingCheckError.into())
            }
        }
    }

    #[test]
    fn test_configuration_debug() {
        let config = GitCheckConfiguration::new();
        assert_eq!(
            format!("{:?}", config),
            "GitCheckConfiguration { 0 commit checks, 0 branch checks, 0 topic checks }",
        );
    }

    const TARGET_COMMIT: &str = "27ff3ef5532d76afa046f76f4dd8f588dc3e83c3";
    const TOPIC_COMMIT: &str = "a61fd3759b61a4a1f740f3fe656bc42151cefbdd";
    const TOPIC2_COMMIT: &str = "112e9b34401724bff57f68cf47c5065d4342b263";

    fn git_context() -> GitContext {
        let gitdir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.git"));
        if !gitdir.exists() {
            panic!("The tests must be run from a git checkout.");
        }

        GitContext::new(gitdir)
    }

    fn run_commit(config: &GitCheckConfiguration) -> CheckResult {
        let ctx = git_context();
        config
            .run_commit(
                &ctx,
                &CommitId::new(TOPIC_COMMIT),
                &Identity::new(
                    "Rust Git Checks Core Tests",
                    "rust-git-checks@example.invalid",
                ),
            )
            .unwrap()
    }

    fn run_topic(
        test_name: &str,
        config: &GitCheckConfiguration,
        commit: &str,
    ) -> TopicCheckResult {
        let ctx = git_context();
        config
            .run_topic(
                &ctx,
                test_name,
                &CommitId::new(TARGET_COMMIT),
                &CommitId::new(commit),
                &Identity::new(
                    "Rust Git Checks Core Tests",
                    "rust-git-checks@example.invalid",
                ),
            )
            .unwrap()
    }

    fn no_strings<'a>() -> iter::Empty<&'a String> {
        iter::empty()
    }

    fn check_result(result: &CheckResult, errors: &[&str]) {
        itertools::assert_equal(result.warnings(), no_strings());
        itertools::assert_equal(result.alerts(), errors);
        itertools::assert_equal(result.errors(), no_strings());
        assert!(!result.temporary());
        assert!(!result.allowed());
        assert!(!result.pass());
    }

    fn check_result_ok(result: &CheckResult) {
        itertools::assert_equal(result.warnings(), no_strings());
        itertools::assert_equal(result.alerts(), no_strings());
        itertools::assert_equal(result.errors(), no_strings());
        assert!(!result.temporary());
        assert!(!result.allowed());
        assert!(result.pass());
    }

    #[test]
    fn test_commit_check_errors_commit() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_check(&check);

        let result = run_commit(&config);

        check_result(
            &result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
    }

    #[test]
    fn test_branch_check_errors_commit() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_branch_check(&check);

        let result = run_commit(&config);

        check_result_ok(&result);
    }

    #[test]
    fn test_topic_check_errors_commit() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_topic_check(&check);

        let result = run_commit(&config);

        check_result_ok(&result);
    }

    #[test]
    fn test_commit_check_errors_topic() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_check(&check);

        let result = run_topic("test_commit_check_errors_topic", &config, TOPIC_COMMIT);

        let mut commit_results = result.commit_results();
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "a61fd3759b61a4a1f740f3fe656bc42151cefbdd");
        check_result(
            commit_result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
        if let Some(res) = commit_results.next() {
            panic!(
                "multiple commits returned from a single-commit topic: {:?}",
                res,
            );
        }
        check_result_ok(result.topic_result());
        check_result(
            &result.into(),
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
    }

    #[test]
    fn test_branch_check_errors_topic() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_branch_check(&check);

        let result = run_topic("test_branch_check_errors_topic", &config, TOPIC_COMMIT);

        let mut commit_results = result.commit_results();
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "a61fd3759b61a4a1f740f3fe656bc42151cefbdd");
        check_result_ok(commit_result);
        if let Some(res) = commit_results.next() {
            panic!(
                "multiple commits returned from a single-commit topic: {:?}",
                res,
            );
        }
        check_result(
            result.topic_result(),
            &["failed to run the test-failing-check-branch branch check"],
        );
        check_result(
            &result.into(),
            &["failed to run the test-failing-check-branch branch check"],
        );
    }

    #[test]
    fn test_topic_check_errors_topic() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_topic_check(&check);

        let result = run_topic("test_topic_check_errors_topic", &config, TOPIC_COMMIT);

        let mut commit_results = result.commit_results();
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "a61fd3759b61a4a1f740f3fe656bc42151cefbdd");
        check_result_ok(commit_result);
        if let Some(res) = commit_results.next() {
            panic!(
                "multiple commits returned from a single-commit topic: {:?}",
                res,
            );
        }
        check_result(
            result.topic_result(),
            &["failed to run the test-failing-check-topic topic check"],
        );
        check_result(
            &result.into(),
            &["failed to run the test-failing-check-topic topic check"],
        );
    }

    #[test]
    fn test_multiple_check_commit() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_check(&check);
        config.add_check(&check);
        config.add_branch_check(&check);
        config.add_branch_check(&check);
        config.add_topic_check(&check);
        config.add_topic_check(&check);

        let result = run_commit(&config);

        check_result(
            &result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
    }

    #[test]
    fn test_multiple_check_topic() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_check(&check);
        config.add_check(&check);
        config.add_branch_check(&check);
        config.add_branch_check(&check);
        config.add_topic_check(&check);
        config.add_topic_check(&check);

        let result = run_topic("test_multiple_check_topic", &config, TOPIC_COMMIT);

        let mut commit_results = result.commit_results();
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "a61fd3759b61a4a1f740f3fe656bc42151cefbdd");
        check_result(
            commit_result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
        if let Some(res) = commit_results.next() {
            panic!(
                "multiple commits returned from a single-commit topic: {:?}",
                res,
            );
        }
        check_result(
            result.topic_result(),
            &[
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-topic topic check",
                "failed to run the test-failing-check-topic topic check",
            ],
        );
        check_result(
            &result.into(),
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-topic topic check",
                "failed to run the test-failing-check-topic topic check",
            ],
        );
    }

    #[test]
    fn test_check_multiple_topic() {
        let check = self::checks::FailingCheck {};
        let mut config = GitCheckConfiguration::new();
        config.add_check(&check);
        config.add_branch_check(&check);
        config.add_topic_check(&check);

        let result = run_topic("test_check_multiple_topic", &config, TOPIC2_COMMIT);

        let mut commit_results = result.commit_results();
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "a61fd3759b61a4a1f740f3fe656bc42151cefbdd");
        check_result(
            commit_result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
            ],
        );
        let (commit, commit_result) = commit_results.next().unwrap();
        assert_eq!(commit.as_str(), "112e9b34401724bff57f68cf47c5065d4342b263");
        check_result(
            commit_result,
            &[
                "failed to run the test-failing-check-commit check on commit \
                 112e9b34401724bff57f68cf47c5065d4342b263",
            ],
        );
        if let Some(res) = commit_results.next() {
            panic!(
                "multiple commits returned from a single-commit topic: {:?}",
                res,
            );
        }
        check_result(
            result.topic_result(),
            &[
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-topic topic check",
            ],
        );
        check_result(
            &result.into(),
            &[
                "failed to run the test-failing-check-commit check on commit \
                 a61fd3759b61a4a1f740f3fe656bc42151cefbdd",
                "failed to run the test-failing-check-commit check on commit \
                 112e9b34401724bff57f68cf47c5065d4342b263",
                "failed to run the test-failing-check-branch branch check",
                "failed to run the test-failing-check-topic topic check",
            ],
        );
    }
}