git-queue 0.1.1

Manage queues of dependent branches and their numbered pull requests
Documentation
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
//! Pure rendering helpers: the status tree, PR titles, and the shared queue
//! navigation block injected into every PR body. Kept side-effect-free so they
//! can be unit-tested without git or the network.

pub(crate) const BEGIN: &str = "<!-- git-queue:begin -->";
pub(crate) const END: &str = "<!-- git-queue:end -->";

/// One entry in a queue line for rendering purposes.
pub(crate) struct Entry {
    pub branch: String,
    pub pr: Option<PrRef>,
    /// The branch currently holds persisted conflict markers.
    pub conflicted: bool,
    /// Paths of the files holding those markers (filled by status/log).
    pub conflicts: Vec<String>,
    /// Commits to render beneath the branch (newest first): `(Stable-Commit-Id?,
    /// subject)`. Empty for `status`; filled by `log`.
    pub commits: Vec<(Option<String>, String)>,
    /// Nesting level: 0 on the main line, +1 for each fork the branch sits
    /// behind. Forked subtrees render indented above their fork parent.
    pub indent: usize,
}

#[derive(Clone)]
pub(crate) struct PrRef {
    pub number: u64,
    pub url: String,
    pub state: String, // OPEN | CLOSED | MERGED
    /// APPROVED | `CHANGES_REQUESTED` | `REVIEW_REQUIRED` | None
    pub review: Option<String>,
}

/// The commit-status context the merge-order gate posts under.
pub(crate) const GATE_CONTEXT: &str = "git-queue/merge-order";

/// One planned merge-order status (the advisory "status gate"), to be posted
/// on the head commit of a PR.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct GateStatus {
    /// Head branch of the PR receiving the status.
    pub branch: String,
    /// true -> green ✓ (mergeable now); false -> red ✗ (out of order).
    pub success: bool,
    pub description: String,
    /// "Details" link for the status: the PR that must merge first.
    pub target_url: Option<String>,
}

/// Plan the advisory merge-order statuses for a queue line (bottom-first): the
/// bottom-most OPEN PR gets a success status, every open PR above it gets a
/// failure status naming the PR that must merge first. Merged/closed PRs and
/// branches without a PR get nothing.
pub(crate) fn gate_plan(entries: &[Entry]) -> Vec<GateStatus> {
    let mut bottom: Option<&PrRef> = None;
    let mut plan = Vec::new();
    for e in entries {
        let Some(pr) = &e.pr else { continue };
        if pr.state != "OPEN" {
            continue;
        }
        match bottom {
            None => {
                plan.push(GateStatus {
                    branch: e.branch.clone(),
                    success: true,
                    description: "Ready — front of the queue, merge this PR first".to_string(),
                    target_url: None,
                });
                bottom = Some(pr);
            }
            Some(b) => plan.push(GateStatus {
                branch: e.branch.clone(),
                success: false,
                description: format!("Do not merge — merge PR #{} first (queue order)", b.number),
                target_url: (!b.url.is_empty()).then(|| b.url.clone()),
            }),
        }
    }
    plan
}

/// Emoji for a PR's review decision.
fn approval_emoji(review: Option<&str>) -> &'static str {
    match review {
        Some("APPROVED") => "",
        Some("CHANGES_REQUESTED") => "♻️",
        _ => "", // REVIEW_REQUIRED / not yet reviewed
    }
}

/// Emoji for a PR's merge state.
fn state_emoji(state: &str) -> &'static str {
    match state {
        "MERGED" => "🟣",
        "CLOSED" => "",
        _ => "🟢", // OPEN
    }
}

/// Numbered title: `[k/n] <subject>`, stripping any prior `[i/j] ` prefix so
/// re-submitting doesn't pile up prefixes.
pub(crate) fn numbered_title(subject: &str, index: usize, total: usize) -> String {
    format!("[{}/{}] {}", index + 1, total, strip_prefix(subject))
}

fn strip_prefix(subject: &str) -> &str {
    let s = subject.trim_start();
    if let Some(rest) = s.strip_prefix('[') {
        if let Some(close) = rest.find(']') {
            let inside = &rest[..close];
            if inside.contains('/') && inside.chars().all(|c| c.is_ascii_digit() || c == '/') {
                return rest[close + 1..].trim_start();
            }
        }
    }
    s
}

