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 (_, review_provider) = detect_review_provider()?;
177    let mut summary = SubmitSummary::default();
178
179    for (branch, parent) in &branch_parents {
180        summary.record(submit_branch(
181            review_provider.as_ref(),
182            branch,
183            parent,
184            dry_run,
185            draft,
186        )?);
187    }
188
189    // Flip drafts in scope to ready for review (the escape hatch for
190    // stk.submitDraft users).
191    if ready {
192        for branch in &branches {
193            let Some(review) = review_provider.review_for_branch(branch)? else {
194                continue;
195            };
196            if review.branch != *branch || !review.draft {
197                continue;
198            }
199            if dry_run {
200                anstream::println!("would mark {} ready", review.id);
201                continue;
202            }
203            let output = review_provider.mark_ready(&review)?;
204            anstream::println!("marked {} ready", review.id);
205            if !output.is_empty() {
206                println!("{output}");
207            }
208        }
209    }
210
211    // A renamed branch's fresh review now exists, so retire the review the old
212    // name still heads. Only handle this when the ledger prune below actually
213    // runs (stack-wide submit): the marker is the sole signal that identifies
214    // the stale row across every other overview, so closing and clearing it in
215    // a single-branch submit - which never prunes - would orphan those rows
216    // permanently. Left set, the marker waits for a later `submit --stack`.
217    let renamed: Vec<(String, String)> = if submit_stack || downstack {
218        branch_parents
219            .iter()
220            .filter_map(|(branch, _)| {
221                stack::renamed_from(branch)
222                    .ok()
223                    .flatten()
224                    .map(|old| (branch.clone(), old))
225            })
226            .collect()
227    } else {
228        Vec::new()
229    };
230    for (_, old) in &renamed {
231        close_superseded_review(review_provider.as_ref(), old, dry_run)?;
232    }
233
234    // After every review exists, write the description, link any issue the
235    // branch name references, then (in stack mode) write the stack overview
236    // into each body.
237    if let Some(desc) = desc {
238        crate::notes::update_description_note(
239            review_provider.as_ref(),
240            &desc_branch,
241            &desc,
242            dry_run,
243        )?;
244    }
245    crate::notes::update_closes_notes(review_provider.as_ref(), &branches, dry_run)?;
246    if submit_stack || downstack {
247        crate::notes::update_stack_notes(
248            review_provider.as_ref(),
249            &branch_parents,
250            dry_run,
251            rebuild_overview,
252        )?;
253    }
254
255    // The ledger has now pruned the superseded entries, so drop the markers.
256    if !dry_run {
257        for (branch, _) in &renamed {
258            stack::clear_renamed_from(branch)?;
259        }
260    }
261
262    anstream::println!(
263        "{}",
264        style::success(&format!(
265            "submit complete: {} created, {} updated, {} skipped",
266            summary.created, summary.updated, summary.skipped
267        ))
268    );
269    Ok(())
270}
271
272/// Retire the open review still heading a renamed-away branch. The fresh
273/// review already exists, so closing here never leaves the work without one.
274/// Prompts (default yes; a non-interactive run proceeds) before closing.
275fn close_superseded_review(
276    review_provider: &dyn ReviewProvider,
277    old: &str,
278    dry_run: bool,
279) -> Result<()> {
280    let Some(review) = review_provider.review_for_branch(old)? else {
281        return Ok(());
282    };
283    if review.branch != *old {
284        return Ok(());
285    }
286
287    if dry_run {
288        anstream::println!("would close superseded review {} for {old}", review.id);
289        return Ok(());
290    }
291    if !crate::prompt::confirm_default_yes(&format!(
292        "close the replaced review {} for {old} and delete its branch? [Y/n] ",
293        review.id
294    ))? {
295        anstream::println!("kept review {} for {old}", review.id);
296        return Ok(());
297    }
298
299    review_provider.close_review(&review, true)?;
300    anstream::println!("closed superseded review {} for {old}", review.id);
301    Ok(())
302}
303
304fn branch_parents(branches: &[String]) -> Result<Vec<(String, String)>> {
305    let mut branch_parents = Vec::new();
306    for branch in branches {
307        let Some(parent) = stack::parent_of(branch)? else {
308            bail!("{branch} has no stack parent; run `git stk adopt` or `git stk sync` first");
309        };
310        branch_parents.push((branch.to_owned(), parent));
311    }
312    Ok(branch_parents)
313}
314
315fn submit_branch(
316    review_provider: &dyn ReviewProvider,
317    branch: &str,
318    parent: &str,
319    dry_run: bool,
320    draft: bool,
321) -> Result<SubmitAction> {
322    if let Some(review) = review_provider.review_for_branch(branch)? {
323        if review.base == parent {
324            if dry_run {
325                anstream::println!(
326                    "would skip {} -> {} ({})",
327                    review.branch,
328                    review.base,
329                    review.id
330                );
331            } else {
332                anstream::println!(
333                    "{}",
334                    style::dim(&format!(
335                        "{} already targets {} ({})",
336                        review.branch, review.base, review.id
337                    ))
338                );
339            }
340            return Ok(SubmitAction::Skipped);
341        }
342
343        let output = if dry_run {
344            String::new()
345        } else {
346            review_provider.update_review_base(&review, parent)?
347        };
348        anstream::println!(
349            "{} {} -> {} {}",
350            if dry_run { "would update" } else { "updated" },
351            style::branch(&review.branch),
352            style::branch(parent),
353            style::dim(&format!("({})", review.id))
354        );
355        if !output.is_empty() {
356            println!("{output}");
357        }
358    } else {
359        let output = if dry_run {
360            String::new()
361        } else {
362            review_provider.create_review(branch, parent, draft)?
363        };
364        anstream::println!(
365            "{} {} -> {}",
366            if dry_run { "would create" } else { "created" },
367            style::branch(branch),
368            style::branch(parent)
369        );
370        if !output.is_empty() {
371            println!("{output}");
372        }
373        return Ok(SubmitAction::Created);
374    }
375
376    Ok(SubmitAction::Updated)
377}
378
379#[derive(Debug, Default)]
380struct SubmitSummary {
381    created: usize,
382    updated: usize,
383    skipped: usize,
384}
385
386impl SubmitSummary {
387    fn record(&mut self, action: SubmitAction) {
388        match action {
389            SubmitAction::Created => self.created += 1,
390            SubmitAction::Updated => self.updated += 1,
391            SubmitAction::Skipped => self.skipped += 1,
392        }
393    }
394}
395
396#[derive(Debug, Clone, Copy, Eq, PartialEq)]
397enum SubmitAction {
398    Created,
399    Updated,
400    Skipped,
401}