1use 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#[derive(serde::Serialize)]
16struct JsonPushError {
17 repo: String,
18 reason: String,
19}
20
21#[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 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(); let mut json_pushed: Vec<String> = Vec::new();
64 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 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 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 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 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 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
257fn has_commits_to_push(
259 repo: &Repository,
260 branch: &str,
261 default_branch: &str,
262) -> anyhow::Result<bool> {
263 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 if branch == default_branch {
285 return Ok(local_ref.peel_to_commit().is_ok());
286 }
287
288 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 match repo.find_reference(&format!("refs/heads/{}", default_branch)) {
296 Ok(r) => r,
297 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 local_oid == remote_oid {
326 return Ok(false);
327 }
328
329 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 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 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 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 let head = repo.head().unwrap();
385 let default_branch = head.shorthand().unwrap().to_string();
386
387 let head_commit = head.peel_to_commit().unwrap();
389 repo.branch("feat/test", &head_commit, false).unwrap();
390
391 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; }
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 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}