/// Build the shared queue-navigation block: a formatted, linked list of every
/// PR in the line in merge order (bottom first), with the current PR bolded and
/// marked. Each entry links to the PR's URL when known.
pub(crate) fn nav_block(line: &[Entry], current: &str, base: &str, queue_name: &str) -> String {
    let total = line.len();
    let mut lines = vec![
        format!(
            "### 📚 {queue_name} PR &nbsp;·&nbsp; {} of {}",
            position_of(line, current),
            total
        ),
        String::new(),
        "Part of a queue. The PRs merge in FIFO order — the numbered order below, #1 \
         first. Merging one supersedes the PRs after it until the author runs \
         `git queue sync` (rebases the rest onto the merged base) and `git queue submit` \
         (retargets their PRs)."
            .to_string(),
        String::new(),
    ];
    // Bottom-first: index 0 merges first.
    for (i, e) in line.iter().enumerate() {
        let is_current = e.branch == current;
        let target = if i == 0 {
            base
        } else {
            line[i - 1].branch.as_str()
        };
        // Merge-state emoji always; approval emoji only while the PR is open
        // (a merged/closed PR's review status is no longer meaningful).
        let status = match &e.pr {
            Some(p) if p.state == "OPEN" => {
                format!(
                    "{}{} ",
                    approval_emoji(p.review.as_deref()),
                    state_emoji(&p.state)
                )
            }
            Some(p) => format!("{} ", state_emoji(&p.state)),
            None => String::new(),
        };
        // Link text: `#<n> branch` linked to the PR URL if we have one.
        let label = match &e.pr {
            Some(p) if !p.url.is_empty() => format!("[#{} `{}`]({})", p.number, e.branch, p.url),
            Some(p) => format!("#{} `{}`", p.number, e.branch),
            None => format!("`{}` _(not submitted)_", e.branch),
        };
        let arrow = format!(" → `{target}`");
        let line_str = if is_current {
            format!("{status}**{label}{arrow}** &nbsp;👈 **this PR**")
        } else {
            format!("{status}{label}{arrow}")
        };
        lines.push(line_str);
    }
    lines.push(String::new());
    lines.push(
        "<sub>✅ approved · ♻️ changes requested · ⏳ review pending &nbsp;|&nbsp; \
         🟣 merged · 🟢 open · ⚫ closed &nbsp;—&nbsp; status as of the last \
         `git queue submit`.</sub>"
            .to_string(),
    );
    lines.push("<sub>🥞 Managed by git-queue — do not edit this list by hand.</sub>".to_string());
    lines.join("\n")
}

/// 1-based position of `current` within the (bottom-first) line.
fn position_of(line: &[Entry], current: &str) -> usize {
    line.iter()
        .position(|e| e.branch == current)
        .map_or(0, |i| i + 1)
}

/// Compose a PR body: the queue map, then optional "About this queue" and
/// "About this branch" sections, all inside the managed BEGIN..END block —
/// every part regenerates from config on each submit.
pub(crate) fn compose_body(queue_description: &str, branch_description: &str, nav: &str) -> String {
    let mut body = format!("{BEGIN}\n{nav}");
    let qd = queue_description.trim();
    if !qd.is_empty() {
        body.push_str(&format!("\n\n# About this queue\n\n{qd}"));
    }
    let bd = strip_block(branch_description);
    // Legacy bodies kept the description under a bare `---` divider outside
    // the managed block; drop that scaffolding if it survived the strip.
    let bd = bd.trim();
    let bd = bd.strip_prefix("---").map_or(bd, str::trim_start);
    if !bd.is_empty() {
        body.push_str(&format!("\n\n# About this branch\n\n{bd}"));
    }
    body.push_str(&format!("\n{END}"));
    body
}

