git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
//! Tag mode: list, create (annotated / lightweight), delete (local / remote), push, release notes.

use crate::git::{self, Opts};
use crate::policy::{self, Op};
use crate::release::{self, Commit};
use crate::{input, model::Config, safety, screen, ui};
use anyhow::{bail, Result};
use std::sync::atomic::AtomicBool;
use std::time::Duration;

const LIST_FORMAT: &str = "%(refname)%1f%(objecttype)%1f%(creatordate:short)%1f%(*objectname:short)%1f%(objectname:short)%1f%(subject)";
const LOG_FORMAT: &str = "--format=%H%x1f%s%x1f%b%x1e";
// Long enough for a browser sign-in prompt.
const NET_TIMEOUT: Duration = Duration::from_secs(300);
const MAX_COMMITS: &str = "500";

// ---------------------------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagEntry {
    pub name: String,
    pub annotated: bool,
    pub date: String,
    /// Short id of the tagged commit.
    pub target: String,
    pub subject: String,
}

/// Parses `LIST_FORMAT` output (one tag per line, fields separated by 0x1f).
pub fn parse_tag_list(text: &str) -> Vec<TagEntry> {
    text.lines()
        .filter_map(|line| {
            let f: Vec<&str> = line.trim_end_matches('\r').splitn(6, '\x1f').collect();
            if f.len() < 6 {
                return None;
            }
            let name = f[0].strip_prefix("refs/tags/")?;
            let target = if f[3].is_empty() { f[4] } else { f[3] };
            Some(TagEntry {
                name: name.to_string(),
                annotated: f[1] == "tag",
                date: f[2].to_string(),
                target: target.to_string(),
                subject: f[5].to_string(),
            })
        })
        .collect()
}

/// Why `name` cannot be a tag name (None when the text itself is acceptable; git's own
/// `check-ref-format` is asked afterwards).
pub fn name_problem(name: &str) -> Option<String> {
    if name.is_empty() {
        Some("The tag name is empty.".into())
    } else if name.starts_with('-') {
        Some("A tag name cannot start with '-'.".into())
    } else if name.chars().any(char::is_whitespace) {
        Some("A tag name cannot contain spaces.".into())
    } else {
        None
    }
}

/// Local tag names that the remote does not have yet.
pub fn missing_on_remote(local: &[TagEntry], remote: &[String]) -> Vec<String> {
    local
        .iter()
        .filter(|t| !remote.contains(&t.name))
        .map(|t| t.name.clone())
        .collect()
}

/// Commits from `git log --format=%H%x1f%s%x1f%b%x1e` output, classified.
pub fn parse_commits(text: &str) -> Vec<Commit> {
    text.split('\x1e')
        .filter_map(|record| {
            let record = record.trim_start_matches(['\r', '\n']);
            let mut fields = record.splitn(3, '\x1f');
            let (_, subject) = (fields.next()?, fields.next()?);
            Some(release::classify_commit(
                subject,
                fields.next().unwrap_or(""),
            ))
        })
        .collect()
}

fn row(t: &TagEntry) -> String {
    let kind = if t.annotated {
        screen::success("[annotated]")
    } else {
        screen::muted("[light]    ")
    };
    let pad = 18usize.saturating_sub(t.name.chars().count());
    format!(
        "{}{} {} {} {} {}",
        screen::accent(&t.name),
        " ".repeat(pad),
        kind,
        t.date,
        screen::muted(&t.target),
        t.subject
    )
}

fn show_command(parts: &[&str]) -> String {
    format!("git {}", parts.join(" "))
}

/// The push that puts a deleted remote tag back from its `tag-delete-remote` backup ref (the
/// local tag is not involved, so it works while a local tag of that name exists).
fn remote_restore_args(remote: &str, name: &str, backup: &str) -> Vec<String> {
    vec![
        "push".into(),
        remote.into(),
        format!("{backup}:refs/tags/{name}"),
    ]
}

// ---------------------------------------------------------------------------------------------
// Executors (run git; tested with TempRepo)
// ---------------------------------------------------------------------------------------------

pub fn list_tags() -> Result<Vec<TagEntry>> {
    let format = format!("--format={LIST_FORMAT}");
    let text = git::git_ok(
        &["for-each-ref", "refs/tags", "--sort=-creatordate", &format],
        &Opts::default(),
    )?;
    Ok(parse_tag_list(&text))
}

