thirdshift 0.8.4

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! What a run is asked: its command's flags, and, for whatever the command
//! says nothing about, the User config. The argument parser fills in the
//! [`Flags`] as the command gave them; what they come to, for each kind of
//! run, is its [`Asks`].

use std::num::NonZeroUsize;

use crate::args;
use crate::base_fix::BaseFixAsk;
use crate::child_run::Given;
use crate::config::UserConfig;
use crate::issue::IssueUrl;
use crate::notification::NotificationAsk;
use crate::run::Goal;

/// The flags a Run, an Architect run and a Pickup run share, as the command
/// gave them: each is none if the command said nothing about it.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Flags {
    /// The goal `merge` or `no-merge` asked for.
    pub goal: Option<Goal>,
    /// What `email` or `no-email` asked for.
    pub email: Option<NotificationAsk>,
    /// How many Tickets a Spec run runs at once, as `parallel <n>` gave it.
    pub parallel: Option<NonZeroUsize>,
    /// What `base-fix` or `no-base-fix` asked for.
    pub base_fix: Option<BaseFixAsk>,
}

/// Everything a Run, or a Spec run, is asked, resolved.
#[derive(Debug, PartialEq, Eq)]
pub struct Asks {
    /// Whether it is a Merge run.
    pub goal: Goal,
    /// What it is asked about its Run notification.
    pub notification: NotificationAsk,
    /// How many Tickets a Spec run runs at once.
    pub tickets_at_once: NonZeroUsize,
    /// Whether the command asked for that with `parallel <n>`, rather than
    /// the User config deciding: only a Spec can be asked it.
    pub parallel_asked: bool,
    /// What it is asked about a Base fix.
    pub base_fix: BaseFixAsk,
    /// Whether it first brings the Launch directory's checkout of the Base
    /// branch up to date with origin.
    pub launch_pull: bool,
}

impl Asks {
    /// What the Run, or the Spec run, started on `issue`'s URL is asked: by
    /// `flags`, else by `config`. Where neither decided about a Base fix,
    /// the command that retries `issue` is the one on its Issue URL with
    /// `flags`.
    pub fn of_run(issue: &IssueUrl, flags: &Flags, config: &UserConfig) -> Asks {
        let goal = flags.goal.unwrap_or(if config.merge_always {
            Goal::Merged
        } else {
            Goal::ReadyForReview
        });
        let base_fix = flags.base_fix.clone().unwrap_or_else(|| {
            if config.base_fix {
                BaseFixAsk::Allow
            } else {
                let retry = retry_with_base_fix(issue, flags);
                BaseFixAsk::Undecided { retry }
            }
        });
        Asks {
            goal,
            notification: flags.notification(config),
            tickets_at_once: flags.parallel.unwrap_or(config.spec_parallel),
            parallel_asked: flags.parallel.is_some(),
            base_fix,
            launch_pull: config.launch_pull,
        }
    }

    /// What a child Run, a Ticket's Run in a Spec run or a Base fix, is
    /// asked, from what it was `given`: it is always a Merge run, sends no
    /// Run notification, leaves the Launch directory alone, and asks about a
    /// Base fix what it was given. Neither its flags nor `config` decide
    /// any of that: those are for what started it. As it runs no Tickets,
    /// `config` says only how many it would run at once.
    pub fn of_child_run(given: &Given, config: &UserConfig) -> Asks {
        Asks {
            goal: Goal::Merged,
            notification: NotificationAsk::Skip,
            tickets_at_once: config.spec_parallel,
            parallel_asked: false,
            base_fix: given.base_fix.clone(),
            launch_pull: false,
        }
    }

    /// What the Spec run or Run an Architect run dispatches its Architect
    /// plan `plan` as is asked by the Architect run's `flags`, else by
    /// `config`: see [`Asks::dispatched`]. The command a Base fix is offered
    /// with retries the plan as a Run of its own: another Architect run
    /// would start a new review instead.
    pub fn of_architect_plan(plan: &IssueUrl, flags: &Flags, config: &UserConfig) -> Asks {
        Asks::dispatched(plan, flags, config)
    }

