1use super::{Repository, utf8};
2use crate::{Runner, process::args};
3use workyard_core::{BranchPlan, Control, Problem};
4
5impl Repository {
6 pub async fn plan(
8 &self,
9 runner: &Runner,
10 task: &str,
11 checkout: bool,
12 from: Option<&str>,
13 resolution: workyard_core::SourceResolution,
14 control: &Control,
15 ) -> Result<BranchPlan, Problem> {
16 let local = self
17 .has_ref(runner, &format!("refs/heads/{task}"), control)
18 .await?;
19 let remote_ref = self
20 .remote
21 .as_ref()
22 .map(|remote| format!("refs/remotes/{remote}/{task}"));
23 let remote_exists = match &remote_ref {
24 Some(reference) => self.has_ref(runner, reference, control).await?,
25 None => false,
26 };
27 if !checkout && (local || remote_exists) {
28 return Err(Problem::new(
29 workyard_core::ProblemCode::BranchExists,
30 format!(
31 "Target branch {task:?} already exists in {:?}.",
32 self.source
33 ),
34 )
35 .remedy(
36 "Use `workyard checkout` or `workyard create --checkout` to permit branch reuse.",
37 )
38 .in_repository(&self.source));
39 }
40
41 if local {
42 self.ensure_not_checked_out(runner, task, control).await?;
43 return Ok(BranchPlan::Reuse);
44 }
45
46 if remote_exists {
47 return Ok(BranchPlan::Track(remote_ref.expect("checked remote")));
48 }
49
50 let (source, explicit_remote) = self.qualify_source(runner, from, control).await?;
51
52 let reference = format!("{source}^{{commit}}");
53 let resolved = runner
54 .git(
55 &self.source,
56 &["rev-parse", "--verify", "--end-of-options", &reference],
57 control,
58 )
59 .await?;
60 if resolved.status.success() {
61 return Ok(BranchPlan::Create(source));
62 }
63
64 let selected_prefix = self
67 .remote
68 .as_ref()
69 .map(|remote| format!("refs/remotes/{remote}/"));
70 let can_fetch = resolution == workyard_core::SourceResolution::FetchPending
71 && explicit_remote
72 && selected_prefix.is_some_and(|prefix| source.starts_with(&prefix));
73 if can_fetch {
74 return Ok(BranchPlan::Create(source));
75 }
76
77 let message = format!(
78 "Starting source {source:?} is unavailable in {:?}.",
79 self.source
80 );
81 let mut problem = Problem::new(workyard_core::ProblemCode::SourceMissing, message)
82 .remedy("Supply an existing local --from/--repo-from branch, explicit commit, or explicit remote-qualified source such as origin/main.")
83 .in_repository(&self.source);
84 problem.detail =
85 from.map(|source| Box::new(workyard_core::ProblemDetail::StartingPoint(source.into())));
86 Err(problem)
87 }
88
89 async fn qualify_source(
90 &self,
91 runner: &Runner,
92 from: Option<&str>,
93 control: &Control,
94 ) -> Result<(String, bool), Problem> {
95 let Some(source) = from else {
96 return Ok((self.default_branch(runner, control).await?, false));
97 };
98 let remotes = runner
101 .checked(&self.source, &args(&["remote"]), control)
102 .await?;
103 let explicit_remote = utf8(&remotes)?
104 .lines()
105 .any(|remote| source.starts_with(&format!("{remote}/")));
106 let local_source = format!("refs/heads/{source}");
107 let source = if explicit_remote {
108 format!("refs/remotes/{source}")
109 } else if self.has_ref(runner, &local_source, control).await? {
110 local_source
111 } else {
112 source.to_owned()
113 };
114
115 Ok((source, explicit_remote))
116 }
117
118 async fn default_branch(&self, runner: &Runner, control: &Control) -> Result<String, Problem> {
119 if let Some(reference) = self.configured_default(runner, control).await? {
120 return Ok(reference);
121 }
122
123 if let Some(remote) = &self.remote {
124 let reference = format!("refs/remotes/{remote}/HEAD");
125 let output = runner
126 .git(
127 &self.source,
128 &["symbolic-ref", "--quiet", &reference],
129 control,
130 )
131 .await?;
132 if output.status.success() {
133 let prefix = format!("refs/remotes/{remote}/");
134 if let Some(branch) = utf8(&output.stdout)?.trim().strip_prefix(&prefix) {
135 let local = format!("refs/heads/{branch}");
136 if self.has_ref(runner, &local, control).await? {
137 return Ok(local);
138 }
139 }
140 }
141 }
142 let message = format!(
143 "No usable local repository-default branch metadata in {:?}.",
144 self.source
145 );
146 Err(
147 Problem::new(workyard_core::ProblemCode::DefaultBranchUnknown, message)
148 .remedy("Supply --from or --repo-from explicitly.")
149 .in_repository(&self.source),
150 )
151 }
152
153 async fn configured_default(
155 &self,
156 runner: &Runner,
157 control: &Control,
158 ) -> Result<Option<String>, Problem> {
159 let query = ["config", "--local", "--get", "workyard.defaultBranch"];
160 let config = runner.git(&self.source, &query, control).await?;
161 match config.status.code() {
162 Some(1) => return Ok(None),
163 Some(0) => {}
164 _ => return Err(config.problem(&self.source, &args(&query))),
165 }
166
167 let branch = utf8(&config.stdout)?.trim_end_matches(['\r', '\n']);
168 let reference = format!("refs/heads/{branch}");
169 if self.has_ref(runner, &reference, control).await? {
170 return Ok(Some(reference));
171 }
172
173 let mut problem = Problem::new(
174 workyard_core::ProblemCode::SourceMissing,
175 format!(
176 "Configured default branch {branch:?} is missing in {:?}.",
177 self.source
178 ),
179 )
180 .remedy("Choose an existing branch with --from or --repo-from.")
181 .in_repository(&self.source);
182 problem.detail = Some(Box::new(workyard_core::ProblemDetail::StartingPoint(
183 branch.into(),
184 )));
185 Err(problem)
186 }
187
188 async fn has_ref(
189 &self,
190 runner: &Runner,
191 reference: &str,
192 control: &Control,
193 ) -> Result<bool, Problem> {
194 let output = runner
195 .git(
196 &self.source,
197 &["show-ref", "--verify", "--quiet", reference],
198 control,
199 )
200 .await?;
201 match output.status.code() {
202 Some(0) => Ok(true),
203 Some(1) => Ok(false),
204 _ => Err(output.problem(
205 &self.source,
206 &args(&["show-ref", "--verify", "--quiet", reference]),
207 )),
208 }
209 }
210
211 async fn ensure_not_checked_out(
212 &self,
213 runner: &Runner,
214 task: &str,
215 control: &Control,
216 ) -> Result<(), Problem> {
217 let output = runner
218 .checked(
219 &self.source,
220 &args(&["worktree", "list", "--porcelain", "-z"]),
221 control,
222 )
223 .await?;
224 let target = format!("branch refs/heads/{task}");
225 if output
226 .split(|byte| *byte == 0)
227 .any(|field| field == target.as_bytes())
228 {
229 let mut problem = Problem::new(
230 workyard_core::ProblemCode::BranchInUse,
231 format!(
232 "Branch {task:?} is already checked out in {:?}.",
233 self.source
234 ),
235 )
236 .remedy(format!(
237 "Inspect `git -C {:?} worktree list --porcelain`; choose a free branch.",
238 self.source
239 ));
240 problem.repositories.push(self.source.clone());
241 return Err(problem);
242 }
243
244 Ok(())
245 }
246}