use crate::fleet::config::GitModules;
use crate::fleet::error::{Result, SuperGitError};
use crate::fleet::git::{GitOps, SubmoduleOps};
use crate::fleet::output::Formatter;
use std::path::Path;
use std::process::Command;
pub fn execute<P: AsRef<Path>>(
repo_root: P,
dry_run: bool,
verbose: bool,
) -> Result<()> {
let gitmodules = GitModules::parse(&repo_root)?;
Formatter::print_info(&format!(
"Staging all changes in superproject + {} submodule(s)",
gitmodules.submodules.len()
));
if dry_run {
Formatter::print_warning("DRY RUN: No changes will be made");
}
let mut successful = 0;
let mut failed = 0;
let mut skipped = 0;
for submodule in &gitmodules.submodules {
if verbose {
Formatter::print_submodule_header(&submodule.name);
}
let submodule_path = repo_root.as_ref().join(&submodule.path);
if !submodule_path.exists() {
Formatter::print_warning(&format!(
"Submodule '{}' not initialized, skipping",
submodule.name
));
skipped += 1;
continue;
}
let repo = match GitOps::open_repo(&submodule_path) {
Ok(r) => r,
Err(e) => {
Formatter::print_error(&format!(
"Failed to open '{}': {}",
submodule.name, e
));
failed += 1;
continue;
}
};
let is_clean = match GitOps::is_clean(&repo) {
Ok(c) => c,
Err(e) => {
Formatter::print_error(&format!(
"Failed to check status of '{}': {}",
submodule.name, e
));
failed += 1;
continue;
}
};
if is_clean {
if verbose {
Formatter::print_info(&format!("No changes in '{}'", submodule.name));
}
skipped += 1;
continue;
}
if dry_run {
let files = GitOps::get_uncommitted_files(&repo).unwrap_or_default();
Formatter::print_info(&format!(
"Would stage {} file(s) in '{}'",
files.len(),
submodule.name
));
successful += 1;
continue;
}
match SubmoduleOps::stage(&repo_root, submodule) {
Ok(_) => {
Formatter::print_success(&format!("Staged changes in '{}'", submodule.name));
successful += 1;
}
Err(e) => {
Formatter::print_error(&format!(
"Failed to stage in '{}': {}",
submodule.name, e
));
failed += 1;
}
}
}
if verbose {
Formatter::print_submodule_header("[SUPERPROJECT]");
}
if !dry_run {
let output = Command::new("git")
.arg("add")
.arg("-A")
.current_dir(&repo_root)
.output()?;
if output.status.success() {
Formatter::print_success("Staged changes in superproject");
successful += 1;
} else {
Formatter::print_error(&format!(
"Failed to stage superproject: {}",
String::from_utf8_lossy(&output.stderr)
));
failed += 1;
}
} else {
Formatter::print_info("Would stage changes in superproject");
successful += 1;
}
if !dry_run {
Formatter::print_summary(successful, failed, skipped);
}
if failed > 0 {
return Err(SuperGitError::Other(format!(
"{} repository/submodule(s) failed to stage",
failed
)));
}
Ok(())
}