fn has_remote(cfg: &Config) -> bool {
    git::git_ok(&["remote"], &Opts::default())
        .map(|text| text.lines().any(|l| l.trim() == cfg.default_remote))
        .unwrap_or(false)
}

fn sign_by_default() -> bool {
    git::git_ok(
        &["config", "--bool", "--get", "tag.gpgsign"],
        &Opts::default(),
    )
    .map(|v| v == "true")
    .unwrap_or(false)
}

/// Validates `name` as a tag name, including git's own ref-format rules.
pub fn check_name(name: &str) -> Result<()> {
    if let Some(problem) = name_problem(name) {
        bail!(problem);
    }
    let full = format!("refs/tags/{name}");
    let out = git::git_raw(&["check-ref-format", &full], &Opts::default())?;
    if !out.ok() {
        bail!("'{name}' is not a valid tag name (see git check-ref-format).");
    }
    Ok(())
}

/// Creates a tag. `message` Some -> annotated (`-s` instead of `-a` when `sign`); None -> lightweight.
pub fn create_tag(
    name: &str,
    message: Option<&str>,
    rev: Option<&str>,
    sign: bool,
) -> Result<String> {
    check_name(name)?;
    if rev.is_some_and(|r| r.starts_with('-')) {
        bail!("A revision cannot start with '-'.");
    }
    let mut args = vec!["tag"];
    if let Some(message) = message {
        if message.trim().is_empty() {
            bail!("The tag message is empty.");
        }
        args.extend([if sign { "-s" } else { "-a" }, name, "-m", message]);
    } else {
        args.push(name);
    }
    args.extend(rev);
    git::git_ok(&args, &Opts::default())
}

/// Deletes a local tag after saving it under `refs/gct/backup/` (the tag object for annotated
/// tags, the commit for lightweight ones); returns that ref.
pub fn delete_local(name: &str) -> Result<String> {
    check_name(name)?;
    let full = format!("refs/tags/{name}");
    git::git_ok(&["cat-file", "-t", &full], &Opts::default())?;
    let backup = safety::backup("tag-delete", &full)?;
    git::git_ok(&["tag", "-d", name], &Opts::default())?;
    Ok(backup)
}

/// Recreates `refs/tags/<name>` from a backup ref (refuses when the tag exists).
#[cfg(test)] // the restore command is shown to the user; tests prove it works
pub fn restore_tag(name: &str, backup_ref: &str) -> Result<()> {
    check_name(name)?;
    let full = format!("refs/tags/{name}");
    git::git_ok(&["update-ref", &full, backup_ref, ""], &Opts::default())?;
    Ok(())
}

/// Runs a network git command with the standard timeout; a cancel or timeout is a plain error.
pub fn run_net(args: &[&str], cancel: Option<&AtomicBool>) -> Result<git::Out> {
    let opts = Opts {
        timeout: Some(NET_TIMEOUT),
        cancel,
        ..Opts::default()
    };
    let out = git::git_raw(args, &opts)?;
    if out.cancelled {
        bail!("Cancelled by you.");
    }
    if out.code.is_none() {
        bail!(
            "git {} timed out after {}s.",
            args.first().copied().unwrap_or(""),
            NET_TIMEOUT.as_secs()
        );
    }
    if !out.ok() {
        let err = out.stderr.trim();
        bail!("{}", if err.is_empty() { "git failed" } else { err });
    }
    Ok(out)
}

pub fn remote_tag_names(remote: &str, cancel: Option<&AtomicBool>) -> Result<Vec<String>> {
    Ok(remote_tags(remote, cancel)?
        .into_iter()
        .map(|(name, _)| name)
        .collect())
}

/// (name, object id) of every tag on the remote, as `ls-remote` reports them.
pub fn remote_tags(remote: &str, cancel: Option<&AtomicBool>) -> Result<Vec<(String, String)>> {
    let out = run_net(&["ls-remote", "--tags", remote], cancel)?;
    Ok(release::parse_ls_remote_oids(&String::from_utf8_lossy(
        &out.stdout,
    )))
}