    /// What the Spec run or Run a Pickup run dispatches the Ready issue
    /// `issue` as is asked by the Pickup run's `flags`, else by `config`:
    /// see [`Asks::dispatched`]. `parallel` is ignored for an issue that is
    /// not a Spec, as `is_spec` says, since the command can't know which
    /// the Pickup run will take. It is left out of the command a Base fix is
    /// offered with too, which retries the issue as a Run of its own:
    /// another Pickup run never takes an issue that was started.
    pub fn of_ready_issue(
        issue: &IssueUrl,
        is_spec: bool,
        flags: &Flags,
        config: &UserConfig,
    ) -> Asks {
        let flags = Flags {
            parallel: flags.parallel.filter(|_| is_spec),
            ..flags.clone()
        };
        Asks::dispatched(issue, &flags, config)
    }

    /// What the Spec run or Run that an Architect run or a Pickup run
    /// dispatches `issue` as is asked: what [`Asks::of_run`] would ask a Run
    /// started on the Issue URL with `flags`, except that it sends no Run
    /// notification of its own. The run that dispatched it sends the one, as
    /// [`Flags::notification`] asks.
    fn dispatched(issue: &IssueUrl, flags: &Flags, config: &UserConfig) -> Asks {
        Asks {
            notification: NotificationAsk::Skip,
            ..Asks::of_run(issue, flags, config)
        }
    }
}

impl Flags {
    /// Whether any flag here is for the Spec run or Run that an Architect
    /// run or a Pickup run dispatches: every one but `email` and `no-email`,
    /// which ask that run for its own Run notification.
    pub fn any_for_dispatched_run(&self) -> bool {
        let for_dispatched_run = Flags {
            email: None,
            ..self.clone()
        };
        for_dispatched_run != Flags::default()
    }

    /// What a run with these flags is asked about its own Run notification:
    /// what `email` or `no-email` asked for, else what `config` says. It is
    /// a Run's ask, and an Architect run's or a Pickup run's for the one
    /// notification it sends itself.
    pub fn notification(&self, config: &UserConfig) -> NotificationAsk {
        self.email.clone().unwrap_or(if config.email.always {
            NotificationAsk::Send(None)
        } else {
            NotificationAsk::Skip
        })
    }
}

