thirdshift 0.8.3

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
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The User config: `~/.thirdshift/config.toml`, this machine's defaults for
//! every Run. Only a Run, `email-test` and `setup` read it, so a broken one
//! can't block `update`, `version` or `help`, and only a Run offers Setup
//! when there is none.

use std::io::Write;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use toml::{Table, Value};
use toml_edit::{DocumentMut, Item};

use crate::git::Git;
use crate::questions::{self, Answers};
use crate::resend_key::Credentials;
use crate::{email, github, progress};

/// The settings a User config can hold. Each is what a Run does when its
/// command says nothing about it.
#[derive(Debug, PartialEq, Eq)]
pub struct UserConfig {
    /// `merge.always`: every Run is a Merge run unless told `no-merge`.
    pub merge_always: bool,
    /// `base.fix`: every Run may start a Base fix unless told `no-base-fix`.
    pub base_fix: bool,
    /// `launch.pull`: every Run fast-forwards the Launch directory's
    /// checkout of the Base branch to `origin`.
    pub launch_pull: bool,
    /// `logs.dir`, with a leading `~` expanded: the root of the logs, with
    /// each repository's in `<owner>/<repo>/`, by default
    /// `~/.thirdshift/logs`.
    pub logs_dir: PathBuf,
    /// `activity.quiet_skips`: a skipped Architect run or Pickup run prints
    /// nothing, its Activity log line its only trace.
    pub quiet_skips: bool,
    /// The `[email]` section.
    pub email: EmailSettings,
    /// `spec.parallel`: how many Tickets a Spec run runs at once, by
    /// default 3.
    pub spec_parallel: NonZeroUsize,
    /// `pickup.limit`: the Claim limit, how many open issues carrying a
    /// Claim stop a Pickup run from taking another, by default 3.
    pub pickup_limit: NonZeroUsize,
}

/// The `[email]` section: where email goes and who it comes from. The Resend
/// API key is never here, only in `RESEND_API_KEY` or the Credentials, so the
/// file holds no secret.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct EmailSettings {
    /// `email.always`: every Run, and every Architect run, sends a Run
    /// notification unless told `no-email`.
    pub always: bool,
    /// `email.to`: the address email goes to when the command names none.
    pub to: Option<String>,
    /// `email.from`: the sender, in place of Resend's shared test sender.
    pub from: Option<String>,
}

impl UserConfig {
    /// The User config under `$HOME`, or the defaults if there is none.
    pub fn load() -> Result<Self> {
        let (home, path) = home_and_path()?;
        match std::fs::read_to_string(&path) {
            Ok(text) => UserConfig::parse(&text, &path, &home),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                Ok(UserConfig::defaults(&home))
            }
            Err(error) => Err(error).with_context(|| format!("can't read {}", path.display())),
        }
    }

    /// What a Run does with no User config under `home`.
    fn defaults(home: &Path) -> Self {
        UserConfig {
            merge_always: false,
            base_fix: false,
            launch_pull: false,
            logs_dir: home.join(".thirdshift/logs"),
            quiet_skips: false,
            email: EmailSettings::default(),
            spec_parallel: NonZeroUsize::new(3).unwrap(),
            pickup_limit: NonZeroUsize::new(3).unwrap(),
        }
    }

    /// Parse `text`, the contents of the User config at `path`, expanding a
    /// leading `~` to `home`. Any key or section thirdshift doesn't know is an
    /// error, so a typo can't silently leave a setting unset.
    fn parse(text: &str, path: &Path, home: &Path) -> Result<Self> {
        let file = format!("the User config {}", path.display());
        let table: Table = text
            .parse()
            .map_err(|error| anyhow!("{error}"))
            .with_context(|| format!("can't parse {file}"))?;
        let mut config = UserConfig::defaults(home);
        for (section, value) in &table {
            let known = matches!(
                section.as_str(),
                "merge" | "base" | "launch" | "logs" | "activity" | "email" | "spec" | "pickup"
            );
            let settings = match value {
                Value::Table(settings) if known => settings,
                Value::Table(_) => bail!("unknown section [{section}] in {file}"),
                _ if known => bail!("{section} must be the section [{section}] in {file}"),
                _ => bail!("unknown key {section} in {file}"),
            };
            for (key, value) in settings {
                match (section.as_str(), key.as_str(), value) {
                    ("merge", "always", Value::Boolean(always)) => config.merge_always = *always,
                    ("merge", "always", _) => bail!("merge.always must be true or false in {file}"),
                    ("base", "fix", Value::Boolean(fix)) => config.base_fix = *fix,
                    ("base", "fix", _) => bail!("base.fix must be true or false in {file}"),
                    ("launch", "pull", Value::Boolean(pull)) => config.launch_pull = *pull,
                    ("launch", "pull", _) => bail!("launch.pull must be true or false in {file}"),
                    ("logs", "dir", Value::String(dir)) => match expand_home(dir, home) {
                        Some(dir) => config.logs_dir = dir,
                        None => bail!(
                            "logs.dir must be an absolute path, ~ or start with ~/, not {dir:?}, in {file}"
                        ),
                    },
                    ("logs", "dir", _) => bail!("logs.dir must be a string in {file}"),
                    ("activity", "quiet_skips", Value::Boolean(quiet)) => {
                        config.quiet_skips = *quiet
                    }
                    ("activity", "quiet_skips", _) => {
                        bail!("activity.quiet_skips must be true or false in {file}")
                    }
                    ("email", "always", Value::Boolean(always)) => config.email.always = *always,
                    ("email", "always", _) => bail!("email.always must be true or false in {file}"),
                    ("email", "to", Value::String(to)) => config.email.to = Some(to.clone()),
                    ("email", "from", Value::String(from)) => {
                        config.email.from = Some(from.clone())
                    }
                    ("email", "to" | "from", _) => {
                        bail!("{section}.{key} must be a quoted email address in {file}")
                    }
                    ("spec", "parallel", value) => {
                        config.spec_parallel = whole_number_from_1(value, "spec.parallel", &file)?
                    }
                    ("pickup", "limit", value) => {
                        config.pickup_limit = whole_number_from_1(value, "pickup.limit", &file)?
                    }
                    _ => bail!("unknown key {section}.{key} in {file}"),
                }
            }
        }
        Ok(config)
    }
}