/// Backs up the remote's version of a tag (object id `oid` from `ls-remote`), downloading the
/// object first when this repository does not have it. Returns the backup ref.
pub fn backup_remote_tag(
    remote: &str,
    name: &str,
    oid: &str,
    cancel: Option<&AtomicBool>,
) -> Result<String> {
    check_name(name)?;
    if oid.is_empty() || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
        bail!("unexpected object id '{oid}' from the remote");
    }
    if !git::git_raw(&["cat-file", "-e", oid], &Opts::default())?.ok() {
        run_net(
            &["fetch", "--no-tags", remote, &format!("refs/tags/{name}")],
            cancel,
        )?;
    }
    safety::backup("tag-delete-remote", oid)
}

pub fn push_tag(remote: &str, name: &str, cancel: Option<&AtomicBool>) -> Result<()> {
    check_name(name)?;
    run_net(&["push", remote, &format!("refs/tags/{name}")], cancel).map(|_| ())
}

pub fn push_all_tags(remote: &str, cancel: Option<&AtomicBool>) -> Result<()> {
    run_net(&["push", remote, "--tags"], cancel).map(|_| ())
}

/// Deletes the tag on the remote. Always the full ref, never the bare name.
pub fn delete_remote_tag(remote: &str, name: &str, cancel: Option<&AtomicBool>) -> Result<()> {
    check_name(name)?;
    run_net(
        &["push", remote, "--delete", &format!("refs/tags/{name}")],
        cancel,
    )
    .map(|_| ())
}

fn net_job<T: Send>(msg: &str, job: impl FnOnce(&AtomicBool) -> Result<T> + Send) -> Result<T> {
    ui::git_job_cancellable(msg, job)
}

/// The nearest tag reachable from `rev` (None when there is none).
fn describe_base(rev: &str) -> Option<String> {
    git::git_ok(&["describe", "--tags", "--abbrev=0", rev], &Opts::default())
        .ok()
        .filter(|t| !t.is_empty())
}

/// Commits in `base..end` (the whole history up to 500 when `base` is None); empty on error.
fn commits_between(base: Option<&str>, end: &str) -> Vec<Commit> {
    let range = match base {
        Some(base) => format!("{base}..{end}"),
        None => end.to_string(),
    };
    git::git_ok(
        &["log", &range, "--no-merges", "-n", MAX_COMMITS, LOG_FORMAT],
        &Opts::default(),
    )
    .map(|text| parse_commits(&text))
    .unwrap_or_default()
}

/// Suggested next tag name and release notes for a tag created at `rev`.
pub fn suggestion(rev: &str) -> (String, String) {
    let base = describe_base(rev);
    let commits = commits_between(base.as_deref(), rev);
    let current = base.as_deref().and_then(release::parse_semver);
    let next = release::suggest_next(&commits, current.as_ref());
    (
        next.to_string_with_prefix(),
        release::render_changelog(&commits),
    )
}

// ---------------------------------------------------------------------------------------------
// Interactive flows
// ---------------------------------------------------------------------------------------------

#[derive(Clone, Copy, PartialEq, Eq)]
enum Act {
    Details,
    New,
    Light,
    Delete,
    DeleteRemote,
    Push,
    PushAll,
    Changelog,
    TagNotes,
}

const MENU: [(&str, Act, bool, bool); 9] = [
    ("Details of this tag", Act::Details, true, false),
    ("Release notes of this tag", Act::TagNotes, true, false),
    ("New annotated tag", Act::New, false, false),
    ("New lightweight tag", Act::Light, false, false),
    (
        "Changelog since the latest tag",
        Act::Changelog,
        false,
        false,
    ),
    ("Delete this tag locally", Act::Delete, true, false),
    ("Push this tag to the remote", Act::Push, true, true),
    ("Push all tags to the remote", Act::PushAll, false, true),
    (
        "Delete this tag on the remote",
        Act::DeleteRemote,
        true,
        true,
    ),
];

fn note(title: &str, lines: Vec<String>) -> Result<()> {
    ui::notice(title, &lines)
}

