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_provider, 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    #[arg(add = ArgValueCompleter::new(completions::branch_candidates))]
17    branch: Option<String>,
18    /// Print what would change without creating or updating reviews.
19    #[arg(long, action = ArgAction::SetTrue)]
20    dry_run: bool,
21    /// Submit the whole stack parent-first, from anywhere in it.
22    #[arg(long, conflicts_with = "branch")]
23    stack: bool,
24    /// Submit only the current branch, overriding stk.submitStack.
25    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "stack")]
26    no_stack: bool,
27    /// Submit the stack from its bottom through the current branch only,
28    /// leaving work-in-progress branches above it unsubmitted.
29    #[arg(
30        long,
31        action = ArgAction::SetTrue,
32        conflicts_with_all = ["branch", "stack", "no_stack"],
33    )]
34    downstack: bool,
35    /// Push branches (-u --force-with-lease) before submitting.
36    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_push")]
37    push: bool,
38    /// Do not push branches, overriding stk.pushOnSubmit.
39    #[arg(long, action = ArgAction::SetTrue)]
40    no_push: bool,
41    /// Set a description block at the top of the review body; an empty
42    /// string clears it. Applies to the current or named branch only.
43    #[arg(long, short = 'd')]
44    desc: Option<String>,
45    /// Create new reviews as drafts.
46    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_draft")]
47    draft: bool,
48    /// Create new reviews ready for review, overriding stk.submitDraft.
49    #[arg(long, action = ArgAction::SetTrue)]
50    no_draft: bool,
51    /// Mark the submitted branches' existing draft reviews as ready.
52    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "draft")]
53    ready: bool,
54    /// Rebuild each review's stack overview from the live stack plus merged
55    /// history, dropping closed or orphaned rows that drifted in. Stack mode.
56    #[arg(long, action = ArgAction::SetTrue)]
57    rebuild_overview: bool,
58}
59
60impl Run for Submit {
61    fn run(self) -> Result<()> {
62        // Stack mode: --stack forces it on; --no-stack or an explicit branch
63        // forces it off; otherwise stk.submitStack decides.
64        let submit_stack = if self.stack {
65            true
66        } else if self.no_stack || self.branch.is_some() {
67            false
68        } else {
69            settings::bool_setting(settings::SUBMIT_STACK_KEY)?
70        };
71
72        // Draft mode: --draft forces it on, --no-draft off; otherwise
73        // stk.submitDraft decides.
74        let draft = if self.draft {
75            true
76        } else if self.no_draft {
77            false
78        } else {
79            settings::bool_setting(settings::SUBMIT_DRAFT_KEY)?
80        };
81
82        submit(
83            self.branch.as_deref(),
84            submit_stack,
85            self.downstack,
86            self.dry_run,
87            PushMode::from_flags(self.push, self.no_push),
88            self.desc.as_deref(),
89            draft,
90            self.ready,
91            self.rebuild_overview,
92        )
93    }
94}
95
96#[allow(clippy::too_many_arguments)]
97pub fn submit(
98    branch: Option<&str>,
99    submit_stack: bool,
100    downstack: bool,
101    dry_run: bool,
102    push_mode: crate::cli::PushMode,
103    desc: Option<&str>,
104    draft: bool,
105    ready: bool,
106    rebuild_overview: bool,
107) -> Result<()> {
108    let branch = branch
109        .map(str::to_owned)
110        .map_or_else(git::current_branch, Ok)?;
111    // The description targets this branch's review even in stack mode.
112    let desc_branch = branch.clone();
113
114    let branches = if downstack {
115        // Bottom of the stack through the current branch: anything above is
116        // work in progress that stays local.
117        stack::path_from_root(&branch)?
118    } else if submit_stack {
119        // The stack containing the current branch: its own line, bottom
120        // through current and out to its descendants. Sibling stacks that
121        // merely share the trunk are left for their own submit.
122        stack::stack_line(&branch)?
123    } else {
124        vec![branch.clone()]
125    };
126
127    // The trunk is never part of a stack, so a stack-wide submit from it has
128    // nothing of its own to submit (its descendants are sibling stacks). Say so
129    // plainly rather than pushing an empty set or sweeping every stack.
130    if submit_stack || downstack {
131        let trunk = stack::trunk_branch(&git::local_branches()?);
132        if Some(&branch) == trunk.as_ref() {
133            if stack::children_for_branch(&branch)?.is_empty() {
134                bail!("no stacked branches to submit");
135            }
136            bail!("you are on the trunk ({branch}); check out a stacked branch first");
137        }
138    }
139
140    let branch_parents = branch_parents(&branches)?;
141
142    // Push after stack validation but before any provider calls: creating a
143    // review requires the branch to exist remotely, and -u --force-with-lease
144    // covers both first pushes and safely updating rebased branches.
145    let push = settings::push_enabled(push_mode, settings::PUSH_ON_SUBMIT_KEY)?;
146    if push {
147        let remote = settings::remote()?;
148        if dry_run {
149            anstream::println!(
150                "would push {} to {remote}",
151                style::branch(&branches.join(" "))
152            );
153        } else {
154            git::push_set_upstream_force_with_lease(&remote, &branches)?;
155            anstream::println!("pushed {} to {remote}", style::branch(&branches.join(" ")));
156            // Carry the stack's parent map along so another clone can rebuild
157            // it with `git stk repair --from-remote`.
158            stack::publish_metadata(&remote);
159        }
160    }
161
162    let provider = detect_provider()?;
163    let review_provider = review_provider(provider.kind);
164    let mut summary = SubmitSummary::default();
165
166    for (branch, parent) in &branch_parents {
167        summary.record(submit_branch(
168            review_provider.as_ref(),
169            branch,
170            parent,
171            dry_run,
172            draft,
173        )?);
174    }
175
176    // Flip drafts in scope to ready for review (the escape hatch for
177    // stk.submitDraft users).
178    if ready {
179        for branch in &branches {
180            let Some(review) = review_provider.review_for_branch(branch)? else {
181                continue;
182            };
183            if review.branch != *branch || !review.draft {
184                continue;
185            }
186            if dry_run {
187                println!("would mark {} ready", review.id);
188                continue;
189            }
190            let output = review_provider.mark_ready(&review)?;
191            anstream::println!("marked {} ready", review.id);
192            if !output.is_empty() {
193                println!("{output}");
194            }
195        }
196    }
197
198    // A renamed branch's fresh review now exists, so retire the review the old
199    // name still heads. Only handle this when the ledger prune below actually
200    // runs (stack-wide submit): the marker is the sole signal that identifies
201    // the stale row across every other overview, so closing and clearing it in
202    // a single-branch submit - which never prunes - would orphan those rows
203    // permanently. Left set, the marker waits for a later `submit --stack`.
204    let renamed: Vec<(String, String)> = if submit_stack || downstack {
205        branch_parents
206            .iter()
207            .filter_map(|(branch, _)| {
208                stack::renamed_from(branch)
209                    .ok()
210                    .flatten()
211                    .map(|old| (branch.clone(), old))
212            })
213            .collect()
214    } else {
215        Vec::new()
216    };
217    for (_, old) in &renamed {
218        close_superseded_review(review_provider.as_ref(), old, dry_run)?;
219    }
220
221    // After every review exists, write the description, link any issue the
222    // branch name references, then (in stack mode) write the stack overview
223    // into each body.
224    if let Some(desc) = desc {
225        crate::notes::update_description_note(
226            review_provider.as_ref(),
227            &desc_branch,
228            desc,
229            dry_run,
230        )?;
231    }
232    crate::notes::update_closes_notes(review_provider.as_ref(), &branches, dry_run)?;
233    if submit_stack || downstack {
234        crate::notes::update_stack_notes(
235            review_provider.as_ref(),
236            &branch_parents,
237            dry_run,
238            rebuild_overview,
239        )?;
240    }
241
242    // The ledger has now pruned the superseded entries, so drop the markers.
243    if !dry_run {
244        for (branch, _) in &renamed {
245            stack::clear_renamed_from(branch)?;
246        }
247    }
248
249    anstream::println!(
250        "{}",
251        style::success(&format!(
252            "submit complete: {} created, {} updated, {} skipped",
253            summary.created, summary.updated, summary.skipped
254        ))
255    );
256    Ok(())
257}
258
259/// Retire the open review still heading a renamed-away branch. The fresh
260/// review already exists, so closing here never leaves the work without one.
261/// Prompts (default yes; a non-interactive run proceeds) before closing.
262fn close_superseded_review(
263    review_provider: &dyn ReviewProvider,
264    old: &str,
265    dry_run: bool,
266) -> Result<()> {
267    let Some(review) = review_provider.review_for_branch(old)? else {
268        return Ok(());
269    };
270    if review.branch != *old {
271        return Ok(());
272    }
273
274    if dry_run {
275        println!("would close superseded review {} for {old}", review.id);
276        return Ok(());
277    }
278    if !crate::prompt::confirm_default_yes(&format!(
279        "close the replaced review {} for {old} and delete its branch? [Y/n] ",
280        review.id
281    ))? {
282        println!("kept review {} for {old}", review.id);
283        return Ok(());
284    }
285
286    review_provider.close_review(&review, true)?;
287    anstream::println!("closed superseded review {} for {old}", review.id);
288    Ok(())
289}
290
291fn branch_parents(branches: &[String]) -> Result<Vec<(String, String)>> {
292    let mut branch_parents = Vec::new();
293    for branch in branches {
294        let Some(parent) = stack::parent_for_branch(branch)? else {
295            bail!("{branch} has no stack parent; run `git stk adopt` or `git stk sync` first");
296        };
297        branch_parents.push((branch.to_owned(), parent));
298    }
299    Ok(branch_parents)
300}
301
302fn submit_branch(
303    review_provider: &dyn ReviewProvider,
304    branch: &str,
305    parent: &str,
306    dry_run: bool,
307    draft: bool,
308) -> Result<SubmitAction> {
309    if let Some(review) = review_provider.review_for_branch(branch)? {
310        if review.base == parent {
311            if dry_run {
312                println!(
313                    "would skip {} -> {} ({})",
314                    review.branch, review.base, review.id
315                );
316            } else {
317                anstream::println!(
318                    "{}",
319                    style::dim(&format!(
320                        "{} already targets {} ({})",
321                        review.branch, review.base, review.id
322                    ))
323                );
324            }
325            return Ok(SubmitAction::Skipped);
326        }
327
328        let output = if dry_run {
329            String::new()
330        } else {
331            review_provider.update_review_base(&review, parent)?
332        };
333        anstream::println!(
334            "{} {} -> {} {}",
335            if dry_run { "would update" } else { "updated" },
336            style::branch(&review.branch),
337            style::branch(parent),
338            style::dim(&format!("({})", review.id))
339        );
340        if !output.is_empty() {
341            println!("{output}");
342        }
343    } else {
344        let output = if dry_run {
345            String::new()
346        } else {
347            review_provider.create_review(branch, parent, draft)?
348        };
349        anstream::println!(
350            "{} {} -> {}",
351            if dry_run { "would create" } else { "created" },
352            style::branch(branch),
353            style::branch(parent)
354        );
355        if !output.is_empty() {
356            println!("{output}");
357        }
358        return Ok(SubmitAction::Created);
359    }
360
361    Ok(SubmitAction::Updated)
362}
363
364#[derive(Debug, Default)]
365struct SubmitSummary {
366    created: usize,
367    updated: usize,
368    skipped: usize,
369}
370
371impl SubmitSummary {
372    fn record(&mut self, action: SubmitAction) {
373        match action {
374            SubmitAction::Created => self.created += 1,
375            SubmitAction::Updated => self.updated += 1,
376            SubmitAction::Skipped => self.skipped += 1,
377        }
378    }
379}
380
381#[derive(Debug, Clone, Copy, Eq, PartialEq)]
382enum SubmitAction {
383    Created,
384    Updated,
385    Skipped,
386}