/// Setup: write the User config. From a terminal, the Setup questions come
/// first, each with the current value as its default answer, and the answers
/// are written, with `base.fix`, asked about only when every Run is a Merge
/// run, otherwise at its default; with no terminal, nothing is asked, and every setting is at
/// its default, with `email.to` as the suggested address, if there is one.
/// An existing User config is edited in place, once it parses as a Run would
/// parse it: its comments and key order stay, as do the values Setup didn't
/// ask about, and each key it lacks is added at its default, so Setup with no
/// terminal never resets a configured machine. A Resend API key the user
/// gave is saved in the Credentials once the User config is written; with no
/// terminal, the Credentials are never read or written. Nothing is written
/// until the last answer is in. A test email, if the user asked for one, goes
/// once the files are written, as `email-test` sends it.
pub fn setup() -> Result<String> {
    let (home, path) = home_and_path()?;
    let existing = match std::fs::read_to_string(&path) {
        Ok(text) => Some(text),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => {
            return Err(error).with_context(|| format!("can't read {}", path.display()));
        }
    };
    let mut text = match &existing {
        Some(text) => {
            UserConfig::parse(text, &path, &home)?;
            complete(text)?
        }
        None => with_email_to(suggested_address(&home)),
    };
    let mut answered = None;
    if questions::has_terminal() {
        let answers;
        (text, answers) = ask(&text, &path, &home)?;
        answered = Some(answers);
    }
    let asked = answered.is_some();
    let mut written = match &existing {
        None => {
            write_new(&home, &path, &text)?;
            format!("wrote the User config {}", path.display())
        }
        Some(existing) if *existing == text && asked => {
            format!(
                "the User config {} already holds your answers",
                path.display()
            )
        }
        Some(existing) if *existing == text => format!(
            "the User config {} already lists every setting",
            path.display()
        ),
        Some(_) => {
            replace(&path, &text).with_context(|| format!("can't write {}", path.display()))?;
            if asked {
                format!("wrote your answers to the User config {}", path.display())
            } else {
                format!(
                    "added the missing settings to the User config {}",
                    path.display()
                )
            }
        }
    };
    let Some(asked) = &answered else {
        return Ok(written);
    };
    if let Some(key) = asked.answers.key() {
        progress::step(written);
        asked.credentials.save(key)?;
        written = format!("wrote {}", asked.credentials);
    }
    if !asked.answers.send_test() {
        return Ok(written);
    }
    progress::step(written);
    let config = UserConfig::load()?;
    Ok(email::send_test(None, &config.email)?.to_string())
}

