1use 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#[derive(Debug, Serialize)]
25struct StartReport {
26 schema: &'static str,
28 mode: &'static str,
30 forge: &'static str,
32 repo: String,
34 issue: u64,
36 title: String,
38 #[serde(skip_serializing_if = "Option::is_none")]
40 branch: Option<String>,
41 origin: &'static str,
43 checkout_mode: &'static str,
45 #[serde(skip_serializing_if = "Option::is_none")]
47 path: Option<String>,
48 #[serde(skip_serializing_if = "Option::is_none")]
50 checkout: Option<String>,
51 #[serde(skip_serializing_if = "Vec::is_empty")]
53 others: Vec<String>,
54 #[serde(skip_serializing_if = "Option::is_none")]
56 detail: Option<String>,
57 next: Vec<String>,
59}
60
61pub 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
96struct Overrides<'a> {
99 forge: Option<&'a str>,
101 repo: Option<&'a str>,
103 workflow: Option<&'a str>,
105 base: Option<&'a str>,
107}
108
109struct Ground {
111 forge: Forge,
113 repo: String,
115 api_host: Option<String>,
124 workflow: CheckoutMode,
126 workflow_source: &'static str,
128}
129
130fn 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
146fn 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 (None, None) => Ok((
182 CheckoutMode::LinkedWorktree,
183 "the default, with no landing record",
184 )),
185 }
186}
187
188fn 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
211fn 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 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 reachable(
272 forge,
273 detected.host.as_deref().or(reference.host.as_deref()),
274 )?;
275 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
311fn 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 let main = crate::commands::worktree::main_checkout(target)?;
325 crate::requirements::require(
328 "rk issue start",
329 &[crate::requirements::Tool::ForgeCli(ground.forge)],
330 )?;
331 let cli = resolve_cli(ground.forge)?;
332 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
364fn 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 if apply && let Some(why) = detail {
391 return Err(stale_refs(branch, resolved, &why));
392 }
393 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
416fn 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
435fn 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 return Ok(());
467 }
468 let held = crate::commands::worktree::git(main, &["status", "--porcelain"])?;
469 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
485fn 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
503fn 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 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 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
568fn 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
580fn 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
646fn 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
668fn 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}