fn failed(error: anyhow::Error) -> Result<()> {
    if input::is_cancel(&error) {
        return Err(error);
    }
    note(
        "Tag mode",
        vec![screen::danger(crate::cmdlog::mask(&error.to_string()))],
    )
}

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    loop {
        let tags = match list_tags() {
            Ok(tags) => tags,
            Err(error) => {
                return note(
                    "Tag mode",
                    vec![screen::danger(crate::cmdlog::mask(&error.to_string()))],
                )
            }
        };
        let remote = has_remote(config);
        let mut header = vec![if remote {
            format!("Remote: {}", config.default_remote)
        } else {
            screen::warning(format!(
                "No remote named '{}': push and remote delete are hidden.",
                config.default_remote
            ))
        }];
        if tags.is_empty() {
            header.push(String::new());
            header.push("No tags yet. Press n to create v0.1.0".into());
        }
        header.extend(ui::explain(
            config,
            &["A tag is a permanent name for a commit, like v1.0.0. Annotated tags also store a message."],
        ));
        let rows: Vec<String> = tags.iter().map(row).collect();
        let mut keys = vec![
            ui::Key {
                key: 'n',
                label: "new annotated",
            },
            ui::Key {
                key: 'l',
                label: "new light",
            },
            ui::Key {
                key: 'd',
                label: "delete local",
            },
            ui::Key {
                key: 'c',
                label: "changelog",
            },
            ui::Key {
                key: 'r',
                label: "refresh",
            },
        ];
        if remote {
            keys.extend([
                ui::Key {
                    key: 'p',
                    label: "push",
                },
                ui::Key {
                    key: 'P',
                    label: "push all (Shift)",
                },
                ui::Key {
                    key: 'D',
                    label: "delete remote (Shift)",
                },
            ]);
        }
        let choice = ui::action_list("Tags", &header, &rows, &keys, &mut index)?;
        let (act, selected) = match choice {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Open(i) => {
                let options: Vec<(&str, Act)> = MENU
                    .iter()
                    .filter(|(_, _, needs_tag, needs_remote)| {
                        (!needs_tag || i < tags.len()) && (!needs_remote || remote)
                    })
                    .map(|(label, act, _, _)| (*label, *act))
                    .collect();
                let labels: Vec<&str> = options.iter().map(|o| o.0).collect();
                match ui::choose("Tag actions", &[], &labels)? {
                    Some(n) => (options[n].1, i),
                    None => continue,
                }
            }
            ui::Choice::Action(key, i) => {
                let act = match key {
                    'n' => Act::New,
                    'l' => Act::Light,
                    'd' => Act::Delete,
                    'D' => Act::DeleteRemote,
                    'p' => Act::Push,
                    'P' => Act::PushAll,
                    'c' => Act::Changelog,
                    _ => continue,
                };
                (act, i)
            }
        };
        let tag = tags.get(selected);
        let needs_tag = matches!(
            act,
            Act::Details | Act::TagNotes | Act::Delete | Act::DeleteRemote | Act::Push
        );
        if needs_tag && tag.is_none() {
            continue;
        }
        let name = tag.map_or("", |t| t.name.as_str());
        let result = match act {
            Act::Details => details(config, name),
            Act::TagNotes => notes(config, Some(name)),
            Act::New => create_flow(config, None, true),
            Act::Light => create_flow(config, None, false),
            Act::Changelog => notes(config, None),
            Act::Delete => delete_flow(config, tag),
            Act::DeleteRemote => delete_remote_flow(config, name),
            Act::Push => push_flow(config, name),
            Act::PushAll => push_all_flow(config, &tags),
        };
        if let Err(error) = result {
            failed(error)?;
        }
    }
}

/// Asks for a name/message and creates a tag at `rev` (cross-mode entry point).
pub fn create_at(cfg: &mut Config, rev: &str) -> Result<()> {
    create_flow(cfg, Some(rev), true).or_else(failed)
}

fn details(cfg: &Config, name: &str) -> Result<()> {
    let full = format!("refs/tags/{name}");
    let text = ui::run_git(
        cfg,
        "Loading tag",
        &["show", "--stat", "--format=fuller", &full],
    )?;
    let lines: Vec<String> = text.lines().map(str::to_string).collect();
    ui::pager(&format!("Tag {name}"), &lines, "")
}

