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, Workflow};
20use crate::output::Output;
21use crate::probes;
22use crate::setup::context::resolve_cli;
23
24#[derive(Debug, Serialize)]
26struct StartReport {
27 schema: &'static str,
29 mode: &'static str,
31 forge: &'static str,
33 repo: String,
35 issue: u64,
37 title: String,
39 #[serde(skip_serializing_if = "Option::is_none")]
41 branch: Option<String>,
42 origin: &'static str,
44 workflow: &'static str,
46 #[serde(skip_serializing_if = "Option::is_none")]
48 path: Option<String>,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 checkout: Option<String>,
52 #[serde(skip_serializing_if = "Vec::is_empty")]
54 others: Vec<String>,
55 #[serde(skip_serializing_if = "Option::is_none")]
57 detail: Option<String>,
58 next: Vec<String>,
60}
61
62pub fn run(args: &IssueArgs) -> Result<(), RkError> {
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: Workflow,
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(target: &Utf8Path, named: Option<&str>) -> Result<(Workflow, &'static str), RkError> {
153 let recorded = manifest::load(target)?.map(|held| held.parameters.workflow);
154 match (named, recorded) {
155 (Some(raw), Some(held)) => {
156 if Workflow::parse(raw)? != held {
157 return Err(RkError::refusal(
158 Diagnostic::new(
159 Reason::StateDrift,
160 format!(
161 "--workflow {raw} disagrees with the landing record, which states {}",
162 held.as_str()
163 ),
164 )
165 .expected("a flag that states the recorded mode, or no flag at all")
166 .action("rk upgrade --workflow <mode> --apply changes the recorded mode")
167 .target_state("unchanged"),
168 ));
169 }
170 Ok((held, "the landing record, restated by --workflow"))
171 }
172 (Some(raw), None) => Ok((Workflow::parse(raw)?, "the --workflow flag")),
173 (None, Some(held)) => Ok((held, "the landing record")),
174 (None, None) => Ok((Workflow::Worktree, "the default, with no landing record")),
179 }
180}
181
182fn reachable(forge: Forge, host: Option<&str>) -> Result<(), RkError> {
188 let Some(host) = host else { return Ok(()) };
189 if forge != Forge::Github || host.eq_ignore_ascii_case("github.com") {
190 return Ok(());
191 }
192 Err(RkError::refusal(
193 Diagnostic::new(
194 Reason::ForgeUnsupported,
195 format!("this clone's origin is {host}, and rk issue start reaches github.com alone"),
196 )
197 .expected("a github.com remote, or a GitLab project")
198 .action(
199 "start the branch with gh issue develop --repo <host>/<owner>/<name>, then rk worktree add it",
200 )
201 .target_state("unchanged"),
202 ))
203}
204
205fn ground(
208 target: &Utf8Path,
209 reference: &issue::Reference,
210 overrides: &Overrides<'_>,
211) -> Result<Ground, RkError> {
212 if !target.is_dir() {
213 return Err(RkError::missing(
214 Diagnostic::new(
215 Reason::TargetNotFound,
216 format!("target {target} is not a directory"),
217 )
218 .expected("an existing repository to act on"),
219 ));
220 }
221 let named = overrides
222 .forge
223 .map(|name| {
224 Forge::parse(name).ok_or_else(|| {
225 RkError::Usage(format!(
226 "unknown forge '{name}'; the forges are: github, gitlab"
227 ))
228 })
229 })
230 .transpose()?;
231 let detected = detect::detect(target.as_std_path());
232 issue::agrees(reference, &detected).map_err(RkError::Usage)?;
236 let Some(forge) = named.or(detected.forge) else {
237 let diagnostic = detected
238 .host
239 .as_ref()
240 .map_or_else(
241 || {
242 Diagnostic::new(
243 Reason::ForgeUndetected,
244 "no forge detected: the target has no origin remote",
245 )
246 },
247 |host| {
248 Diagnostic::new(
249 Reason::ForgeUndetected,
250 format!("no forge detected: the host {host} is not recognized"),
251 )
252 },
253 )
254 .expected("a github.com or gitlab remote, or an override")
255 .action("pass --forge <github|gitlab>, and --repo <path> if the remote is absent");
256 return Err(if detected.host.is_some() {
257 RkError::refusal(diagnostic)
258 } else {
259 RkError::missing(diagnostic)
260 });
261 };
262 reachable(
266 forge,
267 detected.host.as_deref().or(reference.host.as_deref()),
268 )?;
269 contradicts(
274 "forge",
275 named.map(Forge::as_str),
276 detected.forge.map(Forge::as_str),
277 )?;
278 let Some(repo) = overrides
279 .repo
280 .map(str::to_owned)
281 .or_else(|| reference.repo.clone())
282 .or_else(|| detected.repo.clone())
283 else {
284 return Err(RkError::missing(
285 Diagnostic::new(
286 Reason::ForgeUndetected,
287 "no repository detected: the target has no origin remote",
288 )
289 .expected("an origin remote naming the project")
290 .action("pass --repo <owner/name>"),
291 ));
292 };
293 contradicts("repository", Some(repo.as_str()), detected.repo.as_deref())?;
294 contradicts("repository", Some(repo.as_str()), reference.repo.as_deref())?;
295 let (workflow, workflow_source) = mode_of(target, overrides.workflow)?;
296 Ok(Ground {
297 forge,
298 repo,
299 api_host: reference.host.clone(),
300 workflow,
301 workflow_source,
302 })
303}
304
305fn start(
307 target: &Utf8Path,
308 reference: &str,
309 overrides: &Overrides<'_>,
310 apply: bool,
311 out: Output,
312) -> Result<(), RkError> {
313 let reference = issue::parse_reference(reference).map_err(RkError::Usage)?;
314 let ground = ground(target, &reference, overrides)?;
315 let main = crate::commands::worktree::main_checkout(target)?;
319 probes::require_forge_cli(ground.forge)?;
322 let cli = resolve_cli(ground.forge)?;
323 let seatable = |branch: &str| -> Result<(), RkError> {
326 match ground.workflow {
327 Workflow::Worktree => {
328 crate::commands::worktree::plan_seat(target, branch, overrides.base, false)
329 .map(|_| ())
330 }
331 Workflow::Branches => branch_seatable(&main, branch),
332 }
333 };
334 let resolved = issue::resolve(
335 &cli,
336 target.as_std_path(),
337 &issue::Ask {
338 forge: ground.forge,
339 repo: &ground.repo,
340 reference: &reference,
341 host: ground.api_host.as_deref(),
342 base: overrides.base,
343 apply,
344 seatable: &seatable,
345 },
346 )?;
347 match ground.workflow {
348 Workflow::Worktree => seat_worktree(target, &ground, &resolved, overrides.base, apply, out),
349 Workflow::Branches => seat_branch(&main, &ground, &resolved, apply, out),
350 }
351}
352
353fn seat_worktree(
356 target: &Utf8Path,
357 ground: &Ground,
358 resolved: &Resolved,
359 base: Option<&str>,
360 apply: bool,
361 out: Output,
362) -> Result<(), RkError> {
363 let Some(branch) = resolved.branch.as_deref() else {
364 return report(out, ground, resolved, None, None, apply);
365 };
366 let seat = crate::commands::worktree::plan_seat(target, branch, base, apply)?;
367 let mut note = None;
368 let path = match seat {
369 crate::commands::worktree::Seat::Satisfied { path } => path,
370 crate::commands::worktree::Seat::Fresh {
371 path,
372 source,
373 detail,
374 } => {
375 if apply && let Some(why) = detail {
380 return Err(stale_refs(branch, resolved, &why));
381 }
382 if !matches!(source.kind, "adopted" | "remote") {
389 if apply {
390 return Err(unreachable_tip(branch, resolved));
391 }
392 note = Some(format!(
393 "origin/{branch} is not in this clone yet; the apply fetches first, and refuses rather than seat a branch from the trunk"
394 ));
395 }
396 if apply {
397 crate::commands::worktree::create_seat(target, &source)?;
398 }
399 path
400 }
401 };
402 report_with(out, ground, resolved, Some(path), None, apply, note)
403}
404
405fn unreachable_tip(branch: &str, resolved: &Resolved) -> RkError {
408 RkError::refusal(
409 Diagnostic::new(
410 Reason::StateDrift,
411 format!("the forge carries {branch} and this clone cannot reach its tip"),
412 )
413 .expected(format!(
414 "origin/{branch} present, or {branch} already local"
415 ))
416 .action("git fetch origin, then rerun")
417 .target_state(format!(
418 "unchanged; issue #{} keeps its branch at the forge",
419 resolved.number
420 )),
421 )
422}
423
424fn branch_seatable(main: &Utf8Path, branch: &str) -> Result<(), RkError> {
438 let trunk = crate::config::trunk_of(main.as_std_path())?;
439 if let Some(seat) = crate::commands::worktree::seat_of(main, branch)? {
440 if seat != main {
441 return Err(RkError::refusal(
442 Diagnostic::new(
443 Reason::StateDrift,
444 format!(
445 "branch {branch} is checked out at {seat}, and one branch has one seat"
446 ),
447 )
448 .expected("the branch free, or already in the main checkout")
449 .action(format!("git -C {seat} switch {trunk}, then rerun"))
450 .target_state("unchanged"),
451 ));
452 }
453 return Ok(());
456 }
457 let held = crate::commands::worktree::git(main, &["status", "--porcelain"])?;
458 if !held.status.success() || !held.stdout.is_empty() {
461 return Err(RkError::refusal(
462 Diagnostic::new(
463 Reason::StateDrift,
464 format!("{main} carries uncommitted work, and this mode checks {branch} out there"),
465 )
466 .expected("a clean main checkout to seat the branch in")
467 .action("commit or stash the work, then rerun")
468 .target_state("unchanged"),
469 ));
470 }
471 Ok(())
472}
473
474fn stale_refs(branch: &str, resolved: &Resolved, why: &str) -> RkError {
476 RkError::refusal(
477 Diagnostic::new(
478 Reason::StateDrift,
479 format!(
480 "this clone could not refresh from the forge, so its {branch} may be stale: {why}"
481 ),
482 )
483 .expected("a fetch that answered, so the seat starts from the tip the forge holds")
484 .action("git fetch origin, then rerun")
485 .target_state(format!(
486 "unchanged; issue #{} keeps its branch at the forge",
487 resolved.number
488 )),
489 )
490}
491
492fn seat_branch(
501 main: &Utf8Path,
502 ground: &Ground,
503 resolved: &Resolved,
504 apply: bool,
505 out: Output,
506) -> Result<(), RkError> {
507 let Some(branch) = resolved.branch.as_deref() else {
508 return report(out, ground, resolved, None, None, apply);
509 };
510 if !apply {
511 return report(out, ground, resolved, None, Some(branch.to_owned()), false);
512 }
513 let git = |args: &[&str]| crate::commands::worktree::git(main, args);
517 let fetched = git(&["fetch", "origin"])?;
518 if !fetched.status.success() {
519 return Err(stale_refs(branch, resolved, &last_line(&fetched.stderr)));
520 }
521 let local = git(&[
522 "rev-parse",
523 "--verify",
524 "--quiet",
525 "--end-of-options",
526 &format!("refs/heads/{branch}^{{commit}}"),
527 ])?;
528 let switched = if local.status.success() {
529 git(&["switch", branch])?
530 } else {
531 git(&[
532 "switch",
533 "--track",
534 "-c",
535 branch,
536 &format!("refs/remotes/origin/{branch}"),
537 ])?
538 };
539 if !switched.status.success() {
540 return Err(RkError::subprocess(
543 Diagnostic::new(
544 Reason::SubprocessFailed,
545 format!(
546 "git refused to check out {branch}: {}",
547 last_line(&switched.stderr)
548 ),
549 )
550 .expected("a working tree the checkout can move")
551 .target_state("the branch exists on the forge and is not checked out here"),
552 ));
553 }
554 report(out, ground, resolved, None, Some(branch.to_owned()), true)
555}
556
557fn report(
559 out: Output,
560 ground: &Ground,
561 resolved: &Resolved,
562 path: Option<Utf8PathBuf>,
563 checkout: Option<String>,
564 apply: bool,
565) -> Result<(), RkError> {
566 report_with(out, ground, resolved, path, checkout, apply, None)
567}
568
569fn report_with(
571 out: Output,
572 ground: &Ground,
573 resolved: &Resolved,
574 path: Option<Utf8PathBuf>,
575 checkout: Option<String>,
576 apply: bool,
577 note: Option<String>,
578) -> Result<(), RkError> {
579 let mode = if apply { "apply" } else { "preview" };
580 out.result_line(format!("issue: #{} {}", resolved.number, resolved.title));
581 out.result_line(format!(
582 "branch: {} ({})",
583 resolved.branch.as_deref().unwrap_or("named by the forge"),
584 match resolved.origin {
585 "already" => "already linked at the forge",
586 "forge" => "minted at the forge",
587 _ => "not minted yet",
588 }
589 ));
590 out.result_line(format!(
591 "seat: {} ({} says so)",
592 path.as_ref().map_or_else(
593 || checkout.as_deref().map_or_else(
594 || "unknown".to_owned(),
595 |branch| format!("checkout {branch}")
596 ),
597 ToString::to_string
598 ),
599 ground.workflow_source
600 ));
601 if !resolved.others.is_empty() {
602 out.warn(format!(
603 "the issue carries other linked branches, and the first was taken: {}",
604 resolved.others.join(", ")
605 ));
606 }
607 let detail = match (resolved.detail.clone(), note) {
608 (Some(had), Some(note)) => Some(format!("{had}; {note}")),
609 (Some(one), None) | (None, Some(one)) => Some(one),
610 (None, None) => None,
611 };
612 if let Some(detail) = &detail {
613 out.warn(detail);
614 }
615 let next = next_lines(ground, resolved, path.as_ref(), apply);
616 out.next(&next);
617 out.emit(&StartReport {
618 schema: "rk.issue-start/1",
619 mode,
620 forge: ground.forge.as_str(),
621 repo: ground.repo.clone(),
622 issue: resolved.number,
623 title: resolved.title.clone(),
624 branch: resolved.branch.clone(),
625 origin: resolved.origin,
626 workflow: ground.workflow.as_str(),
627 path: path.map(|path| path.to_string()),
628 checkout,
629 others: resolved.others.clone(),
630 detail,
631 next,
632 })
633}
634
635fn next_lines(
637 ground: &Ground,
638 resolved: &Resolved,
639 path: Option<&Utf8PathBuf>,
640 apply: bool,
641) -> Vec<String> {
642 if !apply {
643 return vec![format!(
644 "rk issue start {} --apply mints the branch and seats it",
645 resolved.number
646 )];
647 }
648 match (ground.workflow, path) {
649 (Workflow::Worktree, Some(path)) => vec![
650 format!("cd {path}"),
651 "rk worktree list reports every seat".to_owned(),
652 ],
653 _ => vec!["rk status reports what this target carries".to_owned()],
654 }
655}
656
657fn last_line(bytes: &[u8]) -> String {
659 String::from_utf8_lossy(bytes)
660 .lines()
661 .rev()
662 .find(|line| !line.trim().is_empty())
663 .unwrap_or("no output")
664 .to_owned()
665}