/// The first Run's offer of Setup, made only from a terminal and only when
/// there is no User config. Yes asks the Setup questions and writes the
/// answers, and the Resend API key to the Credentials if the user gave one;
/// no writes every setting at its default, as `setup` with no terminal does,
/// and leaves the Credentials alone. Either way the Run then loads what was
/// written. A User config or Credentials that can't be written, or a test
/// email that can't go, is a warning, so the Run carries on; Credentials a
/// Run would refuse, or stdin closing before the last answer, end the command
/// before any work, with nothing written.
pub fn offer_setup() -> Result<()> {
    if !questions::has_terminal() {
        return Ok(());
    }
    let (home, path) = home_and_path()?;
    match std::fs::symlink_metadata(&path) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        _ => return Ok(()),
    }
    let accepted = questions::offer(&path)?;
    let mut text = with_email_to(suggested_address(&home));
    let mut answered = None;
    if accepted {
        let answers;
        (text, answers) = ask(&text, &path, &home)?;
        answered = Some(answers);
    }
    if let Err(error) = write_new(&home, &path, &text) {
        progress::step(format_args!(
            "warning: {error:#}; carrying on with the defaults"
        ));
        return Ok(());
    }
    let Some(asked) = &answered else {
        progress::step(format_args!(
            "wrote the User config {} with every setting at its default; \
             thirdshift setup changes it",
            path.display()
        ));
        return Ok(());
    };
    progress::step(format_args!("wrote the User config {}", path.display()));
    if let Some(key) = asked.answers.key() {
        match asked.credentials.save(key) {
            Ok(()) => progress::step(format_args!("wrote {}", asked.credentials)),
            Err(error) => progress::step(format_args!("warning: {error:#}")),
        }
    }
    if asked.answers.send_test() {
        let sent = UserConfig::load().and_then(|config| email::send_test(None, &config.email));
        match sent {
            Ok(sent) => progress::step(sent),
            Err(error) => progress::step(format_args!("warning: {error:#}")),
        }
    }
    Ok(())
}

/// The Setup answers, and the Credentials read before asking, where a key
/// the user gave is saved.
struct Asked {
    answers: Answers,
    credentials: Credentials,
}

/// Ask the Setup questions, with the settings in `text`, the User config at
/// `path`, and the key in the Credentials as the default answers. Credentials
/// a Run would refuse are refused before any question. Returns `text` with
/// the answers, and what was asked.
fn ask(text: &str, path: &Path, home: &Path) -> Result<(String, Asked)> {
    let current = UserConfig::parse(text, path, home)?;
    let credentials = Credentials::read()?;
    let answers = questions::ask(&current, &credentials, || suggested_address(home))?;
    let text = with_answers(text, &answers)?;
    Ok((
        text,
        Asked {
            answers,
            credentials,
        },
    ))
}

/// Write `text` as the User config at `path`, where there is none yet,
/// creating `~/.thirdshift` under `home` if it is missing.
fn write_new(home: &Path, path: &Path, text: &str) -> Result<()> {
    std::fs::create_dir_all(home.join(".thirdshift"))
        .and_then(|()| std::fs::write(path, text))
        .with_context(|| format!("can't write {}", path.display()))
}

/// `text`, a User config with every key, or a commented-out `email.to`, with
/// the values `answers` gives. Only those values change: the spacing and
/// comments around each stay, as does everything else in `text`.
fn with_answers(text: &str, answers: &Answers) -> Result<String> {
    let mut document: DocumentMut = text.parse().context("can't parse the User config")?;
    set(&mut document, "merge", "always", answers.merge_always);
    set(&mut document, "base", "fix", answers.base_fix);
    set(&mut document, "launch", "pull", answers.launch_pull);
    set(
        &mut document,
        "email",
        "always",
        answers.notifications.is_some(),
    );
    if let Some(notifications) = &answers.notifications {
        set(&mut document, "email", "from", notifications.from.as_str());
        set_email_to(&mut document, &notifications.to);
    }
    Ok(document.to_string())
}

/// Set `section.key`, which `document` holds, to `value`, keeping the
/// spacing and comment around the old value, and the comment in the same
/// column where the spaces before it allow. An equal value is left as it was
/// written.
fn set(document: &mut DocumentMut, section: &str, key: &str, value: impl Into<toml_edit::Value>) {
    let value = value.into();
    let old = document[section]
        .as_table_like_mut()
        .and_then(|settings| settings.get_mut(key))
        .and_then(Item::as_value_mut)
        .unwrap_or_else(|| panic!("a completed User config has {section}.{key}"));
    let same = match (old.as_bool(), old.as_str()) {
        (Some(old), _) => value.as_bool() == Some(old),
        (_, Some(old)) => value.as_str() == Some(old),
        _ => false,
    };
    if same {
        return;
    }
    let mut decor = old.decor().clone();
    let suffix = decor_suffix(&decor);
    let spaces = suffix.len() - suffix.trim_start_matches(' ').len();
    if spaces > 0 && suffix[spaces..].starts_with('#') {
        let width = |value: &toml_edit::Value| value.clone().decorated("", "").to_string().len();
        let spaces = (spaces + width(old)).saturating_sub(width(&value)).max(1);
        decor.set_suffix(format!(
            "{}{}",
            " ".repeat(spaces),
            suffix.trim_start_matches(' ')
        ));
    }
    *old = value;
    *old.decor_mut() = decor;
}

