Skip to main content

gitgrip/cli/commands/
push.rs

1//! Push command implementation
2
3use crate::cli::outcome::CliOutcomeError;
4use crate::cli::output::Output;
5use crate::core::manifest::Manifest;
6use crate::core::repo::{
7    filter_repos, get_manifest_repo_info, validate_repo_filters_known, RepoInfo,
8};
9use crate::git::remote::{force_push_branch, push_branch};
10use crate::git::{get_current_branch, open_repo, path_exists};
11use git2::Repository;
12use std::path::Path;
13
14/// JSON-serializable push error for --json output
15#[derive(serde::Serialize)]
16struct JsonPushError {
17    repo: String,
18    reason: String,
19}
20
21/// Run the push command
22#[allow(clippy::too_many_arguments)]
23pub fn run_push(
24    workspace_root: &Path,
25    manifest: &Manifest,
26    set_upstream: bool,
27    force: bool,
28    quiet: bool,
29    json: bool,
30    repos_filter: Option<&[String]>,
31    group_filter: Option<&[String]>,
32) -> anyhow::Result<()> {
33    validate_repo_filters_known(manifest, repos_filter)
34        .map_err(|error| CliOutcomeError::refusal(error.to_string()))?;
35
36    if !json {
37        if force {
38            Output::header("Force pushing changes...");
39        } else {
40            Output::header("Pushing changes...");
41        }
42        println!();
43    }
44
45    let mut repos: Vec<RepoInfo> =
46        filter_repos(manifest, workspace_root, repos_filter, group_filter, false);
47
48    // Include manifest repo, respecting --repo filter
49    let include_manifest = match repos_filter {
50        None => true,
51        Some(filter) => filter.iter().any(|r| r == "manifest"),
52    };
53    if include_manifest {
54        if let Some(manifest_repo) = get_manifest_repo_info(manifest, workspace_root) {
55            repos.push(manifest_repo);
56        }
57    }
58
59    let mut success_count = 0;
60    let mut skip_count = 0;
61    let mut error_count = 0;
62    let mut failed_repos: Vec<(String, String)> = Vec::new(); // (repo_name, error_message)
63    let mut json_pushed: Vec<String> = Vec::new();
64    // What the human summary needs and the count alone cannot carry: WHICH repos
65    // were written to a remote. Kept separate from `json_pushed` so the --json
66    // shape stays exactly as consumers already parse it.
67    let mut pushed_detail: Vec<(String, String, Option<String>)> = Vec::new();
68    let mut json_skipped: Vec<String> = Vec::new();
69    let mut json_failed: Vec<JsonPushError> = Vec::new();
70
71    for repo in &repos {
72        if !path_exists(&repo.absolute_path) {
73            skip_count += 1;
74            continue;
75        }
76
77        match open_repo(&repo.absolute_path) {
78            Ok(git_repo) => {
79                let branch = match get_current_branch(&git_repo) {
80                    Ok(b) => b,
81                    Err(e) => {
82                        if !json {
83                            Output::error(&format!("{}: {}", repo.name, e));
84                        }
85                        error_count += 1;
86                        json_failed.push(JsonPushError {
87                            repo: repo.name.clone(),
88                            reason: e.to_string(),
89                        });
90                        continue;
91                    }
92                };
93
94                // Check if there's anything to push
95                if !has_commits_to_push(&git_repo, &branch, repo.target_branch())? {
96                    if !quiet && !json {
97                        Output::info(&format!("{}: nothing to push", repo.name));
98                    }
99                    skip_count += 1;
100                    json_skipped.push(repo.name.clone());
101                    continue;
102                }
103
104                let action = if force { "Force pushing" } else { "Pushing" };
105                let spinner = if !json {
106                    Some(Output::spinner(&format!("{} {}...", action, repo.name)))
107                } else {
108                    None
109                };
110
111                let result = if force {
112                    force_push_branch(&git_repo, &branch, &repo.push_remote)
113                } else {
114                    push_branch(&git_repo, &branch, &repo.push_remote, set_upstream)
115                };
116
117                match result {
118                    Ok(()) => {
119                        if let Some(s) = spinner {
120                            let msg = if force {
121                                format!("{}: force pushed", repo.name)
122                            } else if set_upstream {
123                                format!("{}: pushed and set upstream", repo.name)
124                            } else {
125                                format!("{}: pushed", repo.name)
126                            };
127                            s.finish_with_message(msg);
128                        }
129                        success_count += 1;
130                        json_pushed.push(repo.name.clone());
131                        // Read AFTER the push returned Ok, so this is the commit
132                        // the remote now carries. Optional rather than unwrap:
133                        // failing to name a sha must not fail a push that already
134                        // succeeded, and "(sha unavailable)" is an honest cell.
135                        let pushed_sha = git_repo
136                            .head()
137                            .ok()
138                            .and_then(|h| h.peel_to_commit().ok())
139                            .map(|c| c.id().to_string());
140                        pushed_detail.push((repo.name.clone(), branch.clone(), pushed_sha));
141                    }
142                    Err(e) => {
143                        // Check if this is a "nothing to push" situation
144                        let error_msg = e.to_string().to_lowercase();
145                        if error_msg.contains("everything up-to-date")
146                            || error_msg.contains("nothing to commit")
147                            || error_msg.contains("nothing to push")
148                            || error_msg.contains("no changes")
149                            || error_msg.contains("already up to date")
150                        {
151                            if let Some(s) = spinner {
152                                if !quiet {
153                                    s.finish_with_message(format!(
154                                        "{}: skipped (nothing to push)",
155                                        repo.name
156                                    ));
157                                } else {
158                                    s.finish_and_clear();
159                                }
160                            }
161                            skip_count += 1;
162                            json_skipped.push(repo.name.clone());
163                        } else {
164                            if let Some(s) = spinner {
165                                s.finish_with_message(format!("{}: failed - {}", repo.name, e));
166                            }
167                            error_count += 1;
168                            failed_repos.push((repo.name.clone(), format!("Error: {}", e)));
169                            json_failed.push(JsonPushError {
170                                repo: repo.name.clone(),
171                                reason: e.to_string(),
172                            });
173                        }
174                    }
175                }
176            }
177            Err(e) => {
178                if !json {
179                    Output::error(&format!("{}: {}", repo.name, e));
180                }
181                error_count += 1;
182                failed_repos.push((repo.name.clone(), format!("Error: {}", e)));
183                json_failed.push(JsonPushError {
184                    repo: repo.name.clone(),
185                    reason: e.to_string(),
186                });
187            }
188        }
189    }
190
191    if json {
192        #[derive(serde::Serialize)]
193        struct JsonPushResult {
194            success: bool,
195            pushed: Vec<String>,
196            skipped: Vec<String>,
197            failed: Vec<JsonPushError>,
198        }
199
200        let result = JsonPushResult {
201            success: error_count == 0,
202            pushed: json_pushed,
203            skipped: json_skipped,
204            failed: json_failed,
205        };
206        println!("{}", serde_json::to_string_pretty(&result)?);
207    } else {
208        println!();
209        let action = if force { "Force pushed" } else { "Pushed" };
210        if error_count == 0 {
211            if success_count > 0 {
212                Output::success(&format!("{} {} repo(s):", action, success_count));
213                // The count was never the useful part. A workspace can mix public
214                // and private remotes, so an operator publishing one reviewed
215                // branch needs to see everything else the same invocation sent.
216                for (name, branch, sha) in &pushed_detail {
217                    match sha {
218                        Some(sha) => println!(
219                            "    {}  refs/heads/{}  ->  {}",
220                            name,
221                            branch,
222                            &sha[..sha.len().min(12)]
223                        ),
224                        None => {
225                            println!("    {}  refs/heads/{}  ->  (sha unavailable)", name, branch)
226                        }
227                    }
228                }
229                if skip_count > 0 {
230                    println!("  {} had nothing to push.", skip_count);
231                }
232            } else {
233                println!("Nothing to push.");
234            }
235        } else {
236            Output::warning(&format!(
237                "{} {}, {} failed, {} skipped",
238                success_count,
239                action.to_lowercase(),
240                error_count,
241                skip_count
242            ));
243
244            // Show which repos failed and why
245            if !failed_repos.is_empty() {
246                println!();
247                for (repo_name, error_msg) in &failed_repos {
248                    println!("  ✗ {}: {}", repo_name, error_msg);
249                }
250            }
251        }
252    }
253
254    Ok(())
255}
256
257/// Check if branch has commits that aren't on the remote
258fn has_commits_to_push(
259    repo: &Repository,
260    branch: &str,
261    default_branch: &str,
262) -> anyhow::Result<bool> {
263    // Try to find the remote tracking branch
264    let remote_ref = format!("refs/remotes/origin/{}", branch);
265
266    let local_ref = match repo.find_reference(&format!("refs/heads/{}", branch)) {
267        Ok(r) => r,
268        Err(_) => return Ok(false),
269    };
270
271    let local_oid = local_ref.target().ok_or_else(|| {
272        anyhow::anyhow!(
273            "Could not resolve local branch '{}'. Ensure it exists and has at least one commit.",
274            branch
275        )
276    })?;
277
278    let remote_branch = match repo.find_reference(&remote_ref) {
279        Ok(r) => r,
280        Err(_) => {
281            // No remote tracking branch for this branch.
282            // If we're on the default branch itself, this is likely the first push
283            // — always allow it.
284            if branch == default_branch {
285                return Ok(local_ref.peel_to_commit().is_ok());
286            }
287
288            // For feature branches, compare against origin/<default_branch>
289            // to check for unique commits (not just "any commits exist").
290            let base_ref = format!("refs/remotes/origin/{}", default_branch);
291            let base = match repo.find_reference(&base_ref) {
292                Ok(r) => r,
293                Err(_) => {
294                    // No remote default branch either — fall back to local default branch
295                    match repo.find_reference(&format!("refs/heads/{}", default_branch)) {
296                        Ok(r) => r,
297                        // Can't determine base; assume there are commits to push
298                        Err(_) => return Ok(true),
299                    }
300                }
301            };
302
303            let base_oid = match base.target() {
304                Some(oid) => oid,
305                None => return Ok(true),
306            };
307
308            if local_oid == base_oid {
309                return Ok(false);
310            }
311
312            let (ahead, _behind) = repo.graph_ahead_behind(local_oid, base_oid)?;
313            return Ok(ahead > 0);
314        }
315    };
316
317    let remote_oid = remote_branch.target().ok_or_else(|| {
318        anyhow::anyhow!(
319            "Could not resolve remote tracking branch 'origin/{}'. Try running `gr sync` first.",
320            branch
321        )
322    })?;
323
324    // If they're the same, nothing to push
325    if local_oid == remote_oid {
326        return Ok(false);
327    }
328
329    // Check if local is ahead of remote
330    let (ahead, _behind) = repo.graph_ahead_behind(local_oid, remote_oid)?;
331    Ok(ahead > 0)
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use std::fs;
338    use tempfile::TempDir;
339
340    fn setup_test_repo() -> (TempDir, Repository) {
341        let temp_dir = TempDir::new().unwrap();
342        let repo = Repository::init(temp_dir.path()).unwrap();
343
344        // Configure user for commits
345        let mut config = repo.config().unwrap();
346        config.set_str("user.name", "Test User").unwrap();
347        config.set_str("user.email", "test@example.com").unwrap();
348
349        // Create initial commit
350        let file_path = temp_dir.path().join("test.txt");
351        fs::write(&file_path, "content").unwrap();
352
353        {
354            let mut index = repo.index().unwrap();
355            index.add_path(std::path::Path::new("test.txt")).unwrap();
356            index.write().unwrap();
357
358            let tree_id = index.write_tree().unwrap();
359            let tree = repo.find_tree(tree_id).unwrap();
360            let sig = repo.signature().unwrap();
361
362            repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
363                .unwrap();
364        }
365
366        (temp_dir, repo)
367    }
368
369    #[test]
370    fn test_has_commits_to_push_no_remote() {
371        let (_temp_dir, repo) = setup_test_repo();
372
373        // On the default branch with no remote — should return true
374        // (this is the initial push scenario)
375        let result = has_commits_to_push(&repo, "master", "master").unwrap();
376        assert!(result);
377    }
378
379    #[test]
380    fn test_has_commits_to_push_new_branch_no_changes() {
381        let (temp_dir, repo) = setup_test_repo();
382
383        // Get the default branch name
384        let head = repo.head().unwrap();
385        let default_branch = head.shorthand().unwrap().to_string();
386
387        // Create a new branch from the same commit (no new commits)
388        let head_commit = head.peel_to_commit().unwrap();
389        repo.branch("feat/test", &head_commit, false).unwrap();
390
391        // The new branch has no unique commits vs the default branch
392        let result = has_commits_to_push(&repo, "feat/test", &default_branch).unwrap();
393        assert!(!result, "Should not push branch with no unique commits");
394
395        let _ = temp_dir; // keep alive
396    }
397
398    #[test]
399    fn test_has_commits_to_push_new_branch_with_changes() {
400        let (temp_dir, repo) = setup_test_repo();
401
402        let head = repo.head().unwrap();
403        let default_branch = head.shorthand().unwrap().to_string();
404        let head_commit = head.peel_to_commit().unwrap();
405
406        // Create a new branch and add a commit
407        repo.branch("feat/test", &head_commit, false).unwrap();
408        repo.set_head("refs/heads/feat/test").unwrap();
409
410        let file_path = temp_dir.path().join("feature.txt");
411        fs::write(&file_path, "new feature").unwrap();
412        let mut index = repo.index().unwrap();
413        index.add_path(std::path::Path::new("feature.txt")).unwrap();
414        index.write().unwrap();
415        let tree_id = index.write_tree().unwrap();
416        let tree = repo.find_tree(tree_id).unwrap();
417        let sig = repo.signature().unwrap();
418        repo.commit(
419            Some("HEAD"),
420            &sig,
421            &sig,
422            "Add feature",
423            &tree,
424            &[&head_commit],
425        )
426        .unwrap();
427
428        let result = has_commits_to_push(&repo, "feat/test", &default_branch).unwrap();
429        assert!(result, "Should push branch with unique commits");
430    }
431}