1use anyhow::{Result, bail};
2use clap::ArgAction;
3use clap_complete::engine::ArgValueCompleter;
4
5use crate::cli::PushMode;
6use crate::commands::Run;
7use crate::completions;
8use crate::providers::{ReviewProvider, detect_review_provider};
9use crate::settings;
10use crate::style;
11use crate::{git, stack};
12
13#[derive(Debug, clap::Args)]
15pub struct Submit {
16 #[arg(add = ArgValueCompleter::new(completions::branch_candidates))]
18 branch: Option<String>,
19 #[arg(long, short = 'n', action = ArgAction::SetTrue)]
21 dry_run: bool,
22 #[arg(long, conflicts_with = "branch")]
24 stack: bool,
25 #[arg(long, action = ArgAction::SetTrue, conflicts_with = "stack")]
27 no_stack: bool,
28 #[arg(
31 long,
32 action = ArgAction::SetTrue,
33 conflicts_with_all = ["branch", "stack", "no_stack"],
34 )]
35 downstack: bool,
36 #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_push")]
38 push: bool,
39 #[arg(long, action = ArgAction::SetTrue)]
41 no_push: bool,
42 #[arg(long, short = 'd')]
45 desc: Option<String>,
46 #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_draft")]
48 draft: bool,
49 #[arg(long, action = ArgAction::SetTrue)]
51 no_draft: bool,
52 #[arg(long, action = ArgAction::SetTrue, conflicts_with = "draft")]
54 ready: bool,
55 #[arg(long, action = ArgAction::SetTrue)]
58 rebuild_overview: bool,
59}
60
61impl Run for Submit {
62 fn run(self) -> Result<()> {
63 let submit_stack = if self.stack {
66 true
67 } else if self.no_stack || self.branch.is_some() {
68 false
69 } else {
70 settings::bool_setting(settings::SUBMIT_STACK_KEY)?
71 };
72
73 let draft = if self.draft {
76 true
77 } else if self.no_draft {
78 false
79 } else {
80 settings::bool_setting(settings::SUBMIT_DRAFT_KEY)?
81 };
82
83 submit(SubmitOptions {
84 branch: self.branch,
85 submit_stack,
86 downstack: self.downstack,
87 dry_run: self.dry_run,
88 push_mode: PushMode::from_flags(self.push, self.no_push),
89 desc: self.desc,
90 draft,
91 ready: self.ready,
92 rebuild_overview: self.rebuild_overview,
93 })
94 }
95}
96
97pub struct SubmitOptions {
100 pub branch: Option<String>,
101 pub submit_stack: bool,
102 pub downstack: bool,
103 pub dry_run: bool,
104 pub push_mode: crate::cli::PushMode,
105 pub desc: Option<String>,
106 pub draft: bool,
107 pub ready: bool,
108 pub rebuild_overview: bool,
109}
110
111pub fn submit(options: SubmitOptions) -> Result<()> {
112 let SubmitOptions {
113 branch,
114 submit_stack,
115 downstack,
116 dry_run,
117 push_mode,
118 desc,
119 draft,
120 ready,
121 rebuild_overview,
122 } = options;
123
124 let branch = branch.map_or_else(git::current_branch, Ok)?;
125 let desc_branch = branch.clone();
127
128 let branches = if downstack {
129 stack::path_from_root(&branch)?
132 } else if submit_stack {
133 stack::stack_line(&branch)?
137 } else {
138 vec![branch.clone()]
139 };
140
141 if submit_stack || downstack {
145 let trunk = stack::trunk_branch(&git::local_branches()?);
146 if Some(&branch) == trunk.as_ref() {
147 if stack::children_of(&branch)?.is_empty() {
148 bail!("no stacked branches to submit");
149 }
150 bail!("you are on the trunk ({branch}); check out a stacked branch first");
151 }
152 }
153
154 let branch_parents = branch_parents(&branches)?;
155
156 let push = settings::push_enabled(push_mode, settings::PUSH_ON_SUBMIT_KEY)?;
160 if push {
161 let remote = settings::remote()?;
162 if dry_run {
163 anstream::println!(
164 "would push {} to {remote}",
165 style::branch(&branches.join(" "))
166 );
167 } else {
168 git::push_set_upstream_force_with_lease(&remote, &branches)?;
169 anstream::println!("pushed {} to {remote}", style::branch(&branches.join(" ")));
170 stack::publish_metadata(&remote);
173 }
174 }
175
176 let (provider, review_provider) = detect_review_provider()?;
177 let mut summary = SubmitSummary::default();
178
179 let mut created = Vec::new();
180 for (branch, parent) in &branch_parents {
181 let action = submit_branch(review_provider.as_ref(), branch, parent, dry_run, draft)?;
182 if action == SubmitAction::Created {
183 created.push(branch.clone());
184 }
185 summary.record(action);
186 }
187
188 crate::notes::seed_template_notes(review_provider.as_ref(), provider.kind, &created, dry_run)?;
192
193 if ready {
196 for branch in &branches {
197 let Some(review) = review_provider.review_for_branch(branch)? else {
198 continue;
199 };
200 if review.branch != *branch || !review.draft {
201 continue;
202 }
203 if dry_run {
204 anstream::println!("would mark {} ready", review.id);
205 continue;
206 }
207 let output = review_provider.mark_ready(&review)?;
208 anstream::println!("marked {} ready", review.id);
209 if !output.is_empty() {
210 println!("{output}");
211 }
212 }
213 }
214
215 let renamed: Vec<(String, String)> = if submit_stack || downstack {
222 branch_parents
223 .iter()
224 .filter_map(|(branch, _)| {
225 stack::renamed_from(branch)
226 .ok()
227 .flatten()
228 .map(|old| (branch.clone(), old))
229 })
230 .collect()
231 } else {
232 Vec::new()
233 };
234 for (_, old) in &renamed {
235 close_superseded_review(review_provider.as_ref(), old, dry_run)?;
236 }
237
238 if let Some(desc) = desc {
242 crate::notes::update_description_note(
243 review_provider.as_ref(),
244 &desc_branch,
245 &desc,
246 dry_run,
247 )?;
248 }
249 crate::notes::update_closes_notes(review_provider.as_ref(), &branches, dry_run)?;
250 if submit_stack || downstack {
251 crate::notes::update_stack_notes(
252 review_provider.as_ref(),
253 &branch_parents,
254 dry_run,
255 rebuild_overview,
256 )?;
257 }
258
259 if !dry_run {
261 for (branch, _) in &renamed {
262 stack::clear_renamed_from(branch)?;
263 }
264 }
265
266 anstream::println!(
267 "{}",
268 style::success(&format!(
269 "submit complete: {} created, {} updated, {} skipped",
270 summary.created, summary.updated, summary.skipped
271 ))
272 );
273 Ok(())
274}
275
276fn close_superseded_review(
280 review_provider: &dyn ReviewProvider,
281 old: &str,
282 dry_run: bool,
283) -> Result<()> {
284 let Some(review) = review_provider.review_for_branch(old)? else {
285 return Ok(());
286 };
287 if review.branch != *old {
288 return Ok(());
289 }
290
291 if dry_run {
292 anstream::println!("would close superseded review {} for {old}", review.id);
293 return Ok(());
294 }
295 if !crate::prompt::confirm_default_yes(&format!(
296 "close the replaced review {} for {old} and delete its branch? [Y/n] ",
297 review.id
298 ))? {
299 anstream::println!("kept review {} for {old}", review.id);
300 return Ok(());
301 }
302
303 review_provider.close_review(&review, true)?;
304 anstream::println!("closed superseded review {} for {old}", review.id);
305 Ok(())
306}
307
308fn branch_parents(branches: &[String]) -> Result<Vec<(String, String)>> {
309 let mut branch_parents = Vec::new();
310 for branch in branches {
311 let Some(parent) = stack::parent_of(branch)? else {
312 bail!("{branch} has no stack parent; run `git stk adopt` or `git stk sync` first");
313 };
314 branch_parents.push((branch.to_owned(), parent));
315 }
316 Ok(branch_parents)
317}
318
319fn submit_branch(
320 review_provider: &dyn ReviewProvider,
321 branch: &str,
322 parent: &str,
323 dry_run: bool,
324 draft: bool,
325) -> Result<SubmitAction> {
326 if let Some(review) = review_provider.review_for_branch(branch)? {
327 if review.base == parent {
328 if dry_run {
329 anstream::println!(
330 "would skip {} -> {} ({})",
331 review.branch,
332 review.base,
333 review.id
334 );
335 } else {
336 anstream::println!(
337 "{}",
338 style::dim(&format!(
339 "{} already targets {} ({})",
340 review.branch, review.base, review.id
341 ))
342 );
343 }
344 return Ok(SubmitAction::Skipped);
345 }
346
347 let output = if dry_run {
348 String::new()
349 } else {
350 review_provider.update_review_base(&review, parent)?
351 };
352 anstream::println!(
353 "{} {} -> {} {}",
354 if dry_run { "would update" } else { "updated" },
355 style::branch(&review.branch),
356 style::branch(parent),
357 style::dim(&format!("({})", review.id))
358 );
359 if !output.is_empty() {
360 println!("{output}");
361 }
362 } else {
363 let output = if dry_run {
364 String::new()
365 } else {
366 review_provider.create_review(branch, parent, draft)?
367 };
368 anstream::println!(
369 "{} {} -> {}",
370 if dry_run { "would create" } else { "created" },
371 style::branch(branch),
372 style::branch(parent)
373 );
374 if !output.is_empty() {
375 println!("{output}");
376 }
377 return Ok(SubmitAction::Created);
378 }
379
380 Ok(SubmitAction::Updated)
381}
382
383#[derive(Debug, Default)]
384struct SubmitSummary {
385 created: usize,
386 updated: usize,
387 skipped: usize,
388}
389
390impl SubmitSummary {
391 fn record(&mut self, action: SubmitAction) {
392 match action {
393 SubmitAction::Created => self.created += 1,
394 SubmitAction::Updated => self.updated += 1,
395 SubmitAction::Skipped => self.skipped += 1,
396 }
397 }
398}
399
400#[derive(Debug, Clone, Copy, Eq, PartialEq)]
401enum SubmitAction {
402 Created,
403 Updated,
404 Skipped,
405}