/// Set `email.to` in `document` to `to`. With no `email.to` there yet, it
/// takes the place of the commented-out one, if there is one, written as
/// `DEFAULTS` would write it, with its comment.
fn set_email_to(document: &mut DocumentMut, to: &str) {
    let email = &mut document["email"];
    let has_to = email
        .as_table_like()
        .is_some_and(|settings| settings.contains_key("to"));
    if has_to {
        set(document, "email", "to", to);
        return;
    }
    let Some(email) = email.as_table_mut().filter(|email| !email.is_dotted()) else {
        let settings = email.as_table_like_mut().expect("[email] is a section");
        settings.insert("to", Item::Value(to.into()));
        return;
    };
    let example: DocumentMut = with_email_to(Some(to.to_string()))
        .parse()
        .expect("DEFAULTS is valid TOML");
    let (key, item) = example["email"]
        .as_table()
        .and_then(|example| example.get_key_value("to"))
        .expect("the example sets email.to");
    let mut key = key.clone();
    key.leaf_decor_mut().set_prefix("");
    let keys: Vec<String> = email.iter().map(|(key, _)| key.to_string()).collect();
    let mut place = keys.len();
    for (at, name) in keys.iter().enumerate() {
        let mut next = email.key_mut(name).expect("the key is in [email]");
        let prefix = decor_prefix(next.leaf_decor());
        let mut end = 0;
        let found = prefix.split_inclusive('\n').find_map(|line| {
            let start = end;
            end += line.len();
            is_commented_out_email_to(line).then_some((start, end))
        });
        let Some((start, end)) = found else {
            continue;
        };
        next.leaf_decor_mut().set_prefix(&prefix[end..]);
        key.leaf_decor_mut().set_prefix(&prefix[..start]);
        place = at;
        break;
    }
    email.insert_formatted(&key, item.clone());
    // Each key keeps its place, and `to` goes just before the key at `place`,
    // or last: odd ranks for the keys that were there, an even one for `to`.
    let rank = |name: &str| match keys.iter().position(|key| key == name) {
        Some(at) => 2 * at + 1,
        None => 2 * place,
    };
    email.sort_values_by(|a, _, b, _| rank(a.get()).cmp(&rank(b.get())));
}

/// Replace the file at `path` with `text` all at once, keeping its
/// permissions, so a failed write leaves it as it was.
pub fn replace(path: &Path, text: &str) -> std::io::Result<()> {
    let permissions = std::fs::metadata(path)?.permissions();
    let dir = path.parent().unwrap_or(Path::new("."));
    let mut file = tempfile::NamedTempFile::new_in(dir)?;
    file.write_all(text.as_bytes())?;
    file.as_file().set_permissions(permissions)?;
    file.persist(path)?;
    Ok(())
}

/// `text`, a User config a Run accepts, with each key it lacks added at its
/// default, as `DEFAULTS` writes it. Everything already in `text` stays as
/// it was: a missing key goes at the end of its section, and a missing
/// section after the last line of `text`. A key added to an inline table
/// gets no comment, as TOML has no place for one there.
fn complete(text: &str) -> Result<String> {
    let mut document: DocumentMut = text.parse().context("can't parse the User config")?;
    let defaults: DocumentMut = DEFAULTS.parse().expect("DEFAULTS is valid TOML");
    let mut missing = DocumentMut::new();
    for (section, default_settings) in defaults.iter() {
        let default_settings = default_settings
            .as_table()
            .expect("every key in DEFAULTS is in a section");
        match document.get_mut(section) {
            None => {
                missing.insert(section, Item::Table(default_settings.clone()));
            }
            Some(Item::Table(settings)) => {
                for (key, item) in default_settings.iter() {
                    if !settings.contains_key(key) {
                        let mut key = default_settings
                            .key(key)
                            .expect("the key is in DEFAULTS")
                            .clone();
                        key.leaf_decor_mut().set_prefix("");
                        settings.insert_formatted(&key, item.clone());
                    }
                }
                if section == "email" && !settings.is_dotted() {
                    note_email_to(settings, default_settings, text);
                }
            }
            Some(Item::Value(toml_edit::Value::InlineTable(settings))) => {
                for (key, item) in default_settings.iter() {
                    if !settings.contains_key(key) {
                        let mut value = item.as_value().expect("DEFAULTS has only values").clone();
                        value.decor_mut().clear();
                        settings.insert(key, value);
                    }
                }
            }
            Some(_) => unreachable!("a Run refuses {section} that isn't a section"),
        }
    }
    let mut completed = document.to_string();
    let missing = missing.to_string();
    let missing = missing.trim_start_matches('\n');
    if !missing.is_empty() && !completed.trim().is_empty() {
        if !completed.ends_with('\n') {
            completed.push('\n');
        }
        completed.push('\n');
    }
    completed.push_str(missing);
    Ok(completed)
}

