rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! What to review: a pull request, a branch, a commit, work in progress or a diff file. Each
//! is turned into a [`Change`], which the terminal report and the window view both show.

use super::propose;
use std::io::Read;
use std::path::{Path, PathBuf};

use super::diff::{self, Diff, FileDiff, Hunk, Kind, Line, Status};
use super::forge::{self, PullRequest};
use super::project::Project;
use super::tree::Tree;
use super::{Options, Source, demo, desc, git, render, rules, session};

/// The tree with nothing in it, which a first commit is compared against.
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// A reviewed change.
pub struct Change {
    /// The repository (or, for a diff file, the folder it was read from).
    pub root: PathBuf,
    /// Names the change across runs, so test results find it again.
    pub id: String,
    /// Changes whenever the content does, so older test results can be told apart.
    pub revision: String,
    pub title: String,
    pub url: Option<String>,
    /// Whether the working copy holds this change, so that it can be tested.
    pub checked_out: bool,
    /// The command that gets it there, if it is not.
    pub checkout: Option<String>,
    /// The description as written.
    pub description: String,
    /// Things worth saying about how it was read.
    pub notes: Vec<String>,
    pub report: render::Report,
    /// The changed files, to be read through and ticked off.
    pub files: Vec<FileDiff>,
    /// The pull request this is, and the commit it was read at, so it can be approved.
    pub pull: Option<(u64, String)>,
    /// The branch this is, if it is one a pull request could be opened for.
    pub branch: Option<propose::Of>,
}

pub enum Loaded {
    Change(Box<Change>),
    /// There is nothing to review, and why.
    Empty(String),
}

/// A target as typed: `#12`, `12`, `pr/12`, a pull request's address, or a name git knows.
#[derive(Debug, PartialEq, Eq)]
pub enum Target {
    Demo,
    PullRequest(u64),
    Name(String),
}

pub fn parse_target(text: &str, is_ref: impl Fn(&str) -> bool) -> Target {
    let text = text.trim();
    if text.eq_ignore_ascii_case("demo") {
        return Target::Demo;
    }
    let number = |s: &str| s.parse::<u64>().ok().filter(|n| *n > 0 && s.bytes().all(|b| b.is_ascii_digit()));
    for prefix in ["#", "pr/", "pr#", "!"] {
        if let Some(n) = text.strip_prefix(prefix).and_then(number) {
            return Target::PullRequest(n);
        }
    }
    if text.starts_with("https://") || text.starts_with("http://") {
        let mut parts = text.split(['?', '#']).next().unwrap_or("").split('/');
        while let Some(p) = parts.next() {
            if ["pull", "pulls", "merge_requests", "pull-requests"].contains(&p)
                && let Some(n) = parts.next().and_then(number)
            {
                return Target::PullRequest(n);
            }
        }
    }
    // Seven digits or more reads as a short commit id.
    match number(text) {
        Some(n) if text.len() < 7 && !is_ref(text) => Target::PullRequest(n),
        _ => Target::Name(text.to_string()),
    }
}

pub fn repository(cwd: &Path) -> Result<PathBuf, String> {
    git::line(cwd, &["rev-parse", "--show-toplevel"])
        .map(PathBuf::from)
        .map_err(|_| format!("{} is not inside a git repository", cwd.display()))
}

/// The branch a pull request would most likely go into.
pub fn default_base(root: &Path) -> Option<String> {
    if let Ok(head) = git::line(root, &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) {
        return Some(head);
    }
    ["origin/main", "origin/master", "main", "master", "develop"]
        .into_iter()
        .find(|b| git::commit_id(root, b).is_some())
        .map(str::to_string)
}

fn git_diff(root: &Path, revisions: &[&str]) -> Result<Diff, String> {
    // The prefixes are spelled out so that `diff.noprefix` and friends cannot change them.
    let mut args = vec!["diff", "--no-color", "--no-ext-diff", "--no-textconv", "-M", "--unified=3", "--src-prefix=a/", "--dst-prefix=b/"];
    args.extend(revisions);
    args.push("--");
    Ok(diff::parse(&git::output(root, &args)?))
}

