use std::path::{Path, PathBuf};
use greengate_runtime::migrate::{system_git, tracked};
use serde::Serialize;
pub const SUBJECT: &str = "chore: rename to greengate names";
pub const BRANCH: &str = "chore/greengate-names";
pub fn needs(repo_abs: &Path) -> bool {
tracked::needs(repo_abs, &system_git).unwrap_or(true)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum Outcome {
Committed { commit: String, leftovers: usize },
Skipped { why: String },
Failed { why: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
pub repo: PathBuf,
#[serde(flatten)]
pub outcome: Outcome,
}
fn git(repo_abs: &Path, args: &[&str]) -> Result<std::process::Output, String> {
std::process::Command::new("git")
.arg("-C")
.arg(repo_abs)
.args(args)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| format!("git {}: {e}", args.join(" ")))
}
fn git_stdout(repo_abs: &Path, args: &[&str]) -> Result<String, String> {
let out = git(repo_abs, args)?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
Err(format!("git {}: {}", args.join(" "), tail(&out)))
}
}
fn tail(out: &std::process::Output) -> String {
let text = format!(
"{}{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
lines[lines.len().saturating_sub(5)..].join("\n")
}
fn current_branch(repo_abs: &Path) -> Result<Option<String>, String> {
let out = git(repo_abs, &["symbolic-ref", "--quiet", "--short", "HEAD"])?;
if out.status.success() {
return Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
));
}
if out.status.code() == Some(1) && out.stderr.is_empty() {
return Ok(None);
}
Err(format!("git symbolic-ref HEAD: {}", tail(&out)))
}
fn undo(repo_abs: &Path, why: String) -> Outcome {
match git_stdout(repo_abs, &["reset", "-q", "--hard", "HEAD"]) {
Ok(_) => Outcome::Failed {
why: format!(
"{why}\nnothing was kept; fix that, then run `{} fix --apply --migrate` again",
greengate_runtime::names::FLEET_BIN
),
},
Err(reset) => Outcome::Failed {
why: format!(
"{why}\nand the undo failed too ({reset}); the rename may be staged: \
`git status` there"
),
},
}
}
pub fn run(repo_abs: &Path) -> Outcome {
let branch = match current_branch(repo_abs) {
Ok(branch) => branch,
Err(why) => return Outcome::Failed { why },
};
if branch.as_deref() != Some(BRANCH) {
return Outcome::Skipped {
why: format!(
"on {}, not {BRANCH}: `git switch -c {BRANCH} origin/HEAD` there (or the default branch)",
branch.as_deref().unwrap_or("a detached HEAD")
),
};
}
match git_stdout(repo_abs, &["status", "--porcelain", "--untracked-files=no"]) {
Ok(status) if status.is_empty() => {}
Ok(_) => {
return Outcome::Skipped {
why: "uncommitted changes to tracked files; commit or put them aside first"
.to_string(),
}
}
Err(why) => return Outcome::Failed { why },
}
let staged = match tracked::migrate_tracked(repo_abs, &system_git) {
Ok(staged) => staged,
Err(refused) if refused.staged_nothing() => {
return Outcome::Skipped {
why: refused.to_string(),
}
}
Err(why) => return undo(repo_abs, why.to_string()),
};
if !staged.changed() {
return Outcome::Skipped {
why: "nothing committed here carries greengate 3.x's names".to_string(),
};
}
if let Err(why) = git_stdout(repo_abs, &["commit", "-q", "-m", SUBJECT]) {
return undo(
repo_abs,
format!("the commit was refused (its hooks say why):\n{why}"),
);
}
match git_stdout(repo_abs, &["rev-parse", "--short", "HEAD"]) {
Ok(commit) => Outcome::Committed {
commit,
leftovers: staged.leftover_count,
},
Err(why) => Outcome::Failed {
why: format!("committed, but its id could not be read: {why}"),
},
}
}