Skip to main content

git_stk/commands/
submit.rs

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/// Create or update a remote review request for a branch.
14#[derive(Debug, clap::Args)]
15pub struct Submit {
16    /// Branch to submit (defaults to the current branch).
17    #[arg(add = ArgValueCompleter::new(completions::branch_candidates))]
18    branch: Option<String>,
19    /// Print what would change without creating or updating reviews.
20    #[arg(long, short = 'n', action = ArgAction::SetTrue)]
21    dry_run: bool,
22    /// Submit the whole stack parent-first, from anywhere in it.
23    #[arg(long, conflicts_with = "branch")]
24    stack: bool,
25    /// Submit only the current branch, overriding stk.submitStack.
26    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "stack")]
27    no_stack: bool,
28    /// Submit the stack from its bottom through the current branch only,
29    /// leaving work-in-progress branches above it unsubmitted.
30    #[arg(
31        long,
32        action = ArgAction::SetTrue,
33        conflicts_with_all = ["branch", "stack", "no_stack"],
34    )]
35    downstack: bool,
36    /// Push branches (-u --force-with-lease) before submitting.
37    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_push")]
38    push: bool,
39    /// Do not push branches, overriding stk.pushOnSubmit.
40    #[arg(long, action = ArgAction::SetTrue)]
41    no_push: bool,
42    /// Set a description block at the top of the review body; an empty
43    /// string clears it. Applies to the current or named branch only.
44    #[arg(long, short = 'd')]
45    desc: Option<String>,
46    /// Create new reviews as drafts.
47    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_draft")]
48    draft: bool,
49    /// Create new reviews ready for review, overriding stk.submitDraft.
50    #[arg(long, action = ArgAction::SetTrue)]
51    no_draft: bool,
52    /// Mark the submitted branches' existing draft reviews as ready.
53    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "draft")]
54    ready: bool,
55    /// Rebuild each review's stack overview from the live stack plus merged
56    /// history, dropping closed or orphaned rows that drifted in. Stack mode.
57    #[arg(long, action = ArgAction::SetTrue)]
58    rebuild_overview: bool,
59}
60
61impl Run for Submit {
62    fn run(self) -> Result<()> {
63        // Stack mode: --stack forces it on; --no-stack or an explicit branch
64        // forces it off; otherwise stk.submitStack decides.
65        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        // Draft mode: --draft forces it on, --no-draft off; otherwise
74        // stk.submitDraft decides.
75        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
97/// The resolved inputs for [`submit`] - one bundle instead of nine positional
98/// arguments. `Submit::run` resolves the flag/config defaults and fills it.
99pub 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    // The description targets this branch's review even in stack mode.
126    let desc_branch = branch.clone();
127
128    let branches = if downstack {
129        // Bottom of the stack through the current branch: anything above is
130        // work in progress that stays local.
131        stack::path_from_root(&branch)?
132    } else if submit_stack {
133        // The stack containing the current branch: its own line, bottom
134        // through current and out to its descendants. Sibling stacks that
135        // merely share the trunk are left for their own submit.
136        stack::stack_line(&branch)?
137    } else {
138        vec![branch.clone()]
139    };
140
141    // The trunk is never part of a stack, so a stack-wide submit from it has
142    // nothing of its own to submit (its descendants are sibling stacks). Say so
143    // plainly rather than pushing an empty set or sweeping every stack.
144    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    // Push after stack validation but before any provider calls: creating a
157    // review requires the branch to exist remotely, and -u --force-with-lease
158    // covers both first pushes and safely updating rebased branches.
159    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            // Carry the stack's parent map along so another clone can rebuild
171            // it with `git stk repair --from-remote`.
172            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    // Seed freshly created reviews from the repo's PR template before the
189    // managed sections go in, so our content appends beneath it rather than
190    // replacing it.
191    crate::notes::seed_template_notes(review_provider.as_ref(), provider.kind, &created, dry_run)?;
192
193    // Flip drafts in scope to ready for review (the escape hatch for
194    // stk.submitDraft users).
195    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    // A renamed branch's fresh review now exists, so retire the review the old
216    // name still heads. Only handle this when the ledger prune below actually
217    // runs (stack-wide submit): the marker is the sole signal that identifies
218    // the stale row across every other overview, so closing and clearing it in
219    // a single-branch submit - which never prunes - would orphan those rows
220    // permanently. Left set, the marker waits for a later `submit --stack`.
221    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    // After every review exists, write the description, link any issue the
239    // branch name references, then (in stack mode) write the stack overview
240    // into each body.
241    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    // The ledger has now pruned the superseded entries, so drop the markers.
260    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
276/// Retire the open review still heading a renamed-away branch. The fresh
277/// review already exists, so closing here never leaves the work without one.
278/// Prompts (default yes; a non-interactive run proceeds) before closing.
279fn 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}