/// Remove a previously injected BEGIN..END block (inclusive) from `body`.
pub(crate) fn strip_block(body: &str) -> String {
    match (body.find(BEGIN), body.find(END)) {
        (Some(start), Some(end)) if end >= start => {
            let after = end + END.len();
            let mut result = String::new();
            result.push_str(&body[..start]);
            result.push_str(&body[after..]);
            result
        }
        _ => body.to_string(),
    }
}

/// Render the status tree, top of queue first. `entries` is bottom-first;
/// `base` is the branch the line merges into (labelled "trunk" when it is the
/// trunk). The current branch gets a `❯` marker in the left margin. With
/// `color`: bold branch names, tinted PR states and warnings, and a distinct
/// colour for commit ids.
pub(crate) fn status_tree(
    entries: &[Entry],
    current: &str,
    base: &str,
    base_is_trunk: bool,
    color: bool,
    // `Some(repo url)` when the terminal renders OSC 8 hyperlinks: PR numbers
    // become clickable links to their PRs.
    link_base: Option<&str>,
) -> String {
    let paint = |code: &str, s: &str| -> String {
        if color {
            format!("\u{1b}[{code}m{s}\u{1b}[0m")
        } else {
            s.to_string()
        }
    };
    let mut out = String::new();
    // Entries arrive top-down (leaves first, base-most branch last); forked
    // subtrees sit directly above their fork parent, one indent level in.
    for e in entries {
        let is_current = e.branch == current;
        let margin = if is_current {
            paint("1;32", "")
        } else {
            "  ".to_string()
        };
        let pad = "  ".repeat(e.indent);
        let node = if is_current { "" } else { "" };
        let name = paint("1", &e.branch);
        let link = |n: u64| -> String {
            match link_base {
                Some(base_url) => {
                    format!("\u{1b}]8;;{base_url}/pull/{n}\u{1b}\\#{n}\u{1b}]8;;\u{1b}\\")
                }
                None => format!("#{n}"),
            }
        };
        let pr = match &e.pr {
            // status/log never touch the network: the number is cached
            // locally, but the live state is only known after submit/sync —
            // show just the number rather than a cryptic placeholder.
            Some(p) if p.state == "?" => format!("  {}", link(p.number)),
            Some(p) => {
                let state = match p.state.as_str() {
                    "OPEN" => paint("32", "OPEN"),
                    "MERGED" => paint("35", "MERGED"),
                    "CLOSED" => paint("31", "CLOSED"),
                    other => other.to_string(),
                };
                format!("  {} [{state}]", link(p.number))
            }
            None => String::new(),
        };
        let warn = if e.conflicted {
            paint("33", "  ⚠ conflicts")
        } else {
            String::new()
        };
        out.push_str(&format!("{margin}{pad}{node} {name}{pr}{warn}\n"));
        for path in &e.conflicts {
            out.push_str(&format!(
                "      {pad}{}\n",
                paint("33", &format!("{path}"))
            ));
        }
        for (id, subject) in &e.commits {
            // Abbreviate the id to `q-` + 8 chars.
            let abbrev = match id {
                Some(id) => {
                    let short: String = id.chars().take(10).collect();
                    paint("36", &format!("{short:<10}"))
                }
                None => paint("2", "(no id)   "),
            };
            out.push_str(&format!("      {pad}{abbrev}  {subject}\n"));
        }
    }
    out.push_str("\n");
    let label = if base_is_trunk { "trunk" } else { "base" };
    out.push_str(&format!("    {base} ({label})\n"));
    out
}

/// A classified line of a unified diff, so the TUI diff pane can colour
/// `+`/`-`/hunk lines (ADR: our own colouring, no syntax highlighting) and
/// render binary changes as a placeholder. The mapping to terminal styles
/// lives in the view; this classification is pure and unit-tested.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(crate) enum DiffLine {
    /// An added line (`+…`, but not the `+++` file header).
    Added,
    /// A removed line (`-…`, but not the `---` file header).
    Removed,
    /// A hunk header (`@@ … @@`).
    Hunk,
    /// File-level metadata (`diff --git`, `index`, `--- `, `+++ `, mode and
    /// rename/copy lines).
    FileHeader,
    /// A binary-file change git renders as a placeholder rather than content.
    Binary,
    /// An unchanged context line (or anything unrecognised).
    Context,
}