/// With no `email.to` in `email`, the `[email]` section of `text`, and no
/// commented-out one either, add the commented-out example line from
/// `defaults`, the `[email]` section of `DEFAULTS`, just before `email.from`:
/// `email.to` has no default to write.
fn note_email_to(email: &mut toml_edit::Table, defaults: &toml_edit::Table, text: &str) {
    if email.contains_key("to") || has_commented_out_email_to(text) {
        return;
    }
    let example = decor_prefix(
        defaults
            .key("from")
            .expect("DEFAULTS has email.from")
            .leaf_decor(),
    );
    let Some(mut from) = email.key_mut("from") else {
        return;
    };
    let decor = from.leaf_decor_mut();
    decor.set_prefix(format!("{example}{}", decor_prefix(decor)));
}

/// The text `decor` puts before a key: the comment and blank lines above it,
/// and its indent.
fn decor_prefix(decor: &toml_edit::Decor) -> String {
    decor
        .prefix()
        .and_then(|prefix| prefix.as_str())
        .unwrap_or("")
        .to_string()
}

/// The text `decor` puts after a value: the spaces and comment that end its
/// line.
fn decor_suffix(decor: &toml_edit::Decor) -> String {
    decor
        .suffix()
        .and_then(|suffix| suffix.as_str())
        .unwrap_or("")
        .to_string()
}

/// Whether the `[email]` section of `text` holds a commented-out `to` line.
fn has_commented_out_email_to(text: &str) -> bool {
    let mut in_email = false;
    for line in text.lines().map(str::trim) {
        if let Some(header) = line.strip_prefix('[') {
            let header = header.split('#').next().unwrap_or("").trim_end();
            in_email = header.strip_suffix(']').map(str::trim) == Some("email");
        } else if in_email && is_commented_out_email_to(line) {
            return true;
        }
    }
    false
}

/// Whether `line`, in the `[email]` section, is a commented-out `to` line.
fn is_commented_out_email_to(line: &str) -> bool {
    line.trim()
        .strip_prefix('#')
        .and_then(|comment| comment.trim_start().strip_prefix("to"))
        .is_some_and(|rest| rest.trim_start().starts_with('='))
}

/// The User config Setup writes with no answers: every key at its default,
/// each with what it does and that default. `email.to` has no default, so it
/// is the one key written commented out.
const DEFAULTS: &str = r#"[merge]
always = false   # every Run is a Merge run, without the merge word; default false

[base]
fix = false      # every Run may start a Base fix, without the base-fix word; default false

[launch]
pull = false     # every Run first fast-forwards your checkout of the Base branch; default false

[email]
always = false                  # every Run sends a Run notification, without the email word; default false
# to = "you@example.com"        # where email goes when the command names no address; no default
from = "onboarding@resend.dev"  # the sender; default onboarding@resend.dev, which only delivers to your Resend account's address

[logs]
dir = "~/.thirdshift/logs"   # the root of the logs, each repository's in <owner>/<repo>/; default ~/.thirdshift/logs

[activity]
quiet_skips = false   # a skipped Architect run or Pickup run prints nothing, leaving only its Activity log line; default false

[spec]
parallel = 3   # how many Tickets a Spec run runs at once; default 3

[pickup]
limit = 3   # how many open issues labelled in-progress stop a Pickup run taking another; default 3
"#;

/// The line `DEFAULTS` holds for `email.to`, which has no default.
const NO_EMAIL_TO: &str = r#"# to = "you@example.com"        # where email goes when the command names no address; no default"#;

/// `DEFAULTS` with `email.to` set to `to`, if there is one.
fn with_email_to(to: Option<String>) -> String {
    let Some(to) = to else {
        return DEFAULTS.to_string();
    };
    let (_, comment) = NO_EMAIL_TO.split_once("  # ").unwrap();
    let line = format!("to = {}", Value::String(to));
    DEFAULTS.replace(NO_EMAIL_TO, &format!("{line:<31} # {comment}"))
}