/// New files git does not track yet, which `git diff` leaves out.
fn untracked(root: &Path) -> Vec<FileDiff> {
    let Ok(list) = git::output(root, &["ls-files", "--others", "--exclude-standard", "-z"]) else { return Vec::new() };
    list.split('\0')
        .filter(|p| !p.is_empty())
        .take(500)
        .map(|path| {
            let full = root.join(path);
            let text = std::fs::metadata(&full)
                .ok()
                .filter(|m| m.is_file() && m.len() < 1_000_000)
                .and_then(|_| std::fs::read_to_string(&full).ok())
                .filter(|t| !t.contains('\0'));
            let lines = text.as_deref().map(|t| {
                t.lines()
                    .enumerate()
                    .map(|(i, l)| Line { kind: Kind::Added, text: l.to_string(), old_no: None, new_no: Some(i as u32 + 1) })
                    .collect::<Vec<_>>()
            });
            FileDiff {
                path: path.to_string(),
                old_path: None,
                status: Status::Added,
                binary: text.is_none(),
                old_mode: None,
                new_mode: None,
                hunks: lines.map(|lines| vec![Hunk { lines }]).unwrap_or_default(),
            }
        })
        .collect()
}

pub fn read_input(cwd: &Path, path: &str) -> Result<String, String> {
    let mut bytes = Vec::new();
    if path == "-" {
        std::io::stdin().read_to_end(&mut bytes).map_err(|e| format!("could not read stdin: {e}"))?;
    } else {
        bytes = std::fs::read(cwd.join(path)).map_err(|e| format!("could not read {path}: {e}"))?;
    }
    // PowerShell's `>` writes UTF-16 with a byte order mark.
    let text = match bytes.as_slice() {
        [0xff, 0xfe, rest @ ..] => String::from_utf16_lossy(&rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect::<Vec<_>>()),
        [0xef, 0xbb, 0xbf, rest @ ..] => String::from_utf8_lossy(rest).into_owned(),
        _ => String::from_utf8_lossy(&bytes).into_owned(),
    };
    Ok(text)
}

/// A change before it is analyzed.
struct Picked {
    root: PathBuf,
    id: String,
    revision: Option<String>,
    title: String,
    against: String,
    url: Option<String>,
    diff: Diff,
    tree: Tree,
    /// (text, where it came from)
    description: Option<(String, String)>,
    /// The commit under review, if it is one.
    head: Option<String>,
    checkout: Option<String>,
    notes: Vec<String>,
    /// What to say if the diff is empty.
    empty: String,
    pull: Option<(u64, String)>,
    branch: Option<propose::Of>,
}

impl Picked {
    fn new(root: &Path, id: String, title: String, against: String, diff: Diff) -> Picked {
        Picked {
            root: root.to_path_buf(),
            id,
            revision: None,
            empty: format!("no changes in {against}"),
            title,
            against,
            url: None,
            diff,
            tree: Tree::Disk(root.to_path_buf()),
            description: None,
            head: None,
            checkout: None,
            notes: Vec::new(),
            pull: None,
            branch: None,
        }
    }

    /// Review a commit's files as committed, whatever is on disk.
    fn at_commit(mut self, sha: &str) -> Result<Picked, String> {
        self.tree = Tree::commit(&self.root, sha)?;
        self.head = Some(sha.to_string());
        self.revision = Some(sha.to_string());
        Ok(self)
    }
}

fn short(sha: &str) -> &str {
    sha.get(..10).unwrap_or(sha)
}

fn commit_messages(root: &Path, range: &str) -> Option<(String, String)> {
    git::output(root, &["log", "--reverse", "--format=%B", range, "--"])
        .ok()
        .filter(|m| !m.trim().is_empty())
        .map(|m| (m, "commit messages".to_string()))
}

fn working_copy(root: &Path, source: &Source) -> Result<Picked, String> {
    let (diff, id, title, against) = if *source == Source::Staged {
        (git_diff(root, &["--cached"])?, "staged", "Staged changes", "staged changes")
    } else {
        // A repository without a commit yet has no HEAD to compare with.
        let from = if git::commit_id(root, "HEAD").is_some() { "HEAD" } else { EMPTY_TREE };
        let mut d = git_diff(root, &[from])?;
        d.files.extend(untracked(root));
        (d, "uncommitted", "Uncommitted changes", "uncommitted changes")
    };
    Ok(Picked::new(root, id.into(), title.into(), against.into(), diff))
}