/// The command that starts the Run on `issue` again as `flags` asked for it,
/// with `base-fix` added.
fn retry_with_base_fix(issue: &IssueUrl, flags: &Flags) -> String {
    let mut command = format!("thirdshift {}", issue.url);
    match flags.goal {
        Some(Goal::Merged) => command += " merge",
        Some(Goal::ReadyForReview) => command += " --no-merge",
        None => {}
    }
    match &flags.email {
        Some(NotificationAsk::Send(Some(to))) => command += &format!(" --email {to}"),
        Some(NotificationAsk::Send(None)) => command += " --email",
        Some(NotificationAsk::Skip) => command += " --no-email",
        None => {}
    }
    if let Some(parallel) = flags.parallel {
        command += &format!(" parallel {parallel}");
    }
    command + " " + args::BASE_FIX
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::child_run::Kind;
    use crate::config::EmailSettings;

    const URL: &str = "https://github.com/acme/widgets/issues/7";

    fn issue() -> IssueUrl {
        IssueUrl::parse(URL).unwrap()
    }

    fn n(n: usize) -> NonZeroUsize {
        NonZeroUsize::new(n).unwrap()
    }

    fn to(address: &str) -> NotificationAsk {
        NotificationAsk::Send(Some(address.to_string()))
    }

    /// A User config that sets nothing: three Tickets at once is its own
    /// default.
    fn no_settings() -> UserConfig {
        UserConfig {
            merge_always: false,
            base_fix: false,
            launch_pull: false,
            logs_dir: PathBuf::from("/home/me/.thirdshift/logs"),
            quiet_skips: false,
            email: EmailSettings::default(),
            spec_parallel: n(3),
            pickup_limit: n(3),
        }
    }

    /// A User config that sets every default a Run can be asked by.
    fn every_setting() -> UserConfig {
        UserConfig {
            merge_always: true,
            base_fix: true,
            launch_pull: true,
            email: EmailSettings {
                always: true,
                to: Some("config@example.com".to_string()),
                from: None,
            },
            spec_parallel: n(5),
            ..no_settings()
        }
    }

    /// The command that starts the Run on [`URL`] again with a Base fix
    /// allowed, `flags` being its other flags as the command would spell
    /// them.
    fn undecided(flags: &str) -> BaseFixAsk {
        BaseFixAsk::Undecided {
            retry: format!("thirdshift {URL}{flags} base-fix"),
        }
    }

    #[test]
    fn a_run_with_neither_a_flag_nor_a_setting_does_only_what_a_run_does() {
        let asks = Asks::of_run(&issue(), &Flags::default(), &no_settings());

        assert_eq!(
            asks,
            Asks {
                goal: Goal::ReadyForReview,
                notification: NotificationAsk::Skip,
                tickets_at_once: n(3),
                parallel_asked: false,
                base_fix: undecided(""),
                launch_pull: false,
            }
        );
    }

    #[test]
    fn the_user_config_decides_each_ask_the_command_says_nothing_about() {
        let asks = Asks::of_run(&issue(), &Flags::default(), &every_setting());

        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                notification: NotificationAsk::Send(None),
                tickets_at_once: n(5),
                parallel_asked: false,
                base_fix: BaseFixAsk::Allow,
                launch_pull: true,
            }
        );
    }

    #[test]
    fn each_flag_decides_its_ask_whatever_the_user_config_says() {
        let against = Flags {
            goal: Some(Goal::ReadyForReview),
            email: Some(NotificationAsk::Skip),
            parallel: Some(n(2)),
            base_fix: Some(BaseFixAsk::Forbid),
        };
        let asks = Asks::of_run(&issue(), &against, &every_setting());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::ReadyForReview,
                notification: NotificationAsk::Skip,
                tickets_at_once: n(2),
                parallel_asked: true,
                base_fix: BaseFixAsk::Forbid,
                // No flag sets it.
                launch_pull: true,
            }
        );

        let for_it = Flags {
            goal: Some(Goal::Merged),
            email: Some(to("flag@example.com")),
            parallel: Some(n(2)),
            base_fix: Some(BaseFixAsk::Allow),
        };
        let asks = Asks::of_run(&issue(), &for_it, &no_settings());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                notification: to("flag@example.com"),
                tickets_at_once: n(2),
                parallel_asked: true,
                base_fix: BaseFixAsk::Allow,
                launch_pull: false,
            }
        );
    }

    /// What a child Run of `kind` is given, asked `base_fix` about a Base fix.
    fn given(kind: Kind, base_fix: BaseFixAsk) -> Given {
        Given {
            kind,
            stamp: "20261003T120000-0400".to_string(),
            base_fix,
        }
    }

    fn ticket() -> Kind {
        Kind::Ticket {
            spec_branch: "issue-20".to_string(),
        }
    }

    fn base_fix() -> Kind {
        Kind::BaseFix {
            base: "main".to_string(),
        }
    }

    #[test]
    fn a_child_run_is_a_merge_run_that_sends_nothing_pulls_nothing_and_starts_no_base_fix() {
        for child in [ticket(), base_fix()] {
            for config in [no_settings(), every_setting()] {
                let given = given(child.clone(), BaseFixAsk::Forbid);

                let asks = Asks::of_child_run(&given, &config);

                assert_eq!(asks.goal, Goal::Merged, "{child:?}");
                assert_eq!(asks.notification, NotificationAsk::Skip, "{child:?}");
                assert!(!asks.launch_pull, "{child:?}");
                assert!(!asks.parallel_asked, "{child:?}");
                assert_eq!(asks.base_fix, BaseFixAsk::Forbid, "{child:?}");
            }
        }
    }

    #[test]
    fn a_child_run_asks_about_a_base_fix_what_it_was_given_whatever_the_user_config_says() {
        let offer = BaseFixAsk::Undecided {
            retry: format!("thirdshift {URL} base-fix"),
        };
        for asked in [BaseFixAsk::Allow, offer] {
            for config in [no_settings(), every_setting()] {
                let asks = Asks::of_child_run(&given(ticket(), asked.clone()), &config);

                assert_eq!(asks.base_fix, asked);
            }
        }
    }

    /// Every flag an Architect run or a Pickup run takes for the run it
    /// dispatches, with `email` for its own Run notification.
    fn dispatch_flags() -> Flags {
        Flags {
            goal: Some(Goal::Merged),
            email: Some(to("flag@example.com")),
            parallel: Some(n(2)),
            base_fix: None,
        }
    }

    #[test]
    fn a_dispatched_architect_plan_sends_no_notification_whoever_decides_its_asks() {
        let asks = Asks::of_architect_plan(&issue(), &dispatch_flags(), &no_settings());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                notification: NotificationAsk::Skip,
                tickets_at_once: n(2),
                parallel_asked: true,
                base_fix: undecided(" merge --email flag@example.com parallel 2"),
                launch_pull: false,
            }
        );

        let asks = Asks::of_architect_plan(&issue(), &Flags::default(), &every_setting());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                // Whatever `email.always` says: the Architect run sends it.
                notification: NotificationAsk::Skip,
                tickets_at_once: n(5),
                parallel_asked: false,
                base_fix: BaseFixAsk::Allow,
                launch_pull: true,
            }
        );
    }

    #[test]
    fn a_dispatched_ready_issue_that_is_a_spec_sends_no_notification_whoever_decides_its_asks() {
        let asks = Asks::of_ready_issue(&issue(), true, &dispatch_flags(), &no_settings());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                notification: NotificationAsk::Skip,
                tickets_at_once: n(2),
                parallel_asked: true,
                base_fix: undecided(" merge --email flag@example.com parallel 2"),
                launch_pull: false,
            }
        );

        let asks = Asks::of_ready_issue(&issue(), true, &Flags::default(), &every_setting());
        assert_eq!(
            asks,
            Asks {
                goal: Goal::Merged,
                // Whatever `email.always` says: the Pickup run sends it.
                notification: NotificationAsk::Skip,
                tickets_at_once: n(5),
                parallel_asked: false,
                base_fix: BaseFixAsk::Allow,
                launch_pull: true,
            }
        );
    }

    #[test]
    fn only_the_email_flags_are_not_for_a_dispatched_run() {
        let email_only = Flags {
            email: Some(to("flag@example.com")),
            ..Flags::default()
        };
        assert!(!Flags::default().any_for_dispatched_run());
        assert!(!email_only.any_for_dispatched_run());
        for flags in [
            Flags {
                goal: Some(Goal::ReadyForReview),
                ..email_only.clone()
            },
            Flags {
                parallel: Some(n(1)),
                ..Flags::default()
            },
            Flags {
                base_fix: Some(BaseFixAsk::Forbid),
                ..Flags::default()
            },
        ] {
            assert!(flags.any_for_dispatched_run(), "{flags:?}");
        }
    }

    #[test]
    fn parallel_is_ignored_for_a_dispatched_ready_issue_that_is_not_a_spec() {
        let asks = Asks::of_ready_issue(&issue(), false, &dispatch_flags(), &every_setting());

        assert!(!asks.parallel_asked);
        assert_eq!(asks.tickets_at_once, n(5));

        // Nor is it in the command that retries the issue, which would fail
        // a Run on an issue that is not a Spec.
        let asks = Asks::of_ready_issue(&issue(), false, &dispatch_flags(), &no_settings());
        assert_eq!(asks.base_fix, undecided(" merge --email flag@example.com"));
        let asks = Asks::of_ready_issue(&issue(), true, &dispatch_flags(), &no_settings());
        assert_eq!(
            asks.base_fix,
            undecided(" merge --email flag@example.com parallel 2")
        );
    }

    /// The Run the command `retry` starts, read by the argument parser.
    fn parsed(retry: &str) -> args::RunArgs {
        let words: Vec<String> = retry.split(' ').skip(1).map(str::to_string).collect();
        match args::parse(&words) {
            Ok(args::Command::Run(run)) => run,
            Ok(_) => panic!("{retry}: not a Run"),
            Err(error) => panic!("{retry}: {error:#}"),
        }
    }

    /// The command `asks` offer a Base fix with.
    fn retry_of(asks: Asks) -> String {
        match asks.base_fix {
            BaseFixAsk::Undecided { retry } => retry,
            decided => panic!("no command to offer: {decided:?}"),
        }
    }

    #[test]
    fn the_retry_command_is_the_issue_url_and_the_flags_as_given_with_base_fix_added() {
        let flags = |goal, email, parallel| Flags {
            goal,
            email,
            parallel,
            base_fix: None,
        };
        for (flags, retry) in [
            (Flags::default(), format!("thirdshift {URL} base-fix")),
            (
                flags(Some(Goal::Merged), Some(NotificationAsk::Send(None)), None),
                format!("thirdshift {URL} merge --email base-fix"),
            ),
            (
                flags(
                    Some(Goal::ReadyForReview),
                    Some(NotificationAsk::Skip),
                    Some(n(2)),
                ),
                format!("thirdshift {URL} --no-merge --no-email parallel 2 base-fix"),
            ),
            (
                flags(None, Some(to("me@example.com")), None),
                format!("thirdshift {URL} --email me@example.com base-fix"),
            ),
        ] {
            let config = no_settings();
            let allowed = Flags {
                base_fix: Some(BaseFixAsk::Allow),
                ..flags.clone()
            };
            // Each kind of run offers the same command: a Run on the Issue
            // URL, whatever dispatched it.
            for (kind, asks) in [
                ("a Run", Asks::of_run(&issue(), &flags, &config)),
                (
                    "an Architect plan",
                    Asks::of_architect_plan(&issue(), &flags, &config),
                ),
                (
                    "a Ready issue that is a Spec",
                    Asks::of_ready_issue(&issue(), true, &flags, &config),
                ),
            ] {
                let offered = retry_of(asks);
                assert_eq!(offered, retry, "{kind}");
                // The command it gives asks for what the run was asked for.
                let again = parsed(&offered);
                assert_eq!(again.issue.url, URL, "{kind}: {offered}");
                assert_eq!(again.flags, allowed, "{kind}: {offered}");
                assert_eq!(again.given, None, "{kind}: {offered}");
            }
            // Without the `parallel` that would fail its Run by hand.
            let offered = retry_of(Asks::of_ready_issue(&issue(), false, &flags, &config));
            let again = parsed(&offered);
            let without_parallel = Flags {
                parallel: None,
                ..allowed
            };
            assert_eq!(again.flags, without_parallel, "{offered}");
        }
    }

    #[test]
    fn an_architect_run_or_a_pickup_run_is_asked_for_its_own_notification_as_a_run_is() {
        for (email, config, asked) in [
            (None, no_settings(), NotificationAsk::Skip),
            (None, every_setting(), NotificationAsk::Send(None)),
            (
                Some(NotificationAsk::Skip),
                every_setting(),
                NotificationAsk::Skip,
            ),
            (
                Some(NotificationAsk::Send(None)),
                no_settings(),
                NotificationAsk::Send(None),
            ),
            (
                Some(to("flag@example.com")),
                every_setting(),
                to("flag@example.com"),
            ),
        ] {
            let flags = Flags {
                email,
                ..dispatch_flags()
            };

            assert_eq!(flags.notification(&config), asked, "{flags:?}");
        }
    }

    #[test]
    fn an_address_after_the_email_flag_wins_over_email_always() {
        let flags = Flags {
            email: Some(to("flag@example.com")),
            ..Flags::default()
        };

        let asks = Asks::of_run(&issue(), &flags, &every_setting());

        assert_eq!(asks.notification, to("flag@example.com"));
    }

    #[test]
    fn email_to_alone_asks_for_no_notification() {
        let mut config = no_settings();
        config.email.to = Some("config@example.com".to_string());

        let asks = Asks::of_run(&issue(), &Flags::default(), &config);

        assert_eq!(asks.notification, NotificationAsk::Skip);
    }
}