diff --git a/cmux-tui/crates/cmux-tui/src/link/mod.rs b/cmux-tui/crates/cmux-tui/src/link/mod.rs index a0d3aae615bd..c9c4a270383b 100644 --- a/cmux-tui/crates/cmux-tui/src/link/mod.rs +++ b/cmux-tui/crates/cmux-tui/src/link/mod.rs @@ -11,6 +11,9 @@ mod dial; mod dial_cli; mod enrollment; mod ensure; +// Not wired into start-chat yet; its CLI entry is `cmux link seed plan`. +#[cfg_attr(not(test), allow(dead_code))] +mod seed; mod start_chat_cli; mod sync_cli; // Wired into `serve` when Cloud hosts run the link (needs the TeamDO peer @@ -115,6 +118,9 @@ pub(crate) fn run(args: &[String]) -> i32 { if args.first().map(String::as_str) == Some("sync") { return sync_cli::run(&args[1..]); } + if args.first().map(String::as_str) == Some("seed") { + return seed::run(&args[1..]); + } // So do `agent` and `access`. if args.first().map(String::as_str) == Some("agent") { return agent_cli::run(&args[1..]); diff --git a/cmux-tui/crates/cmux-tui/src/link/seed.rs b/cmux-tui/crates/cmux-tui/src/link/seed.rs new file mode 100644 index 000000000000..0c0ebeee32cc --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed.rs @@ -0,0 +1,95 @@ +//! `cmux link seed plan --local FOLDER --bundle OUT [--base SHA]`: plans a +//! `git-seed-v1` seed of a git working copy with a GitHub remote and +//! writes its bundle ([`plan`]). Not wired into `start-chat` yet. +//! +//! Output: one JSON line on stdout. A plan is `{"ok":true,"params":{...}, +//! "skipped":[{"path","why"}],"submodules":[{"path","commit"}], +//! "bases":[...],"bundle_bytes":N,"unchanged":false}`, exit 0. A folder that takes the +//! streamed copy instead is `{"ok":false,"code":CODE,"why":TEXT}`, exit 1 +//! ([`plan::FallbackCode`]). Bad usage exits 64. + +mod git; +mod github; +pub(crate) mod plan; +mod secrets; +#[cfg(test)] +mod tests; + +use std::path::PathBuf; + +use serde_json::json; + +const USAGE: &str = "usage: cmux link seed plan --local FOLDER --bundle OUT [--base SHA]"; + +pub(super) fn run(args: &[String]) -> i32 { + if matches!(args.first().map(String::as_str), None | Some("-h" | "--help" | "help")) { + println!("{USAGE}"); + return if args.is_empty() { 64 } else { 0 }; + } + let Some((local, bundle, base)) = parse(args) else { + eprintln!("{USAGE}"); + return 64; + }; + let planned = match &base { + Some(base) => plan::plan_with_base(&local, &bundle, base), + None => plan::plan(&local, &bundle), + }; + match planned { + Ok(planned) => { + let mut line = serde_json::to_value(&planned).unwrap_or_else(|_| json!({})); + if let Some(object) = line.as_object_mut() { + object.insert("ok".into(), json!(true)); + } + println!("{line}"); + 0 + } + Err(fallback) => { + println!( + "{}", + json!({ "ok": false, "code": fallback.code.as_str(), "why": fallback.why }) + ); + 1 + } + } +} + +fn parse(args: &[String]) -> Option<(PathBuf, PathBuf, Option)> { + let (action, rest) = args.split_first()?; + if action != "plan" { + return None; + } + let (mut local, mut bundle, mut base) = (None, None, None); + let mut rest = rest.iter(); + while let Some(flag) = rest.next() { + let value = rest.next()?; + match flag.as_str() { + "--local" => local = Some(PathBuf::from(value)), + "--bundle" => bundle = Some(PathBuf::from(value)), + "--base" => base = Some(value.clone()), + _ => return None, + } + } + Some((local?, bundle?, base)) +} + +#[cfg(test)] +mod cli_tests { + use super::parse; + + fn args(list: &[&str]) -> Vec { + list.iter().map(|arg| (*arg).to_string()).collect() + } + + #[test] + fn parses_plan_flags() { + let (local, bundle, base) = + parse(&args(&["plan", "--local", "/a", "--bundle", "/b", "--base", "abc"])).unwrap(); + assert_eq!(local.to_str(), Some("/a")); + assert_eq!(bundle.to_str(), Some("/b")); + assert_eq!(base.as_deref(), Some("abc")); + assert!(parse(&args(&["plan", "--local", "/a"])).is_none()); + assert!(parse(&args(&["plan", "--local", "/a", "--bundle"])).is_none()); + assert!(parse(&args(&["push", "--local", "/a", "--bundle", "/b"])).is_none()); + assert!(parse(&args(&["plan", "--local", "/a", "--bundle", "/b", "--x", "y"])).is_none()); + } +} diff --git a/cmux-tui/crates/cmux-tui/src/link/seed/git.rs b/cmux-tui/crates/cmux-tui/src/link/seed/git.rs new file mode 100644 index 000000000000..b1c9ece4d8b6 --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed/git.rs @@ -0,0 +1,88 @@ +//! Every git call of the seed plan. Each one turns off fsmonitor, refuses +//! implicit bare repositories, reads no system config, runs no hook, starts +//! no background gc, signs nothing and reads nothing from stdin. Caller +//! environment that would point git at another repository, index or object +//! store is dropped; the plan sets its own where it needs one. + +use std::path::Path; +use std::process::{Command, Stdio}; + +/// git with the plan's fixed settings and no `-C` or `--git-dir` yet. +fn base() -> Command { + let mut command = Command::new("git"); + command.args([ + "-c", + "core.fsmonitor=false", + "-c", + "safe.bareRepository=explicit", + "-c", + "core.hooksPath=/dev/null", + "-c", + "gc.auto=0", + "-c", + "maintenance.auto=false", + "-c", + "commit.gpgSign=false", + "-c", + "core.splitIndex=false", + "-c", + "i18n.commitEncoding=UTF-8", + ]); + command + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_TERMINAL_PROMPT", "0") + // `status` and friends never refresh the person's index. + .env("GIT_OPTIONAL_LOCKS", "0") + // A partial clone never fetches a missing blob from here. + .env("GIT_NO_LAZY_FETCH", "1") + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_COMMON_DIR") + .env_remove("GIT_INDEX_FILE") + .env_remove("GIT_OBJECT_DIRECTORY") + .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES") + .env_remove("GIT_NAMESPACE") + .env_remove("GIT_LITERAL_PATHSPECS") + .env_remove("GIT_GLOB_PATHSPECS") + .env_remove("GIT_NOGLOB_PATHSPECS") + .env_remove("GIT_ICASE_PATHSPECS") + .stdin(Stdio::null()); + command +} + +/// git in the working copy (or any folder) at `folder`. +pub(super) fn at(folder: &Path) -> Command { + let mut command = base(); + command.arg("-C").arg(folder); + command +} + +/// git in the bare repository at `git_dir`. +pub(super) fn bare(git_dir: &Path) -> Command { + let mut command = base(); + command.arg("--git-dir").arg(git_dir); + command +} + +/// stdout of a successful run, else git's stderr (or why it did not run). +pub(super) fn output(command: &mut Command) -> Result, String> { + let out = command.output().map_err(|error| format!("cannot run git: {error}"))?; + if out.status.success() { + Ok(out.stdout) + } else { + let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); + Err(if stderr.is_empty() { format!("git exited with {}", out.status) } else { stderr }) + } +} + +/// stdout of a successful run as text, without its trailing newline. +pub(super) fn text(command: &mut Command) -> Result { + let bytes = output(command)?; + let text = String::from_utf8_lossy(&bytes); + Ok(text.trim_end_matches(['\n', '\r']).to_string()) +} + +/// stdout of a successful run with any output; None on failure or nothing. +pub(super) fn optional(command: &mut Command) -> Option { + text(command).ok().filter(|line| !line.is_empty()) +} diff --git a/cmux-tui/crates/cmux-tui/src/link/seed/github.rs b/cmux-tui/crates/cmux-tui/src/link/seed/github.rs new file mode 100644 index 000000000000..8a632a662ddd --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed/github.rs @@ -0,0 +1,138 @@ +//! Which remote URLs are GitHub repositories, in the one https form the +//! machine clones. + +/// A GitHub repository, `owner/name`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct GithubRepo { + pub(super) owner: String, + pub(super) name: String, +} + +impl GithubRepo { + /// `https://github.com/OWNER/NAME.git`. + pub(super) fn url(&self) -> String { + format!("https://github.com/{}/{}.git", self.owner, self.name) + } + + /// `OWNER/NAME`. + pub(super) fn slug(&self) -> String { + format!("{}/{}", self.owner, self.name) + } +} + +/// The GitHub repository `url` names: `https://github.com/O/N(.git)`, +/// `git@github.com:O/N(.git)` or `ssh://git@github.com/O/N(.git)`. Any +/// login in an https URL is dropped. None for anything else. +pub(super) fn parse(url: &str) -> Option { + let url = url.trim(); + let path = if let Some(rest) = strip_prefix_ignore_case(url, "https://") { + // A login (`x-access-token:...@`) never goes further. + let (authority, path) = rest.split_once('/')?; + let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host); + if !host.eq_ignore_ascii_case("github.com") { + return None; + } + path + } else if let Some(rest) = strip_prefix_ignore_case(url, "ssh://git@github.com/") { + rest + } else { + strip_prefix_ignore_case(url, "git@github.com:")? + }; + let path = path.strip_suffix('/').unwrap_or(path); + let (owner, name) = path.split_once('/')?; + let name = name.strip_suffix(".git").unwrap_or(name); + if !valid_owner(owner) || !valid_name(name) { + return None; + } + Some(GithubRepo { owner: owner.to_string(), name: name.to_string() }) +} + +/// `url` with any login between `://` and `@` left out, for messages. +pub(super) fn redact(url: &str) -> String { + if let Some((scheme, rest)) = url.split_once("://") { + let (authority, path) = rest.split_once('/').unwrap_or((rest, "")); + if let Some((_, host)) = authority.rsplit_once('@') { + return format!("{scheme}://{host}/{path}"); + } + } + url.to_string() +} + +fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + let head = text.get(..prefix.len())?; + head.eq_ignore_ascii_case(prefix).then(|| &text[prefix.len()..]) +} + +fn valid_owner(owner: &str) -> bool { + !owner.is_empty() + && !owner.starts_with('-') + && owner.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') +} + +fn valid_name(name: &str) -> bool { + !name.is_empty() + && name != "." + && name != ".." + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn slug(url: &str) -> Option { + parse(url).map(|repo| repo.slug()) + } + + #[test] + fn github_forms_normalize_to_https() { + for url in [ + "https://github.com/acme/widget", + "https://github.com/acme/widget.git", + "https://github.com/acme/widget/", + "https://GitHub.com/acme/widget.git", + "https://x-access-token:secret@github.com/acme/widget.git", + "git@github.com:acme/widget.git", + "git@github.com:acme/widget", + "ssh://git@github.com/acme/widget.git", + "ssh://git@github.com/acme/widget", + ] { + let repo = parse(url).unwrap_or_else(|| panic!("{url} is GitHub")); + assert_eq!(repo.url(), "https://github.com/acme/widget.git", "{url}"); + assert_eq!(repo.slug(), "acme/widget"); + } + assert_eq!(slug("https://github.com/a-b/c.d_e.git").as_deref(), Some("a-b/c.d_e")); + } + + #[test] + fn other_urls_are_not_github() { + for url in [ + "https://gitlab.com/acme/widget.git", + "https://github.com.evil.example/acme/widget.git", + "https://evil.example/github.com/acme/widget.git", + "http://github.com/acme/widget.git", + "git@gitlab.com:acme/widget.git", + "ssh://git@github.com:22/acme/widget.git", + "file:///srv/acme/widget.git", + "/srv/acme/widget.git", + "https://github.com/acme", + "https://github.com/acme/widget/tree/main", + "https://github.com/-acme/widget", + "https://github.com/acme/..", + "", + ] { + assert_eq!(parse(url), None, "{url}"); + } + } + + #[test] + fn redact_drops_logins() { + assert_eq!( + redact("https://user:token@gitlab.com/acme/widget.git"), + "https://gitlab.com/acme/widget.git" + ); + assert_eq!(redact("git@gitlab.com:acme/widget.git"), "git@gitlab.com:acme/widget.git"); + } +} diff --git a/cmux-tui/crates/cmux-tui/src/link/seed/plan.rs b/cmux-tui/crates/cmux-tui/src/link/seed/plan.rs new file mode 100644 index 000000000000..e85d42fce2c2 --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed/plan.rs @@ -0,0 +1,713 @@ +//! The Mac side of `git-seed-v1` (design/cloud.md, "Getting the project +//! onto the machine"): decides whether a folder can be seeded from its +//! GitHub remote and builds the one bundle of what the remote lacks. +//! +//! The bundle carries `refs/cmux-seed/head` (HEAD), `refs/cmux-seed/index` +//! (a commit of the staged tree, parent HEAD), `refs/cmux-seed/work` (a +//! commit of the working tree with untracked files that are not ignored, +//! less the secrets [`secrets`] names, parent the index commit) and +//! `refs/cmux-seed/stash` when there is a stash, with `^BASE` as its one +//! prerequisite. Git leaves out of the bundle any seed ref whose commit +//! the machine already has (HEAD when it is the base; in a delta seed, +//! an unchanged HEAD or index); the params always name every commit. +//! +//! A delta seed ([`plan_since`]) sends only what changed after an earlier +//! seed, with that seed's work and head commits as the prerequisites. +//! +//! The person's index, working tree and refs never change: the index and +//! work commits are built through a copy of the index, and the bundle is +//! made from a scratch bare repository that borrows the repository's +//! objects through alternates, so the seed refs live only there. The seed's +//! blobs, trees and commits are written to the repository's object store +//! unreferenced, as `git stash create` does: a later delta seed builds on +//! them, and gc prunes them in time ([`FallbackCode::NoPrevious`]). + +use std::os::unix::fs::DirBuilderExt as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde::{Deserialize, Serialize}; + +use super::{git, github, secrets}; + +/// The `git.seed.start` params, less `folder` and `bundle` (the remote +/// paths the caller fills in). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SeedParams { + /// `https://github.com/OWNER/NAME.git`. + pub url: String, + /// `OWNER/NAME`. + pub repo: String, + /// The commit the machine clones at; the bundle's prerequisite. + pub base: String, + /// `refs/heads/NAME`, or None when HEAD is detached. + pub head_ref: Option, + pub head: String, + pub index: String, + pub work: String, + pub stash: Option, + /// The sparse-checkout patterns, when sparse checkout is on. + pub sparse: Option, + /// Whether a `.gitattributes` names `filter=lfs`. + pub lfs: bool, + /// The previous seed's work commit for a delta seed ([`plan_since`]), + /// else None. + pub since: Option, +} + +/// An untracked file left out of the work commit, and why in plain words. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Skipped { + pub path: String, + pub why: String, +} + +/// A submodule and the commit checked out in it (the recorded one when it +/// is not checked out). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Submodule { + pub path: String, + pub commit: String, +} + +/// A plan the machine can seed from, with its bundle written. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Planned { + pub params: SeedParams, + pub skipped: Vec, + pub submodules: Vec, + /// Bases to try, best first: the merge-base with the upstream, the + /// merge-base with the remote's default branch, that branch's tip. + /// When the machine answers `seed.base_missing`, re-plan with the + /// next one through [`plan_with_base`]. + pub bases: Vec, + /// Bytes of the bundle; 0 when [`Self::unchanged`] (no bundle is + /// written then). + pub bundle_bytes: u64, + /// A delta seed found HEAD, the index and the working tree as the + /// previous seed left them: nothing to send. + pub unchanged: bool, +} + +/// The commits an earlier seed of this folder sent ([`plan_since`]). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PreviousSeed { + pub head: String, + pub index: String, + pub work: String, +} + +/// Why a folder takes the streamed copy instead of a seed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FallbackCode { + /// Not inside a git working copy (or a bare repository). + NotGit, + /// Inside a working copy, but not its top folder. + NotTop, + /// The repository has no commit yet. + NoCommit, + /// The repository has no remote. + NoRemote, + /// Several remotes, no upstream and none called `origin`. + AmbiguousRemote, + /// The chosen remote is not a GitHub repository. + NotGithub, + /// No commit this Mac has is known to be on the remote. + NoBase, + /// The index has unresolved merge conflicts. + Unmerged, + /// A submodule has commits not on its remote, or uncommitted changes. + SubmoduleLocalWork, + /// A delta seed's previous commits are not in this repository (a gc + /// dropped them, or they came from another one). + NoPrevious, + /// git failed in a way the plan did not expect. + GitFailed, +} + +impl FallbackCode { + pub fn as_str(self) -> &'static str { + match self { + Self::NotGit => "not_git", + Self::NotTop => "not_top", + Self::NoCommit => "no_commit", + Self::NoRemote => "no_remote", + Self::AmbiguousRemote => "ambiguous_remote", + Self::NotGithub => "not_github", + Self::NoBase => "no_base", + Self::Unmerged => "unmerged", + Self::SubmoduleLocalWork => "submodule_local_work", + Self::NoPrevious => "no_previous", + Self::GitFailed => "git_failed", + } + } +} + +/// The folder takes the copy: [`FallbackCode`] and why in plain words. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Fallback { + pub code: FallbackCode, + pub why: String, +} + +impl Fallback { + fn new(code: FallbackCode, why: impl Into) -> Self { + Self { code, why: why.into() } + } +} + +fn failed(what: &str, error: String) -> Fallback { + Fallback::new(FallbackCode::GitFailed, format!("{what}: {error}")) +} + +/// Plans a seed of the working copy at `folder` from its best base and +/// writes the bundle to `out_bundle`. +pub fn plan(folder: &Path, out_bundle: &Path) -> Result { + let repo = Repo::open(folder)?; + let bases = repo.bases(); + let Some(base) = bases.first().cloned() else { + return Err(Fallback::new( + FallbackCode::NoBase, + format!( + "no commit on {} is known to share history with this folder's HEAD", + repo.remote + ), + )); + }; + build(&repo, out_bundle, &Since::Base(&base), bases) +} + +/// [`plan`] from `base` (one of [`Planned::bases`], after the machine +/// found the remote lacks the first). +pub fn plan_with_base(folder: &Path, out_bundle: &Path, base: &str) -> Result { + let repo = Repo::open(folder)?; + if !(4..=64).contains(&base.len()) || !base.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(Fallback::new(FallbackCode::NoBase, format!("{base:?} is not a commit id"))); + } + let Some(base) = git::optional(git::at(&repo.top).args([ + "rev-parse", + "--verify", + "-q", + format!("{base}^{{commit}}").as_str(), + ])) else { + return Err(Fallback::new( + FallbackCode::NoBase, + format!("this Mac does not have commit {base}"), + )); + }; + let bases = repo.bases(); + build(&repo, out_bundle, &Since::Base(&base), bases) +} + +/// A delta seed after `previous` (a seed the machine already applied): +/// the same refs, with `previous.work` and `previous.head` as the +/// prerequisites, so the bundle holds only what changed since. +/// [`SeedParams::base`] and [`SeedParams::since`] are `previous.work`; +/// [`Planned::bases`] is empty. When HEAD, the index and the working tree +/// are as `previous` left them, the answer is [`Planned::unchanged`] and +/// no bundle is written. The stash is carried but not compared. +pub fn plan_since( + folder: &Path, + out_bundle: &Path, + previous: &PreviousSeed, +) -> Result { + let repo = Repo::open(folder)?; + for id in [&previous.head, &previous.index, &previous.work] { + let hex = (4..=64).contains(&id.len()) && id.bytes().all(|byte| byte.is_ascii_hexdigit()); + if !hex || repo.commit(id).as_deref() != Some(id.as_str()) { + return Err(Fallback::new( + FallbackCode::NoPrevious, + format!("the previous seed's commit {id} is not in this repository"), + )); + } + } + build(&repo, out_bundle, &Since::Previous(previous), Vec::new()) +} + +/// What the machine already has. +enum Since<'a> { + Base(&'a str), + Previous(&'a PreviousSeed), +} + +/// The working copy as the plan sees it. +struct Repo { + top: PathBuf, + head: String, + head_ref: Option, + remote: String, + /// HEAD's upstream (`refs/remotes/...`) when it is on [`Self::remote`]. + upstream: Option, + github: github::GithubRepo, +} + +impl Repo { + fn open(folder: &Path) -> Result { + let shown = folder.display(); + let top = + git::text(git::at(folder).args(["rev-parse", "--show-toplevel"])).map_err(|_| { + Fallback::new(FallbackCode::NotGit, format!("{shown} is not a git working copy")) + })?; + let top = PathBuf::from(top); + let same = match (std::fs::canonicalize(folder), std::fs::canonicalize(&top)) { + (Ok(folder), Ok(top)) => folder == top, + _ => false, + }; + if !same { + return Err(Fallback::new( + FallbackCode::NotTop, + format!("{shown} is inside the git working copy at {}", top.display()), + )); + } + let Some(head) = + git::optional(git::at(&top).args(["rev-parse", "--verify", "-q", "HEAD^{commit}"])) + else { + return Err(Fallback::new(FallbackCode::NoCommit, "the repository has no commit yet")); + }; + let head_ref = git::optional(git::at(&top).args(["symbolic-ref", "-q", "HEAD"])); + let remotes: Vec = git::text(git::at(&top).arg("remote")) + .map_err(|error| failed("listing remotes", error))? + .lines() + .map(str::to_string) + .collect(); + if remotes.is_empty() { + return Err(Fallback::new(FallbackCode::NoRemote, "the repository has no remote")); + } + let tracked = head_ref.as_deref().and_then(|head_ref| upstream_of(&top, head_ref)); + let tracked = tracked.filter(|(remote, _)| remotes.contains(remote)); + let remote = if let Some((remote, _)) = &tracked { + remote.clone() + } else if remotes.iter().any(|remote| remote == "origin") { + "origin".to_string() + } else if let [only] = remotes.as_slice() { + only.clone() + } else { + return Err(Fallback::new( + FallbackCode::AmbiguousRemote, + format!( + "the repository has {} remotes, none is origin and the branch tracks none", + remotes.len() + ), + )); + }; + let github = remote_repo(&top, &remote)?; + Ok(Self { + top, + head, + head_ref, + remote, + upstream: tracked.map(|(_, upstream)| upstream), + github, + }) + } + + /// [`Planned::bases`], with duplicates left out. + fn bases(&self) -> Vec { + let mut bases = Vec::new(); + if let Some(upstream) = self.upstream.as_deref().and_then(|name| self.commit(name)) { + bases.extend(self.merge_base(&upstream)); + } + let remote = &self.remote; + let default = [ + format!("refs/remotes/{remote}/HEAD"), + format!("refs/remotes/{remote}/main"), + format!("refs/remotes/{remote}/master"), + ] + .iter() + .find_map(|name| self.commit(name)); + if let Some(tip) = default { + bases.extend(self.merge_base(&tip)); + bases.push(tip); + } + let mut seen = std::collections::HashSet::new(); + bases.retain(|base| seen.insert(base.clone())); + bases + } + + fn commit(&self, name: &str) -> Option { + git::optional(git::at(&self.top).args([ + "rev-parse", + "--verify", + "-q", + format!("{name}^{{commit}}").as_str(), + ])) + } + + fn merge_base(&self, other: &str) -> Option { + git::optional(git::at(&self.top).args(["merge-base", self.head.as_str(), other])) + } + + /// An absolute path inside the repository's git dir (`--git-path`). + fn git_path(&self, name: &str) -> Result { + git::text(git::at(&self.top).args([ + "rev-parse", + "--path-format=absolute", + "--git-path", + name, + ])) + .map(PathBuf::from) + .map_err(|error| failed("finding the git dir", error)) + } +} + +/// The remote and full upstream ref `head_ref` tracks, if any. +fn upstream_of(top: &Path, head_ref: &str) -> Option<(String, String)> { + let line = git::optional(git::at(top).args([ + "for-each-ref", + "--format=%(upstream:remotename)%09%(upstream)", + "--", + head_ref, + ]))?; + let (remote, upstream) = line.split_once('\t')?; + (!remote.is_empty() && upstream.starts_with("refs/remotes/")) + .then(|| (remote.to_string(), upstream.to_string())) +} + +/// The GitHub repository `remote` points at. The configured URL is tried +/// first (a `url.*.insteadOf` rewrite may point elsewhere for fetches), +/// then the rewritten one (a shorthand that rewrites to GitHub). +fn remote_repo(top: &Path, remote: &str) -> Result { + let raw = git::optional(git::at(top).args([ + "config", + "--get", + format!("remote.{remote}.url").as_str(), + ])); + let rewritten = git::optional(git::at(top).args(["remote", "get-url", remote])); + for url in [&raw, &rewritten].into_iter().flatten() { + if let Some(repo) = github::parse(url) { + return Ok(repo); + } + } + let shown = raw.or(rewritten).map_or_else(|| "no URL".to_string(), |url| github::redact(&url)); + Err(Fallback::new( + FallbackCode::NotGithub, + format!("the remote {remote} is {shown}, not a GitHub repository"), + )) +} + +/// A scratch folder, removed when dropped. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Result { + let parent = std::env::temp_dir(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_nanos()); + for attempt in 0..32 { + let path = parent.join(format!("cmux-seed-{}-{nanos}-{attempt}", std::process::id())); + match std::fs::DirBuilder::new().mode(0o700).create(&path) { + Ok(()) => return Ok(Self(path)), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => { + return Err(failed("making a scratch folder", error.to_string())); + } + } + } + Err(failed("making a scratch folder", "every name was taken".to_string())) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The fixed identity and date of the index and work commits, so the same +/// tree on the same HEAD always gives the same commit. +const SEED_NAME: &str = "cmux seed"; +const SEED_EMAIL: &str = "seed@cmux.invalid"; +const SEED_DATE: &str = "946684800 +0000"; + +fn build( + repo: &Repo, + out_bundle: &Path, + since: &Since<'_>, + bases: Vec, +) -> Result { + let submodules = submodules(repo)?; + let scratch = Scratch::new()?; + let store = scratch.0.join("store.git"); + git::output(git::at(&scratch.0).args(["init", "-q", "--bare", "--template="]).arg(&store)) + .map_err(|error| failed("making the scratch repository", error))?; + let objects = repo.git_path("objects")?; + std::fs::create_dir_all(store.join("objects/info")) + .map_err(|error| failed("making the scratch object store", error.to_string()))?; + write(&store.join("objects/info/alternates"), format!("{}\n", objects.display()))?; + // A shallow clone's grafts, so walks stop where this Mac's history does. + let shallow = repo.git_path("shallow")?; + if shallow.is_file() { + std::fs::copy(shallow, store.join("shallow")) + .map_err(|error| failed("copying the shallow list", error.to_string()))?; + } + let index = scratch.0.join("index"); + let real_index = repo.git_path("index")?; + if real_index.is_file() { + std::fs::copy(real_index, &index) + .map_err(|error| failed("copying the index", error.to_string()))?; + } else { + run(repo.scratch_git(&index).args(["read-tree", repo.head.as_str()]), "reading HEAD")?; + } + + let index_tree = repo.write_tree(&index)?; + let index_commit = commit(repo, &index_tree, &repo.head, "cmux seed index")?; + + let skipped = untracked_left_out(repo)?; + let sparse = sparse_patterns(repo)?; + // In a sparse checkout `--sparse` also takes untracked files outside + // the patterns; entries git keeps out of the working tree stay as they + // are either way. + let sparse_flag: &[&str] = if sparse.is_some() { &["--sparse"] } else { &[] }; + run(repo.scratch_git(&index).args(["add", "-A"]).args(sparse_flag), "adding the working tree")?; + if !skipped.is_empty() { + let list = scratch.0.join("left-out"); + let mut paths = Vec::new(); + for item in &skipped { + paths.extend_from_slice(item.path.trim_end_matches('/').as_bytes()); + paths.push(0); + } + write(&list, paths)?; + run( + repo.scratch_git(&index) + .env("GIT_LITERAL_PATHSPECS", "1") + .args([ + "rm", + "--cached", + "-r", + "-f", + "-q", + "--ignore-unmatch", + "--pathspec-file-nul", + ]) + .args(sparse_flag) + .arg(format!("--pathspec-from-file={}", list.display())), + "leaving out secrets", + )?; + } + let work_tree = repo.write_tree(&index)?; + let work_commit = commit(repo, &work_tree, &index_commit, "cmux seed work")?; + + let stash = repo.commit("refs/stash"); + let lfs = uses_lfs(repo, &skipped); + + let mut refs = vec![ + ("refs/cmux-seed/head", repo.head.as_str()), + ("refs/cmux-seed/index", index_commit.as_str()), + ("refs/cmux-seed/work", work_commit.as_str()), + ]; + if let Some(stash) = &stash { + refs.push(("refs/cmux-seed/stash", stash.as_str())); + } + // The work commit's parents are the index commit and HEAD, so the same + // work sha means all three are as the previous seed left them. + let (base, unchanged) = match since { + Since::Base(base) => ((*base).to_string(), false), + Since::Previous(previous) => (previous.work.clone(), previous.work == work_commit), + }; + let mut bundle_bytes = 0; + if !unchanged { + for (name, id) in &refs { + run(git::bare(&store).args(["update-ref", *name, *id]), "naming the seed commits")?; + } + let mut bundle = git::bare(&store); + bundle.args(["bundle", "create", "-q"]).arg(out_bundle); + bundle.args(refs.iter().map(|(name, _)| *name)); + match since { + Since::Base(base) => { + bundle.arg(format!("^{base}")); + } + Since::Previous(previous) => { + bundle.arg(format!("^{}", previous.work)).arg(format!("^{}", previous.head)); + // The new commits are siblings of the previous ones, not + // descendants, so git would not look inside the previous + // trees and would send every unchanged file again. Their + // trees, excluded too, keep it to what changed. + for id in [&previous.head, &previous.index, &previous.work] { + bundle.arg(format!("^{id}^{{tree}}")); + } + } + } + run(&mut bundle, "making the bundle")?; + bundle_bytes = std::fs::metadata(out_bundle) + .map_err(|error| failed("reading the bundle", error.to_string()))? + .len(); + } + let since = match since { + Since::Base(_) => None, + Since::Previous(previous) => Some(previous.work.clone()), + }; + + Ok(Planned { + params: SeedParams { + url: repo.github.url(), + repo: repo.github.slug(), + base, + head_ref: repo.head_ref.clone(), + head: repo.head.clone(), + index: index_commit, + work: work_commit, + stash, + sparse, + lfs, + since, + }, + skipped, + submodules, + bases, + bundle_bytes, + unchanged, + }) +} + +impl Repo { + /// git in the working copy with the scratch index. + fn scratch_git(&self, index: &Path) -> Command { + let mut command = git::at(&self.top); + command.env("GIT_INDEX_FILE", index); + command + } + + fn write_tree(&self, index: &Path) -> Result { + git::text(self.scratch_git(index).arg("write-tree")).map_err(|error| { + if error.contains("unmerged") { + Fallback::new( + FallbackCode::Unmerged, + "the index has unresolved merge conflicts; resolve them or the folder is copied", + ) + } else { + failed("writing a tree", error) + } + }) + } +} + +fn commit(repo: &Repo, tree: &str, parent: &str, message: &str) -> Result { + git::text( + git::at(&repo.top) + .env("GIT_AUTHOR_NAME", SEED_NAME) + .env("GIT_AUTHOR_EMAIL", SEED_EMAIL) + .env("GIT_AUTHOR_DATE", SEED_DATE) + .env("GIT_COMMITTER_NAME", SEED_NAME) + .env("GIT_COMMITTER_EMAIL", SEED_EMAIL) + .env("GIT_COMMITTER_DATE", SEED_DATE) + .args(["commit-tree", "--no-gpg-sign", "-p", parent, "-m", message, tree]), + ) + .map_err(|error| failed("making a seed commit", error)) +} + +fn run(command: &mut Command, what: &str) -> Result<(), Fallback> { + git::output(command).map(drop).map_err(|error| failed(what, error)) +} + +fn write(path: &Path, contents: impl AsRef<[u8]>) -> Result<(), Fallback> { + std::fs::write(path, contents) + .map_err(|error| failed(&format!("writing {}", path.display()), error.to_string())) +} + +/// Untracked files that are not ignored but stay on this Mac: likely +/// secrets, and git repositories nested in the folder (not submodules). +fn untracked_left_out(repo: &Repo) -> Result, Fallback> { + let listed = + git::output(git::at(&repo.top).args(["ls-files", "-z", "--others", "--exclude-standard"])) + .map_err(|error| failed("listing untracked files", error))?; + let mut skipped = Vec::new(); + for path in listed.split(|byte| *byte == 0).filter(|path| !path.is_empty()) { + let path = String::from_utf8_lossy(path).into_owned(); + let why = if path.ends_with('/') { + Some("a separate git repository inside this folder (not a submodule)") + } else { + secrets::reason(&repo.top, &path) + }; + if let Some(why) = why { + skipped.push(Skipped { path, why: why.to_string() }); + } + } + Ok(skipped) +} + +/// Each submodule with the commit checked out in it. One with a commit not +/// on its remote-tracking refs, or with uncommitted changes, is local work +/// this plan cannot seed yet. +fn submodules(repo: &Repo) -> Result, Fallback> { + let staged = git::output(git::at(&repo.top).args(["ls-files", "-z", "-s"])) + .map_err(|error| failed("listing the index", error))?; + let mut found = Vec::new(); + for entry in staged.split(|byte| *byte == 0).filter(|entry| !entry.is_empty()) { + let entry = String::from_utf8_lossy(entry); + let Some((meta, path)) = entry.split_once('\t') else { continue }; + let mut fields = meta.split(' '); + if fields.next() != Some("160000") { + continue; + } + let recorded = fields.next().unwrap_or_default().to_string(); + let checkout = repo.top.join(path); + if !checkout.join(".git").exists() { + found.push(Submodule { path: path.to_string(), commit: recorded }); + continue; + } + let local_work = |why: String| { + Fallback::new(FallbackCode::SubmoduleLocalWork, format!("submodule {path} {why}")) + }; + let commit = git::optional(git::at(&checkout).args([ + "rev-parse", + "--verify", + "-q", + "HEAD^{commit}", + ])) + .ok_or_else(|| local_work("has no commit checked out".to_string()))?; + let dirty = git::text(git::at(&checkout).args(["status", "--porcelain"])) + .map_err(|error| failed(&format!("reading submodule {path}"), error))?; + if !dirty.is_empty() { + return Err(local_work("has uncommitted changes".to_string())); + } + let on_remote = git::optional(git::at(&checkout).args([ + "for-each-ref", + "--count=1", + "--format=%(refname)", + "--contains", + commit.as_str(), + "refs/remotes", + ])); + if on_remote.is_none() { + return Err(local_work(format!("is at {commit}, which is not on its remote"))); + } + found.push(Submodule { path: path.to_string(), commit }); + } + Ok(found) +} + +/// The sparse-checkout patterns when sparse checkout is on. +fn sparse_patterns(repo: &Repo) -> Result, Fallback> { + let on = git::optional(git::at(&repo.top).args(["config", "--bool", "core.sparseCheckout"])); + if on.as_deref() != Some("true") { + return Ok(None); + } + let file = repo.git_path("info/sparse-checkout")?; + Ok(Some(std::fs::read_to_string(file).unwrap_or_default())) +} + +/// Whether any `.gitattributes` in the working tree (tracked, or untracked +/// and going) names `filter=lfs`. +fn uses_lfs(repo: &Repo, skipped: &[Skipped]) -> bool { + let listed = git::output(git::at(&repo.top).args([ + "ls-files", + "-z", + "--cached", + "--others", + "--exclude-standard", + "--", + ":(glob)**/.gitattributes", + ])) + .unwrap_or_default(); + listed + .split(|byte| *byte == 0) + .filter(|path| !path.is_empty()) + .map(|path| String::from_utf8_lossy(path).into_owned()) + .filter(|path| !skipped.iter().any(|item| &item.path == path)) + .any(|path| { + std::fs::read(repo.top.join(&path)) + .is_ok_and(|text| String::from_utf8_lossy(&text).contains("filter=lfs")) + }) +} diff --git a/cmux-tui/crates/cmux-tui/src/link/seed/secrets.rs b/cmux-tui/crates/cmux-tui/src/link/seed/secrets.rs new file mode 100644 index 000000000000..7de87f2f05cb --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed/secrets.rs @@ -0,0 +1,78 @@ +//! Untracked files the seed leaves out because they likely hold secrets. +//! Tracked files are never left out: the remote already has them. + +use std::path::Path; + +/// Why the untracked file at `relative` (under `top`) stays on this Mac, +/// or None when it goes. +pub(super) fn reason(top: &Path, relative: &str) -> Option<&'static str> { + let name = relative.rsplit('/').next().unwrap_or(relative); + if name.starts_with(".env") { + return Some(".env file: it may hold secrets, so it is shared only on purpose"); + } + let lower = name.to_ascii_lowercase(); + if ["id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"].iter().any(|key| lower.starts_with(key)) + && !lower.ends_with(".pub") + { + return Some("SSH private key"); + } + if [".pem", ".p12", ".pfx", ".key"].iter().any(|ext| lower.ends_with(ext)) { + return Some("key or certificate file"); + } + if name == ".netrc" { + return Some("credentials file (.netrc)"); + } + let token_markers: &[&str] = match name { + ".npmrc" => &["_authToken", "_auth", "_password"], + ".pypirc" => &["password"], + _ => &[], + }; + if !token_markers.is_empty() { + let text = std::fs::read(top.join(relative)).unwrap_or_default(); + let text = String::from_utf8_lossy(&text); + if token_markers.iter().any(|marker| text.contains(marker)) { + return Some("package registry credentials file with a token"); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn secrets_are_named() { + let top = Path::new("/nonexistent"); + for path in [ + ".env", + ".env.local", + ".envrc", + "app/.env.production", + "id_rsa", + "keys/id_ed25519", + "id_ecdsa_work", + "cert.pem", + "deploy/server.KEY", + "bundle.p12", + ".netrc", + ] { + assert!(reason(top, path).is_some(), "{path}"); + } + for path in + ["README.md", "id_rsa.pub", "src/env.rs", ".envrc-notes/x", "keyboard.rs", ".npmrc"] + { + assert_eq!(reason(top, path), None, "{path}"); + } + } + + #[test] + fn registry_files_with_tokens_are_secrets() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(".npmrc"), "//registry.npmjs.org/:_authToken=abc\n") + .unwrap(); + std::fs::write(dir.path().join(".pypirc"), "[pypi]\nusername = x\n").unwrap(); + assert!(reason(dir.path(), ".npmrc").is_some()); + assert_eq!(reason(dir.path(), ".pypirc"), None); + } +} diff --git a/cmux-tui/crates/cmux-tui/src/link/seed/tests.rs b/cmux-tui/crates/cmux-tui/src/link/seed/tests.rs new file mode 100644 index 000000000000..42dfbd337bcc --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/link/seed/tests.rs @@ -0,0 +1,507 @@ +//! The seed plan against real repositories: a bare repository stands in +//! for GitHub (a `url.*.insteadOf` rewrite sends the GitHub URL there), a +//! working copy is cloned from it, and a second clone at the base plays +//! the machine, unbundling and checking out what the plan sent. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use super::plan::{plan, plan_since, plan_with_base, FallbackCode, Planned, PreviousSeed}; + +const URL: &str = "https://github.com/acme/widget.git"; + +/// git for fixtures, with a fixed identity and no person's settings. +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(["-c", "user.name=Test", "-c", "user.email=test@example.invalid"]) + .args(["-c", "commit.gpgSign=false", "-c", "init.defaultBranch=main"]) + .args(["-c", "protocol.file.allow=always", "-c", "advice.detachedHead=false"]) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} in {}: {}", + dir.display(), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim_end().to_string() +} + +fn write(path: &Path, text: impl AsRef<[u8]>) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +struct Fixture { + dir: tempfile::TempDir, + remote: PathBuf, + work: PathBuf, +} + +impl Fixture { + /// A remote with one pushed commit and a working copy cloned from it + /// whose `origin` is the GitHub URL. + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let remote = dir.path().join("remote.git"); + git(dir.path(), &["init", "-q", "--bare", "remote.git"]); + let work = dir.path().join("work"); + git(dir.path(), &["clone", "-q", &file_url(&remote), "work"]); + write(&work.join("README.md"), "widget\n"); + write(&work.join("src/lib.rs"), "pub fn one() {}\n"); + write(&work.join("gone.txt"), "deleted later\n"); + write(&work.join(".gitignore"), "node_modules/\n*.log\n"); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", "first"]); + git(&work, &["push", "-q", "origin", "HEAD:main"]); + git(&work, &["remote", "set-head", "origin", "main"]); + git(&work, &["branch", "-q", "--set-upstream-to=origin/main"]); + point_at_github(&work, &remote); + Self { dir, remote, work } + } + + fn path(&self, name: &str) -> PathBuf { + self.dir.path().join(name) + } + + /// The machine: a clone of the remote at `base` that fetches the + /// bundle's refs. + fn machine(&self, planned: &Planned, bundle: &Path, name: &str) -> PathBuf { + let machine = self.path(name); + git(self.dir.path(), &["clone", "-q", &file_url(&self.remote), name]); + git(&machine, &["checkout", "-q", "--detach", &planned.params.base]); + apply(&machine, bundle); + machine + } +} + +/// Verifies `bundle` against the machine's clone and fetches its refs. +fn apply(machine: &Path, bundle: &Path) { + git(machine, &["bundle", "verify", "-q", bundle.to_str().unwrap()]); + git(machine, &["fetch", "-q", bundle.to_str().unwrap(), "+refs/cmux-seed/*:refs/cmux-seed/*"]); +} + +fn previous_of(planned: &Planned) -> PreviousSeed { + PreviousSeed { + head: planned.params.head.clone(), + index: planned.params.index.clone(), + work: planned.params.work.clone(), + } +} + +fn file_url(path: &Path) -> String { + format!("file://{}", path.display()) +} + +/// `origin` is the GitHub URL; fetches go to the bare repository. +fn point_at_github(work: &Path, remote: &Path) { + git(work, &["remote", "set-url", "origin", URL]); + git(work, &["config", &format!("url.{}.insteadOf", file_url(remote)), URL]); +} + +/// The person's view of the repository, to show the plan changed nothing. +fn snapshot(work: &Path) -> (String, String, String) { + ( + git(work, &["status", "--porcelain=v2", "--branch", "--untracked-files=all", "--ignored"]), + git(work, &["for-each-ref", "--format=%(refname) %(objectname)"]), + git(work, &["stash", "list"]), + ) +} + +/// Every regular file under `root` except `.git`, by relative path. +fn files(root: &Path) -> BTreeMap> { + let mut found = BTreeMap::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if entry.file_name() == ".git" { + continue; + } + if entry.file_type().unwrap().is_dir() { + stack.push(path); + } else { + let relative = path.strip_prefix(root).unwrap().to_string_lossy().into_owned(); + found.insert(relative, std::fs::read(path).unwrap()); + } + } + } + found +} + +fn bundle_prerequisites(bundle: &Path) -> Vec { + let bytes = std::fs::read(bundle).unwrap(); + let end = bytes.windows(2).position(|pair| pair == b"\n\n").unwrap(); + String::from_utf8_lossy(&bytes[..end]) + .lines() + .filter_map(|line| line.strip_prefix('-')) + .map(|line| line.split(' ').next().unwrap().to_string()) + .collect() +} + +#[test] +fn seeds_unpushed_commits_and_the_working_state() { + let f = Fixture::new(); + let work = &f.work; + let pushed = git(work, &["rev-parse", "HEAD"]); + write(&work.join("src/lib.rs"), "pub fn one() {}\npub fn two() {}\n"); + git(work, &["commit", "-q", "-am", "unpushed"]); + let unpushed = git(work, &["rev-parse", "HEAD"]); + // Staged, then changed again unstaged; a staged new file; a deletion. + write(&work.join("README.md"), "widget, staged\n"); + write(&work.join("staged-new.txt"), "new and staged\n"); + git(work, &["add", "README.md", "staged-new.txt"]); + write(&work.join("README.md"), "widget, staged, then edited\n"); + std::fs::remove_file(work.join("gone.txt")).unwrap(); + // Untracked: plain, big, ignored, secrets. + write(&work.join("notes/todo.md"), "untracked\n"); + let big: Vec = (0..3_000_000u32).map(|n| (n % 251) as u8).collect(); + write(&work.join("data/big.bin"), big); + write(&work.join("node_modules/left-pad/index.js"), "module.exports = 1;\n"); + write(&work.join("debug.log"), "ignored\n"); + write(&work.join(".env"), "TOKEN=secret\n"); + write(&work.join("config/.env.local"), "TOKEN=secret\n"); + write(&work.join("id_rsa"), "-----BEGIN OPENSSH PRIVATE KEY-----\n"); + let before = snapshot(work); + + let bundle = f.path("seed.bundle"); + let planned = plan(work, &bundle).unwrap_or_else(|fallback| panic!("{fallback:?}")); + assert_eq!(snapshot(work), before, "the plan changed the working copy"); + + let params = &planned.params; + assert_eq!(params.url, URL); + assert_eq!(params.repo, "acme/widget"); + assert_eq!(params.base, pushed); + assert_eq!(params.head, unpushed); + assert_eq!(params.head_ref.as_deref(), Some("refs/heads/main")); + assert_eq!(params.stash, None); + assert_eq!(params.sparse, None); + assert!(!params.lfs); + assert_eq!(planned.bases, vec![pushed.clone()]); + assert_eq!(bundle_prerequisites(&bundle), vec![pushed]); + assert_eq!(planned.bundle_bytes, std::fs::metadata(&bundle).unwrap().len()); + let mut skipped: Vec<_> = planned.skipped.iter().map(|item| item.path.as_str()).collect(); + skipped.sort_unstable(); + assert_eq!(skipped, vec![".env", "config/.env.local", "id_rsa"]); + assert!(planned.skipped.iter().all(|item| !item.why.is_empty())); + + let machine = f.machine(&planned, &bundle, "machine"); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/head"]), unpushed); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/index"]), params.index); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/work"]), params.work); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/index^"]), unpushed); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/work^"]), params.index); + // INDEX is exactly what is staged. + let staged = git(work, &["diff", "--cached", "--name-status"]); + let index_diff = git(&machine, &["diff", "--name-status", &unpushed, ¶ms.index]); + assert_eq!(index_diff, staged); + assert_eq!(git(&machine, &["show", &format!("{}:README.md", params.index)]), "widget, staged"); + // WORK is the working tree, less ignored files and secrets. + git(&machine, &["checkout", "-q", "--detach", ¶ms.work]); + let mut expected = files(work); + expected.retain(|path, _| { + !path.starts_with("node_modules/") + && path != "debug.log" + && !skipped.contains(&path.as_str()) + }); + assert_eq!(files(&machine), expected); +} + +#[test] +fn the_same_tree_gives_the_same_commits() { + let f = Fixture::new(); + write(&f.work.join("notes.txt"), "untracked\n"); + write(&f.work.join("README.md"), "changed\n"); + let one = plan(&f.work, &f.path("one.bundle")).unwrap(); + let two = plan(&f.work, &f.path("two.bundle")).unwrap(); + assert_eq!(one.params, two.params); + // HEAD is the base: the bundle has no head ref, the params still say it. + assert_eq!(one.params.head, one.params.base); + let machine = f.machine(&one, &f.path("one.bundle"), "machine"); + git(&machine, &["checkout", "-q", "--detach", &one.params.work]); + assert_eq!(std::fs::read_to_string(machine.join("notes.txt")).unwrap(), "untracked\n"); +} + +#[test] +fn detached_head_has_no_head_ref() { + let f = Fixture::new(); + git(&f.work, &["checkout", "-q", "--detach", "HEAD"]); + write(&f.work.join("a.txt"), "a\n"); + git(&f.work, &["add", "a.txt"]); + git(&f.work, &["commit", "-q", "-m", "detached work"]); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + assert_eq!(planned.params.head_ref, None); + assert_eq!(planned.params.head, git(&f.work, &["rev-parse", "HEAD"])); + // No upstream: the remote's default branch gives the base. + assert_eq!(planned.params.base, git(&f.work, &["rev-parse", "origin/main"])); + f.machine(&planned, &f.path("seed.bundle"), "machine"); +} + +#[test] +fn the_stash_is_carried() { + let f = Fixture::new(); + write(&f.work.join("README.md"), "stashed change\n"); + git(&f.work, &["stash", "push", "-q"]); + let stash = git(&f.work, &["rev-parse", "refs/stash"]); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + assert_eq!(planned.params.stash.as_deref(), Some(stash.as_str())); + let machine = f.machine(&planned, &f.path("seed.bundle"), "machine"); + assert_eq!(git(&machine, &["rev-parse", "refs/cmux-seed/stash"]), stash); + assert_eq!(git(&machine, &["show", "refs/cmux-seed/stash:README.md"]), "stashed change"); +} + +#[test] +fn a_linked_worktree_is_planned_from_its_own_state() { + let f = Fixture::new(); + let linked = f.path("linked"); + git(&f.work, &["worktree", "add", "-q", "-b", "feature", linked.to_str().unwrap()]); + write(&linked.join("feature.txt"), "feature\n"); + git(&linked, &["add", "feature.txt"]); + git(&linked, &["commit", "-q", "-m", "feature"]); + write(&linked.join("scratch.txt"), "untracked in the linked worktree\n"); + let before = snapshot(&linked); + let planned = plan(&linked, &f.path("seed.bundle")).unwrap(); + assert_eq!(snapshot(&linked), before); + assert_eq!(planned.params.head_ref.as_deref(), Some("refs/heads/feature")); + assert_eq!(planned.params.head, git(&linked, &["rev-parse", "HEAD"])); + let machine = f.machine(&planned, &f.path("seed.bundle"), "machine"); + git(&machine, &["checkout", "-q", "--detach", &planned.params.work]); + assert_eq!(files(&machine), files(&linked)); +} + +#[test] +fn sparse_patterns_are_sent() { + let f = Fixture::new(); + git(&f.work, &["sparse-checkout", "set", "--no-cone", "/README.md", "/src/"]); + assert!(!f.work.join("gone.txt").exists()); + write(&f.work.join("src/new.rs"), "new\n"); + write(&f.work.join("outside.txt"), "untracked outside the patterns\n"); + let before = snapshot(&f.work); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + let sparse = planned.params.sparse.clone().expect("sparse patterns"); + assert!(sparse.contains("/README.md") && sparse.contains("/src/"), "{sparse}"); + let machine = f.machine(&planned, &f.path("seed.bundle"), "machine"); + // Files outside the sparse patterns are kept, not deleted, in WORK. + let tree = git(&machine, &["ls-tree", "-r", "--name-only", &planned.params.work]); + assert!(tree.lines().any(|path| path == "gone.txt"), "{tree}"); + assert!(tree.lines().any(|path| path == "src/new.rs"), "{tree}"); + assert!(tree.lines().any(|path| path == "outside.txt"), "{tree}"); + assert_eq!(snapshot(&f.work), before); +} + +#[test] +fn lfs_attributes_are_noticed() { + let f = Fixture::new(); + write(&f.work.join(".gitattributes"), "*.psd filter=lfs diff=lfs merge=lfs -text\n"); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + assert!(planned.params.lfs); +} + +#[test] +fn a_shallow_clone_seeds_while_the_base_is_local() { + let f = Fixture::new(); + let shallow = f.path("shallow"); + git(f.dir.path(), &["clone", "-q", "--depth", "1", &file_url(&f.remote), "shallow"]); + point_at_github(&shallow, &f.remote); + write(&shallow.join("more.txt"), "more\n"); + git(&shallow, &["add", "more.txt"]); + git(&shallow, &["commit", "-q", "-m", "on a shallow clone"]); + let planned = plan(&shallow, &f.path("seed.bundle")).unwrap(); + assert_eq!(planned.params.base, git(&shallow, &["rev-parse", "origin/main"])); + f.machine(&planned, &f.path("seed.bundle"), "machine"); +} + +#[test] +fn a_base_this_mac_lacks_falls_back() { + let f = Fixture::new(); + let missing = "0123456789abcdef0123456789abcdef01234567"; + let fallback = plan_with_base(&f.work, &f.path("seed.bundle"), missing).unwrap_err(); + assert_eq!(fallback.code, FallbackCode::NoBase); + // A base it has works, and the candidates still come back. + let base = git(&f.work, &["rev-parse", "HEAD"]); + let planned = plan_with_base(&f.work, &f.path("seed.bundle"), &base).unwrap(); + assert_eq!(planned.params.base, base); + assert_eq!(planned.bases, vec![base]); +} + +#[test] +fn bases_fall_back_to_the_default_tip() { + let f = Fixture::new(); + // The remote's main moves on; a local branch with no upstream. + let other = f.path("other"); + git(f.dir.path(), &["clone", "-q", &file_url(&f.remote), "other"]); + write(&other.join("upstream.txt"), "upstream\n"); + git(&other, &["add", "upstream.txt"]); + git(&other, &["commit", "-q", "-m", "upstream moves"]); + git(&other, &["push", "-q", "origin", "HEAD:main"]); + let fork_point = git(&f.work, &["rev-parse", "HEAD"]); + git(&f.work, &["checkout", "-q", "-b", "topic", "--no-track"]); + git(&f.work, &["fetch", "-q", "origin"]); + let tip = git(&f.work, &["rev-parse", "origin/main"]); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + assert_eq!(planned.bases, vec![fork_point, tip.clone()]); + let retried = plan_with_base(&f.work, &f.path("retry.bundle"), &tip).unwrap(); + assert_eq!(retried.params.base, tip); + let machine = f.machine(&retried, &f.path("retry.bundle"), "machine"); + git(&machine, &["checkout", "-q", "--detach", &retried.params.work]); + assert!(!machine.join("upstream.txt").exists()); +} + +#[test] +fn submodule_local_work_falls_back() { + let f = Fixture::new(); + let lib_remote = f.path("lib.git"); + git(f.dir.path(), &["init", "-q", "--bare", "lib.git"]); + let lib = f.path("lib"); + git(f.dir.path(), &["clone", "-q", &file_url(&lib_remote), "lib"]); + write(&lib.join("lib.txt"), "lib\n"); + git(&lib, &["add", "lib.txt"]); + git(&lib, &["commit", "-q", "-m", "lib"]); + git(&lib, &["push", "-q", "origin", "HEAD:main"]); + git(&f.work, &["submodule", "add", "-q", &file_url(&lib_remote), "vendor/lib"]); + git(&f.work, &["commit", "-q", "-m", "add lib"]); + let planned = plan(&f.work, &f.path("seed.bundle")).unwrap(); + let lib_head = git(&lib, &["rev-parse", "HEAD"]); + assert_eq!(planned.submodules.len(), 1); + assert_eq!(planned.submodules[0].path, "vendor/lib"); + assert_eq!(planned.submodules[0].commit, lib_head); + + let checkout = f.work.join("vendor/lib"); + write(&checkout.join("lib.txt"), "dirty\n"); + let dirty = plan(&f.work, &f.path("seed.bundle")).unwrap_err(); + assert_eq!(dirty.code, FallbackCode::SubmoduleLocalWork, "{}", dirty.why); + git(&checkout, &["commit", "-q", "-am", "local only"]); + let unpushed = plan(&f.work, &f.path("seed.bundle")).unwrap_err(); + assert_eq!(unpushed.code, FallbackCode::SubmoduleLocalWork, "{}", unpushed.why); +} + +#[test] +fn folders_that_cannot_be_seeded_say_why() { + let f = Fixture::new(); + let bundle = f.path("seed.bundle"); + let code = |folder: &Path| plan(folder, &bundle).unwrap_err().code; + + let plain = f.path("plain"); + std::fs::create_dir(&plain).unwrap(); + assert_eq!(code(&plain), FallbackCode::NotGit); + assert_eq!(code(&f.work.join("src")), FallbackCode::NotTop); + + let fresh = f.path("fresh"); + git(f.dir.path(), &["init", "-q", "fresh"]); + git(&fresh, &["remote", "add", "origin", URL]); + assert_eq!(code(&fresh), FallbackCode::NoCommit); + + let lonely = f.path("lonely"); + git(f.dir.path(), &["init", "-q", "lonely"]); + write(&lonely.join("a.txt"), "a\n"); + git(&lonely, &["add", "a.txt"]); + git(&lonely, &["commit", "-q", "-m", "a"]); + assert_eq!(code(&lonely), FallbackCode::NoRemote); + git(&lonely, &["remote", "add", "upstream", URL]); + git(&lonely, &["remote", "add", "mirror", URL]); + assert_eq!(code(&lonely), FallbackCode::AmbiguousRemote); + // One remote is chosen even when it is not origin; it has no base yet. + git(&lonely, &["remote", "remove", "mirror"]); + assert_eq!(code(&lonely), FallbackCode::NoBase); + + git(&f.work, &["remote", "set-url", "origin", "https://user:token@gitlab.com/acme/widget.git"]); + let fallback = plan(&f.work, &bundle).unwrap_err(); + assert_eq!(fallback.code, FallbackCode::NotGithub); + assert!(!fallback.why.contains("token"), "{}", fallback.why); +} + +#[test] +fn unmerged_index_falls_back() { + let f = Fixture::new(); + git(&f.work, &["checkout", "-q", "-b", "side"]); + write(&f.work.join("README.md"), "side\n"); + git(&f.work, &["commit", "-q", "-am", "side"]); + git(&f.work, &["checkout", "-q", "main"]); + write(&f.work.join("README.md"), "main\n"); + git(&f.work, &["commit", "-q", "-am", "main"]); + let merge = Command::new("git") + .arg("-C") + .arg(&f.work) + .args(["-c", "user.name=T", "-c", "user.email=t@t.invalid", "merge", "-q", "side"]) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .output() + .unwrap(); + assert!(!merge.status.success()); + let fallback = plan(&f.work, &f.path("seed.bundle")).unwrap_err(); + assert_eq!(fallback.code, FallbackCode::Unmerged, "{}", fallback.why); +} + +#[test] +fn a_delta_seed_sends_only_what_changed() { + let f = Fixture::new(); + let work = &f.work; + let big: Vec = + (0..2_000_000u32).map(|n| (n.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + write(&work.join("data/big.bin"), big); + write(&work.join("README.md"), "first edit\n"); + let full_bundle = f.path("full.bundle"); + let full = plan(work, &full_bundle).unwrap(); + assert_eq!(full.params.since, None); + assert!(!full.unchanged); + let machine = f.machine(&full, &full_bundle, "machine"); + + // Nothing changed: the same commits, nothing to send. + let previous = previous_of(&full); + let same_bundle = f.path("same.bundle"); + let same = plan_since(work, &same_bundle, &previous).unwrap(); + assert!(same.unchanged); + assert_eq!(same.bundle_bytes, 0); + assert!(!same_bundle.exists()); + assert_eq!(same.params.work, full.params.work); + + write(&work.join("README.md"), "second edit\n"); + write(&work.join("notes/new.txt"), "new untracked\n"); + let before = snapshot(work); + let delta_bundle = f.path("delta.bundle"); + let delta = plan_since(work, &delta_bundle, &previous).unwrap(); + assert_eq!(snapshot(work), before); + assert!(!delta.unchanged); + assert_eq!(delta.params.base, full.params.work); + assert_eq!(delta.params.since.as_deref(), Some(full.params.work.as_str())); + assert!(delta.bases.is_empty()); + // Every prerequisite is a commit the machine has from the first seed; + // the unchanged index commit is one (the new work commit's parent). + assert_eq!(delta.params.index, full.params.index); + let known = [&full.params.work, &full.params.index, &full.params.head]; + let prerequisites = bundle_prerequisites(&delta_bundle); + assert!(!prerequisites.is_empty()); + assert!(prerequisites.iter().all(|id| known.contains(&id)), "{prerequisites:?}"); + assert!( + delta.bundle_bytes * 20 < full.bundle_bytes, + "delta {} vs full {}", + delta.bundle_bytes, + full.bundle_bytes + ); + + apply(&machine, &delta_bundle); + git(&machine, &["checkout", "-q", "--detach", &delta.params.work]); + assert_eq!(files(&machine), files(work)); +} + +#[test] +fn a_delta_seed_needs_the_previous_commits() { + let f = Fixture::new(); + let head = git(&f.work, &["rev-parse", "HEAD"]); + let missing = "0123456789abcdef0123456789abcdef01234567".to_string(); + let previous = PreviousSeed { head: head.clone(), index: missing.clone(), work: missing }; + let fallback = plan_since(&f.work, &f.path("seed.bundle"), &previous).unwrap_err(); + assert_eq!(fallback.code, FallbackCode::NoPrevious, "{}", fallback.why); + let short = PreviousSeed { head: head[..7].to_string(), index: head.clone(), work: head }; + let fallback = plan_since(&f.work, &f.path("seed.bundle"), &short).unwrap_err(); + assert_eq!(fallback.code, FallbackCode::NoPrevious); +}