/// Release notes: of tag `name` (since the tag before it) or, with None, since the latest tag.
fn notes(cfg: &Config, name: Option<&str>) -> Result<()> {
    let (title, base, end) = match name {
        Some(name) => {
            let full = format!("refs/tags/{name}");
            (
                format!("Release notes for {name}"),
                describe_base(&format!("{full}^")),
                full,
            )
        }
        None => (
            "Changes since the latest tag".to_string(),
            describe_base("HEAD"),
            "HEAD".to_string(),
        ),
    };
    let commits = commits_between(base.as_deref(), &end);
    let mut lines = vec![match &base {
        Some(base) => format!("Since {base} ({} commits)", commits.len()),
        None => format!(
            "No earlier tag: whole history ({} commits, max {MAX_COMMITS})",
            commits.len()
        ),
    }];
    lines.push(String::new());
    let text = release::render_changelog(&commits);
    if text.is_empty() {
        lines.push("No commits to report.".into());
    } else {
        lines.extend(text.lines().map(str::to_string));
    }
    lines.extend(ui::explain(
        cfg,
        &["Commits written like 'feat: x' or 'fix: y' are grouped by type."],
    ));
    ui::pager(&title, &lines, "")
}

fn create_flow(cfg: &mut Config, rev: Option<&str>, annotated: bool) -> Result<()> {
    let target = match rev {
        Some(rev) => rev.to_string(),
        None => {
            let Some(answer) = ui::ask("Tag which commit (blank = HEAD)", "HEAD")? else {
                return Ok(());
            };
            let answer = answer.trim();
            if answer.is_empty() {
                "HEAD".to_string()
            } else {
                answer.to_string()
            }
        }
    };
    if target.starts_with('-') {
        return note(
            "Tag mode",
            vec![screen::danger("A revision cannot start with '-'.")],
        );
    }
    let spec = format!("{target}^{{commit}}");
    if !git::git_raw(
        &["rev-parse", "--verify", "--quiet", &spec],
        &Opts::default(),
    )?
    .ok()
    {
        return note(
            "Tag mode",
            vec![screen::danger(format!("'{target}' is not a commit."))],
        );
    }
    let (suggested, changelog) = suggestion(&target);
    let Some(name) = ui::ask("Tag name", &suggested)? else {
        return Ok(());
    };
    let name = name.trim().to_string();
    if let Err(error) = check_name(&name) {
        return note("Tag mode", vec![screen::danger(error.to_string())]);
    }
    let mut message = None;
    let mut sign = false;
    if annotated {
        let headline = format!("Release {name}");
        let full = if changelog.is_empty() {
            headline.clone()
        } else {
            format!("{headline}\n\n{changelog}")
        };
        let preview: Vec<String> = full.lines().take(12).map(str::to_string).collect();
        let text = match ui::choose(
            "Tag message",
            &preview,
            &[
                "Use these release notes",
                "Type a one-line message",
                "Edit in my editor",
            ],
        )? {
            Some(0) => full,
            Some(1) => match ui::ask("Tag message", &headline)? {
                Some(text) => text,
                None => return Ok(()),
            },
            Some(_) => ui::suspended(|| input::external_editor(&full))?,
            None => return Ok(()),
        };
        if text.trim().is_empty() {
            return note(
                "Tag mode",
                vec![screen::danger("The tag message is empty; nothing created.")],
            );
        }
        if sign_by_default() {
            match ui::choose(
                "Sign this tag? (tag.gpgsign is on)",
                &[],
                &["Yes, sign with GPG (-s)", "No, unsigned (-a)"],
            )? {
                Some(0) => sign = true,
                Some(_) => {}
                None => return Ok(()),
            }
        }
        message = Some(text.trim().to_string());
    }
    let flag = if sign { "-s" } else { "-a" };
    let shown = match (&message, rev) {
        (Some(_), _) => format!("git tag {flag} {name} -m \"<message>\" {target}"),
        (None, _) => format!("git tag {name} {target}"),
    };
    if !ui::confirm_action(cfg, &format!("Create tag {name} on {target}."), &shown)? {
        return Ok(());
    }
    let label = format!("Creating tag {name}");
    let (n, m, t) = (name.clone(), message.clone(), target.clone());
    ui::git_job(&label, move || create_tag(&n, m.as_deref(), Some(&t), sign))?;
    let mut lines = vec![
        screen::success(format!(
            "Created {} tag {name} on {target}.",
            if annotated {
                "annotated"
            } else {
                "lightweight"
            }
        )),
        format!("{} {shown}", screen::muted("Ran:")),
    ];
    lines.extend(ui::explain(
        cfg,
        &["The tag exists only on your computer until you push it."],
    ));
    note("Tag created", lines)?;
    if has_remote(cfg) {
        let remote = cfg.default_remote.clone();
        let option = format!("Push {name} to {remote}");
        if ui::choose(&format!("Share tag {name}?"), &[], &["Not now", &option])? == Some(1) {
            push_flow(cfg, &name)?;
        }
    }
    Ok(())
}