/// The commits a branch has that `base` lacks.
fn branch(root: &Path, name: Option<&str>, base: Option<&str>) -> Result<Picked, String> {
    let base = match base {
        Some(b) => b.to_string(),
        None => default_base(root).ok_or("cannot tell which branch to compare with; name it: review --base origin/main")?,
    };
    let shown = name.unwrap_or("HEAD");
    let base_id = git::commit_id(root, &base).ok_or_else(|| format!("`{base}` is not a branch or commit here"))?;
    let head_id = git::commit_id(root, shown).ok_or_else(|| format!("`{shown}` is not a branch or commit here"))?;
    let current = git::line(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok();
    let label = name.map(str::to_string).or_else(|| current.clone()).unwrap_or_else(|| "HEAD".into());
    let diff = git_diff(root, &[&format!("{base_id}...{head_id}")])?;
    let mut p = Picked::new(root, format!("branch {label}"), format!("Branch {label}"), format!("{base}...{label}"), diff);
    p.empty = format!(
        "`{label}` has no commits that `{base}` lacks. For work in progress use `review --uncommitted`; \
         to compare the current branch with `{label}`, use `review --base {label}`"
    );
    p.description = commit_messages(root, &format!("{base_id}..{head_id}"));
    let reference = match name {
        Some(n) => git::line(root, &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", n]).ok(),
        None => current.as_ref().map(|c| format!("refs/heads/{c}")),
    };
    p.branch = reference.filter(|r| proposable(r, &base)).map(|name| propose::Of { name, base: Some(base.clone()) });
    p.checkout = name.map(|n| match n.strip_prefix("origin/") {
        Some(local) => format!("git switch {local}"),
        None => format!("git switch {n}"),
    });
    p.at_commit(&head_id)
}

/// Whether `reference` is a branch that could be merged into `base`: any branch but
/// `base` itself.
fn proposable(reference: &str, base: &str) -> bool {
    let name = reference
        .strip_prefix("refs/heads/")
        .or_else(|| reference.strip_prefix("refs/remotes/").and_then(|r| r.split_once('/')).map(|(_, n)| n));
    let base = base.strip_prefix("origin/").unwrap_or(base);
    name.is_some_and(|n| n != base && n != "HEAD")
}

/// One commit, against its first parent.
fn commit(root: &Path, id: &str) -> Result<Picked, String> {
    let parent = git::commit_id(root, &format!("{id}^1")).unwrap_or_else(|| EMPTY_TREE.to_string());
    let diff = git_diff(root, &[&parent, id])?;
    let subject = git::line(root, &["log", "-1", "--format=%s", id, "--"])?;
    let mut p = Picked::new(root, format!("commit {id}"), format!("{} {subject}", short(id)), format!("commit {}", short(id)), diff);
    p.description = git::output(root, &["log", "-1", "--format=%B", id, "--"]).ok().map(|m| (m, "commit message".to_string()));
    p.checkout = Some(format!("git switch --detach {}", short(id)));
    p.at_commit(id)
}

fn named(root: &Path, name: &str, base: Option<&str>) -> Result<Picked, String> {
    let full = git::line(root, &["rev-parse", "--verify", "--quiet", "--symbolic-full-name", "--end-of-options", name]).unwrap_or_default();
    if full.starts_with("refs/heads/") || full.starts_with("refs/remotes/") {
        // `HEAD` names the last commit, not the branch it happens to be on.
        if name != "HEAD" {
            return branch(root, Some(name), base);
        }
    }
    if let Some(id) = git::commit_id(root, name) {
        return match base {
            Some(b) => branch(root, Some(name), Some(b)),
            None => commit(root, &id),
        };
    }
    // A branch that has only been fetched.
    let remote = format!("origin/{name}");
    if git::commit_id(root, &remote).is_some() {
        return branch(root, Some(&remote), base);
    }
    Err(format!("`{name}` is not a pull request number, branch or commit (try `git fetch`, or `pr` to see what is there)"))
}

/// Whether a branch name from a host is safe to put in a refspec.
fn plain_ref(name: &str) -> bool {
    !name.is_empty() && !name.contains("..") && !name.chars().any(|c| c.is_whitespace() || c.is_control() || ":*?[\\^~".contains(c))
}

fn fetch(root: &Path, remote: &str, specs: &[String]) -> Result<(), String> {
    let mut args = vec!["fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options", remote];
    args.extend(specs.iter().map(String::as_str));
    git::output(root, &args).map(|_| ())
}

fn pull_request(root: &Path, number: u64, base: Option<&str>) -> Result<Picked, String> {
    let (remote, _) = forge::remote(root)?;
    let local = |what: &str| format!("refs/rustimal/pr/{number}/{what}");
    let head_spec = |from: &str| format!("+{from}:{}", local("head"));
    let found = forge::pull_request(root, number);
    let mut notes = Vec::new();
    let info: Option<PullRequest> = match &found {
        Ok((kind, pr)) => {
            let from = match kind.head_ref(number) {
                Some(r) => r,
                None if plain_ref(&pr.head_branch) => format!("refs/heads/{}", pr.head_branch),
                None => return Err(format!("pull request #{number} has no branch that can be fetched")),
            };
            let mut specs = vec![head_spec(&from)];
            if plain_ref(&pr.base) {
                specs.push(format!("+refs/heads/{}:{}", pr.base, local("base")));
            }
            fetch(root, &remote, &specs).map_err(|e| format!("could not fetch pull request #{number}: {e}"))?;
            Some(pr.clone())
        }
        Err(why) => {
            // Without the API, git can still fetch the refs most hosts keep.
            let kinds = [forge::Kind::GitHub, forge::Kind::GitLab, forge::Kind::BitbucketServer];
            if !kinds.iter().filter_map(|k| k.head_ref(number)).any(|r| fetch(root, &remote, &[head_spec(&r)]).is_ok()) {
                return Err(format!("could not get pull request #{number}: {why}"));
            }
            notes.push(format!("the title and description could not be read ({why}); the commit messages stand in"));
            None
        }
    };
    let head = git::commit_id(root, &local("head")).ok_or("the fetched pull request has no commit")?;
    let (base_name, base_rev) = match (base, &info) {
        (Some(b), _) => (b.to_string(), b.to_string()),
        (None, Some(pr)) if plain_ref(&pr.base) => (pr.base.clone(), local("base")),
        _ => {
            let b = default_base(root).ok_or("cannot tell which branch the pull request goes into; add --base")?;
            (b.clone(), b)
        }
    };
    if let Some(pr) = &info
        && !pr.head_sha.is_empty()
        && !head.starts_with(&pr.head_sha)
    {
        notes.push(format!("the host says the pull request is at {}, but {} was fetched; reload in a moment", short(&pr.head_sha), short(&head)));
    }
    let base_id = git::commit_id(root, &base_rev).ok_or_else(|| format!("`{base_name}` is not a branch or commit here"))?;
    let diff = git_diff(root, &[&format!("{base_id}...{head}")])?;
    let title = match &info {
        Some(pr) => format!("#{number} {}", pr.title),
        None => format!("Pull request #{number}"),
    };
    let mut p = Picked::new(root, format!("pr {number}"), title, format!("{base_name}...#{number}"), diff);
    p.empty = format!("pull request #{number} adds nothing to `{base_name}`; it may be merged already");
    p.description = match &info {
        Some(pr) => Some((pr.body.clone(), "PR description".to_string())).filter(|(b, _)| !b.trim().is_empty()),
        None => commit_messages(root, &format!("{base_id}..{head}")),
    };
    p.url = info.map(|pr| pr.url).filter(|u| u.starts_with("https://"));
    p.checkout = Some(format!("git switch --detach {}", short(&head)));
    p.pull = Some((number, head.clone()));
    p.notes = notes;
    p.at_commit(&head)
}

fn demo_change() -> Result<Picked, String> {
    let root = demo::create()?;
    let mut p = branch(&root, Some(demo::BRANCH), Some("main"))?;
    p.id = "demo".into();
    p.title = demo::TITLE.into();
    p.description = Some((demo::DESCRIPTION.into(), "PR description".into()));
    // The demo is only there to be looked at; there is nothing to switch to or propose.
    p.checkout = None;
    p.branch = None;
    Ok(p)
}

fn pick(cwd: &Path, o: &Options) -> Result<Picked, String> {
    if let Source::File(path) = &o.source {
        let root = repository(cwd).unwrap_or_else(|_| cwd.to_path_buf());
        let against = if path == "-" { "stdin".to_string() } else { path.clone() };
        let diff = diff::parse(&read_input(cwd, path)?);
        return Ok(Picked::new(&root, format!("diff {against}"), format!("Diff {against}"), against, diff));
    }
    // The demo brings its own repository.
    if o.target.as_deref().is_some_and(|t| parse_target(t, |_| false) == Target::Demo) {
        return demo_change();
    }
    let root = repository(cwd)?;
    if o.source != Source::Branch {
        return working_copy(&root, &o.source);
    }
    let base = o.base.as_deref();
    match o.target.as_deref().map(|t| parse_target(t, |name| git::commit_id(&root, &format!("refs/heads/{name}")).is_some())) {
        None => {
            let mut p = branch(&root, None, base)?;
            if git::output(&root, &["status", "--porcelain"]).is_ok_and(|s| !s.trim().is_empty()) {
                p.notes.push("uncommitted changes are not part of this review (see --uncommitted)".into());
            }
            Ok(p)
        }
        Some(Target::Demo) => demo_change(),
        Some(Target::PullRequest(n)) => pull_request(&root, n, base),
        Some(Target::Name(name)) => named(&root, &name, base),
    }
}

/// Find the change, read it and run the rules over it.
pub fn load(cwd: &Path, o: &Options) -> Result<Loaded, String> {
    let p = pick(cwd, o)?;
    if p.diff.files.is_empty() {
        return Ok(Loaded::Empty(p.empty));
    }
    let given = match &o.desc {
        Some(path) => Some((read_input(cwd, path)?, "PR description".to_string())),
        None => p.description,
    };
    let description = given.as_ref().map(|(text, from)| desc::parse(text, from));
    let project = Project::from_tree(p.tree);
    let findings = rules::analyze(&rules::Cx { diff: &p.diff, project: &project, desc: description.as_ref() });
    let report = render::Report {
        against: p.against,
        project: project.describe(),
        files: p.diff.files.len(),
        added: p.diff.added_count(),
        removed: p.diff.removed_count(),
        plan: render::plan(&findings),
        described_steps: description.as_ref().and_then(|d| d.test_section()).map(|s| s.body.clone()).unwrap_or_default(),
        findings,
    };
    let current = git::commit_id(&p.root, "HEAD");
    let checked_out = p.head.is_none() || p.head == current || p.id == "demo";
    let revision = p.revision.unwrap_or_else(|| session::fingerprint_diff(&p.diff));
    Ok(Loaded::Change(Box::new(Change {
        checkout: p.checkout.filter(|_| !checked_out),
        root: p.root,
        id: p.id,
        revision,
        title: p.title,
        url: p.url,
        checked_out,
        description: given.map(|(text, _)| text).unwrap_or_default(),
        notes: p.notes,
        report,
        files: p.diff.files,
        pull: p.pull,
        branch: p.branch,
    })))
}

/// A line in the list of things that can be reviewed.
#[derive(Clone, Debug)]
pub struct Entry {
    /// What `review` takes to open it.
    pub target: String,
    pub title: String,
    pub detail: String,
}

/// What this repository offers without asking its host.
#[derive(Default)]
pub struct Local {
    pub work: Vec<Entry>,
    pub branches: Vec<Entry>,
    pub commits: Vec<Entry>,
}

pub fn local(root: &Path) -> Local {
    let mut out = Local::default();
    let changed = git::output(root, &["status", "--porcelain"]).map_or(0, |s| s.lines().count());
    if changed > 0 {
        let detail = format!("{changed} changed {}", if changed == 1 { "file" } else { "files" });
        out.work.push(Entry { target: "--uncommitted".into(), title: "Uncommitted changes".into(), detail });
    }
    let format = "--format=%(refname:short)%1f%(contents:subject)%1f%(committerdate:relative)%1f%(HEAD)";
    if let Ok(list) = git::output(root, &["for-each-ref", "--sort=-committerdate", "--count=12", format, "refs/heads"]) {
        out.branches = list
            .lines()
            .filter_map(|l| {
                let mut f = l.split('\x1f');
                let (name, subject, age, head) = (f.next()?, f.next()?, f.next()?, f.next()?);
                let current = if head == "*" { "current · " } else { "" };
                Some(Entry { target: name.into(), title: name.into(), detail: format!("{current}{age} · {subject}") })
            })
            .collect();
    }
    if let Ok(list) = git::output(root, &["log", "-n", "12", "--format=%h%x1f%s%x1f%cr%x1f%an", "--"]) {
        out.commits = list
            .lines()
            .filter_map(|l| {
                let mut f = l.split('\x1f');
                let (id, subject, age, author) = (f.next()?, f.next()?, f.next()?, f.next()?);
                // A short id of digits alone would read as a pull request number.
                Some(Entry { target: format!("{id}^{{commit}}"), title: format!("{id} {subject}"), detail: format!("{age} · {author}") })
            })
            .collect();
    }
    out
}

pub fn pull_request_entry(p: &PullRequest) -> Entry {
    let draft = if p.draft { "draft · " } else { "" };
    Entry {
        target: format!("#{}", p.number),
        title: format!("#{} {}", p.number, p.title),
        detail: format!("{draft}{} · {} → {}", p.author, p.head_branch, p.base),
    }
}

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

    #[test]
    fn tells_pull_requests_from_branches_and_commits() {
        let none = |_: &str| false;
        for pr in ["12", "#12", "pr/12", "!12", "https://github.com/a/b/pull/12", "https://gl.example/a/b/-/merge_requests/12?x=1"] {
            assert_eq!(parse_target(pr, none), Target::PullRequest(12), "{pr}");
        }
        assert_eq!(parse_target("1234567", none), Target::Name("1234567".into()), "a short commit id");
        assert_eq!(parse_target("2024", |n| n == "2024"), Target::Name("2024".into()), "a branch of that name wins");
        assert_eq!(parse_target("Demo", none), Target::Demo);
        for name in ["main", "feature/12", "abc1234", "HEAD~2", "0", "#x"] {
            assert_eq!(parse_target(name, none), Target::Name(name.into()), "{name}");
        }
    }

    fn options(target: Option<&str>, base: Option<&str>) -> Options {
        Options { target: target.map(Into::into), base: base.map(Into::into), ..Default::default() }
    }

    fn change(l: Result<Loaded, String>) -> Box<Change> {
        match l.unwrap() {
            Loaded::Change(c) => c,
            Loaded::Empty(why) => panic!("{why}"),
        }
    }

    #[test]
    fn reviews_a_branch_or_a_commit_by_name() {
        let s = Scratch::new("source-names");
        git::testing::init(&s.0);
        s.write("a.txt", "one\n");
        git::testing::commit(&s.0, "first");
        git::testing::run(&s.0, &["switch", "--quiet", "-c", "feature"]);
        s.write("a.txt", "one\ntwo\n");
        git::testing::commit(&s.0, "second");
        s.write("b.txt", "three\n");
        git::testing::commit(&s.0, "third");
        git::testing::run(&s.0, &["switch", "--quiet", "main"]);

        let c = change(load(&s.0, &options(Some("feature"), None)));
        assert_eq!((c.report.files, c.report.added, c.id.as_str()), (2, 2, "branch feature"));
        assert!(!c.checked_out);
        assert_eq!(c.checkout.as_deref(), Some("git switch feature"));

        let c = change(load(&s.0, &options(Some("feature~1"), None)));
        assert_eq!((c.report.files, c.report.added), (1, 1));
        assert!(c.title.ends_with(" second"), "{}", c.title);

        let first = change(load(&s.0, &options(Some("HEAD"), None)));
        assert!(first.checked_out && first.title.ends_with(" first"), "a first commit has no parent");

        assert!(matches!(load(&s.0, &options(Some("main"), None)), Ok(Loaded::Empty(why)) if why.contains("--base main")));
        assert!(load(&s.0, &options(Some("nope"), None)).is_err_and(|e| e.contains("`nope`")));
        assert!(load(&s.0, &options(Some("--output=x"), None)).is_err(), "a name is never an option");
        assert!(!s.0.join("x").exists());

        let l = local(&s.0);
        assert_eq!(l.branches.len(), 2);
        assert_eq!(l.commits.len(), 1);
        assert!(l.work.is_empty());
    }

    #[test]
    fn hosted_branch_names_cannot_add_to_a_refspec() {
        assert!(plain_ref("feature/x-1"));
        for bad in ["", "a:refs/heads/main", "a b", "a..b", "*", "a^", "x\n"] {
            assert!(!plain_ref(bad), "{bad:?}");
        }
    }
}