//! Remotes (M4.10) against local bare repositories, never the network: //! clone with progress, push with and without upstream, a rejected push, //! fetch, pull by merge and by rebase, pull without upstream, remote //! management with redacted URLs, cancel before and during a call, and //! the clean-up after a failed clone. Every test skips with a message //! when git is not installed. #![allow( clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing )] use std::path::Path; use std::process::Command; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use lutra_vcs::{Cancel, Git, Network, ProgressSink, PullMode, Repo, VcsError}; /// The installed git, or `None` (with a message) when there is none. fn installed() -> Option { match Git::detect("") { Ok(git) => Some(git), Err(e) => { eprintln!("skipped: no usable git installed ({e})"); None } } } /// Runs git in `dir` for test setup and asserts it succeeded. fn git(dir: &Path, args: &[&str]) -> String { let out = Command::new("git") .args(args) .current_dir(dir) .env_remove("GIT_DIR") .env_remove("GIT_WORK_TREE") .env_remove("GIT_INDEX_FILE") .output() .unwrap(); assert!( out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_string() } /// Gives a work tree a local identity, no signing and no line-ending /// conversion. fn configure(dir: &Path) { for (key, value) in [ ("user.name", "Lutra Test"), ("user.email", "test@lutra.invalid"), ("commit.gpgsign", "false"), ("core.autocrlf", "false"), ] { git(dir, &["config", key, value]); } } /// Writes `name` with `text` and commits it. fn commit(dir: &Path, name: &str, text: &str) { std::fs::write(dir.join(name), text).unwrap(); git(dir, &["add", "--", name]); git(dir, &["commit", "-q", "-m", &format!("change {name}")]); } /// A bare repository `remote.git` with one commit on `main`, and its path. fn bare_with_commit(root: &Path) -> std::path::PathBuf { let bare = root.join("remote.git"); std::fs::create_dir(&bare).unwrap(); git(&bare, &["init", "-q", "--bare", "-b", "main"]); let seed = root.join("seed"); std::fs::create_dir(&seed).unwrap(); git(&seed, &["init", "-q", "-b", "main"]); configure(&seed); commit(&seed, "a.txt", "one\n"); git(&seed, &["push", "-q", bare.to_str().unwrap(), "main"]); bare } /// Clones `bare` into `root/` through Lutra, configures it, writes /// the files again without line-ending conversion, and opens it. fn clone_open(git_: &Git, bare: &Path, root: &Path, name: &str) -> Repo { let dir = root.join(name); git_.clone_repo(bare.to_str().unwrap(), &dir, &Network::default()) .unwrap(); configure(&dir); git(&dir, &["checkout-index", "-f", "-u", "-a"]); git_.open(&dir).unwrap().unwrap() } /// A file's text with `\r\n` as `\n` (a global `core.autocrlf` applies to /// clones). fn read(path: &Path) -> String { std::fs::read_to_string(path).unwrap().replace("\r\n", "\n") } /// A network setting that records every progress line. fn recording() -> (Network, Arc>>) { let lines = Arc::new(Mutex::new(Vec::new())); let copy = Arc::clone(&lines); let net = Network { progress: Some(ProgressSink(Arc::new(move |line: &str| { copy.lock().unwrap().push(line.to_string()); }))), cancel: None, }; (net, lines) } #[test] fn clone_reports_progress_and_lists_origin() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let dir = tmp.path().join("work"); let (net, lines) = recording(); g.clone_repo(bare.to_str().unwrap(), &dir, &net).unwrap(); assert_eq!(read(&dir.join("a.txt")), "one\n"); assert!( lines .lock() .unwrap() .iter() .any(|l| l.contains("Cloning into")), "progress: {:?}", lines.lock().unwrap() ); let repo = g.open(&dir).unwrap().unwrap(); let remotes = repo.remotes().unwrap(); assert_eq!(remotes.len(), 1); assert_eq!(remotes[0].name, "origin"); assert!( remotes[0] .fetch_url .as_deref() .unwrap() .contains("remote.git") ); assert_eq!( repo.head().unwrap().upstream.as_deref(), Some("origin/main") ); } #[test] fn clone_refuses_a_full_folder_and_cleans_up_after_failure() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let full = tmp.path().join("full"); std::fs::create_dir(&full).unwrap(); std::fs::write(full.join("x"), "x").unwrap(); let bare = bare_with_commit(tmp.path()); let err = g .clone_repo(bare.to_str().unwrap(), &full, &Network::default()) .unwrap_err(); assert!(err.is_invalid_input(), "{err}"); assert!(full.join("x").exists()); let missing = tmp.path().join("missing.git"); let target = tmp.path().join("new"); let err = g .clone_repo(missing.to_str().unwrap(), &target, &Network::default()) .unwrap_err(); let VcsError::Git(message) = err else { panic!("{err:?}") }; assert!( message.starts_with("The remote repository was not found"), "{message}" ); assert!(!target.exists()); let relative = g.clone_repo( bare.to_str().unwrap(), Path::new("rel"), &Network::default(), ); assert!(relative.unwrap_err().is_invalid_input()); let option = g.clone_repo( "--upload-pack=x", &tmp.path().join("o"), &Network::default(), ); assert!(option.unwrap_err().is_invalid_input()); } #[test] fn a_cancelled_clone_stops_and_leaves_nothing() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let target = tmp.path().join("cancelled"); std::fs::create_dir(&target).unwrap(); let cancel = Cancel::new(); cancel.cancel(); let net = Network { progress: None, cancel: Some(cancel), }; let err = g .clone_repo(bare.to_str().unwrap(), &target, &net) .unwrap_err(); assert_eq!(err, VcsError::Cancelled); assert!(target.is_dir(), "an empty folder given by the user stays"); assert_eq!(std::fs::read_dir(&target).unwrap().count(), 0); } #[test] fn push_sets_the_upstream_once_and_a_diverged_push_is_rejected() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let first = clone_open(&g, &bare, tmp.path(), "first"); let second = clone_open(&g, &bare, tmp.path(), "second"); git(first.root(), &["switch", "-q", "-c", "feature"]); commit(first.root(), "f.txt", "feature\n"); let (net, lines) = recording(); let pushed = first.push(None, &net).unwrap(); assert_eq!(pushed.remote, "origin"); assert_eq!(pushed.branch, "feature"); assert!(pushed.upstream_set); assert_eq!( first.head().unwrap().upstream.as_deref(), Some("origin/feature") ); assert!(!lines.lock().unwrap().is_empty()); commit(first.root(), "f.txt", "feature 2\n"); let again = first.push(None, &Network::default()).unwrap(); assert!(!again.upstream_set); assert_eq!( git(&bare, &["rev-parse", "feature"]), git(first.root(), &["rev-parse", "HEAD"]) ); git(first.root(), &["switch", "-q", "main"]); commit(first.root(), "a.txt", "from first\n"); first.push(None, &Network::default()).unwrap(); commit(second.root(), "b.txt", "from second\n"); let err = second.push(None, &Network::default()).unwrap_err(); let VcsError::Git(message) = err else { panic!("{err:?}") }; assert!(message.starts_with("The push was rejected"), "{message}"); assert!(message.contains("rejected")); } #[test] fn fetch_then_pull_by_merge_and_by_rebase() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let first = clone_open(&g, &bare, tmp.path(), "first"); let second = clone_open(&g, &bare, tmp.path(), "second"); commit(first.root(), "a.txt", "two\n"); first.push(None, &Network::default()).unwrap(); second.fetch(None, &Network::default()).unwrap(); assert_eq!(second.head().unwrap().behind, Some(1)); second.fetch(Some("origin"), &Network::default()).unwrap(); second.pull(PullMode::Merge, &Network::default()).unwrap(); assert_eq!(read(&second.root().join("a.txt")), "two\n"); commit(first.root(), "a.txt", "three\n"); first.push(None, &Network::default()).unwrap(); commit(second.root(), "local.txt", "mine\n"); second.pull(PullMode::Rebase, &Network::default()).unwrap(); assert_eq!(read(&second.root().join("a.txt")), "three\n"); let parents = git(second.root(), &["rev-list", "--parents", "-n", "1", "HEAD"]); assert_eq!(parents.split(' ').count(), 2, "rebased, no merge commit"); let head = second.head().unwrap(); assert_eq!((head.ahead, head.behind), (Some(1), Some(0))); let err = second.fetch(Some("-x"), &Network::default()).unwrap_err(); assert!(err.is_invalid_input()); } #[test] fn pull_without_upstream_explains_itself() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let repo = clone_open(&g, &bare, tmp.path(), "work"); git(repo.root(), &["switch", "-q", "-c", "lonely"]); let err = repo.pull(PullMode::Merge, &Network::default()).unwrap_err(); let VcsError::Git(message) = err else { panic!("{err:?}") }; assert!( message.starts_with("The current branch has no upstream"), "{message}" ); } #[test] fn remotes_are_added_changed_and_removed_with_redacted_urls() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let repo = clone_open(&g, &bare, tmp.path(), "work"); repo.remote_add("fork", "https://me:s3cret@example.invalid/a/b.git") .unwrap(); let remotes = repo.remotes().unwrap(); let fork = remotes.iter().find(|r| r.name == "fork").unwrap(); assert_eq!( fork.fetch_url.as_deref(), Some("https://***@example.invalid/a/b.git") ); assert!(repo.remote_add("fork", "x").is_err(), "exists already"); repo.remote_set_url("fork", "git@example.invalid:a/b.git") .unwrap(); let fork_url = repo .remotes() .unwrap() .into_iter() .find(|r| r.name == "fork") .and_then(|r| r.fetch_url); assert_eq!(fork_url.as_deref(), Some("git@example.invalid:a/b.git")); repo.remote_remove("fork").unwrap(); assert_eq!(repo.remotes().unwrap().len(), 1); let err = repo.remote_remove("fork").unwrap_err(); assert!(matches!(err, VcsError::Git(_)), "{err:?}"); assert!( repo.remote_add("bad name", "x") .unwrap_err() .is_invalid_input() ); assert!( repo.remote_add("ok", "ext::sh -c x") .unwrap_err() .is_invalid_input() ); repo.remote_remove("origin").unwrap(); git(repo.root(), &["switch", "-q", "-c", "nowhere"]); let err = repo.push(None, &Network::default()).unwrap_err(); assert!(err.to_string().contains("no remote to push to"), "{err}"); } #[test] fn cancel_stops_a_running_push() { let Some(g) = installed() else { return }; let tmp = tempfile::tempdir().unwrap(); let bare = bare_with_commit(tmp.path()); let hook = bare.join("hooks").join("pre-receive"); std::fs::write(&hook, "#!/bin/sh\nsleep 30\n").unwrap(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); } let repo = clone_open(&g, &bare, tmp.path(), "work"); commit(repo.root(), "a.txt", "slow\n"); let cancel = Cancel::new(); let net = Network { progress: None, cancel: Some(cancel.clone()), }; let stopper = std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(500)); cancel.cancel(); }); let started = Instant::now(); let err = repo.push(None, &net).unwrap_err(); stopper.join().unwrap(); assert_eq!(err, VcsError::Cancelled); assert!( started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed() ); }