/// Classify one raw line of `git show`/`git diff` output. The `---`/`+++`
/// file headers are matched before the `+`/`-` content cases, so they never
/// read as removed/added lines.
pub(crate) fn classify_diff_line(line: &str) -> DiffLine {
    if line.starts_with("@@") {
        DiffLine::Hunk
    } else if line.starts_with("diff --git")
        || line.starts_with("index ")
        || line.starts_with("--- ")
        || line.starts_with("+++ ")
        || line.starts_with("new file")
        || line.starts_with("deleted file")
        || line.starts_with("old mode")
        || line.starts_with("new mode")
        || line.starts_with("rename ")
        || line.starts_with("copy ")
        || line.starts_with("similarity ")
        || line.starts_with("dissimilarity ")
    {
        DiffLine::FileHeader
    } else if line.starts_with("Binary files") || line.starts_with("GIT binary patch") {
        DiffLine::Binary
    } else if line.starts_with('+') {
        DiffLine::Added
    } else if line.starts_with('-') {
        DiffLine::Removed
    } else {
        DiffLine::Context
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]
    use super::*;

    #[test]
    fn classifies_diff_lines_headers_before_content() {
        use DiffLine::*;
        assert_eq!(classify_diff_line("@@ -1,3 +1,4 @@ fn main"), Hunk);
        assert_eq!(classify_diff_line("diff --git a/x b/x"), FileHeader);
        assert_eq!(classify_diff_line("index 0000..1111 100644"), FileHeader);
        // The file headers must win over the +/- content rules.
        assert_eq!(classify_diff_line("--- a/x"), FileHeader);
        assert_eq!(classify_diff_line("+++ b/x"), FileHeader);
        assert_eq!(classify_diff_line("new file mode 100644"), FileHeader);
        assert_eq!(classify_diff_line("+added line"), Added);
        assert_eq!(classify_diff_line("-removed line"), Removed);
        assert_eq!(classify_diff_line(" context"), Context);
        assert_eq!(
            classify_diff_line("Binary files a/i.png and b/i.png differ"),
            Binary
        );
    }

    #[test]
    fn strips_prior_number_prefix() {
        assert_eq!(numbered_title("[2/9] Add widget", 0, 3), "[1/3] Add widget");
        assert_eq!(numbered_title("Add widget", 2, 3), "[3/3] Add widget");
        // Not a number prefix -> left intact.
        assert_eq!(numbered_title("[wip] thing", 0, 1), "[1/1] [wip] thing");
    }

    #[test]
    fn compose_builds_sections_and_stays_idempotent() {
        // A branch description that still contains an old managed block.
        let branch_desc = format!("{BEGIN}\nold\n{END}\n\n---\n\nHello");
        let composed = compose_body("The plan.", &branch_desc, "new-nav");
        assert!(composed.starts_with(BEGIN));
        assert!(composed.ends_with(END));
        assert!(composed.contains("new-nav"));
        assert!(!composed.contains("old"), "old nav must be stripped");
        assert!(composed.contains("# About this queue\n\nThe plan."));
        assert!(composed.contains("# About this branch\n\nHello"));
        assert_eq!(composed.matches(BEGIN).count(), 1);
    }

    #[test]
    fn compose_omits_empty_sections() {
        let composed = compose_body("", "", "nav");
        assert_eq!(composed, format!("{BEGIN}\nnav\n{END}"));
        let q_only = compose_body("Q.", "", "nav");
        assert!(q_only.contains("About this queue") && !q_only.contains("About this branch"));
    }

    fn entry(branch: &str, number: u64, url: &str, state: &str, review: Option<&str>) -> Entry {
        Entry {
            branch: branch.to_string(),
            pr: Some(PrRef {
                number,
                url: url.to_string(),
                state: state.to_string(),
                review: review.map(std::string::ToString::to_string),
            }),
            conflicted: false,
            conflicts: Vec::new(),
            commits: Vec::new(),
            indent: 0,
        }
    }

    #[test]
    fn gate_plan_marks_bottom_ready_and_blocks_the_rest() {
        let line = vec![
            entry("api", 10, "https://x/pull/10", "OPEN", None),
            entry("service", 11, "https://x/pull/11", "OPEN", None),
            entry("ui", 12, "https://x/pull/12", "OPEN", None),
        ];
        let plan = gate_plan(&line);
        assert_eq!(plan.len(), 3);
        assert!(plan[0].success);
        assert_eq!(plan[0].branch, "api");
        assert_eq!(plan[0].target_url, None);
        for s in &plan[1..] {
            assert!(!s.success);
            assert!(s.description.contains("#10"), "{}", s.description);
            assert_eq!(s.target_url.as_deref(), Some("https://x/pull/10"));
        }
    }

    #[test]
    fn gate_plan_skips_merged_and_promotes_next_open_pr() {
        let line = vec![
            entry("api", 10, "https://x/pull/10", "MERGED", None),
            entry("service", 11, "https://x/pull/11", "OPEN", None),
            entry("ui", 12, "https://x/pull/12", "OPEN", None),
        ];
        let plan = gate_plan(&line);
        assert_eq!(plan.len(), 2);
        assert!(plan[0].success);
        assert_eq!(plan[0].branch, "service");
        assert!(!plan[1].success);
        assert!(
            plan[1].description.contains("#11"),
            "{}",
            plan[1].description
        );
    }

    #[test]
    fn gate_plan_ignores_closed_prs_and_unsubmitted_branches() {
        let mut line = vec![
            entry("api", 10, "https://x/pull/10", "CLOSED", None),
            entry("service", 11, "https://x/pull/11", "OPEN", None),
        ];
        line.push(Entry {
            branch: "ui".to_string(),
            pr: None,
            conflicted: false,
            conflicts: Vec::new(),
            commits: Vec::new(),
            indent: 0,
        });
        let plan = gate_plan(&line);
        assert_eq!(plan.len(), 1);
        assert!(plan[0].success);
        assert_eq!(plan[0].branch, "service");
    }

    #[test]
    fn gate_plan_is_empty_when_no_pr_is_open() {
        let line = vec![
            entry("api", 10, "https://x/pull/10", "MERGED", None),
            entry("service", 11, "https://x/pull/11", "CLOSED", None),
        ];
        assert!(gate_plan(&line).is_empty());
        assert!(gate_plan(&[]).is_empty());
    }

    #[test]
    fn gate_plan_descriptions_fit_github_status_limit() {
        // The GitHub statuses API caps descriptions at 140 characters.
        let line = vec![
            entry(
                "api",
                4_294_967_295,
                "https://x/pull/4294967295",
                "OPEN",
                None,
            ),
            entry("ui", 12, "https://x/pull/12", "OPEN", None),
        ];
        for s in gate_plan(&line) {
            assert!(s.description.len() <= 140, "{}", s.description);
        }
    }

    #[test]
    fn nav_block_links_marks_current_and_shows_status() {
        let line = vec![
            entry("api", 10, "https://x/pull/10", "MERGED", Some("APPROVED")),
            entry(
                "service",
                11,
                "https://x/pull/11",
                "OPEN",
                Some("CHANGES_REQUESTED"),
            ),
            entry("ui", 12, "https://x/pull/12", "OPEN", None),
        ];
        let nav = nav_block(&line, "service", "main", "payments");
        assert!(nav.contains("📚 payments PR"), "{nav}");
        // Merged PR: state emoji only (approval no longer meaningful).
        assert!(
            nav.contains("🟣 [#10 `api`](https://x/pull/10) → `main`"),
            "{nav}"
        );
        // Current PR: emojis, then bolded label targeting the branch below.
        assert!(
            nav.contains("♻️🟢 **[#11 `service`](https://x/pull/11) → `api`**"),
            "{nav}"
        );
        // Not-yet-reviewed open PR.
        assert!(nav.contains("⏳🟢 [#12 `ui`]"), "{nav}");
        assert!(nav.contains("👈 **this PR**"));
        assert!(nav.contains("2 of 3"));
        assert!(nav.contains("FIFO"), "merge order described as FIFO");
        assert!(
            !nav.contains("bottom-first"),
            "confusing bottom-first wording removed"
        );
    }
}