Skip to main content

release_kit/commands/
issue.rs

1//! `rk issue start`: one command from an issue to the branch the forge
2//! named, seated the way the recorded mode says.
3//!
4//! Not a worktree verb, because the worktree verbs are mode-free by
5//! design and starting from an issue is not: branches mode has no
6//! worktree to add. The order of the run is what makes the refusals
7//! cheap — the local reads and the reference check come first, the
8//! forge-CLI gate next, and the network last — so every failure but a
9//! forge outage costs one local process and leaves the clone untouched.
10
11use camino::{Utf8Path, Utf8PathBuf};
12use serde::Serialize;
13
14use crate::cli::issue::{IssueAction, IssueArgs};
15use crate::detect::{self, Forge};
16use crate::diagnostic::{Diagnostic, Reason};
17use crate::error::RkError;
18use crate::issue::{self, Resolved};
19use crate::landing::manifest::{self, CheckoutMode};
20use crate::output::Output;
21use crate::setup::context::resolve_cli;
22
23/// One `rk issue start` report.
24#[derive(Debug, Serialize)]
25struct StartReport {
26    /// The shape version of this JSON.
27    schema: &'static str,
28    /// `preview` or `apply`.
29    mode: &'static str,
30    /// The forge acted on.
31    forge: &'static str,
32    /// The project path.
33    repo: String,
34    /// The issue, as the forge numbers it.
35    issue: u64,
36    /// The issue's title.
37    title: String,
38    /// The branch, where one is known.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    branch: Option<String>,
41    /// Where the name came from: `already`, `forge`, or `pending`.
42    origin: &'static str,
43    /// The recorded checkout mode this run seated by.
44    checkout_mode: &'static str,
45    /// The worktree path, under worktree mode.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    path: Option<String>,
48    /// The branch checked out in place, under branches mode.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    checkout: Option<String>,
51    /// Every other branch the forge links to this issue.
52    #[serde(skip_serializing_if = "Vec::is_empty")]
53    others: Vec<String>,
54    /// A state the operator must see rather than one rk decided quietly.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    detail: Option<String>,
57    /// What to run next.
58    next: Vec<String>,
59}
60
61/// Dispatch the issue surface.
62///
63/// # Errors
64///
65/// Refuses a target that is not a repository, a reference that names
66/// another project, an undetected forge, a forge CLI below its floor, a
67/// GitLab template rendering a name the landed grammar refuses, and every
68/// seating refusal `rk worktree add` already carries.
69pub fn run(args: &IssueArgs) -> Result<(), RkError> {
70    crate::requirements::require("rk issue", &[crate::requirements::Tool::Git])?;
71    match &args.action {
72        IssueAction::Start {
73            issue,
74            target,
75            forge,
76            repo,
77            workflow,
78            base,
79            apply,
80            json,
81        } => start(
82            target,
83            issue,
84            &Overrides {
85                forge: forge.as_deref(),
86                repo: repo.as_deref(),
87                workflow: workflow.as_deref(),
88                base: base.as_deref(),
89            },
90            *apply,
91            Output::new(*json),
92        ),
93    }
94}
95
96/// What the operator overrode, where detection or the record would
97/// otherwise decide.
98struct Overrides<'a> {
99    /// The forge, over the detected one.
100    forge: Option<&'a str>,
101    /// The project path, over the detected one.
102    repo: Option<&'a str>,
103    /// The workflow mode, over the recorded one.
104    workflow: Option<&'a str>,
105    /// The commit-ish a new branch starts from.
106    base: Option<&'a str>,
107}
108
109/// Everything the local reads settled, before the first forge call.
110struct Ground {
111    /// The forge to act on.
112    forge: Forge,
113    /// The project path.
114    repo: String,
115    /// The API host to name explicitly, where one has to be named.
116    ///
117    /// The reference's host alone, because an issue URL is a web address
118    /// and its host is the instance. A remote's host is a transport
119    /// host, which a self-managed instance may serve under a separate
120    /// name — `git@ssh.example.com` for `example.com` — so naming it
121    /// would send the API calls somewhere the forge CLI already resolves
122    /// correctly from the working directory.
123    api_host: Option<String>,
124    /// The mode the seat follows.
125    workflow: CheckoutMode,
126    /// Where the mode came from, for the report.
127    workflow_source: &'static str,
128}
129
130/// Refuse a coordinate that disagrees with one the clone already knows.
131///
132/// A coordinate the clone does not know is absent rather than
133/// contradicted, which is what leaves an override its real job.
134fn contradicts(what: &str, chosen: Option<&str>, known: Option<&str>) -> Result<(), RkError> {
135    let (Some(chosen), Some(known)) = (chosen, known) else {
136        return Ok(());
137    };
138    if chosen == known {
139        return Ok(());
140    }
141    Err(RkError::Usage(format!(
142        "the {what} to act on is {chosen} and this clone's is {known}; the branch would be minted on one project and seated in another"
143    )))
144}
145
146/// The mode the seat follows, and what decided it.
147///
148/// The mode is a landing parameter, changed through the landing verbs
149/// alone, so a runtime flag states it rather than sets it. Where it
150/// disagrees with the record, one clone would work in a mode the
151/// committed project policy does not carry.
152fn mode_of(
153    target: &Utf8Path,
154    named: Option<&str>,
155) -> Result<(CheckoutMode, &'static str), RkError> {
156    let recorded = manifest::load(target)?.map(|held| held.git.checkout_mode);
157    match (named, recorded) {
158        (Some(raw), Some(held)) => {
159            if CheckoutMode::parse(raw)? != held {
160                return Err(RkError::refusal(
161                    Diagnostic::new(
162                        Reason::StateDrift,
163                        format!(
164                            "--checkout-mode {raw} disagrees with the landing record, which states {}",
165                            held.as_str()
166                        ),
167                    )
168                    .expected("a flag that states the recorded mode, or no flag at all")
169                    .action("rk upgrade --checkout-mode <mode> --apply changes the recorded mode")
170                    .target_state("unchanged"),
171                ));
172            }
173            Ok((held, "the landing record, restated by --checkout-mode"))
174        }
175        (Some(raw), None) => Ok((CheckoutMode::parse(raw)?, "the --checkout-mode flag")),
176        (None, Some(held)) => Ok((held, "the landing record")),
177        // A target with no record is treated as the convention's own
178        // mode rather than as branches: the record's serde default exists
179        // for records written before the parameter, not for targets that
180        // never landed.
181        (None, None) => Ok((
182            CheckoutMode::LinkedWorktree,
183            "the default, with no landing record",
184        )),
185    }
186}
187
188/// Refuse a forge on a host this verb's calls would not reach.
189///
190/// Every GitHub call here goes to the CLI's default host. An enterprise
191/// remote reaches this verb only through `--forge`, and acting on the
192/// wrong host is worse than saying plainly that this verb carries one.
193fn reachable(forge: Forge, host: Option<&str>) -> Result<(), RkError> {
194    let Some(host) = host else { return Ok(()) };
195    if forge != Forge::Github || host.eq_ignore_ascii_case("github.com") {
196        return Ok(());
197    }
198    Err(RkError::refusal(
199        Diagnostic::new(
200            Reason::ForgeUnsupported,
201            format!("this clone's origin is {host}, and rk issue start reaches github.com alone"),
202        )
203        .expected("a github.com remote, or a GitLab project")
204        .action(
205            "start the branch with gh issue develop --repo <host>/<owner>/<name>, then rk worktree add it",
206        )
207        .target_state("unchanged"),
208    ))
209}
210
211/// Read the target, the reference, and the recorded mode. Nothing here
212/// touches the network, so every refusal below costs one local read.
213fn ground(
214    target: &Utf8Path,
215    reference: &issue::Reference,
216    overrides: &Overrides<'_>,
217) -> Result<Ground, RkError> {
218    if !target.is_dir() {
219        return Err(RkError::missing(
220            Diagnostic::new(
221                Reason::TargetNotFound,
222                format!("target {target} is not a directory"),
223            )
224            .expected("an existing repository to act on"),
225        ));
226    }
227    let named = overrides
228        .forge
229        .map(|name| {
230            Forge::parse(name).ok_or_else(|| {
231                RkError::Usage(format!(
232                    "unknown forge '{name}'; the forges are: github, gitlab"
233                ))
234            })
235        })
236        .transpose()?;
237    let detected = detect::detect(target.as_std_path());
238    // The reference is held to the clone before anything else: an agent
239    // pasting a URL while sitting in another checkout would otherwise
240    // mint on one project and seat in another.
241    issue::agrees(reference, &detected).map_err(RkError::Usage)?;
242    let Some(forge) = named.or(detected.forge) else {
243        let diagnostic = detected
244            .host
245            .as_ref()
246            .map_or_else(
247                || {
248                    Diagnostic::new(
249                        Reason::ForgeUndetected,
250                        "no forge detected: the target has no origin remote",
251                    )
252                },
253                |host| {
254                    Diagnostic::new(
255                        Reason::ForgeUndetected,
256                        format!("no forge detected: the host {host} is not recognized"),
257                    )
258                },
259            )
260            .expected("a github.com or gitlab remote, or an override")
261            .action("pass --forge <github|gitlab>, and --repo <path> if the remote is absent");
262        return Err(if detected.host.is_some() {
263            RkError::refusal(diagnostic)
264        } else {
265            RkError::missing(diagnostic)
266        });
267    };
268    // The reference names a host too, and it is authoritative where the
269    // clone has none: an issue URL for another host must not be acted on
270    // at the CLI's default one.
271    reachable(
272        forge,
273        detected.host.as_deref().or(reference.host.as_deref()),
274    )?;
275    // An override supplies a coordinate detection could not, and never
276    // replaces one it could: minting on the project the operator named
277    // and seating the branch in the clone they are standing in is the
278    // same cross-project mistake the reference check refuses.
279    contradicts(
280        "forge",
281        named.map(Forge::as_str),
282        detected.forge.map(Forge::as_str),
283    )?;
284    let Some(repo) = overrides
285        .repo
286        .map(str::to_owned)
287        .or_else(|| reference.repo.clone())
288        .or_else(|| detected.repo.clone())
289    else {
290        return Err(RkError::missing(
291            Diagnostic::new(
292                Reason::ForgeUndetected,
293                "no repository detected: the target has no origin remote",
294            )
295            .expected("an origin remote naming the project")
296            .action("pass --repo <owner/name>"),
297        ));
298    };
299    contradicts("repository", Some(repo.as_str()), detected.repo.as_deref())?;
300    contradicts("repository", Some(repo.as_str()), reference.repo.as_deref())?;
301    let (workflow, workflow_source) = mode_of(target, overrides.workflow)?;
302    Ok(Ground {
303        forge,
304        repo,
305        api_host: reference.host.clone(),
306        workflow,
307        workflow_source,
308    })
309}
310
311/// Mint the issue's branch at the forge and seat it.
312fn start(
313    target: &Utf8Path,
314    reference: &str,
315    overrides: &Overrides<'_>,
316    apply: bool,
317    out: Output,
318) -> Result<(), RkError> {
319    let reference = issue::parse_reference(reference).map_err(RkError::Usage)?;
320    let ground = ground(target, &reference, overrides)?;
321    // The target is a repository before anything reaches the network.
322    // Without this, a mint could succeed and the run then fail on a
323    // local prerequisite, leaving a remote branch no report accounts for.
324    let main = crate::commands::worktree::main_checkout(target)?;
325    // The gate before the first forge call, so a stale CLI costs one
326    // local process rather than a half-finished remote change.
327    crate::requirements::require(
328        "rk issue start",
329        &[crate::requirements::Tool::ForgeCli(ground.forge)],
330    )?;
331    let cli = resolve_cli(ground.forge)?;
332    // Where the forge lets rk know the name before it writes, every
333    // local refusal the seat carries runs first.
334    let seatable = |branch: &str| -> Result<(), RkError> {
335        match ground.workflow {
336            CheckoutMode::LinkedWorktree => {
337                crate::commands::worktree::plan_seat(target, branch, overrides.base, false)
338                    .map(|_| ())
339            }
340            CheckoutMode::MainWorktree => branch_seatable(&main, branch),
341        }
342    };
343    let resolved = issue::resolve(
344        &cli,
345        target.as_std_path(),
346        &issue::Ask {
347            forge: ground.forge,
348            repo: &ground.repo,
349            reference: &reference,
350            host: ground.api_host.as_deref(),
351            base: overrides.base,
352            apply,
353            seatable: &seatable,
354        },
355    )?;
356    match ground.workflow {
357        CheckoutMode::LinkedWorktree => {
358            seat_worktree(target, &ground, &resolved, overrides.base, apply, out)
359        }
360        CheckoutMode::MainWorktree => seat_branch(&main, &ground, &resolved, apply, out),
361    }
362}
363
364/// Worktree mode: the derived sibling path, through the same planning and
365/// the same refusals `rk worktree add` uses.
366fn seat_worktree(
367    target: &Utf8Path,
368    ground: &Ground,
369    resolved: &Resolved,
370    base: Option<&str>,
371    apply: bool,
372    out: Output,
373) -> Result<(), RkError> {
374    let Some(branch) = resolved.branch.as_deref() else {
375        return report(out, ground, resolved, None, None, apply);
376    };
377    let seat = crate::commands::worktree::plan_seat(target, branch, base, apply)?;
378    let mut note = None;
379    let path = match seat {
380        crate::commands::worktree::Seat::Satisfied { path } => path,
381        crate::commands::worktree::Seat::Fresh {
382            path,
383            source,
384            detail,
385        } => {
386            // An apply refreshes first, and `detail` is set only where
387            // that refresh failed. A remote-tracking ref left over from
388            // an older fetch is not the tip the forge holds now, so it
389            // is not something to seat from and call success.
390            if apply && let Some(why) = detail {
391                return Err(stale_refs(branch, resolved, &why));
392            }
393            // The forge holds this branch, so the seat comes from its
394            // real tip — an adopted local branch, or the remote-tracking
395            // ref. Anything else would build a same-named branch sharing
396            // none of the forge's history. A preview says so, because it
397            // does not fetch and the refs it reads may simply be stale;
398            // an apply fetched first, so there it is a refusal.
399            if !matches!(source.kind, "adopted" | "remote") {
400                if apply {
401                    return Err(unreachable_tip(branch, resolved));
402                }
403                note = Some(format!(
404                    "origin/{branch} is not in this clone yet; the apply fetches first, and refuses rather than seat a branch from the trunk"
405                ));
406            }
407            if apply {
408                crate::commands::worktree::create_seat(target, &source)?;
409            }
410            path
411        }
412    };
413    report_with(out, ground, resolved, Some(path), None, apply, note)
414}
415
416/// The branch the forge holds is not reachable locally, so no seat is
417/// made from something else that happens to share its name.
418fn unreachable_tip(branch: &str, resolved: &Resolved) -> RkError {
419    RkError::refusal(
420        Diagnostic::new(
421            Reason::StateDrift,
422            format!("the forge carries {branch} and this clone cannot reach its tip"),
423        )
424        .expected(format!(
425            "origin/{branch} present, or {branch} already local"
426        ))
427        .action("git fetch origin, then rerun")
428        .target_state(format!(
429            "unchanged; issue #{} keeps its branch at the forge",
430            resolved.number
431        )),
432    )
433}
434
435/// What the branches-mode checkout needs, checked before the forge is
436/// written to.
437///
438/// `git switch` refuses a branch another worktree has checked out, and it
439/// refuses to move a working tree whose changes it would lose. Both are
440/// knowable here, and a branch created at the forge and then refused
441/// locally is a remote change no report accounts for.
442///
443/// The second check is deliberately stricter than git, which permits a
444/// switch whose changes do not conflict. Whether they conflict is not
445/// knowable without doing the switch, and this mode seats a branch the
446/// operator is about to start work on: a clean checkout is what that
447/// asks for, and the remedy is one command.
448fn branch_seatable(main: &Utf8Path, branch: &str) -> Result<(), RkError> {
449    let trunk = crate::config::trunk_of(main.as_std_path())?;
450    if let Some(seat) = crate::commands::worktree::seat_of(main, branch)? {
451        if seat != main {
452            return Err(RkError::refusal(
453                Diagnostic::new(
454                    Reason::StateDrift,
455                    format!(
456                        "branch {branch} is checked out at {seat}, and one branch has one seat"
457                    ),
458                )
459                .expected("the branch free, or already in the main checkout")
460                .action(format!("git -C {seat} switch {trunk}, then rerun"))
461                .target_state("unchanged"),
462            ));
463        }
464        // The branch is already seated here, so nothing is checked out
465        // over anything: the switch is a no-op and carries no risk.
466        return Ok(());
467    }
468    let held = crate::commands::worktree::git(main, &["status", "--porcelain"])?;
469    // A probe that cannot answer counts as dirty: this runs before a
470    // remote write, so the closed direction is the safe one.
471    if !held.status.success() || !held.stdout.is_empty() {
472        return Err(RkError::refusal(
473            Diagnostic::new(
474                Reason::StateDrift,
475                format!("{main} carries uncommitted work, and this mode checks {branch} out there"),
476            )
477            .expected("a clean main checkout to seat the branch in")
478            .action("commit or stash the work, then rerun")
479            .target_state("unchanged"),
480        ));
481    }
482    Ok(())
483}
484
485/// The refresh failed, so no local ref is proof of what the forge holds.
486fn stale_refs(branch: &str, resolved: &Resolved, why: &str) -> RkError {
487    RkError::refusal(
488        Diagnostic::new(
489            Reason::StateDrift,
490            format!(
491                "this clone could not refresh from the forge, so its {branch} may be stale: {why}"
492            ),
493        )
494        .expected("a fetch that answered, so the seat starts from the tip the forge holds")
495        .action("git fetch origin, then rerun")
496        .target_state(format!(
497            "unchanged; issue #{} keeps its branch at the forge",
498            resolved.number
499        )),
500    )
501}
502
503/// Branches mode: the branch checked out in the main checkout.
504///
505/// The main checkout is where this mode works branches, so the switch
506/// runs there whichever of the repository's worktrees `--target` named.
507///
508/// Both forges create the branch on the remote, so an apply always sees
509/// the same case — a remote tip with no local branch — unless a previous
510/// run already made one.
511fn seat_branch(
512    main: &Utf8Path,
513    ground: &Ground,
514    resolved: &Resolved,
515    apply: bool,
516    out: Output,
517) -> Result<(), RkError> {
518    let Some(branch) = resolved.branch.as_deref() else {
519        return report(out, ground, resolved, None, None, apply);
520    };
521    if !apply {
522        return report(out, ground, resolved, None, Some(branch.to_owned()), false);
523    }
524    // Through the shared runner, which scrubs the hook variables: a run
525    // from inside a git hook must act on the named checkout and never on
526    // the hook's own repository.
527    let git = |args: &[&str]| crate::commands::worktree::git(main, args);
528    let fetched = git(&["fetch", "origin"])?;
529    if !fetched.status.success() {
530        return Err(stale_refs(branch, resolved, &last_line(&fetched.stderr)));
531    }
532    let local = git(&[
533        "rev-parse",
534        "--verify",
535        "--quiet",
536        "--end-of-options",
537        &format!("refs/heads/{branch}^{{commit}}"),
538    ])?;
539    let switched = if local.status.success() {
540        git(&["switch", branch])?
541    } else {
542        git(&[
543            "switch",
544            "--track",
545            "-c",
546            branch,
547            &format!("refs/remotes/origin/{branch}"),
548        ])?
549    };
550    if !switched.status.success() {
551        // git refuses a dirty switch itself, so its own last line is the
552        // honest reason rather than one rk invents.
553        return Err(RkError::subprocess(
554            Diagnostic::new(
555                Reason::SubprocessFailed,
556                format!(
557                    "git refused to check out {branch}: {}",
558                    last_line(&switched.stderr)
559                ),
560            )
561            .expected("a working tree the checkout can move")
562            .target_state("the branch exists on the forge and is not checked out here"),
563        ));
564    }
565    report(out, ground, resolved, None, Some(branch.to_owned()), true)
566}
567
568/// One report, in either mode.
569fn report(
570    out: Output,
571    ground: &Ground,
572    resolved: &Resolved,
573    path: Option<Utf8PathBuf>,
574    checkout: Option<String>,
575    apply: bool,
576) -> Result<(), RkError> {
577    report_with(out, ground, resolved, path, checkout, apply, None)
578}
579
580/// [`report`], carrying a note the seating step raised.
581fn report_with(
582    out: Output,
583    ground: &Ground,
584    resolved: &Resolved,
585    path: Option<Utf8PathBuf>,
586    checkout: Option<String>,
587    apply: bool,
588    note: Option<String>,
589) -> Result<(), RkError> {
590    let mode = if apply { "apply" } else { "preview" };
591    out.result_line(format!("issue:  #{} {}", resolved.number, resolved.title));
592    out.result_line(format!(
593        "branch: {}  ({})",
594        resolved.branch.as_deref().unwrap_or("named by the forge"),
595        match resolved.origin {
596            "already" => "already linked at the forge",
597            "forge" => "minted at the forge",
598            _ => "not minted yet",
599        }
600    ));
601    out.result_line(format!(
602        "seat:   {} ({} says so)",
603        path.as_ref().map_or_else(
604            || checkout.as_deref().map_or_else(
605                || "unknown".to_owned(),
606                |branch| format!("checkout {branch}")
607            ),
608            ToString::to_string
609        ),
610        ground.workflow_source
611    ));
612    if !resolved.others.is_empty() {
613        out.warn(format!(
614            "the issue carries other linked branches, and the first was taken: {}",
615            resolved.others.join(", ")
616        ));
617    }
618    let detail = match (resolved.detail.clone(), note) {
619        (Some(had), Some(note)) => Some(format!("{had}; {note}")),
620        (Some(one), None) | (None, Some(one)) => Some(one),
621        (None, None) => None,
622    };
623    if let Some(detail) = &detail {
624        out.warn(detail);
625    }
626    let next = next_lines(ground, resolved, path.as_ref(), apply);
627    out.next(&next);
628    out.emit(&StartReport {
629        schema: "rk.issue-start/2",
630        mode,
631        forge: ground.forge.as_str(),
632        repo: ground.repo.clone(),
633        issue: resolved.number,
634        title: resolved.title.clone(),
635        branch: resolved.branch.clone(),
636        origin: resolved.origin,
637        checkout_mode: ground.workflow.as_str(),
638        path: path.map(|path| path.to_string()),
639        checkout,
640        others: resolved.others.clone(),
641        detail,
642        next,
643    })
644}
645
646/// What to run next, which differs by mode and by whether this ran.
647fn next_lines(
648    ground: &Ground,
649    resolved: &Resolved,
650    path: Option<&Utf8PathBuf>,
651    apply: bool,
652) -> Vec<String> {
653    if !apply {
654        return vec![format!(
655            "rk issue start {} --apply mints the branch and seats it",
656            resolved.number
657        )];
658    }
659    match (ground.workflow, path) {
660        (CheckoutMode::LinkedWorktree, Some(path)) => vec![
661            format!("cd {path}"),
662            "rk worktree list reports every seat".to_owned(),
663        ],
664        _ => vec!["rk status reports what this target carries".to_owned()],
665    }
666}
667
668/// The last non-empty stderr line, for a one-line reason.
669fn last_line(bytes: &[u8]) -> String {
670    String::from_utf8_lossy(bytes)
671        .lines()
672        .rev()
673        .find(|line| !line.trim().is_empty())
674        .unwrap_or("no output")
675        .to_owned()
676}