1use std::collections::BTreeMap;
27use std::ffi::{OsStr, OsString};
28use std::io::{self, Read};
29use std::path::{Path, PathBuf};
30use std::process::{Command, Stdio};
31use std::sync::{Arc, Mutex, mpsc};
32use std::time::Duration;
33
34use crate::brand;
35use crate::env::{Env, Os};
36use crate::error::{CoreError, ErrorCode};
37use crate::fs::Fs;
38use crate::process::{self, hide_window};
39use crate::remote::config::{RemoteConfig, RemoteKind, check_name};
40use crate::remote::folder::{PullReport, SiblingPull};
41use crate::store::merge::{MergeOutcome, PendingMerge, RecordedConflict, write_merge_state};
42use crate::store::{CommitId, LOCK_TIMEOUT, Store, StoreLock};
43
44pub const IDLE_TIMEOUT: Duration = Duration::from_secs(120);
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
49pub enum GitAuth {
50 #[default]
52 System,
53 Gh,
55 Token,
57}
58
59impl GitAuth {
60 pub const fn as_str(self) -> &'static str {
61 match self {
62 GitAuth::System => "system",
63 GitAuth::Gh => "gh",
64 GitAuth::Token => "token",
65 }
66 }
67
68 pub fn parse(text: Option<&str>) -> Result<Self, CoreError> {
70 match text {
71 None | Some("system") => Ok(Self::System),
72 Some("gh") => Ok(Self::Gh),
73 Some("token") => Ok(Self::Token),
74 Some(other) => Err(CoreError::new(
75 ErrorCode::InvalidValue,
76 format!("unknown auth {other:?}; expected system, gh or token"),
77 )),
78 }
79 }
80}
81
82pub fn is_github_url(url: &str) -> bool {
84 let host = url_host(url).unwrap_or_default();
85 host.eq_ignore_ascii_case("github.com") || host.eq_ignore_ascii_case("www.github.com")
86}
87
88pub fn url_scheme_host(url: &str) -> Option<(String, String)> {
92 if let Some((scheme, rest)) = url.split_once("://") {
93 if scheme.eq_ignore_ascii_case("file") {
94 return None;
95 }
96 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
97 let host = authority.rsplit('@').next().unwrap_or_default();
98 return (!host.is_empty())
99 .then(|| (scheme.to_ascii_lowercase(), host.to_ascii_lowercase()));
100 }
101 let (before, _) = url.split_once(':')?;
104 if before.contains('/') || before.contains('\\') || before.len() < 2 {
105 return None;
106 }
107 let host = before.rsplit('@').next().unwrap_or_default();
108 (!host.is_empty()).then(|| ("ssh".to_owned(), host.to_ascii_lowercase()))
109}
110
111fn url_host(url: &str) -> Option<String> {
112 url_scheme_host(url).map(|(_, host)| {
113 host.rsplit_once(':')
114 .map_or(host.clone(), |(name, _)| name.to_owned())
115 })
116}
117
118pub fn locate(env: &Env, fs: &dyn Fs) -> Option<PathBuf> {
121 locate_program(env, fs, "git")
122}
123
124pub fn git_not_found(needed_for: &str) -> CoreError {
128 CoreError::new(
129 ErrorCode::ToolNotFound,
130 format!("Git isn't installed or isn't on PATH; install Git to use {needed_for}."),
131 )
132}
133
134pub(crate) fn locate_program(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
136 let (separator, file) = match env.os() {
137 Os::Windows => (';', format!("{name}.exe")),
138 Os::Linux | Os::MacOs => (':', name.to_owned()),
139 };
140 let path_var = env.var("PATH")?.to_string_lossy().into_owned();
141 path_var
142 .split(separator)
143 .map(|dir| PathBuf::from(dir.trim().trim_matches('"')))
144 .filter(|dir| dir.is_absolute())
145 .map(|dir| dir.join(&file))
146 .find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct Invocation {
154 pub program: PathBuf,
155 pub args: Vec<OsString>,
156 pub env: Vec<(OsString, OsString)>,
157 pub cwd: PathBuf,
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Default)]
162pub struct RunOutput {
163 pub success: bool,
164 pub stdout: String,
165 pub stderr: String,
166 pub timed_out: bool,
168}
169
170pub trait Runner: Send + Sync {
172 fn run(&self, invocation: &Invocation, progress: &mut dyn FnMut(&str))
175 -> io::Result<RunOutput>;
176}
177
178#[derive(Debug, Clone, Copy)]
181pub struct SystemRunner {
182 pub idle_timeout: Duration,
183}
184
185impl Default for SystemRunner {
186 fn default() -> Self {
187 Self {
188 idle_timeout: IDLE_TIMEOUT,
189 }
190 }
191}
192
193pub const SSH_BATCH_COMMAND: &str = "ssh -o BatchMode=yes";
195
196pub fn ssh_batch_mode(
206 hiding: bool,
207 invocation: &Invocation,
208 configured: impl FnOnce() -> Option<bool>,
209) -> Option<(OsString, OsString)> {
210 let git = invocation
211 .program
212 .file_stem()
213 .is_some_and(|stem| stem.eq_ignore_ascii_case("git"));
214 if !hiding || !git {
215 return None;
216 }
217 let own_env = invocation.env.iter().any(|(name, _)| {
218 name.eq_ignore_ascii_case("GIT_SSH_COMMAND") || name.eq_ignore_ascii_case("GIT_SSH")
219 });
220 let own_arg = invocation.args.iter().any(|arg| {
221 arg.to_string_lossy()
222 .to_ascii_lowercase()
223 .contains("core.sshcommand")
224 });
225 if own_env || own_arg || configured() != Some(false) {
226 return None;
227 }
228 Some(("GIT_SSH_COMMAND".into(), SSH_BATCH_COMMAND.into()))
229}
230
231fn ssh_command_configured(invocation: &Invocation) -> Option<bool> {
235 let status = hide_window(&mut Command::new(&invocation.program))
236 .args(["config", "--get", "core.sshCommand"])
237 .env_clear()
238 .envs(invocation.env.iter().map(|(k, v)| (k, v)))
239 .current_dir(&invocation.cwd)
240 .stdin(Stdio::null())
241 .stdout(Stdio::null())
242 .stderr(Stdio::null())
243 .status()
244 .ok()?;
245 match status.code() {
246 Some(0) => Some(true),
247 Some(1) => Some(false),
248 _ => None,
249 }
250}
251
252impl Runner for SystemRunner {
253 fn run(
254 &self,
255 invocation: &Invocation,
256 progress: &mut dyn FnMut(&str),
257 ) -> io::Result<RunOutput> {
258 let batch = ssh_batch_mode(process::hiding_console_windows(), invocation, || {
259 ssh_command_configured(invocation)
260 });
261 let mut child = hide_window(&mut Command::new(&invocation.program))
262 .args(&invocation.args)
263 .env_clear()
264 .envs(invocation.env.iter().map(|(k, v)| (k, v)))
265 .envs(batch)
266 .current_dir(&invocation.cwd)
267 .stdin(Stdio::null())
268 .stdout(Stdio::piped())
269 .stderr(Stdio::piped())
270 .spawn()?;
271 let mut stdout = child.stdout.take().expect("piped");
272 let mut stderr = child.stderr.take().expect("piped");
273 let (sender, receiver) = mpsc::channel::<String>();
274 let out_sender = sender.clone();
275 let stdout_bytes = Arc::new(Mutex::new(Vec::new()));
276 let out_bytes = Arc::clone(&stdout_bytes);
277 let out_thread = std::thread::spawn(move || {
282 let mut buf = [0u8; 4096];
283 loop {
284 match stdout.read(&mut buf) {
285 Ok(0) | Err(_) => break,
286 Ok(n) => {
287 if let Ok(mut bytes) = out_bytes.lock() {
288 bytes.extend_from_slice(&buf[..n]);
289 }
290 let _ = out_sender.send(String::new());
292 }
293 }
294 }
295 });
296 let err_thread = std::thread::spawn(move || {
297 let mut line = Vec::new();
298 let mut buf = [0u8; 4096];
299 loop {
300 match stderr.read(&mut buf) {
301 Ok(0) | Err(_) => break,
302 Ok(n) => {
303 for &byte in &buf[..n] {
304 if byte == b'\n' || byte == b'\r' {
305 let text = String::from_utf8_lossy(&line).into_owned();
306 line.clear();
307 if sender.send(text).is_err() {
308 return;
309 }
310 } else {
311 line.push(byte);
312 }
313 }
314 }
315 }
316 }
317 if !line.is_empty() {
318 let _ = sender.send(String::from_utf8_lossy(&line).into_owned());
319 }
320 });
321 let mut stderr_text = String::new();
322 let mut timed_out = false;
323 loop {
324 match receiver.recv_timeout(self.idle_timeout) {
325 Ok(line) => {
326 if !line.is_empty() {
327 progress(&line);
328 stderr_text.push_str(&line);
329 stderr_text.push('\n');
330 }
331 }
332 Err(mpsc::RecvTimeoutError::Timeout) => {
333 timed_out = true;
334 kill_tree(invocation, &mut child);
335 break;
336 }
337 Err(mpsc::RecvTimeoutError::Disconnected) => break,
338 }
339 }
340 let status = child.wait()?;
341 if !timed_out {
342 let _ = out_thread.join();
344 let _ = err_thread.join();
345 }
346 while let Ok(line) = receiver.try_recv() {
347 if !line.is_empty() {
348 stderr_text.push_str(&line);
349 stderr_text.push('\n');
350 }
351 }
352 let stdout = stdout_bytes.lock().map(|b| b.clone()).unwrap_or_default();
353 Ok(RunOutput {
354 success: status.success() && !timed_out,
355 stdout: String::from_utf8_lossy(&stdout).into_owned(),
356 stderr: stderr_text,
357 timed_out,
358 })
359 }
360}
361
362fn kill_tree(invocation: &Invocation, child: &mut std::process::Child) {
367 if cfg!(windows) {
368 let root = invocation
369 .env
370 .iter()
371 .find(|(name, _)| name.eq_ignore_ascii_case("SYSTEMROOT"))
372 .map_or_else(
373 || PathBuf::from(r"C:\Windows"),
374 |(_, value)| PathBuf::from(value),
375 );
376 let _ = hide_window(&mut Command::new(
377 root.join("System32").join("taskkill.exe"),
378 ))
379 .args(["/T", "/F", "/PID", &child.id().to_string()])
380 .stdin(Stdio::null())
381 .stdout(Stdio::null())
382 .stderr(Stdio::null())
383 .status();
384 }
385 let _ = child.kill();
386}
387
388pub struct GitCli<'a> {
390 pub git: PathBuf,
392 pub runner: &'a dyn Runner,
393 pub helper: Option<PathBuf>,
395}
396
397impl<'a> GitCli<'a> {
398 pub fn from_env(
400 env: &Env,
401 fs: &dyn Fs,
402 runner: &'a dyn Runner,
403 helper: Option<PathBuf>,
404 ) -> Result<Self, CoreError> {
405 let git = locate(env, fs).ok_or_else(|| git_not_found("Git remotes"))?;
406 Ok(Self {
407 git,
408 runner,
409 helper,
410 })
411 }
412}
413
414pub fn auth_args(
416 remote: &RemoteConfig,
417 helper: Option<&Path>,
418 os: Os,
419) -> Result<Vec<OsString>, CoreError> {
420 check_name(&remote.name)?;
423 let helper_flag = |value: String| -> Vec<OsString> {
424 vec![
425 "-c".into(),
426 "credential.helper=".into(),
427 "-c".into(),
428 format!("credential.helper={value}").into(),
429 ]
430 };
431 Ok(match GitAuth::parse(remote.auth.as_deref())? {
432 GitAuth::System => Vec::new(),
433 GitAuth::Gh => helper_flag("!gh auth git-credential".to_owned()),
434 GitAuth::Token => {
435 let exe = helper.ok_or_else(|| {
436 CoreError::new(
437 ErrorCode::InvalidValue,
438 "auth = token needs the surjection binary as the credential helper",
439 )
440 })?;
441 let mut path = exe.to_string_lossy().into_owned();
444 if os == Os::Windows {
445 path = path.replace('\\', "/");
446 }
447 if path.contains(['"', '$', '`', '\\']) {
448 return Err(CoreError::new(
449 ErrorCode::InvalidPath,
450 "the surjection binary's path cannot be quoted for git",
451 )
452 .with_path(exe));
453 }
454 helper_flag(format!(
455 "!\"{path}\" git-credential --remote {}",
456 remote.name
457 ))
458 }
459 })
460}
461
462fn url(remote: &RemoteConfig) -> Result<&str, CoreError> {
463 check_name(&remote.name)?;
464 if remote.kind != RemoteKind::Git {
465 return Err(CoreError::new(
466 ErrorCode::InvalidValue,
467 format!("{} is not a git remote", remote.name),
468 ));
469 }
470 let url = remote
471 .url
472 .as_deref()
473 .filter(|u| !u.trim().is_empty())
474 .ok_or_else(|| {
475 CoreError::new(
476 ErrorCode::MissingField,
477 format!("git remote {} has no url", remote.name),
478 )
479 })?;
480 if url.starts_with('-') {
481 return Err(CoreError::new(
482 ErrorCode::InvalidValue,
483 format!("git remote {} has an invalid url {url:?}", remote.name),
484 ));
485 }
486 Ok(url)
487}
488
489const REPOSITORY_VARS: [&str; 16] = [
493 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
494 "GIT_COMMON_DIR",
495 "GIT_CONFIG",
496 "GIT_CONFIG_COUNT",
497 "GIT_CONFIG_PARAMETERS",
498 "GIT_DIR",
499 "GIT_GRAFT_FILE",
500 "GIT_IMPLICIT_WORK_TREE",
501 "GIT_INDEX_FILE",
502 "GIT_INTERNAL_SUPER_PREFIX",
503 "GIT_NAMESPACE",
504 "GIT_NO_REPLACE_OBJECTS",
505 "GIT_OBJECT_DIRECTORY",
506 "GIT_PREFIX",
507 "GIT_REPLACE_REF_BASE",
508 "GIT_SHALLOW_FILE",
509];
510
511fn invocation(store: &Store<'_>, git: &GitCli<'_>, args: Vec<OsString>) -> Invocation {
512 let overridden = |name: &OsStr| {
513 let name = name.to_string_lossy();
514 name.eq_ignore_ascii_case("GIT_TERMINAL_PROMPT")
515 || name.eq_ignore_ascii_case("GIT_WORK_TREE")
516 || name.eq_ignore_ascii_case(brand::HOME_ENV_VAR)
517 || name.eq_ignore_ascii_case(brand::legacy::HOME_ENV_VAR)
518 || REPOSITORY_VARS
519 .iter()
520 .any(|var| name.eq_ignore_ascii_case(var))
521 };
522 let mut env: Vec<(OsString, OsString)> = store
523 .env()
524 .vars()
525 .map(|(name, value)| (OsString::from(name), value.to_owned()))
526 .filter(|(name, _)| !overridden(name))
527 .collect();
528 env.push(("GIT_TERMINAL_PROMPT".into(), "0".into()));
529 if let Some(home) = store.root().parent() {
532 env.push((brand::HOME_ENV_VAR.into(), home.as_os_str().to_owned()));
533 }
534 Invocation {
535 program: git.git.clone(),
536 args,
537 env,
538 cwd: store.root().to_path_buf(),
539 }
540}
541
542fn is_non_fast_forward(output: &RunOutput) -> bool {
544 let lower = output.stderr.to_lowercase();
545 lower.contains("[rejected]")
546 && (lower.contains("non-fast-forward") || lower.contains("fetch first"))
547}
548
549fn failure(remote: &RemoteConfig, action: &str, output: &RunOutput) -> CoreError {
552 let lower = output.stderr.to_lowercase();
553 let first = output
554 .stderr
555 .lines()
556 .map(str::trim)
557 .rfind(|line| {
558 line.starts_with("fatal:") || line.starts_with("error:") || line.contains("rejected]")
559 })
560 .or_else(|| {
561 output
562 .stderr
563 .lines()
564 .map(str::trim)
565 .rfind(|l| !l.is_empty())
566 })
567 .unwrap_or("no error message");
568 let first: String = first.chars().take(300).collect();
569 let code = if output.timed_out {
570 ErrorCode::RemoteUnreachable
571 } else if lower.contains("[rejected]")
572 || lower.contains("[remote rejected]")
573 || lower.contains("failed to push some refs")
574 {
575 ErrorCode::RemoteRejected
576 } else if lower.contains("authentication failed")
577 || lower.contains("permission denied (publickey")
578 || lower.contains("could not read username")
579 || lower.contains("could not read password")
580 || lower.contains("terminal prompts disabled")
581 || lower.contains("returned error: 401")
582 || lower.contains("returned error: 403")
583 {
584 ErrorCode::RemoteAuthFailed
585 } else {
586 ErrorCode::RemoteUnreachable
587 };
588 let message = if output.timed_out {
589 format!(
590 "git {action} with {} printed nothing for too long and was stopped",
591 remote.name
592 )
593 } else {
594 format!("git {action} with {} failed: {first}", remote.name)
595 };
596 CoreError::new(code, message)
597}
598
599fn run_raw(
601 store: &Store<'_>,
602 git: &GitCli<'_>,
603 args: Vec<OsString>,
604 progress: &mut dyn FnMut(&str),
605) -> Result<RunOutput, CoreError> {
606 let invocation = invocation(store, git, args);
607 git.runner.run(&invocation, progress).map_err(|err| {
608 CoreError::new(ErrorCode::ToolNotFound, format!("cannot run git: {err}"))
609 .with_path(&git.git)
610 })
611}
612
613fn run(
614 store: &Store<'_>,
615 git: &GitCli<'_>,
616 remote: &RemoteConfig,
617 action: &str,
618 args: Vec<OsString>,
619 progress: &mut dyn FnMut(&str),
620) -> Result<RunOutput, CoreError> {
621 let output = run_raw(store, git, args, progress)?;
622 if output.success {
623 Ok(output)
624 } else {
625 Err(failure(remote, action, &output))
626 }
627}
628
629#[derive(Debug, Clone, PartialEq, Eq)]
631pub struct GitPush {
632 pub head: CommitId,
633 pub pulled: Option<PullReport>,
635}
636
637pub fn push(
642 store: &Store<'_>,
643 git: &GitCli<'_>,
644 remote: &RemoteConfig,
645 progress: &mut dyn FnMut(&str),
646) -> Result<GitPush, CoreError> {
647 match push_once(store, git, remote, progress)? {
648 Ok(head) => Ok(GitPush { head, pulled: None }),
649 Err(output) if is_non_fast_forward(&output) => {
650 let report = pull(store, git, remote, progress)?;
651 if let Some(err) = report
652 .siblings
653 .iter()
654 .find_map(|s| s.outcome.as_ref().err())
655 {
656 return Err(err.clone());
657 }
658 if report.conflicts() > 0 {
659 return Err(CoreError::new(
660 ErrorCode::MergeConflict,
661 format!(
662 "{} has changes that conflict with this machine's; nothing pushed",
663 remote.name
664 ),
665 ));
666 }
667 match push_once(store, git, remote, progress)? {
668 Ok(head) => Ok(GitPush {
669 head,
670 pulled: Some(report),
671 }),
672 Err(output) => Err(failure(remote, "push", &output)),
673 }
674 }
675 Err(output) => Err(failure(remote, "push", &output)),
676 }
677}
678
679fn push_once(
681 store: &Store<'_>,
682 git: &GitCli<'_>,
683 remote: &RemoteConfig,
684 progress: &mut dyn FnMut(&str),
685) -> Result<Result<CommitId, RunOutput>, CoreError> {
686 let url = url(remote)?;
687 let head = store.head()?;
688 let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
689 args.extend(
690 [
691 "push",
692 "--progress",
693 "--",
694 url,
695 "refs/heads/main:refs/heads/main",
696 "refs/tags/*:refs/tags/*",
697 ]
698 .map(OsString::from),
699 );
700 let output = run_raw(store, git, args, progress)?;
701 Ok(if output.success {
702 Ok(head)
703 } else {
704 Err(output)
705 })
706}
707
708pub fn fetch(
711 store: &Store<'_>,
712 git: &GitCli<'_>,
713 remote: &RemoteConfig,
714 progress: &mut dyn FnMut(&str),
715) -> Result<Option<CommitId>, CoreError> {
716 let url = url(remote)?;
717 let tracking = format!("refs/remotes/{}/main", remote.name);
718 let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
719 args.extend(
720 [
721 "fetch".to_owned(),
722 "--progress".to_owned(),
723 "--no-write-fetch-head".to_owned(),
724 "--".to_owned(),
725 url.to_owned(),
726 format!("+refs/heads/main:{tracking}"),
727 "+refs/tags/*:refs/tags/*".to_owned(),
728 ]
729 .map(OsString::from),
730 );
731 let _lock = StoreLock::acquire(store.fs(), store.state_dir(), LOCK_TIMEOUT)?;
732 match run(store, git, remote, "fetch", args, progress) {
733 Ok(_) => {}
734 Err(err) if is_empty_remote(&err) => return Ok(None),
735 Err(err) => return Err(err),
736 }
737 store.reference_target(&tracking)
738}
739
740fn is_empty_remote(err: &CoreError) -> bool {
741 let lower = err.message().to_lowercase();
742 lower.contains("couldn't find remote ref") || lower.contains("could not find remote ref")
743}
744
745pub fn pull(
749 store: &Store<'_>,
750 git: &GitCli<'_>,
751 remote: &RemoteConfig,
752 progress: &mut dyn FnMut(&str),
753) -> Result<PullReport, CoreError> {
754 let tag_targets = |store: &Store<'_>| -> Result<BTreeMap<String, CommitId>, CoreError> {
755 Ok(store
756 .tags()?
757 .into_iter()
758 .map(|tag| (tag.name, tag.target))
759 .collect())
760 };
761 let before = tag_targets(store)?;
762 let incoming = fetch(store, git, remote, progress)?;
763 let after = tag_targets(store)?;
764 let head_before = store.head()?;
765 let mut report = PullReport {
766 remote: remote.name.clone(),
767 tag: None,
768 head_before: head_before.clone(),
769 head_after: head_before,
770 siblings: Vec::new(),
771 artifacts: Vec::new(),
772 tags_imported: after
773 .keys()
774 .filter(|name| !before.contains_key(*name))
775 .cloned()
776 .collect(),
777 tags_moved: after
780 .iter()
781 .filter(|(name, target)| before.get(*name).is_some_and(|old| old != *target))
782 .map(|(name, _)| name.clone())
783 .collect(),
784 };
785 let refusal = incoming.as_ref().and_then(|incoming| {
789 store
790 .check_incoming(incoming, &format!("The remote \"{}\"", remote.name))
791 .err()
792 });
793 let attempted = if incoming.is_some() && refusal.is_none() {
795 vec![remote.name.clone()]
796 } else {
797 Vec::new()
798 };
799 let mut pending = Vec::new();
800 if let Some(incoming) = incoming {
801 let outcome = match refusal {
802 Some(err) => Err(err),
803 None => {
804 if !store.contains(&incoming) {
805 report.tag = Some(store.create_auto_tag("pre-pull")?);
806 }
807 store.merge_incoming(&incoming, &remote.name)
808 }
809 };
810 if let Ok(MergeOutcome::Conflicts { base, conflicts }) = &outcome {
811 pending.push(PendingMerge {
812 source: remote.name.clone(),
813 incoming: incoming.to_string(),
814 base: base.as_ref().map(ToString::to_string),
815 conflicts: conflicts.iter().map(RecordedConflict::from).collect(),
816 });
817 }
818 report.siblings.push(SiblingPull {
819 machine_id: None,
820 label: remote.name.clone(),
821 outcome,
822 });
823 }
824 write_merge_state(store.fs(), store.state_dir(), &attempted, &pending)?;
825 report.head_after = store.head()?;
826 Ok(report)
827}