| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Git remotes for `git sync`: their addresses, the labels braid knows them |
| 5 | //! by, and the git commands that fetch from them and push to them. |
| 6 | //! |
| 7 | //! Fetching and pushing run the `git` binary as a subprocess, since gitoxide |
| 8 | //! does not push yet. Each command runs in braid's mirror of the remote, with |
| 9 | //! the caller's environment (so credentials, SSH settings and proxies work as |
| 10 | //! for any git command) except for the variables that would point git at |
| 11 | //! another repository, and with these settings on top of the user's: no |
| 12 | //! hooks, no automatic garbage collection or maintenance in the mirror, and |
| 13 | //! no `ext::` transport. |
| 14 | |
| 15 | use std::ffi::OsString; |
| 16 | use std::path::{Path, PathBuf}; |
| 17 | use std::process::{Command, Output, Stdio}; |
| 18 | |
| 19 | use braid_git::GitOid; |
| 20 | |
| 21 | use crate::Error; |
| 22 | |
| 23 | /// The longest name a label keeps from its remote, before the hash. |
| 24 | const MAX_LABEL_NAME: usize = 40; |
| 25 | |
| 26 | /// Hex digits of the hash at the end of a label. |
| 27 | const LABEL_HASH_DIGITS: usize = 12; |
| 28 | |
| 29 | /// A git remote: where it is, and the label braid knows it by. |
| 30 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 31 | pub struct Remote { |
| 32 | address: String, |
| 33 | label: String, |
| 34 | } |
| 35 | |
| 36 | impl Remote { |
| 37 | /// Reads a remote as given to `git sync`: a URL (`https://`, `ssh://`, |
| 38 | /// `file://` and so on), an scp-like address such as `host:path`, or a |
| 39 | /// path. |
| 40 | /// |
| 41 | /// A path is made absolute, against the current directory, and resolved |
| 42 | /// when it exists, since the git commands run in the mirror. An address |
| 43 | /// that is empty, starts with `-`, or holds a control character is |
| 44 | /// refused. |
| 45 | /// |
| 46 | /// The label is the last name of the address's path, without `.git` and |
| 47 | /// with every byte other than ASCII letters, digits, `.`, `_` and `-` |
| 48 | /// turned into `-` (at most 40 of them, `remote` if none is left), then a |
| 49 | /// `-` and the first 12 hex digits of the BLAKE3 hash of the address |
| 50 | /// without any user name or password and without a trailing `/` or |
| 51 | /// `.git`. So `https://example.org/team/project.git` is `project-` and 12 |
| 52 | /// hex digits, with or without `.git`, a trailing `/` or credentials, and |
| 53 | /// credentials never reach a label. |
| 54 | pub fn new(remote: &str) -> Result<Remote, Error> { |
| 55 | let invalid = |reason| Error::InvalidRemote { |
| 56 | remote: remote.to_owned(), |
| 57 | reason, |
| 58 | }; |
| 59 | if remote.is_empty() { |
| 60 | return Err(invalid("it is empty")); |
| 61 | } |
| 62 | if remote.starts_with('-') { |
| 63 | return Err(invalid("it starts with '-'")); |
| 64 | } |
| 65 | if remote.chars().any(char::is_control) { |
| 66 | return Err(invalid("it holds a control character")); |
| 67 | } |
| 68 | let address = if remote.contains("://") || is_scp_like(remote) { |
| 69 | remote.to_owned() |
| 70 | } else { |
| 71 | local_path(remote)? |
| 72 | }; |
| 73 | let label = label_of(&address); |
| 74 | Ok(Remote { address, label }) |
| 75 | } |
| 76 | |
| 77 | /// The address git is given: the remote as written, or for a path, the |
| 78 | /// absolute path. |
| 79 | pub fn address(&self) -> &str { |
| 80 | &self.address |
| 81 | } |
| 82 | |
| 83 | /// The label: a short name for the remote, made only of ASCII letters, |
| 84 | /// digits, `.`, `_` and `-`. See [`Remote::new`]. |
| 85 | pub fn label(&self) -> &str { |
| 86 | &self.label |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | /// Whether git reads an address as `[user@]host:path`, which goes over SSH: |
| 91 | /// a colon with no slash before it. |
| 92 | fn is_scp_like(address: &str) -> bool { |
| 93 | match address.find(':') { |
| 94 | Some(colon) => colon > 0 && !address[..colon].contains('/'), |
| 95 | None => false, |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// A local path, absolute, and resolved when it exists. |
| 100 | fn local_path(path: &str) -> Result<String, Error> { |
| 101 | let absolute = std::path::absolute(path)?; |
| 102 | let resolved = absolute.canonicalize().unwrap_or_else(|_| absolute.clone()); |
| 103 | Ok(match resolved.to_str() { |
| 104 | Some(text) => text.to_owned(), |
| 105 | None => absolute.to_string_lossy().into_owned(), |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | /// The address without user name, password, trailing `/` or `.git`. |
| 110 | fn normalized(address: &str) -> String { |
| 111 | let mut text = if let Some(scheme) = address.find("://") { |
| 112 | let start = scheme + 3; |
| 113 | let end = address[start..] |
| 114 | .find('/') |
| 115 | .map_or(address.len(), |slash| start + slash); |
| 116 | match address[start..end].rfind('@') { |
| 117 | Some(at) => format!("{}{}", &address[..start], &address[start + at + 1..]), |
| 118 | None => address.to_owned(), |
| 119 | } |
| 120 | } else if is_scp_like(address) { |
| 121 | let colon = address.find(':').unwrap_or(0); |
| 122 | match address[..colon].rfind('@') { |
| 123 | Some(at) => address[at + 1..].to_owned(), |
| 124 | None => address.to_owned(), |
| 125 | } |
| 126 | } else { |
| 127 | address.to_owned() |
| 128 | }; |
| 129 | while text.ends_with('/') { |
| 130 | text.pop(); |
| 131 | } |
| 132 | if let Some(stripped) = text.strip_suffix(".git") { |
| 133 | text.truncate(stripped.len()); |
| 134 | } |
| 135 | while text.ends_with('/') { |
| 136 | text.pop(); |
| 137 | } |
| 138 | text |
| 139 | } |
| 140 | |
| 141 | fn label_of(address: &str) -> String { |
| 142 | let normalized = normalized(address); |
| 143 | let last = normalized.rsplit(['/', ':']).next().unwrap_or(""); |
| 144 | let mut name = String::new(); |
| 145 | for c in last.chars() { |
| 146 | let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { |
| 147 | c |
| 148 | } else { |
| 149 | '-' |
| 150 | }; |
| 151 | if !(c == '-' && name.ends_with('-')) { |
| 152 | name.push(c); |
| 153 | } |
| 154 | } |
| 155 | let mut name = name.trim_matches(['-', '.']).to_owned(); |
| 156 | if name.len() > MAX_LABEL_NAME { |
| 157 | name.truncate(MAX_LABEL_NAME); |
| 158 | name = name.trim_end_matches(['-', '.']).to_owned(); |
| 159 | } |
| 160 | if name.is_empty() { |
| 161 | name.push_str("remote"); |
| 162 | } |
| 163 | let hash = blake3::hash(normalized.as_bytes()).to_hex(); |
| 164 | format!("{name}-{}", &hash[..LABEL_HASH_DIGITS]) |
| 165 | } |
| 166 | |
| 167 | /// Environment variables that would point git at another repository, or |
| 168 | /// change which objects it sees. The commands sync runs never inherit them. |
| 169 | const REPOSITORY_VARIABLES: [&str; 13] = [ |
| 170 | "GIT_DIR", |
| 171 | "GIT_WORK_TREE", |
| 172 | "GIT_INDEX_FILE", |
| 173 | "GIT_OBJECT_DIRECTORY", |
| 174 | "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 175 | "GIT_COMMON_DIR", |
| 176 | "GIT_NAMESPACE", |
| 177 | "GIT_CEILING_DIRECTORIES", |
| 178 | "GIT_REPLACE_REF_BASE", |
| 179 | "GIT_NO_REPLACE_OBJECTS", |
| 180 | "GIT_GRAFT_FILE", |
| 181 | "GIT_SHALLOW_FILE", |
| 182 | "GIT_QUARANTINE_PATH", |
| 183 | ]; |
| 184 | |
| 185 | /// Settings every command sync runs gets on top of the user's. |
| 186 | const SETTINGS: [&str; 4] = [ |
| 187 | "core.hooksPath=/dev/null", |
| 188 | "gc.auto=0", |
| 189 | "maintenance.auto=false", |
| 190 | "protocol.ext.allow=never", |
| 191 | ]; |
| 192 | |
| 193 | /// Whether a fetch found the branch. |
| 194 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 195 | pub(crate) enum Fetched { |
| 196 | /// The branch was fetched into the ref asked for. |
| 197 | Branch, |
| 198 | /// The remote has no such branch. |
| 199 | Absent, |
| 200 | } |
| 201 | |
| 202 | /// What a push did. |
| 203 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 204 | pub(crate) enum Pushed { |
| 205 | /// The remote branch points at the commit now. |
| 206 | Done, |
| 207 | /// The remote branch did not move; this is git's reason. |
| 208 | Refused(String), |
| 209 | } |
| 210 | |
| 211 | /// The `git` binary, run with extra environment variables. |
| 212 | #[derive(Clone, Copy, Debug)] |
| 213 | pub(crate) struct Git<'a> { |
| 214 | env: &'a [(OsString, OsString)], |
| 215 | } |
| 216 | |
| 217 | impl<'a> Git<'a> { |
| 218 | pub(crate) fn new(env: &'a [(OsString, OsString)]) -> Self { |
| 219 | Git { env } |
| 220 | } |
| 221 | |
| 222 | /// A git command that runs in the repository `git_dir`, if given. |
| 223 | fn command(&self, git_dir: Option<&Path>) -> Command { |
| 224 | let mut command = Command::new("git"); |
| 225 | command.envs(self.env.iter().map(|(key, value)| (key, value))); |
| 226 | for variable in REPOSITORY_VARIABLES { |
| 227 | command.env_remove(variable); |
| 228 | } |
| 229 | for setting in SETTINGS { |
| 230 | command.arg("-c").arg(setting); |
| 231 | } |
| 232 | if let Some(dir) = git_dir { |
| 233 | command.arg("--git-dir").arg(dir).current_dir(dir); |
| 234 | } |
| 235 | command |
| 236 | .stdin(Stdio::null()) |
| 237 | .stdout(Stdio::piped()) |
| 238 | .stderr(Stdio::piped()); |
| 239 | command |
| 240 | } |
| 241 | |
| 242 | /// Runs a command and returns its output, whatever its exit status. |
| 243 | fn output(&self, what: &'static str, mut command: Command) -> Result<Output, Error> { |
| 244 | command.output().map_err(|err| Error::GitCommand { |
| 245 | command: what, |
| 246 | detail: format!("cannot run git: {err}"), |
| 247 | }) |
| 248 | } |
| 249 | |
| 250 | /// Runs a command that must succeed. |
| 251 | fn run(&self, what: &'static str, command: Command) -> Result<Output, Error> { |
| 252 | let output = self.output(what, command)?; |
| 253 | if output.status.success() { |
| 254 | Ok(output) |
| 255 | } else { |
| 256 | Err(failure(what, &output)) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | /// Creates an empty bare repository, without hooks or other templates. |
| 261 | pub(crate) fn init_bare(&self, path: &Path) -> Result<(), Error> { |
| 262 | let mut command = self.command(None); |
| 263 | if let Some(parent) = path.parent() { |
| 264 | command.current_dir(parent); |
| 265 | } |
| 266 | command |
| 267 | .args(["init", "--quiet", "--bare", "--template="]) |
| 268 | .arg(path); |
| 269 | self.run("init", command).map(drop) |
| 270 | } |
| 271 | |
| 272 | /// Fetches the branch `branch` (a full ref name) of `remote` into the ref |
| 273 | /// `into` of the repository `git_dir`, which is deleted first so that |
| 274 | /// the fetch never needs to force it. No tags, no submodules. |
| 275 | pub(crate) fn fetch( |
| 276 | &self, |
| 277 | git_dir: &Path, |
| 278 | remote: &str, |
| 279 | branch: &str, |
| 280 | into: &str, |
| 281 | ) -> Result<Fetched, Error> { |
| 282 | let mut delete = self.command(Some(git_dir)); |
| 283 | delete.args(["update-ref", "-d", into]); |
| 284 | self.run("update-ref", delete)?; |
| 285 | |
| 286 | let mut fetch = self.command(Some(git_dir)); |
| 287 | fetch |
| 288 | .args([ |
| 289 | "fetch", |
| 290 | "--quiet", |
| 291 | "--no-tags", |
| 292 | "--no-recurse-submodules", |
| 293 | "--", |
| 294 | remote, |
| 295 | ]) |
| 296 | .arg(format!("{branch}:{into}")); |
| 297 | let output = self.output("fetch", fetch)?; |
| 298 | if output.status.success() { |
| 299 | return Ok(Fetched::Branch); |
| 300 | } |
| 301 | // A missing branch is not an error; anything else is. |
| 302 | match self.ls_remote(git_dir, remote, branch) { |
| 303 | Ok(None) => Ok(Fetched::Absent), |
| 304 | _ => Err(failure("fetch", &output)), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | /// The commit the ref `name` (a full ref name) points to on `remote`. |
| 309 | pub(crate) fn ls_remote( |
| 310 | &self, |
| 311 | git_dir: &Path, |
| 312 | remote: &str, |
| 313 | name: &str, |
| 314 | ) -> Result<Option<GitOid>, Error> { |
| 315 | let mut command = self.command(Some(git_dir)); |
| 316 | command.args(["ls-remote", "--", remote, name]); |
| 317 | let output = self.run("ls-remote", command)?; |
| 318 | let text = String::from_utf8_lossy(&output.stdout); |
| 319 | for line in text.lines() { |
| 320 | if let Some((oid, found)) = line.split_once('\t') |
| 321 | && found == name |
| 322 | { |
| 323 | return oid.parse().map(Some).map_err(|_| Error::GitCommand { |
| 324 | command: "ls-remote", |
| 325 | detail: format!("unexpected output {line:?}"), |
| 326 | }); |
| 327 | } |
| 328 | } |
| 329 | Ok(None) |
| 330 | } |
| 331 | |
| 332 | /// Pushes `commit` from the repository `git_dir` to the branch `branch` |
| 333 | /// (a full ref name) of `remote`, only if that branch still points to |
| 334 | /// `expected` (`None`: only if it does not exist): an atomic push with a |
| 335 | /// lease, never a forced one. |
| 336 | pub(crate) fn push( |
| 337 | &self, |
| 338 | git_dir: &Path, |
| 339 | remote: &str, |
| 340 | branch: &str, |
| 341 | commit: GitOid, |
| 342 | expected: Option<GitOid>, |
| 343 | ) -> Result<Pushed, Error> { |
| 344 | let lease = match expected { |
| 345 | Some(oid) => format!("--force-with-lease={branch}:{oid}"), |
| 346 | None => format!("--force-with-lease={branch}:"), |
| 347 | }; |
| 348 | let refspec = format!("{commit}:{branch}"); |
| 349 | let mut command = self.command(Some(git_dir)); |
| 350 | command |
| 351 | .args(["push", "--atomic", "--porcelain"]) |
| 352 | .arg(lease) |
| 353 | .args(["--", remote]) |
| 354 | .arg(&refspec); |
| 355 | let output = self.output("push", command)?; |
| 356 | // Porcelain lines are `<flag> TAB <from>:<to> TAB <summary>`. |
| 357 | let text = String::from_utf8_lossy(&output.stdout); |
| 358 | for line in text.lines() { |
| 359 | let mut fields = line.splitn(3, '\t'); |
| 360 | let (Some(flag), Some(spec)) = (fields.next(), fields.next()) else { |
| 361 | continue; |
| 362 | }; |
| 363 | if spec != refspec { |
| 364 | continue; |
| 365 | } |
| 366 | let summary = fields.next().unwrap_or("").trim(); |
| 367 | return Ok(match flag { |
| 368 | // A fast-forward, a new branch, or already there. |
| 369 | " " | "*" | "=" => Pushed::Done, |
| 370 | _ => Pushed::Refused(summary.to_owned()), |
| 371 | }); |
| 372 | } |
| 373 | Err(failure("push", &output)) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// The error for a git command that failed: its exit status and what it |
| 378 | /// said. |
| 379 | fn failure(what: &'static str, output: &Output) -> Error { |
| 380 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 381 | let said: Vec<&str> = stderr |
| 382 | .lines() |
| 383 | .map(str::trim) |
| 384 | .filter(|line| !line.is_empty()) |
| 385 | .collect(); |
| 386 | let status = match output.status.code() { |
| 387 | Some(code) => format!("exit status {code}"), |
| 388 | None => "killed".to_owned(), |
| 389 | }; |
| 390 | Error::GitCommand { |
| 391 | command: what, |
| 392 | detail: if said.is_empty() { |
| 393 | status |
| 394 | } else { |
| 395 | format!("{status}: {}", said.join("; ")) |
| 396 | }, |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /// A temporary bare repository, removed when dropped: where a dry run |
| 401 | /// fetches, borrowing the objects of the mirror when there is one. |
| 402 | #[derive(Debug)] |
| 403 | pub(crate) struct Scratch { |
| 404 | path: PathBuf, |
| 405 | } |
| 406 | |
| 407 | impl Scratch { |
| 408 | pub(crate) fn create(git: &Git<'_>, borrow: Option<&Path>) -> Result<Scratch, Error> { |
| 409 | let base = std::path::absolute(std::env::temp_dir())?; |
| 410 | let nanos = std::time::SystemTime::now() |
| 411 | .duration_since(std::time::UNIX_EPOCH) |
| 412 | .map_or(0, |elapsed| elapsed.subsec_nanos()); |
| 413 | let mut attempt = 0u32; |
| 414 | let scratch = loop { |
| 415 | let path = base.join(format!( |
| 416 | "braid-sync-{}-{nanos}-{attempt}.git", |
| 417 | std::process::id() |
| 418 | )); |
| 419 | match std::fs::create_dir(&path) { |
| 420 | Ok(()) => break Scratch { path }, |
| 421 | Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists && attempt < 64 => { |
| 422 | attempt += 1; |
| 423 | } |
| 424 | Err(err) => return Err(err.into()), |
| 425 | } |
| 426 | }; |
| 427 | git.init_bare(&scratch.path)?; |
| 428 | if let Some(mirror) = borrow { |
| 429 | let info = scratch.path.join("objects").join("info"); |
| 430 | std::fs::create_dir_all(&info)?; |
| 431 | let objects = std::path::absolute(mirror.join("objects"))?; |
| 432 | let mut line = objects.into_os_string(); |
| 433 | line.push("\n"); |
| 434 | std::fs::write(info.join("alternates"), line.as_encoded_bytes())?; |
| 435 | } |
| 436 | Ok(scratch) |
| 437 | } |
| 438 | |
| 439 | pub(crate) fn path(&self) -> &Path { |
| 440 | &self.path |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | impl Drop for Scratch { |
| 445 | fn drop(&mut self) { |
| 446 | let _ = std::fs::remove_dir_all(&self.path); |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | #[cfg(test)] |
| 451 | mod tests { |
| 452 | use super::*; |
| 453 | |
| 454 | fn label(remote: &str) -> String { |
| 455 | Remote::new(remote).unwrap().label().to_owned() |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn labels() { |
| 460 | let https = label("https://example.org/team/project.git"); |
| 461 | assert!(https.starts_with("project-"), "{https}"); |
| 462 | assert_eq!(https.len(), "project-".len() + LABEL_HASH_DIGITS); |
| 463 | assert!( |
| 464 | https[8..] |
| 465 | .bytes() |
| 466 | .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) |
| 467 | ); |
| 468 | // The same remote written differently, or with credentials. |
| 469 | for same in [ |
| 470 | "https://example.org/team/project", |
| 471 | "https://example.org/team/project/", |
| 472 | "https://user:secret@example.org/team/project.git", |
| 473 | "https://token@example.org/team/project.git/", |
| 474 | ] { |
| 475 | assert_eq!(label(same), https, "{same}"); |
| 476 | } |
| 477 | assert_ne!(label("https://example.org/other/project.git"), https); |
| 478 | // scp-like addresses, with or without a user. |
| 479 | let scp = label("git@example.org:team/project.git"); |
| 480 | assert_eq!(label("example.org:team/project"), scp); |
| 481 | assert!(scp.starts_with("project-")); |
| 482 | assert_ne!(scp, https); |
| 483 | // Odd names are cleaned, and nothing of the user part is kept. |
| 484 | assert!(label("https://example.org/a/My Repo!!.git").starts_with("My-Repo-")); |
| 485 | assert!(label("https://example.org/").starts_with("example.org-")); |
| 486 | assert!(label("file:///").starts_with("remote-")); |
| 487 | let long = format!("https://example.org/{}", "x".repeat(100)); |
| 488 | assert_eq!(label(&long).len(), MAX_LABEL_NAME + 1 + LABEL_HASH_DIGITS); |
| 489 | assert!(!label("https://secret@example.org/r.git").contains("secret")); |
| 490 | } |
| 491 | |
| 492 | #[test] |
| 493 | fn local_paths_become_absolute() { |
| 494 | let dir = tempfile::tempdir().unwrap(); |
| 495 | let path = dir.path().join("remote.git"); |
| 496 | std::fs::create_dir(&path).unwrap(); |
| 497 | let remote = Remote::new(path.to_str().unwrap()).unwrap(); |
| 498 | assert!(Path::new(remote.address()).is_absolute()); |
| 499 | assert!(remote.label().starts_with("remote-")); |
| 500 | let relative = Remote::new("some/relative/dir.git").unwrap(); |
| 501 | assert!(Path::new(relative.address()).is_absolute()); |
| 502 | assert!(relative.address().ends_with("some/relative/dir.git")); |
| 503 | assert!(relative.label().starts_with("dir-")); |
| 504 | // An scp-like address and a path with a colon after a slash. |
| 505 | assert_eq!(Remote::new("host:dir").unwrap().address(), "host:dir"); |
| 506 | assert!(Path::new(Remote::new("./a:b").unwrap().address()).is_absolute()); |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn refused_remotes() { |
| 511 | for bad in ["", "-upload-pack=touch", "a\nb", "a\0b", "a\tb"] { |
| 512 | assert!( |
| 513 | matches!(Remote::new(bad), Err(Error::InvalidRemote { .. })), |
| 514 | "{bad:?}" |
| 515 | ); |
| 516 | } |
| 517 | } |
| 518 | } |