/// The address Setup suggests for `email.to`: the public email of the user's
/// GitHub profile, else the global git `user.email`, unless that is a
/// `@users.noreply.github.com` address, which can't receive mail. Only Setup
/// looks it up; a Run never falls back to it.
fn suggested_address(home: &Path) -> Option<String> {
    let github = github::profile_email().ok().flatten();
    github.filter(|email| !email.is_empty()).or_else(|| {
        let git = Git::new(home).run(&["config", "--global", "user.email"]);
        git.ok().filter(|email| {
            !email.is_empty()
                && !email
                    .to_ascii_lowercase()
                    .ends_with("@users.noreply.github.com")
        })
    })
}

/// `value`, which `file` gives the setting `key`, as a whole number from 1
/// up, or an error naming both if it is anything else.
fn whole_number_from_1(value: &Value, key: &str, file: &str) -> Result<NonZeroUsize> {
    value
        .as_integer()
        .and_then(|n| usize::try_from(n).ok())
        .and_then(NonZeroUsize::new)
        .with_context(|| format!("{key} must be a whole number from 1 up in {file}"))
}

/// `$HOME`, and the User config's path under it.
fn home_and_path() -> Result<(PathBuf, PathBuf)> {
    let home = home()?;
    let path = home.join(".thirdshift/config.toml");
    Ok((home, path))
}

/// The user's home folder, `$HOME`, where `~/.thirdshift` is.
pub fn home() -> Result<PathBuf> {
    std::env::var_os("HOME")
        .filter(|home| !home.is_empty())
        .map(PathBuf::from)
        .context("HOME is not set")
}

