use crate::staging::CanonicalTarget;
use std::path::Path;
pub const DEFAULT_BRANCH: &str = "main";
pub const REMOTE_NAME: &str = "origin";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedGit {
pub remote: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitSetup {
Initialized {
branch: String,
remote: Option<String>,
},
Existing,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitReport {
pub setup: GitSetup,
pub warning: Option<String>,
}
impl PlannedGit {
pub fn preview_line(&self) -> String {
match &self.remote {
None => "git init".to_owned(),
Some(url) => format!(
"git init (remote {REMOTE_NAME} {})",
crate::source::without_userinfo(url)
),
}
}
}
impl GitReport {
pub fn lines(&self) -> Vec<String> {
let mut lines = Vec::from_iter(self.warning.clone());
lines.push(match &self.setup {
GitSetup::Initialized {
branch,
remote: None,
} => format!("Initialized git repository on branch {branch}"),
GitSetup::Initialized {
branch,
remote: Some(url),
} => format!(
"Initialized git repository on branch {branch} with remote {REMOTE_NAME} {}",
crate::source::without_userinfo(url)
),
GitSetup::Existing => {
"Target is already inside a git repository; left it unchanged".to_owned()
}
});
lines
}
}
#[derive(Debug, thiserror::Error)]
pub enum GitTargetError {
#[error(
"the remote {url} already has history; clone it first, then apply the template into the clone"
)]
RemoteHasHistory { url: String },
#[error("could not check whether {path} is inside a git repository: {message}")]
Discover { path: String, message: String },
#[error("could not initialize a git repository at {path}: {message}")]
Init { path: String, message: String },
#[error("the credential resolver refused the remote {url}: {reason}")]
CredentialRefused { url: String, reason: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoteState {
Empty,
HasHistory,
Unreachable(String),
Refused(String),
}
#[derive(Debug)]
pub enum Preflight {
Existing,
Initialize {
remote: Option<String>,
warning: Option<String>,
},
}
pub fn default_branch(configured: Option<&str>) -> &str {
match configured.map(str::trim) {
None | Some("") | Some("master") => DEFAULT_BRANCH,
Some(name) => name,
}
}
pub fn preflight(
planned: &PlannedGit,
target: &CanonicalTarget,
) -> Result<Preflight, GitTargetError> {
preflight_with(planned, target, &probe)
}
pub(crate) fn preflight_with(
planned: &PlannedGit,
target: &CanonicalTarget,
probe: &dyn Fn(&str) -> RemoteState,
) -> Result<Preflight, GitTargetError> {
if inside_repository(target.as_path())? {
return Ok(Preflight::Existing);
}
let warning = match planned.remote.as_deref() {
None => None,
Some(url) => match probe(&probe_location(url, target.as_path())) {
RemoteState::Empty => None,
RemoteState::HasHistory => {
return Err(GitTargetError::RemoteHasHistory {
url: crate::source::without_userinfo(url),
});
}
RemoteState::Refused(reason) => {
return Err(GitTargetError::CredentialRefused {
url: crate::source::without_userinfo(url),
reason,
});
}
RemoteState::Unreachable(message) => Some(format!(
"warning: could not inspect the remote {}; added it without a history check: {message}",
crate::source::without_userinfo(url)
)),
},
};
Ok(Preflight::Initialize {
remote: planned.remote.clone(),
warning,
})
}
pub fn set_up(preflight: Preflight, target: &CanonicalTarget) -> Result<GitReport, GitTargetError> {
Ok(match preflight {
Preflight::Existing => GitReport {
setup: GitSetup::Existing,
warning: None,
},
Preflight::Initialize { remote, warning } => GitReport {
setup: GitSetup::Initialized {
branch: initialize(target.as_path(), remote.as_deref())?,
remote,
},
warning,
},
})
}
fn probe_location(url: &str, target: &Path) -> String {
let Ok(parsed) = gix::url::parse(gix::bstr::BStr::new(url)) else {
return url.to_owned();
};
if parsed.scheme != gix::url::Scheme::File {
return url.to_owned();
}
let path = gix::path::from_bstr(&parsed.path);
if !path.is_relative() || path.has_root() {
return match without_verbatim(&path) {
Some(plain) => plain.to_string_lossy().into_owned(),
None => url.to_owned(),
};
}
let mut resolved = without_verbatim(target).unwrap_or_else(|| target.to_path_buf());
let mut parts = path.components().peekable();
while let Some(part) = parts.peek() {
match part {
std::path::Component::ParentDir => {
resolved.pop();
}
std::path::Component::CurDir => {}
_ => break,
}
parts.next();
}
resolved.extend(parts);
resolved.to_string_lossy().into_owned()
}
fn without_verbatim(path: &Path) -> Option<std::path::PathBuf> {
let text = path.to_str()?;
let rest = text
.strip_prefix(r"\\?\")
.or_else(|| text.strip_prefix("//?/"))?;
let bytes = rest.as_bytes();
(bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
.then(|| std::path::PathBuf::from(rest))
}
fn inside_repository(path: &Path) -> Result<bool, GitTargetError> {
let start = path
.ancestors()
.find(|p| p.exists())
.unwrap_or(path)
.to_path_buf();
match gix::discover(&start) {
Ok(_) => Ok(true),
Err(gix::discover::Error::Discover(
gix::discover::upwards::Error::NoGitRepository { .. }
| gix::discover::upwards::Error::NoGitRepositoryWithinCeiling { .. }
| gix::discover::upwards::Error::NoGitRepositoryWithinFs { .. },
)) => Ok(false),
Err(err) => Err(GitTargetError::Discover {
path: path.display().to_string(),
message: err.to_string(),
}),
}
}
pub fn probe(url: &str) -> RemoteState {
let supplied = crate::source::Supplied::default();
match list_refs(url, &supplied) {
Ok(0) => RemoteState::Empty,
Ok(_) => RemoteState::HasHistory,
Err(message) => match supplied.refusal() {
Some(reason) => RemoteState::Refused(reason),
None => {
RemoteState::Unreachable(supplied.message(crate::source::redacted(&message, url)))
}
},
}
}
fn list_refs(url: &str, supplied: &crate::source::Supplied) -> Result<usize, String> {
let scratch = tempfile::tempdir().map_err(|e| e.to_string())?;
let repo = gix::init_bare(scratch.path()).map_err(|e| e.to_string())?;
let remote = repo
.remote_at(url)
.map_err(|e| e.to_string())?
.with_refspecs(["+refs/*:refs/probe/*"], gix::remote::Direction::Fetch)
.map_err(|e| e.to_string())?;
let mut connection = remote
.connect(gix::remote::Direction::Fetch)
.map_err(|e| e.to_string())?;
let mut roots = None;
crate::source::prepare_connection(&mut connection, &mut roots, supplied)
.map_err(|e| e.to_string())?;
let (map, _) = connection
.ref_map(
gix::progress::Discard,
gix::remote::ref_map::Options {
prefix_from_spec_as_filter_on_remote: false,
..Default::default()
},
)
.map_err(|e| e.to_string())?;
Ok(map
.remote_refs
.iter()
.filter(|r| !matches!(r, gix::protocol::handshake::Ref::Unborn { .. }))
.count())
}
pub fn initialize(target: &Path, remote: Option<&str>) -> Result<String, GitTargetError> {
let fail = |message: String| GitTargetError::Init {
path: target.display().to_string(),
message,
};
let repo = gix::init(target).map_err(|e| fail(e.to_string()))?;
let configured = repo
.config_snapshot()
.string("init.defaultBranch")
.map(|v| v.to_string());
let branch = default_branch(configured.as_deref()).to_owned();
set_head(&repo, &branch).map_err(fail)?;
if let Some(url) = remote {
add_remote(&repo, url).map_err(|message| fail(crate::source::redacted(&message, url)))?;
}
Ok(branch)
}
fn set_head(repo: &gix::Repository, branch: &str) -> Result<(), String> {
use gix::refs::{
FullName, Target,
transaction::{Change, LogChange, PreviousValue, RefEdit},
};
let referent = FullName::try_from(format!("refs/heads/{branch}"))
.map_err(|e| format!("invalid branch name {branch:?}: {e}"))?;
let head = FullName::try_from("HEAD").map_err(|e| e.to_string())?;
repo.edit_reference(RefEdit {
change: Change::Update {
log: LogChange::default(),
expected: PreviousValue::Any,
new: Target::Symbolic(referent),
},
name: head,
deref: false,
})
.map(|_| ())
.map_err(|e| e.to_string())
}
fn add_remote(repo: &gix::Repository, url: &str) -> Result<(), String> {
repo.remote_at(url).map_err(|e| e.to_string())?;
let path = repo.common_dir().join("config");
let mut file =
gix::config::File::from_path_no_includes(path.clone(), gix::config::Source::Local)
.map_err(|e| e.to_string())?;
{
let mut section = file
.section_mut_or_create_new("remote", Some(REMOTE_NAME.into()))
.map_err(|e| e.to_string())?;
section.push("url", url).map_err(|e| e.to_string())?;
section
.push(
"fetch",
format!("+refs/heads/*:refs/remotes/{REMOTE_NAME}/*").as_str(),
)
.map_err(|e| e.to_string())?;
}
let mut out = std::fs::File::create(&path).map_err(|e| e.to_string())?;
file.write_to(&mut out).map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests;