use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;
use crate::brand;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::process::{self, hide_window};
use crate::remote::config::{RemoteConfig, RemoteKind, check_name};
use crate::remote::folder::{PullReport, SiblingPull};
use crate::store::merge::{MergeOutcome, PendingMerge, RecordedConflict, write_merge_state};
use crate::store::{CommitId, LOCK_TIMEOUT, Store, StoreLock};
pub const IDLE_TIMEOUT: Duration = Duration::from_secs(120);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GitAuth {
#[default]
System,
Gh,
Token,
}
impl GitAuth {
pub const fn as_str(self) -> &'static str {
match self {
GitAuth::System => "system",
GitAuth::Gh => "gh",
GitAuth::Token => "token",
}
}
pub fn parse(text: Option<&str>) -> Result<Self, CoreError> {
match text {
None | Some("system") => Ok(Self::System),
Some("gh") => Ok(Self::Gh),
Some("token") => Ok(Self::Token),
Some(other) => Err(CoreError::new(
ErrorCode::InvalidValue,
format!("unknown auth {other:?}; expected system, gh or token"),
)),
}
}
}
pub fn is_github_url(url: &str) -> bool {
let host = url_host(url).unwrap_or_default();
host.eq_ignore_ascii_case("github.com") || host.eq_ignore_ascii_case("www.github.com")
}
pub fn url_scheme_host(url: &str) -> Option<(String, String)> {
if let Some((scheme, rest)) = url.split_once("://") {
if scheme.eq_ignore_ascii_case("file") {
return None;
}
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let host = authority.rsplit('@').next().unwrap_or_default();
return (!host.is_empty())
.then(|| (scheme.to_ascii_lowercase(), host.to_ascii_lowercase()));
}
let (before, _) = url.split_once(':')?;
if before.contains('/') || before.contains('\\') || before.len() < 2 {
return None;
}
let host = before.rsplit('@').next().unwrap_or_default();
(!host.is_empty()).then(|| ("ssh".to_owned(), host.to_ascii_lowercase()))
}
fn url_host(url: &str) -> Option<String> {
url_scheme_host(url).map(|(_, host)| {
host.rsplit_once(':')
.map_or(host.clone(), |(name, _)| name.to_owned())
})
}
pub fn locate(env: &Env, fs: &dyn Fs) -> Option<PathBuf> {
locate_program(env, fs, "git")
}
pub fn git_not_found(needed_for: &str) -> CoreError {
CoreError::new(
ErrorCode::ToolNotFound,
format!("Git isn't installed or isn't on PATH; install Git to use {needed_for}."),
)
}
pub(crate) fn locate_program(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
let (separator, file) = match env.os() {
Os::Windows => (';', format!("{name}.exe")),
Os::Linux | Os::MacOs => (':', name.to_owned()),
};
let path_var = env.var("PATH")?.to_string_lossy().into_owned();
path_var
.split(separator)
.map(|dir| PathBuf::from(dir.trim().trim_matches('"')))
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join(&file))
.find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invocation {
pub program: PathBuf,
pub args: Vec<OsString>,
pub env: Vec<(OsString, OsString)>,
pub cwd: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RunOutput {
pub success: bool,
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
}
pub trait Runner: Send + Sync {
fn run(&self, invocation: &Invocation, progress: &mut dyn FnMut(&str))
-> io::Result<RunOutput>;
}
#[derive(Debug, Clone, Copy)]
pub struct SystemRunner {
pub idle_timeout: Duration,
}
impl Default for SystemRunner {
fn default() -> Self {
Self {
idle_timeout: IDLE_TIMEOUT,
}
}
}
pub const SSH_BATCH_COMMAND: &str = "ssh -o BatchMode=yes";
pub fn ssh_batch_mode(
hiding: bool,
invocation: &Invocation,
configured: impl FnOnce() -> Option<bool>,
) -> Option<(OsString, OsString)> {
let git = invocation
.program
.file_stem()
.is_some_and(|stem| stem.eq_ignore_ascii_case("git"));
if !hiding || !git {
return None;
}
let own_env = invocation.env.iter().any(|(name, _)| {
name.eq_ignore_ascii_case("GIT_SSH_COMMAND") || name.eq_ignore_ascii_case("GIT_SSH")
});
let own_arg = invocation.args.iter().any(|arg| {
arg.to_string_lossy()
.to_ascii_lowercase()
.contains("core.sshcommand")
});
if own_env || own_arg || configured() != Some(false) {
return None;
}
Some(("GIT_SSH_COMMAND".into(), SSH_BATCH_COMMAND.into()))
}
fn ssh_command_configured(invocation: &Invocation) -> Option<bool> {
let status = hide_window(&mut Command::new(&invocation.program))
.args(["config", "--get", "core.sshCommand"])
.env_clear()
.envs(invocation.env.iter().map(|(k, v)| (k, v)))
.current_dir(&invocation.cwd)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.ok()?;
match status.code() {
Some(0) => Some(true),
Some(1) => Some(false),
_ => None,
}
}
impl Runner for SystemRunner {
fn run(
&self,
invocation: &Invocation,
progress: &mut dyn FnMut(&str),
) -> io::Result<RunOutput> {
let batch = ssh_batch_mode(process::hiding_console_windows(), invocation, || {
ssh_command_configured(invocation)
});
let mut child = hide_window(&mut Command::new(&invocation.program))
.args(&invocation.args)
.env_clear()
.envs(invocation.env.iter().map(|(k, v)| (k, v)))
.envs(batch)
.current_dir(&invocation.cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdout = child.stdout.take().expect("piped");
let mut stderr = child.stderr.take().expect("piped");
let (sender, receiver) = mpsc::channel::<String>();
let out_sender = sender.clone();
let stdout_bytes = Arc::new(Mutex::new(Vec::new()));
let out_bytes = Arc::clone(&stdout_bytes);
let out_thread = std::thread::spawn(move || {
let mut buf = [0u8; 4096];
loop {
match stdout.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
if let Ok(mut bytes) = out_bytes.lock() {
bytes.extend_from_slice(&buf[..n]);
}
let _ = out_sender.send(String::new());
}
}
}
});
let err_thread = std::thread::spawn(move || {
let mut line = Vec::new();
let mut buf = [0u8; 4096];
loop {
match stderr.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &byte in &buf[..n] {
if byte == b'\n' || byte == b'\r' {
let text = String::from_utf8_lossy(&line).into_owned();
line.clear();
if sender.send(text).is_err() {
return;
}
} else {
line.push(byte);
}
}
}
}
}
if !line.is_empty() {
let _ = sender.send(String::from_utf8_lossy(&line).into_owned());
}
});
let mut stderr_text = String::new();
let mut timed_out = false;
loop {
match receiver.recv_timeout(self.idle_timeout) {
Ok(line) => {
if !line.is_empty() {
progress(&line);
stderr_text.push_str(&line);
stderr_text.push('\n');
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {
timed_out = true;
kill_tree(invocation, &mut child);
break;
}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
let status = child.wait()?;
if !timed_out {
let _ = out_thread.join();
let _ = err_thread.join();
}
while let Ok(line) = receiver.try_recv() {
if !line.is_empty() {
stderr_text.push_str(&line);
stderr_text.push('\n');
}
}
let stdout = stdout_bytes.lock().map(|b| b.clone()).unwrap_or_default();
Ok(RunOutput {
success: status.success() && !timed_out,
stdout: String::from_utf8_lossy(&stdout).into_owned(),
stderr: stderr_text,
timed_out,
})
}
}
fn kill_tree(invocation: &Invocation, child: &mut std::process::Child) {
if cfg!(windows) {
let root = invocation
.env
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("SYSTEMROOT"))
.map_or_else(
|| PathBuf::from(r"C:\Windows"),
|(_, value)| PathBuf::from(value),
);
let _ = hide_window(&mut Command::new(
root.join("System32").join("taskkill.exe"),
))
.args(["/T", "/F", "/PID", &child.id().to_string()])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
}
pub struct GitCli<'a> {
pub git: PathBuf,
pub runner: &'a dyn Runner,
pub helper: Option<PathBuf>,
}
impl<'a> GitCli<'a> {
pub fn from_env(
env: &Env,
fs: &dyn Fs,
runner: &'a dyn Runner,
helper: Option<PathBuf>,
) -> Result<Self, CoreError> {
let git = locate(env, fs).ok_or_else(|| git_not_found("Git remotes"))?;
Ok(Self {
git,
runner,
helper,
})
}
}
pub fn auth_args(
remote: &RemoteConfig,
helper: Option<&Path>,
os: Os,
) -> Result<Vec<OsString>, CoreError> {
check_name(&remote.name)?;
let helper_flag = |value: String| -> Vec<OsString> {
vec![
"-c".into(),
"credential.helper=".into(),
"-c".into(),
format!("credential.helper={value}").into(),
]
};
Ok(match GitAuth::parse(remote.auth.as_deref())? {
GitAuth::System => Vec::new(),
GitAuth::Gh => helper_flag("!gh auth git-credential".to_owned()),
GitAuth::Token => {
let exe = helper.ok_or_else(|| {
CoreError::new(
ErrorCode::InvalidValue,
"auth = token needs the surjection binary as the credential helper",
)
})?;
let mut path = exe.to_string_lossy().into_owned();
if os == Os::Windows {
path = path.replace('\\', "/");
}
if path.contains(['"', '$', '`', '\\']) {
return Err(CoreError::new(
ErrorCode::InvalidPath,
"the surjection binary's path cannot be quoted for git",
)
.with_path(exe));
}
helper_flag(format!(
"!\"{path}\" git-credential --remote {}",
remote.name
))
}
})
}
fn url(remote: &RemoteConfig) -> Result<&str, CoreError> {
check_name(&remote.name)?;
if remote.kind != RemoteKind::Git {
return Err(CoreError::new(
ErrorCode::InvalidValue,
format!("{} is not a git remote", remote.name),
));
}
let url = remote
.url
.as_deref()
.filter(|u| !u.trim().is_empty())
.ok_or_else(|| {
CoreError::new(
ErrorCode::MissingField,
format!("git remote {} has no url", remote.name),
)
})?;
if url.starts_with('-') {
return Err(CoreError::new(
ErrorCode::InvalidValue,
format!("git remote {} has an invalid url {url:?}", remote.name),
));
}
Ok(url)
}
const REPOSITORY_VARS: [&str; 16] = [
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_COMMON_DIR",
"GIT_CONFIG",
"GIT_CONFIG_COUNT",
"GIT_CONFIG_PARAMETERS",
"GIT_DIR",
"GIT_GRAFT_FILE",
"GIT_IMPLICIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_INTERNAL_SUPER_PREFIX",
"GIT_NAMESPACE",
"GIT_NO_REPLACE_OBJECTS",
"GIT_OBJECT_DIRECTORY",
"GIT_PREFIX",
"GIT_REPLACE_REF_BASE",
"GIT_SHALLOW_FILE",
];
fn invocation(store: &Store<'_>, git: &GitCli<'_>, args: Vec<OsString>) -> Invocation {
let overridden = |name: &OsStr| {
let name = name.to_string_lossy();
name.eq_ignore_ascii_case("GIT_TERMINAL_PROMPT")
|| name.eq_ignore_ascii_case("GIT_WORK_TREE")
|| name.eq_ignore_ascii_case(brand::HOME_ENV_VAR)
|| name.eq_ignore_ascii_case(brand::legacy::HOME_ENV_VAR)
|| REPOSITORY_VARS
.iter()
.any(|var| name.eq_ignore_ascii_case(var))
};
let mut env: Vec<(OsString, OsString)> = store
.env()
.vars()
.map(|(name, value)| (OsString::from(name), value.to_owned()))
.filter(|(name, _)| !overridden(name))
.collect();
env.push(("GIT_TERMINAL_PROMPT".into(), "0".into()));
if let Some(home) = store.root().parent() {
env.push((brand::HOME_ENV_VAR.into(), home.as_os_str().to_owned()));
}
Invocation {
program: git.git.clone(),
args,
env,
cwd: store.root().to_path_buf(),
}
}
fn is_non_fast_forward(output: &RunOutput) -> bool {
let lower = output.stderr.to_lowercase();
lower.contains("[rejected]")
&& (lower.contains("non-fast-forward") || lower.contains("fetch first"))
}
fn failure(remote: &RemoteConfig, action: &str, output: &RunOutput) -> CoreError {
let lower = output.stderr.to_lowercase();
let first = output
.stderr
.lines()
.map(str::trim)
.rfind(|line| {
line.starts_with("fatal:") || line.starts_with("error:") || line.contains("rejected]")
})
.or_else(|| {
output
.stderr
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
})
.unwrap_or("no error message");
let first: String = first.chars().take(300).collect();
let code = if output.timed_out {
ErrorCode::RemoteUnreachable
} else if lower.contains("[rejected]")
|| lower.contains("[remote rejected]")
|| lower.contains("failed to push some refs")
{
ErrorCode::RemoteRejected
} else if lower.contains("authentication failed")
|| lower.contains("permission denied (publickey")
|| lower.contains("could not read username")
|| lower.contains("could not read password")
|| lower.contains("terminal prompts disabled")
|| lower.contains("returned error: 401")
|| lower.contains("returned error: 403")
{
ErrorCode::RemoteAuthFailed
} else {
ErrorCode::RemoteUnreachable
};
let message = if output.timed_out {
format!(
"git {action} with {} printed nothing for too long and was stopped",
remote.name
)
} else {
format!("git {action} with {} failed: {first}", remote.name)
};
CoreError::new(code, message)
}
fn run_raw(
store: &Store<'_>,
git: &GitCli<'_>,
args: Vec<OsString>,
progress: &mut dyn FnMut(&str),
) -> Result<RunOutput, CoreError> {
let invocation = invocation(store, git, args);
git.runner.run(&invocation, progress).map_err(|err| {
CoreError::new(ErrorCode::ToolNotFound, format!("cannot run git: {err}"))
.with_path(&git.git)
})
}
fn run(
store: &Store<'_>,
git: &GitCli<'_>,
remote: &RemoteConfig,
action: &str,
args: Vec<OsString>,
progress: &mut dyn FnMut(&str),
) -> Result<RunOutput, CoreError> {
let output = run_raw(store, git, args, progress)?;
if output.success {
Ok(output)
} else {
Err(failure(remote, action, &output))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitPush {
pub head: CommitId,
pub pulled: Option<PullReport>,
}
pub fn push(
store: &Store<'_>,
git: &GitCli<'_>,
remote: &RemoteConfig,
progress: &mut dyn FnMut(&str),
) -> Result<GitPush, CoreError> {
match push_once(store, git, remote, progress)? {
Ok(head) => Ok(GitPush { head, pulled: None }),
Err(output) if is_non_fast_forward(&output) => {
let report = pull(store, git, remote, progress)?;
if let Some(err) = report
.siblings
.iter()
.find_map(|s| s.outcome.as_ref().err())
{
return Err(err.clone());
}
if report.conflicts() > 0 {
return Err(CoreError::new(
ErrorCode::MergeConflict,
format!(
"{} has changes that conflict with this machine's; nothing pushed",
remote.name
),
));
}
match push_once(store, git, remote, progress)? {
Ok(head) => Ok(GitPush {
head,
pulled: Some(report),
}),
Err(output) => Err(failure(remote, "push", &output)),
}
}
Err(output) => Err(failure(remote, "push", &output)),
}
}
fn push_once(
store: &Store<'_>,
git: &GitCli<'_>,
remote: &RemoteConfig,
progress: &mut dyn FnMut(&str),
) -> Result<Result<CommitId, RunOutput>, CoreError> {
let url = url(remote)?;
let head = store.head()?;
let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
args.extend(
[
"push",
"--progress",
"--",
url,
"refs/heads/main:refs/heads/main",
"refs/tags/*:refs/tags/*",
]
.map(OsString::from),
);
let output = run_raw(store, git, args, progress)?;
Ok(if output.success {
Ok(head)
} else {
Err(output)
})
}
pub fn fetch(
store: &Store<'_>,
git: &GitCli<'_>,
remote: &RemoteConfig,
progress: &mut dyn FnMut(&str),
) -> Result<Option<CommitId>, CoreError> {
let url = url(remote)?;
let tracking = format!("refs/remotes/{}/main", remote.name);
let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
args.extend(
[
"fetch".to_owned(),
"--progress".to_owned(),
"--no-write-fetch-head".to_owned(),
"--".to_owned(),
url.to_owned(),
format!("+refs/heads/main:{tracking}"),
"+refs/tags/*:refs/tags/*".to_owned(),
]
.map(OsString::from),
);
let _lock = StoreLock::acquire(store.fs(), store.state_dir(), LOCK_TIMEOUT)?;
match run(store, git, remote, "fetch", args, progress) {
Ok(_) => {}
Err(err) if is_empty_remote(&err) => return Ok(None),
Err(err) => return Err(err),
}
store.reference_target(&tracking)
}
fn is_empty_remote(err: &CoreError) -> bool {
let lower = err.message().to_lowercase();
lower.contains("couldn't find remote ref") || lower.contains("could not find remote ref")
}
pub fn pull(
store: &Store<'_>,
git: &GitCli<'_>,
remote: &RemoteConfig,
progress: &mut dyn FnMut(&str),
) -> Result<PullReport, CoreError> {
let tag_targets = |store: &Store<'_>| -> Result<BTreeMap<String, CommitId>, CoreError> {
Ok(store
.tags()?
.into_iter()
.map(|tag| (tag.name, tag.target))
.collect())
};
let before = tag_targets(store)?;
let incoming = fetch(store, git, remote, progress)?;
let after = tag_targets(store)?;
let head_before = store.head()?;
let mut report = PullReport {
remote: remote.name.clone(),
tag: None,
head_before: head_before.clone(),
head_after: head_before,
siblings: Vec::new(),
artifacts: Vec::new(),
tags_imported: after
.keys()
.filter(|name| !before.contains_key(*name))
.cloned()
.collect(),
tags_moved: after
.iter()
.filter(|(name, target)| before.get(*name).is_some_and(|old| old != *target))
.map(|(name, _)| name.clone())
.collect(),
};
let refusal = incoming.as_ref().and_then(|incoming| {
store
.check_incoming(incoming, &format!("The remote \"{}\"", remote.name))
.err()
});
let attempted = if incoming.is_some() && refusal.is_none() {
vec![remote.name.clone()]
} else {
Vec::new()
};
let mut pending = Vec::new();
if let Some(incoming) = incoming {
let outcome = match refusal {
Some(err) => Err(err),
None => {
if !store.contains(&incoming) {
report.tag = Some(store.create_auto_tag("pre-pull")?);
}
store.merge_incoming(&incoming, &remote.name)
}
};
if let Ok(MergeOutcome::Conflicts { base, conflicts }) = &outcome {
pending.push(PendingMerge {
source: remote.name.clone(),
incoming: incoming.to_string(),
base: base.as_ref().map(ToString::to_string),
conflicts: conflicts.iter().map(RecordedConflict::from).collect(),
});
}
report.siblings.push(SiblingPull {
machine_id: None,
label: remote.name.clone(),
outcome,
});
}
write_merge_state(store.fs(), store.state_dir(), &attempted, &pending)?;
report.head_after = store.head()?;
Ok(report)
}