/// `path` as an absolute path, with a leading `~` expanded to `home`, or
/// `None` if it is relative: the directory a Run is launched from is no base
/// for a setting that holds for every Run.
fn expand_home(path: &str, home: &Path) -> Option<PathBuf> {
    let path = match path.strip_prefix('~') {
        Some("") => home.to_path_buf(),
        Some(rest) => home.join(rest.strip_prefix('/')?),
        None => PathBuf::from(path),
    };
    path.is_absolute().then_some(path)
}

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

    fn parse(text: &str) -> Result<UserConfig> {
        UserConfig::parse(
            text,
            Path::new("/home/me/.thirdshift/config.toml"),
            Path::new("/home/me"),
        )
    }

    #[test]
    fn the_defaults_setup_writes_are_what_a_run_does_with_no_user_config() {
        let mut config = parse(DEFAULTS).unwrap();
        assert_eq!(
            config.email.from.as_deref(),
            Some(crate::email::DEFAULT_FROM)
        );
        config.email.from = None;
        assert_eq!(config, UserConfig::defaults(Path::new("/home/me")));
    }

    #[test]
    fn a_suggested_address_sets_email_to_in_place_of_the_commented_out_line() {
        assert!(DEFAULTS.contains(&format!("\n{NO_EMAIL_TO}\n")));
        assert_eq!(with_email_to(None), DEFAULTS);
        let text = with_email_to(Some("o\"brien@example.com".to_string()));
        let config = parse(&text).unwrap();
        assert_eq!(config.email.to.as_deref(), Some("o\"brien@example.com"));
        let line = text.lines().find(|line| line.starts_with("to = ")).unwrap();
        let from = text
            .lines()
            .find(|line| line.starts_with("from = "))
            .unwrap();
        assert_eq!(
            line.find(" # "),
            from.find("  # ").map(|at| at + 1),
            "{text}"
        );
    }

    #[test]
    fn merge_always_is_read() {
        assert!(parse("[merge]\nalways = true\n").unwrap().merge_always);
        assert!(!parse("[merge]\nalways = false\n").unwrap().merge_always);
        assert!(!parse("").unwrap().merge_always);
    }

    #[test]
    fn base_fix_is_read() {
        assert!(parse("[base]\nfix = true\n").unwrap().base_fix);
        assert!(!parse("[base]\nfix = false\n").unwrap().base_fix);
        assert!(!parse("").unwrap().base_fix);
    }

    #[test]
    fn launch_pull_is_read() {
        assert!(parse("[launch]\npull = true\n").unwrap().launch_pull);
        assert!(!parse("[launch]\npull = false\n").unwrap().launch_pull);
        assert!(!parse("").unwrap().launch_pull);
    }

    #[test]
    fn spec_parallel_is_read_and_defaults_to_3() {
        let config = parse("[spec]\nparallel = 5\n").unwrap();
        assert_eq!(config.spec_parallel.get(), 5);
        for text in ["", "[spec]\n"] {
            assert_eq!(parse(text).unwrap().spec_parallel.get(), 3, "{text:?}");
        }
    }

    #[test]
    fn pickup_limit_is_read_and_defaults_to_3() {
        let config = parse("[pickup]\nlimit = 1\n").unwrap();
        assert_eq!(config.pickup_limit.get(), 1);
        for text in ["", "[pickup]\n"] {
            assert_eq!(parse(text).unwrap().pickup_limit.get(), 3, "{text:?}");
        }
    }

    #[test]
    fn email_settings_are_read() {
        let config = parse("[email]\nto = \"me@example.com\"\nfrom = \"ts@acme.dev\"\n").unwrap();
        assert_eq!(config.email.to.as_deref(), Some("me@example.com"));
        assert_eq!(config.email.from.as_deref(), Some("ts@acme.dev"));
        assert_eq!(parse("[email]\n").unwrap().email, EmailSettings::default());
        assert!(parse("[email]\nalways = true\n").unwrap().email.always);
        assert!(!parse("[email]\nalways = false\n").unwrap().email.always);
    }

    #[test]
    fn activity_quiet_skips_is_read_and_defaults_to_false() {
        assert!(
            parse("[activity]\nquiet_skips = true\n")
                .unwrap()
                .quiet_skips
        );
        for text in ["", "[activity]\n", "[activity]\nquiet_skips = false\n"] {
            assert!(!parse(text).unwrap().quiet_skips, "{text:?}");
        }
    }

    #[test]
    fn logs_dir_is_read_with_a_leading_tilde_expanded_and_defaults_under_home() {
        for (dir, expanded) in [
            ("~/elsewhere/logs", "/home/me/elsewhere/logs"),
            ("~", "/home/me"),
            ("/var/log/thirdshift", "/var/log/thirdshift"),
        ] {
            let config = parse(&format!("[logs]\ndir = {dir:?}\n")).unwrap();
            assert_eq!(config.logs_dir, PathBuf::from(expanded), "{dir}");
        }
        for text in ["", "[logs]\n"] {
            assert_eq!(
                parse(text).unwrap().logs_dir,
                PathBuf::from("/home/me/.thirdshift/logs"),
                "{text:?}"
            );
        }
    }

    #[test]
    fn errors_name_the_file_and_the_offending_key() {
        for (text, named) in [
            ("[merge\n", "can't parse the User config"),
            ("[merge]\nalway = true\n", "unknown key merge.alway"),
            ("[log]\n", "unknown section [log]"),
            (
                "[logs]\ndirectory = \"/tmp\"\n",
                "unknown key logs.directory",
            ),
            ("logs = \"/tmp\"\n", "logs must be the section [logs]"),
            ("[logs]\ndir = 3\n", "logs.dir must be a string"),
            (
                "[logs]\ndir = \"logs\"\n",
                "logs.dir must be an absolute path",
            ),
            (
                "[logs]\ndir = \"./logs\"\n",
                "logs.dir must be an absolute path",
            ),
            (
                "[logs]\ndir = \"~other/logs\"\n",
                "logs.dir must be an absolute path",
            ),
            ("[logs]\ndir = \"\"\n", "logs.dir must be an absolute path"),
            ("merge = true\n", "merge must be the section [merge]"),
            ("colour = true\n", "unknown key colour "),
            (
                "[merge]\nalways = 1\n",
                "merge.always must be true or false",
            ),
            ("[base]\nfx = true\n", "unknown key base.fx"),
            ("base = true\n", "base must be the section [base]"),
            ("[base]\nfix = \"yes\"\n", "base.fix must be true or false"),
            ("[launch]\npul = true\n", "unknown key launch.pul"),
            ("launch = true\n", "launch must be the section [launch]"),
            (
                "[launch]\npull = \"yes\"\n",
                "launch.pull must be true or false",
            ),
            ("[email]\nadress = \"a@b.c\"\n", "unknown key email.adress"),
            ("email = \"a@b.c\"\n", "email must be the section [email]"),
            (
                "[email]\nalways = \"yes\"\n",
                "email.always must be true or false",
            ),
            (
                "[email]\nto = 1\n",
                "email.to must be a quoted email address",
            ),
            ("[spec]\nparalel = 2\n", "unknown key spec.paralel"),
            ("spec = 2\n", "spec must be the section [spec]"),
            (
                "[spec]\nparallel = 0\n",
                "spec.parallel must be a whole number from 1 up",
            ),
            (
                "[spec]\nparallel = -1\n",
                "spec.parallel must be a whole number from 1 up",
            ),
            (
                "[spec]\nparallel = 2.5\n",
                "spec.parallel must be a whole number from 1 up",
            ),
            (
                "[spec]\nparallel = \"2\"\n",
                "spec.parallel must be a whole number from 1 up",
            ),
            ("[pickup]\nlimt = 2\n", "unknown key pickup.limt"),
            ("pickup = 2\n", "pickup must be the section [pickup]"),
            (
                "[pickup]\nlimit = 0\n",
                "pickup.limit must be a whole number from 1 up",
            ),
            (
                "[pickup]\nlimit = -1\n",
                "pickup.limit must be a whole number from 1 up",
            ),
            (
                "[pickup]\nlimit = 2.5\n",
                "pickup.limit must be a whole number from 1 up",
            ),
            (
                "[pickup]\nlimit = \"2\"\n",
                "pickup.limit must be a whole number from 1 up",
            ),
        ] {
            let error = format!("{:#}", parse(text).unwrap_err());
            assert!(error.contains(named), "{text:?}: {error}");
            assert!(
                error.contains("/home/me/.thirdshift/config.toml"),
                "{text:?}: {error}"
            );
        }
    }

    /// `text` completed, after checking a Run reads it with the settings it
    /// had, plus the defaults for the keys it lacked.
    fn completed(text: &str) -> String {
        let completed = complete(text).unwrap();
        let before = parse(text).unwrap();
        let mut after = parse(&completed).unwrap_or_else(|error| panic!("{error:#}\n{completed}"));
        if before.email.from.is_none() {
            assert_eq!(
                after.email.from.as_deref(),
                Some(crate::email::DEFAULT_FROM)
            );
            after.email.from = None;
        }
        assert_eq!(after, before, "{completed}");
        let again = complete(&completed).unwrap();
        assert_eq!(again, completed, "completing twice changed it");
        completed
    }

    #[test]
    fn completing_an_empty_user_config_writes_the_defaults() {
        assert_eq!(completed(""), DEFAULTS);
    }

    #[test]
    fn completing_the_defaults_changes_nothing() {
        assert_eq!(completed(DEFAULTS), DEFAULTS);
    }

    #[test]
    fn completing_keeps_every_line_already_there_in_order() {
        for text in [
            "# top\n[merge]\nalways = true # mine\n",
            "[merge]\nalways = true",
            "[email]\n# to = \"me@example.com\"\nalways = true\n",
            "[email]\n# a note on from\nfrom = \"ts@acme.dev\"\n",
            "[logs]\ndir = \"/var/log/ts\"\n\n[merge]\nalways = true\n",
            "merge.always = true\nlaunch = { pull = true }\n",
            "[email]\nto = \"me@example.com\"\n",
        ] {
            let completed = completed(text);
            let mut lines = completed.lines();
            for line in text.lines() {
                assert!(
                    lines.any(|kept| kept == line),
                    "{line:?} of {text:?} is lost or moved:\n{completed}"
                );
            }
        }
    }

    #[test]
    fn completing_adds_email_to_commented_out_once() {
        for text in [
            "",
            "[email]\nalways = true\n",
            "[email]\n# a note on from\nfrom = \"ts@acme.dev\"\n",
            "[email]\n# to = \"me@example.com\"\n",
            "[ email ]  # mine\n# to = \"me@example.com\"\n",
        ] {
            let completed = completed(text);
            let examples = completed
                .lines()
                .filter(|line| line.starts_with("# to = "))
                .count();
            assert_eq!(examples, 1, "{text:?}:\n{completed}");
        }
        let completed = completed("[email]\nto = \"me@example.com\"\n");
        assert!(!completed.contains("# to ="), "{completed}");
    }

    fn notifications_to(to: &str) -> Answers {
        Answers {
            merge_always: false,
            base_fix: false,
            launch_pull: false,
            notifications: Some(questions::Notifications {
                to: to.to_string(),
                from: crate::email::DEFAULT_FROM.to_string(),
                key: None,
                send_test: false,
            }),
        }
    }

    #[test]
    fn an_answered_address_takes_the_place_of_the_commented_out_line() {
        let answered = with_answers(DEFAULTS, &notifications_to("me@example.com")).unwrap();
        let expected = with_email_to(Some("me@example.com".to_string())).replace(
            "always = false                  #",
            "always = true                   #",
        );
        assert_eq!(answered, expected);
    }

    #[test]
    fn an_answered_address_keeps_the_lines_around_the_commented_out_one() {
        let text =
            "[email]\nalways = false\n\n# mine\n# to = \"x@y.z\"\n# more\nfrom = \"a@b.c\"\n";
        let answered = with_answers(
            &complete(text).unwrap(),
            &notifications_to("me@example.com"),
        )
        .unwrap();
        let lines: Vec<&str> = answered.lines().collect();
        assert_eq!(
            lines[..4],
            ["[email]", "always = true", "", "# mine"],
            "{answered}"
        );
        assert!(
            lines[4].starts_with("to = \"me@example.com\""),
            "{answered}"
        );
        assert_eq!(
            lines[5..7],
            ["# more", "from = \"onboarding@resend.dev\""],
            "{answered}"
        );
    }
}