fn delete_flow(cfg: &Config, tag: Option<&TagEntry>) -> Result<()> {
    let Some(tag) = tag else { return Ok(()) };
    let command = show_command(&["tag", "-d", &tag.name]);
    let verdict = policy::check(cfg, &Op::DeleteTag { remote: false });
    if !ui::gate(
        cfg,
        &verdict,
        &format!("Delete the local tag {}.", tag.name),
        &command,
    )? {
        return Ok(());
    }
    let name = tag.name.clone();
    let backup = ui::git_job("Deleting tag", move || delete_local(&name))?;
    let lines = vec![
        screen::success(format!("Deleted local tag {}.", tag.name)),
        format!("{} {command}", screen::muted("Ran:")),
        format!("Backup: {backup}"),
        format!("Restore: git update-ref refs/tags/{} {backup}", tag.name),
    ];
    note("Tag deleted", lines)
}

fn delete_remote_flow(cfg: &Config, name: &str) -> Result<()> {
    let remote = cfg.default_remote.clone();
    let on_remote = {
        let r = remote.clone();
        net_job("Checking the remote", move |c| remote_tags(&r, Some(c)))?
    };
    let Some((_, remote_oid)) = on_remote.into_iter().find(|(t, _)| t == name) else {
        return note(
            "Tag mode",
            vec![format!("{name} is not on {remote}; nothing to delete.")],
        );
    };
    let command = show_command(&["push", &remote, "--delete", &format!("refs/tags/{name}")]);
    let verdict = policy::check(cfg, &Op::DeleteTag { remote: true });
    if !ui::gate(
        cfg,
        &verdict,
        &format!("Delete tag {name} on {remote}. Others may be using it."),
        &command,
    )? {
        return Ok(());
    }
    if !ui::confirm_typed(
        &format!("{name} exists on {remote} and will be removed there."),
        &command,
        name,
    )? {
        return Ok(());
    }
    let (r, n) = (remote.clone(), name.to_string());
    let backup = net_job("Saving a backup of the remote tag", move |c| {
        backup_remote_tag(&r, &n, &remote_oid, Some(c))
    })?;
    let (r, n) = (remote.clone(), name.to_string());
    net_job("Deleting the tag on the remote", move |c| {
        delete_remote_tag(&r, &n, Some(c))
    })?;
    let lines = vec![
        screen::success(format!(
            "Deleted {name} on {remote}. The local tag is untouched."
        )),
        format!("{} {command}", screen::muted("Ran:")),
        format!("Backup: {backup}"),
        format!(
            "Restore on {remote}: git {}",
            remote_restore_args(&remote, name, &backup).join(" ")
        ),
    ];
    note("Remote tag deleted", lines)
}

fn push_flow(cfg: &Config, name: &str) -> Result<()> {
    let remote = cfg.default_remote.clone();
    let command = show_command(&["push", &remote, &format!("refs/tags/{name}")]);
    let (r, n) = (remote.clone(), name.to_string());
    net_job(&format!("Pushing {name}"), move |c| {
        push_tag(&r, &n, Some(c))
    })?;
    let mut lines = vec![
        screen::success(format!("Pushed {name} to {remote}.")),
        format!("{} {command}", screen::muted("Ran:")),
    ];
    lines.extend(ui::explain(cfg, &["Now other people can fetch this tag."]));
    note("Tag pushed", lines)
}

