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::{git, stack};
11
12/// Create or update a remote review request for a branch.
13#[derive(Debug, clap::Args)]
14pub struct Submit {
15    #[arg(add = ArgValueCompleter::new(completions::branch_candidates))]
16    branch: Option<String>,
17    /// Print what would change without creating or updating reviews.
18    #[arg(long, action = ArgAction::SetTrue)]
19    dry_run: bool,
20    /// Submit the whole stack parent-first, from anywhere in it.
21    #[arg(long, conflicts_with = "branch")]
22    stack: bool,
23    /// Submit only the current branch, overriding stk.submitStack.
24    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "stack")]
25    no_stack: bool,
26    /// Push branches (-u --force-with-lease) before submitting.
27    #[arg(long, action = ArgAction::SetTrue, conflicts_with = "no_push")]
28    push: bool,
29    /// Do not push branches, overriding stk.pushOnSubmit.
30    #[arg(long, action = ArgAction::SetTrue)]
31    no_push: bool,
32}
33
34impl Run for Submit {
35    fn run(self) -> Result<()> {
36        // Stack mode: --stack forces it on; --no-stack or an explicit branch
37        // forces it off; otherwise stk.submitStack decides.
38        let submit_stack = if self.stack {
39            true
40        } else if self.no_stack || self.branch.is_some() {
41            false
42        } else {
43            settings::bool_setting(settings::SUBMIT_STACK_KEY)?
44        };
45
46        submit(
47            self.branch.as_deref(),
48            submit_stack,
49            self.dry_run,
50            PushMode::from_flags(self.push, self.no_push),
51        )
52    }
53}
54
55pub fn submit(
56    branch: Option<&str>,
57    submit_stack: bool,
58    dry_run: bool,
59    push_mode: crate::cli::PushMode,
60) -> Result<()> {
61    let branch = branch
62        .map(str::to_owned)
63        .map_or_else(git::current_branch, Ok)?;
64
65    let branches = if submit_stack {
66        // The whole stack containing the current branch, from anywhere in it:
67        // walk to the root, then take its descendants. The root is excluded
68        // only when it is the trunk (the base everything sits on); an
69        // unanchored root stays in so validation can point at the missing
70        // parent instead of silently skipping it.
71        let root = stack::stack_root(&branch)?;
72        let trunk = stack::trunk_branch(&git::local_branches()?);
73        let full = stack::branch_and_descendants(&root)?;
74        if Some(root) == trunk {
75            full.into_iter().skip(1).collect()
76        } else {
77            full
78        }
79    } else {
80        vec![branch]
81    };
82
83    let branch_parents = branch_parents(&branches)?;
84
85    // Push after stack validation but before any provider calls: creating a
86    // review requires the branch to exist remotely, and -u --force-with-lease
87    // covers both first pushes and safely updating rebased branches.
88    let push = settings::push_enabled(push_mode, settings::PUSH_ON_SUBMIT_KEY)?;
89    if push {
90        let remote = settings::remote()?;
91        if dry_run {
92            println!("would push {} to {remote}", branches.join(" "));
93        } else {
94            git::push_set_upstream_force_with_lease(&remote, &branches)?;
95            println!("pushed {} to {remote}", branches.join(" "));
96        }
97    }
98
99    let provider = detect_provider()?;
100    let review_provider = review_provider(provider.kind);
101    let mut summary = SubmitSummary::default();
102
103    for (branch, parent) in &branch_parents {
104        summary.record(submit_branch(
105            review_provider.as_ref(),
106            branch,
107            parent,
108            dry_run,
109        )?);
110    }
111
112    // After every review exists, write the stack overview into each body.
113    if submit_stack {
114        crate::notes::update_stack_notes(review_provider.as_ref(), &branch_parents, dry_run)?;
115    }
116
117    println!(
118        "submit complete: {} created, {} updated, {} skipped",
119        summary.created, summary.updated, summary.skipped
120    );
121    Ok(())
122}
123
124fn branch_parents(branches: &[String]) -> Result<Vec<(String, String)>> {
125    let mut branch_parents = Vec::new();
126    for branch in branches {
127        let Some(parent) = stack::parent_for_branch(branch)? else {
128            bail!("{branch} has no stack parent; run `git stk adopt` or `git stk sync` first");
129        };
130        branch_parents.push((branch.to_owned(), parent));
131    }
132    Ok(branch_parents)
133}
134
135fn submit_branch(
136    review_provider: &dyn ReviewProvider,
137    branch: &str,
138    parent: &str,
139    dry_run: bool,
140) -> Result<SubmitAction> {
141    if let Some(review) = review_provider.review_for_branch(branch)? {
142        if review.base == parent {
143            if dry_run {
144                println!(
145                    "would skip {} -> {} ({})",
146                    review.branch, review.base, review.id
147                );
148            } else {
149                println!(
150                    "{} already targets {} ({})",
151                    review.branch, review.base, review.id
152                );
153            }
154            return Ok(SubmitAction::Skipped);
155        }
156
157        let output = if dry_run {
158            String::new()
159        } else {
160            review_provider.update_review_base(&review, parent)?
161        };
162        println!(
163            "{} {} -> {} ({})",
164            if dry_run { "would update" } else { "updated" },
165            review.branch,
166            parent,
167            review.id
168        );
169        if !output.is_empty() {
170            println!("{output}");
171        }
172    } else {
173        let output = if dry_run {
174            String::new()
175        } else {
176            review_provider.create_review(branch, parent)?
177        };
178        println!(
179            "{} {branch} -> {parent}",
180            if dry_run { "would create" } else { "created" }
181        );
182        if !output.is_empty() {
183            println!("{output}");
184        }
185        return Ok(SubmitAction::Created);
186    }
187
188    Ok(SubmitAction::Updated)
189}
190
191#[derive(Debug, Default)]
192struct SubmitSummary {
193    created: usize,
194    updated: usize,
195    skipped: usize,
196}
197
198impl SubmitSummary {
199    fn record(&mut self, action: SubmitAction) {
200        match action {
201            SubmitAction::Created => self.created += 1,
202            SubmitAction::Updated => self.updated += 1,
203            SubmitAction::Skipped => self.skipped += 1,
204        }
205    }
206}
207
208#[derive(Debug, Clone, Copy, Eq, PartialEq)]
209enum SubmitAction {
210    Created,
211    Updated,
212    Skipped,
213}