fn push_all_flow(cfg: &Config, tags: &[TagEntry]) -> Result<()> {
    let remote = cfg.default_remote.clone();
    let on_remote = {
        let r = remote.clone();
        net_job("Checking the remote", move |c| {
            remote_tag_names(&r, Some(c))
        })?
    };
    let missing = missing_on_remote(tags, &on_remote);
    if missing.is_empty() {
        return note(
            "Tag mode",
            vec![format!("{remote} already has every local tag.")],
        );
    }
    let command = show_command(&["push", &remote, "--tags"]);
    let what = format!(
        "Push {} tag(s) missing on {remote}: {}",
        missing.len(),
        missing.join(", ")
    );
    if !ui::confirm_action(cfg, &what, &command)? {
        return Ok(());
    }
    let r = remote.clone();
    net_job("Pushing tags", move |c| push_all_tags(&r, Some(c)))?;
    note(
        "Tags pushed",
        vec![
            screen::success(format!("Pushed {} tag(s) to {remote}.", missing.len())),
            format!("{} {command}", screen::muted("Ran:")),
        ],
    )
}

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

    #[test]
    fn parse_list_annotated_and_light() {
        let text = "refs/tags/v2\x1ftag\x1f2024-01-02\x1fabc1234\x1fdef5678\x1fRelease v2\n\
                    refs/tags/v1\x1fcommit\x1f2024-01-01\x1f\x1fabc0000\x1fcommit 1\r\n\
                    garbage\n";
        let tags = parse_tag_list(text);
        assert_eq!(tags.len(), 2);
        assert!(
            tags[0].annotated && tags[0].target == "abc1234" && tags[0].subject == "Release v2"
        );
        assert!(!tags[1].annotated && tags[1].target == "abc0000" && tags[1].subject == "commit 1");
        assert!(parse_tag_list("").is_empty());
    }

    #[test]
    fn name_rules() {
        assert!(name_problem("v1.0.0").is_none());
        assert!(name_problem("").is_some());
        assert!(name_problem("-x").is_some());
        assert!(name_problem("a b").is_some());
    }

    #[test]
    fn missing_and_commits_parse() {
        let t = |n: &str| TagEntry {
            name: n.into(),
            annotated: true,
            date: String::new(),
            target: String::new(),
            subject: String::new(),
        };
        assert_eq!(
            missing_on_remote(&[t("a"), t("b")], &["a".to_string()]),
            vec!["b"]
        );
        let log = "h1\x1ffeat(x): add\x1fbody\x1e\nh2\x1ffix: bug\x1fBREAKING CHANGE: y\n\x1e";
        let commits = parse_commits(log);
        assert_eq!(commits.len(), 2);
        assert_eq!(commits[0].kind, "feat");
        assert!(commits[1].breaking);
    }

    #[test]
    fn create_list_and_suggest() {
        let repo = TempRepo::new(2);
        repo.run(|| {
            assert!(list_tags().unwrap().is_empty());
            assert_eq!(suggestion("HEAD").0, "v0.1.0");
            create_tag("v1.0.0", Some("Release v1.0.0"), Some("HEAD"), false).unwrap();
            create_tag("light", None, None, false).unwrap();
            let tags = list_tags().unwrap();
            let annotated = tags.iter().find(|t| t.name == "v1.0.0").unwrap();
            assert!(annotated.annotated && annotated.subject == "Release v1.0.0");
            assert!(!tags.iter().find(|t| t.name == "light").unwrap().annotated);
            assert_eq!(suggestion("HEAD").0, "v1.0.1");
            assert!(create_tag("-bad", None, None, false).is_err());
            assert!(create_tag("v1.0.0", Some("again"), None, false).is_err());
            assert!(create_tag("x", Some("  "), None, false).is_err());
        });
    }

    #[test]
    fn push_and_delete_remote_with_full_ref() {
        let repo = TempRepo::new(2).with_remote();
        repo.run(|| {
            create_tag("v1.0.0", Some("m"), None, false).unwrap();
            assert!(remote_tag_names("origin", None).unwrap().is_empty());
            push_tag("origin", "v1.0.0", None).unwrap();
            let remote = repo.git(&["ls-remote", "--tags", "origin"]);
            assert!(remote.contains("refs/tags/v1.0.0"));
            assert_eq!(remote_tag_names("origin", None).unwrap(), vec!["v1.0.0"]);
            delete_remote_tag("origin", "v1.0.0", None).unwrap();
            assert!(repo.git(&["ls-remote", "--tags", "origin"]).is_empty());
            create_tag("v2", None, None, false).unwrap();
            push_all_tags("origin", None).unwrap();
            assert_eq!(remote_tag_names("origin", None).unwrap().len(), 2);
            assert!(run_net(&["ls-remote", "nope-remote"], None).is_err());
        });
    }

    #[test]
    fn delete_local_and_restore_from_backup() {
        let repo = TempRepo::new(2);
        repo.run(|| {
            create_tag("v1.0.0", Some("m"), None, false).unwrap();
            create_tag("light", None, None, false).unwrap();
            let before = repo.git(&["rev-parse", "refs/tags/v1.0.0"]);
            let backup = delete_local("v1.0.0").unwrap();
            assert!(backup.starts_with("refs/gct/backup/"));
            assert!(list_tags().unwrap().iter().all(|t| t.name != "v1.0.0"));
            restore_tag("v1.0.0", &backup).unwrap();
            assert_eq!(repo.git(&["rev-parse", "refs/tags/v1.0.0"]), before);
            assert!(list_tags()
                .unwrap()
                .iter()
                .any(|t| t.name == "v1.0.0" && t.annotated));
            assert!(restore_tag("v1.0.0", &backup).is_err());
            // A lightweight tag is backed up too (the commit it pointed at) and restorable.
            let commit = repo.git(&["rev-parse", "refs/tags/light"]);
            let backup = delete_local("light").unwrap();
            assert_eq!(repo.git(&["rev-parse", &backup]), commit);
            assert!(list_tags().unwrap().iter().all(|t| t.name != "light"));
            restore_tag("light", &backup).unwrap();
            assert_eq!(repo.git(&["rev-parse", "refs/tags/light"]), commit);
        });
    }

    #[test]
    fn remote_tag_backup_uses_the_remote_oid() {
        let repo = TempRepo::new(2).with_remote();
        repo.run(|| {
            create_tag("v1", Some("m"), None, false).unwrap();
            push_tag("origin", "v1", None).unwrap();
            let remote_oid = repo.git(&["rev-parse", "refs/tags/v1"]);
            // The local tag now differs from the remote one.
            repo.git(&["tag", "-d", "v1"]);
            create_tag("v1", None, Some("HEAD~1"), false).unwrap();
            assert_ne!(repo.git(&["rev-parse", "refs/tags/v1"]), remote_oid);
            let found = remote_tags("origin", None).unwrap();
            assert_eq!(found, [("v1".to_string(), remote_oid.clone())]);
            let backup = backup_remote_tag("origin", "v1", &found[0].1, None).unwrap();
            assert_eq!(repo.git(&["rev-parse", &backup]), remote_oid);
            assert!(backup_remote_tag("origin", "v1", "--bad", None).is_err());
        });
    }

    #[test]
    fn remote_restore_command_recreates_the_remote_tag() {
        let repo = TempRepo::new(2).with_remote();
        let remote_git = repo.remote_path().to_string_lossy().into_owned();
        repo.run(|| {
            create_tag("v1", Some("m"), None, false).unwrap();
            push_tag("origin", "v1", None).unwrap();
            let found = remote_tags("origin", None).unwrap();
            let backup = backup_remote_tag("origin", "v1", &found[0].1, None).unwrap();
            delete_remote_tag("origin", "v1", None).unwrap();
            assert!(remote_tags("origin", None).unwrap().is_empty());
            // The local tag still exists (the normal case); the shown command runs as is.
            let args = remote_restore_args("origin", "v1", &backup);
            assert_eq!(
                format!("git {}", args.join(" ")),
                format!("git push origin {backup}:refs/tags/v1")
            );
            let args: Vec<&str> = args.iter().map(String::as_str).collect();
            repo.git(&args);
            assert_eq!(remote_tags("origin", None).unwrap(), found);
        });
        let restored = repo.git(&["--git-dir", &remote_git, "cat-file", "-t", "refs/tags/v1"]);
        assert_eq!(restored, "tag", "the annotated tag object came back");
    }

    #[test]
    fn remote_tag_backup_fetches_a_missing_object() {
        let repo = TempRepo::new(2).with_remote();
        let other = repo.path().parent().unwrap().join("other-tag");
        let other = other.to_string_lossy().into_owned();
        repo.git(&["clone", "-q", &repo.remote_path().to_string_lossy(), &other]);
        repo.git(&[
            "-C",
            &other,
            "-c",
            "user.name=O",
            "-c",
            "user.email=o@e.com",
            "tag",
            "-a",
            "t9",
            "-m",
            "theirs",
        ]);
        repo.git(&["-C", &other, "push", "-q", "origin", "refs/tags/t9"]);
        let want = repo.git(&["-C", &other, "rev-parse", "refs/tags/t9"]);
        repo.run(|| {
            let found = remote_tags("origin", None).unwrap();
            assert_eq!(found, [("t9".to_string(), want.clone())]);
            let backup = backup_remote_tag("origin", "t9", &want, None).unwrap();
            assert_eq!(repo.git(&["rev-parse", &backup]), want);
        });
    }
}