OXYGENHUB

Coverage / crates/oxy-core/src/repo/git.rs 81.7%

1625 of 1990 lines run, 127 of 326 functions · run #427 on main · run missed

1
//! Git bridge (spec §23), export side: each state the current bookmark
2
//! passed through becomes a Git commit through `git fast-import`, with the
3
//! state's full tree and the previous state's commit as parent. A state
4
//! that added exactly one change carries that change's message, author,
5
//! and `Change-Id`/`Oxy-Hash` trailers; every commit carries `Oxy-State`.
6
//!
7
//! Marks make re-exports incremental: `.oxy/git/<target>/git-marks` is
8
//! git's own marks file and `oxy-marks` maps state refs to marks.
9
10
use super::*;
11
use std::process::{Command, Stdio};
12
use std::sync::Arc;
13
14
#[derive(Debug, Clone, Default, PartialEq, Eq)]
15
pub struct GitImportReport {
16
    pub commits: usize,
17
    pub merges: usize,
18
    /// Gitlink entries imported as subrepo nodes with Git pins.
19
    pub submodules: usize,
20
    pub heads: usize,
21
}
22
23
/// A running `git cat-file --batch`, for reading many blobs cheaply.
24
struct CatFile {
25
    child: std::process::Child,
26
    stdin: std::process::ChildStdin,
27
    stdout: std::io::BufReader<std::process::ChildStdout>,
28
}
29
30
impl CatFile {
3126×
    fn start(git_dir: &Path) -> Result<CatFile> {
3226×
        let mut child = Command::new("git")
3326×
            .arg("-C")
3426×
            .arg(git_dir)
3526×
            .args(["cat-file", "--batch"])
3626×
            .stdin(Stdio::piped())
3726×
            .stdout(Stdio::piped())
3826×
            .stderr(Stdio::null())
3926×
            .spawn()
4026×
            .map_err(|e| RepoError::Msg(format!("running git cat-file: {e}")))?;
4126×
        let stdin = child.stdin.take().unwrap();
4226×
        let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
4326×
        Ok(CatFile {
4426×
            child,
4526×
            stdin,
4626×
            stdout,
4726×
        })
4826×
    }
49
50131×
    fn read(&mut self, sha: &str) -> Result<Vec<u8>> {
51
        use std::io::{BufRead, Read};
52131×
        writeln!(self.stdin, "{sha}")?;
53131×
        self.stdin.flush()?;
54131×
        let mut header = String::new();
55131×
        self.stdout.read_line(&mut header)?;
56131×
        let parts: Vec<&str> = header.trim_end().split(' ').collect();
57131×
        if parts.len() != 3 {
580×
            return fail(format!("git cat-file: object {sha} not found"));
59131×
        }
60131×
        let size: usize = parts[2]
61131×
            .parse()
62131×
            .map_err(|_| RepoError::Msg("git cat-file: bad size".into()))?;
63131×
        let mut body = vec![0u8; size];
64131×
        self.stdout.read_exact(&mut body)?;
65131×
        let mut nl = [0u8; 1];
66131×
        self.stdout.read_exact(&mut nl)?;
67131×
        Ok(body)
68131×
    }
69
}
70
71
impl Drop for CatFile {
7226×
    fn drop(&mut self) {
7326×
        let _ = self.child.kill();
7426×
        let _ = self.child.wait();
7526×
    }
76
}
77
78
/// One path a commit changes against its first parent: its new mode and
79
/// blob, or `None` when the commit deletes it.
80
type TreeDiff = Vec<(String, Option<(String, String)>)>;
81
82
/// A running `git diff-tree --stdin`, fed every `commit parent` pair up
83
/// front, whose diffs are read in the same order as they are needed: a
84
/// commit's tree is its first parent's plus its diff, at a cost that
85
/// follows what it changes rather than the whole tree (oxygen#25).
86
struct DiffTree {
87
    child: std::process::Child,
88
    stdout: std::io::BufReader<std::process::ChildStdout>,
89
    feeder: Option<std::thread::JoinHandle<()>>,
90
    /// The header read at the end of the previous diff.
91
    next: Option<String>,
92
}
93
94
impl DiffTree {
9516×
    fn start(git_dir: &Path, pairs: Vec<(String, String)>) -> Result<DiffTree> {
9616×
        let mut child = Command::new("git")
9716×
            .arg("-C")
9816×
            .arg(git_dir)
9916×
            .args([
10016×
                "diff-tree",
10116×
                "--stdin",
10216×
                "--always",
10316×
                "-r",
10416×
                "-z",
10516×
                "--no-renames",
10616×
            ])
10716×
            .stdin(Stdio::piped())
10816×
            .stdout(Stdio::piped())
10916×
            .stderr(Stdio::null())
11016×
            .spawn()
11116×
            .map_err(|e| RepoError::Msg(format!("running git diff-tree: {e}")))?;
11216×
        let mut stdin = child.stdin.take().unwrap();
11316×
        let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
114
        // A thread writes, so git never waits on a full pipe for us to read.
11516×
        let feeder = std::thread::spawn(move || {
116
            // An import that stops before reading every diff kills git
117
            // while this thread may still be writing. oxy restores
118
            // SIGPIPE's default (to end quietly under `| head`), so that
119
            // write would kill the whole process (signal 13, oxygen#81);
120
            // blocked here, it fails with EPIPE and the thread ends.
121
            #[cfg(unix)]
12216×
            unsafe {
12316×
                let mut set: libc::sigset_t = std::mem::zeroed();
12416×
                libc::sigemptyset(&mut set);
12516×
                libc::sigaddset(&mut set, libc::SIGPIPE);
12616×
                libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
12716×
            }
12816×
            let mut w = std::io::BufWriter::new(&mut stdin);
12972×
            for (c, p) in pairs {
13072×
                if writeln!(w, "{c} {p}").is_err() {
1310×
                    return;
13272×
                }
133
            }
13416×
            let _ = w.flush();
13516×
        });
13616×
        Ok(DiffTree {
13716×
            child,
13816×
            stdout,
13916×
            feeder: Some(feeder),
14016×
            next: None,
14116×
        })
14216×
    }
143
144267×
    fn field(&mut self) -> Result<Option<String>> {
145
        use std::io::BufRead;
146267×
        let mut buf = Vec::new();
147267×
        if self.stdout.read_until(0, &mut buf)? == 0 {
14815×
            return Ok(None);
149252×
        }
150252×
        if buf.last() == Some(&0) {
151252×
            buf.pop();
152252×
        }
153252×
        Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
154267×
    }
155
156
    /// The diff of `sha` against the parent it was fed with.
15772×
    fn diff(&mut self, sha: &str) -> Result<TreeDiff> {
15872×
        let header = match self.next.take() {
15957×
            Some(h) => Some(h),
16015×
            None => self.field()?,
161
        };
16272×
        if header.as_deref() != Some(sha) {
1630×
            return fail(format!("git diff-tree: expected {sha}, got {header:?}"));
16472×
        }
16572×
        let mut out = Vec::new();
166162×
        while let Some(f) = self.field()? {
167147×
            let Some(meta) = f.strip_prefix(':') else {
16857×
                self.next = Some(f);
16957×
                break;
170
            };
17190×
            let Some(path) = self.field()? else {
1720×
                return fail("git diff-tree: record without a path");
173
            };
174
            // `oldmode newmode oldsha newsha status`
17590×
            let m: Vec<&str> = meta.split(' ').collect();
17690×
            if m.len() != 5 {
1770×
                return fail(format!("git diff-tree: bad record {f:?}"));
17890×
            }
17990×
            let entry = if m[4].starts_with('D') {
18018×
                None
181
            } else {
18272×
                Some((m[1].to_string(), m[3].to_string()))
183
            };
18490×
            out.push((path, entry));
185
        }
18672×
        Ok(out)
18772×
    }
188
}
189
190
impl Drop for DiffTree {
19116×
    fn drop(&mut self) {
19216×
        let _ = self.child.kill();
19316×
        let _ = self.child.wait();
19416×
        if let Some(f) = self.feeder.take() {
19516×
            let _ = f.join();
19616×
        }
19716×
    }
198
}
199
200
/// The email of a Git author `Name <email>`, lowercased.
2012×
fn git_email(author: &str) -> Option<String> {
2022×
    let (_, rest) = author.rsplit_once('<')?;
2032×
    let email = rest.strip_suffix('>')?.trim();
2042×
    (!email.is_empty()).then(|| email.to_lowercase())
2052×
}
206
207
/// One commit as `git log` describes it.
208
struct GitCommit {
209
    sha: String,
210
    parents: Vec<String>,
211
    author_secs: u64,
212
    author: String,
213
    message: String,
214
}
215
21626×
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> {
21726×
    let out = Command::new("git")
21826×
        .arg("-C")
21926×
        .arg(git_dir)
22026×
        .args([
22126×
            "log",
22226×
            "--reverse",
22326×
            "--topo-order",
22426×
            "--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e",
22526×
            branch,
22626×
        ])
22726×
        .output()
22826×
        .map_err(|e| RepoError::Msg(format!("running git log: {e}")))?;
22926×
    if !out.status.success() {
2300×
        return fail(format!(
231
            "git log {branch} failed: {}",
2320×
            String::from_utf8_lossy(&out.stderr).trim()
233
        ));
23426×
    }
23526×
    let text = String::from_utf8_lossy(&out.stdout);
23626×
    let mut commits = Vec::new();
237182×
    for record in text.split('\x1e') {
238182×
        let record = record.trim_start_matches('\n');
239182×
        if record.trim().is_empty() {
24026×
            continue;
241156×
        }
242156×
        let f: Vec<&str> = record.splitn(5, '\0').collect();
243156×
        if f.len() != 5 {
2440×
            return fail("unexpected git log record");
245156×
        }
246156×
        commits.push(GitCommit {
247156×
            sha: f[0].to_string(),
248156×
            parents: f[1].split_whitespace().map(str::to_string).collect(),
249156×
            author_secs: f[2].parse().unwrap_or(0),
250156×
            author: f[3].to_string(),
251156×
            message: f[4].trim_end().to_string(),
252156×
        });
253
    }
25426×
    Ok(commits)
25526×
}
256
257
/// `path → (mode, blob sha)` for a commit's tree.
25880×
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> {
25980×
    let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?;
26080×
    let mut out = BTreeMap::new();
261256×
    for entry in text.split('\0') {
262256×
        if entry.is_empty() {
26380×
            continue;
264176×
        }
265176×
        let Some((meta, path)) = entry.split_once('\t') else {
2660×
            continue;
267
        };
268176×
        let m: Vec<&str> = meta.split(' ').collect();
269176×
        if m.len() == 3 {
270176×
            out.insert(path.to_string(), (m[0].to_string(), m[2].to_string()));
271176×
        }
272
    }
27380×
    Ok(out)
27480×
}
275
276
/// The ChangeId for a Git commit: its `Change-Id` trailer if it has a
277
/// 32-hex one, else BLAKE3-128 of the commit hash (spec §23).
27888×
fn change_id_for(sha: &str, message: &str) -> ChangeId {
27988×
    for line in message.lines().rev() {
28088×
        if let Some(v) = line.strip_prefix("Change-Id:") {
2814×
            if let Some(id) = ChangeId::from_hex(v.trim()) {
2824×
                return id;
2830×
            }
28484×
        }
285
    }
28684×
    let h = blake3::hash(sha.as_bytes());
28784×
    ChangeId(h.as_bytes()[..16].try_into().unwrap())
28888×
}
289
290
/// Git commits with a known Oxygen counterpart.
291
struct GitKnown {
292
    /// Imported commit → its change.
293
    imported: HashMap<String, ChangeHash>,
294
    /// Exported commit (or a fetched tip) → the bookmark state it equals.
295
    exported: HashMap<String, ObjectRef>,
296
}
297
298
#[derive(Debug, Clone, Default, PartialEq, Eq)]
299
pub struct GitExportReport {
300
    pub exported: usize,
301
    pub skipped: usize,
302
    /// Subrepo nodes with Oxygen pins, which Git cannot represent.
303
    pub skipped_subrepos: usize,
304
    pub branch: String,
305
    pub heads: usize,
306
}
307
308
/// A merge bringing more commits than this sheds its base's graphs first.
309
const MERGE_SHED_COMMITS: usize = 100;
310
311
/// The atoms a kept state's built graphs may hold before they go back into
312
/// its history (#25): about a few hundred megabytes.
313
const KEPT_ATOMS: usize = 1_500_000;
314
/// A kept state with more built graphs than this sheds them.
315
const KEPT_GRAPHS: usize = 2000;
316
/// An import moves its bookmark to the commits done so far every this
317
/// many commits, so one that stops part way resumes from there: imported
318
/// commits are found from the bookmark's history (`imported_commits`).
319
const CHECKPOINT_COMMITS: usize = 2000;
320
321
/// Text files of a merge rendered this many at a time (oxygen#25): a
322
/// batch's graphs are built beside the state and dropped once rendered,
323
/// so what is held for the whole tree is the renderings, not the graphs
324
/// with every deleted line of their history.
325
const MERGE_BATCH: usize = 500;
326
327
thread_local! {
328
    /// A smaller batch for this thread's imports: tests set 1, so a small
329
    /// merge takes the batched path.
330
    static MERGE_BATCH_OVERRIDE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
331
}
332
333
#[cfg(test)]
3344×
pub(crate) fn set_merge_batch_for_tests(n: Option<usize>) {
3354×
    MERGE_BATCH_OVERRIDE.with(|c| c.set(n));
3364×
}
337
33829×
fn merge_batch() -> usize {
33929×
    MERGE_BATCH_OVERRIDE
34029×
        .with(|c| c.get())
34129×
        .filter(|n| *n > 0)
34229×
        .or_else(|| {
34313×
            std::env::var("OXY_MERGE_BATCH")
34413×
                .ok()
34513×
                .and_then(|v| v.parse().ok())
34613×
        })
34729×
        .unwrap_or(MERGE_BATCH)
34829×
}
349
350
impl Repo {
351
    /// As `State::materialize_except`, for a tree whose graphs would not
352
    /// fit in memory at once. The few files the change builder reads
353
    /// graphs for (conflicted ones, and renderings whose lines are not
354
    /// one per live atom) are built in the state afterwards.
3555×
    fn materialize_batched(
3565×
        &self,
3575×
        base: &mut State,
3585×
        need: &[crate::ids::NodeId],
3595×
        skip: &HashSet<crate::ids::NodeId>,
3605×
    ) -> Result<crate::state::Snapshot> {
361
        use crate::graph::Materialized;
362
        use crate::state::{FileContent, FileState};
363
        use rayon::prelude::*;
3645×
        let view = base.tree().view();
3655×
        let mut rendered: HashMap<crate::ids::NodeId, (Vec<u8>, Materialized)> =
3665×
            HashMap::with_capacity(need.len());
3675×
        let mut keep_built: Vec<crate::ids::NodeId> = Vec::new();
36814×
        for batch in need.chunks(merge_batch()) {
36914×
            let t = std::time::Instant::now();
37014×
            let graphs = self.build_graphs_detached(base, batch)?;
37114×
            crate::timing::add("render: build graphs, batch", t.elapsed());
37214×
            let t = std::time::Instant::now();
37314×
            let batch_rendered: Vec<(crate::ids::NodeId, Vec<u8>, Materialized)> = graphs
37414×
                .par_iter()
37514×
                .map(|(node, g)| {
37614×
                    let (bytes, m) = base.render_graph(g);
37714×
                    (*node, bytes, m)
37814×
                })
37914×
                .collect();
38014×
            drop(graphs);
38114×
            crate::timing::add("render: render, batch", t.elapsed());
38214×
            for (node, bytes, m) in batch_rendered {
38314×
                if m.is_conflicted()
38414×
                    || m.live_atoms().len() != crate::diff::split_lines(&bytes).len()
3850×
                {
3860×
                    keep_built.push(node);
38714×
                }
38814×
                rendered.insert(node, (bytes, m));
389
            }
390
        }
3915×
        if !keep_built.is_empty() {
3920×
            self.load_graphs_of(base, &keep_built)?;
3935×
        }
3945×
        let mut files = BTreeMap::new();
3955×
        let mut unrendered = BTreeSet::new();
39616×
        for (path, e) in view.entries.iter() {
39716×
            let f = if e.kind == NodeKind::File && !e.mode.opaque {
39816×
                match rendered.remove(&e.node) {
39914×
                    Some((bytes, materialized)) => FileState {
40014×
                        node: e.node,
40114×
                        kind: e.kind,
40214×
                        mode: e.mode,
40314×
                        content: FileContent::Text {
40414×
                            bytes,
40514×
                            materialized,
40614×
                        },
40714×
                    },
4082×
                    None if skip.contains(&e.node) => {
4092×
                        unrendered.insert(path.clone());
4102×
                        FileState {
4112×
                            node: e.node,
4122×
                            kind: e.kind,
4132×
                            mode: e.mode,
4142×
                            content: FileContent::Text {
4152×
                                bytes: Vec::new(),
4162×
                                materialized: Materialized::default(),
4172×
                            },
4182×
                        }
419
                    }
420
                    None => {
421
                        // Neither asked for nor known unchanged: render it
422
                        // from a built graph, as the whole-tree path does.
4230×
                        self.load_graphs_of(base, &[e.node])?;
4240×
                        base.entry_state(e)
425
                    }
426
                }
427
            } else {
4280×
                base.entry_state(e)
429
            };
43016×
            files.insert(path.clone(), f);
431
        }
4325×
        Ok(crate::state::Snapshot {
4335×
            tree: view,
4345×
            files,
4355×
            unrendered,
4365×
        })
4375×
    }
438
}
439
440177×
fn git(dir: &Path, args: &[&str]) -> Result<String> {
441177×
    let out = Command::new("git")
442177×
        .arg("-C")
443177×
        .arg(dir)
444177×
        .args(args)
445177×
        .output()
446177×
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
447177×
    if !out.status.success() {
4480×
        return fail(format!(
449
            "git {} failed: {}",
4500×
            args.join(" "),
4510×
            String::from_utf8_lossy(&out.stderr).trim()
452
        ));
453177×
    }
454177×
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
455177×
}
456
457
impl Repo {
45850×
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
45950×
        let canonical =
46050×
            crate::portable::canonical(git_dir).unwrap_or_else(|_| git_dir.to_path_buf());
46150×
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
46250×
        let dir = self.oxy.join("git").join(key);
46350×
        fs::create_dir_all(&dir)?;
46450×
        Ok(dir)
46550×
    }
466
467
    /// `state ref → Git commit sha` for bookmark states that equal a Git
468
    /// commit's tree (recorded by import and fetch).
46947×
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
47047×
        let mut out = BTreeMap::new();
47147×
        if let Ok(text) = fs::read_to_string(path) {
47212×
            for line in text.lines() {
47312×
                if let Some((h, sha)) = line.split_once(' ') {
47412×
                    if let Some(h) = ObjectRef::from_hex(h) {
47512×
                        out.insert(h, sha.trim().to_string());
47612×
                    }
4770×
                }
478
            }
47937×
        }
48047×
        Ok(out)
48147×
    }
482
48315×
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
48415×
        let path = self.git_marks_dir(git_dir)?.join("git-states");
48515×
        let mut states = Self::read_git_states(&path)?;
48615×
        states.insert(*state, sha.to_string());
48715×
        let text: String = states
48815×
            .iter()
48916×
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
49015×
            .collect();
49115×
        write_atomic(&path, text.as_bytes())
49215×
    }
493
494
    /// The bare mirror this repository keeps for the Git remote `url`.
4957×
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
4967×
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
4977×
        let dir = self.oxy.join("git").join(key).join("mirror.git");
4987×
        if !dir.join("HEAD").exists() {
4991×
            fs::create_dir_all(&dir)?;
5001×
            git(&dir, &["init", "--bare", "-q"])?;
5016×
        }
5027×
        Ok(dir)
5037×
    }
504
505
    /// Git commits already imported into the bookmark, by sha.
50630×
    pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
50730×
        let mut map = HashMap::new();
508112×
        for e in self.log()? {
509112×
            if e.is_working_copy {
51030×
                continue;
51182×
            }
51282×
            if let Some(sha) = e
51382×
                .change
51482×
                .message
51582×
                .lines()
51682×
                .rev()
517158×
                .find_map(|l| l.strip_prefix("Git-Commit: "))
51876×
            {
51976×
                map.insert(sha.trim().to_string(), e.hash);
52076×
            }
521
        }
52230×
        Ok(map)
52330×
    }
524
525
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
526
    /// A remote without that branch yet leaves the mirror as it is.
5277×
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
5287×
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
5297×
        match git(mirror, &["fetch", "-q", url, &spec]) {
5307×
            Ok(_) => Ok(()),
5310×
            Err(e) => {
5320×
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
5330×
                if ls.trim().is_empty() {
5340×
                    Ok(())
535
                } else {
5360×
                    Err(e)
537
                }
538
            }
539
        }
5407×
    }
541
542
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
543
    /// through a mirror and import the commits not yet in the bookmark
544
    /// (spec §23). Works on a repository that already has history: the
545
    /// new changes join the bookmark like a pull.
5463×
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
547
        // A local path, made absolute: git runs it from inside the mirror.
5483×
        let local = crate::portable::canonical(Path::new(url))
5493×
            .ok()
5503×
            .filter(|_| !url.contains("://"));
5513×
        let absolute = local.as_ref().map(|p| p.to_string_lossy().into_owned());
5523×
        let url = absolute.as_deref().unwrap_or(url);
5533×
        let mirror = self.git_mirror(url)?;
5543×
        self.git_mirror_fetch(&mirror, url, branch)?;
5553×
        if git(
5563×
            &mirror,
5573×
            &[
5583×
                "rev-parse",
5593×
                "--verify",
5603×
                "-q",
5613×
                &format!("refs/heads/{branch}"),
5623×
            ],
5633×
        )
5643×
        .is_err()
565
        {
5660×
            return fail(format!("{url} has no branch {branch:?}"));
5673×
        }
5683×
        self.import_git_commits(
5693×
            &mirror,
5703×
            branch,
5713×
            &format!("oxy git fetch {url} {branch}"),
5721×
            &mut |_| {},
573
        )
5743×
    }
575
576
    /// Export the bookmark to `branch` of the Git repository at `url`
577
    /// through the mirror and push it. The remote's tip must already have
578
    /// been fetched (`git_fetch`), so the push fast-forwards.
5794×
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
5804×
        let mirror = self.git_mirror(url)?;
5814×
        self.git_mirror_fetch(&mirror, url, branch)?;
5824×
        if let Ok(tip) = git(
5834×
            &mirror,
5844×
            &[
5854×
                "rev-parse",
5864×
                "--verify",
5874×
                "-q",
5884×
                &format!("refs/heads/{branch}"),
5894×
            ],
5904×
        ) {
5914×
            let known = self.git_known(&mirror)?;
5924×
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
5931×
                return fail(format!(
594
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
595
                ));
5963×
            }
5970×
        }
5983×
        let report = self.git_export_as(&mirror, branch)?;
5993×
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
6003×
        git(&mirror, &["push", "-q", url, &spec])?;
6013×
        Ok(report)
6024×
    }
603
60435×
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
60535×
        let mut out = BTreeMap::new();
60635×
        if let Ok(text) = fs::read_to_string(path) {
60718×
            for line in text.lines() {
60818×
                if let Some((h, m)) = line.split_once(' ') {
60918×
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
61018×
                        out.insert(h, m);
61118×
                    }
6120×
                }
613
            }
61424×
        }
61535×
        Ok(out)
61635×
    }
617
618
    /// Export the current bookmark to the Git repository at `git_dir`,
619
    /// creating a bare one if nothing is there. Each state the bookmark
620
    /// passed through (per the operation log) becomes one commit whose tree
621
    /// is that state, so the Git branch is a linear history of full trees.
6227×
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
6237×
        let bookmark = self.config.bookmark.clone();
6247×
        self.git_export_as(git_dir, &bookmark)
6257×
    }
626
627
    /// `git_export` to the Git branch `branch`. A state that came from a
628
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
629
    /// onto that commit, so a push back to the Git remote fast-forwards.
63012×
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
63112×
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
6324×
            fs::create_dir_all(git_dir)?;
6334×
            git(git_dir, &["init", "--bare", "-q"])?;
6348×
        }
63512×
        let marks_dir = self.git_marks_dir(git_dir)?;
63612×
        let git_marks = marks_dir.join("git-marks");
63712×
        let oxy_marks_path = marks_dir.join("oxy-marks");
63812×
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
63912×
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
64012×
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
641
64212×
        let bookmark = self.config.bookmark.clone();
64312×
        let mut stream: Vec<u8> = Vec::new();
64412×
        let mut report = GitExportReport {
64512×
            branch: branch.to_string(),
64612×
            heads: self.bookmark_heads()?.len(),
64712×
            ..Default::default()
648
        };
649
650
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
65112×
        let mut ops = self.op_log()?;
65212×
        ops.reverse();
65312×
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
654
        // The fast-import parent of the next commit: `:mark` or a commit sha.
65512×
        let mut last_parent: Option<String> = None;
65649×
        for (_, op) in &ops {
65749×
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
6580×
                continue;
659
            };
66049×
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
66112×
                continue;
66237×
            }
66337×
            let Ok(state) = self.store.get_state(&state_ref) else {
6640×
                continue;
665
            };
66637×
            if state.heads.is_empty() {
66712×
                prev = Some((state_ref, vec![]));
66812×
                continue;
66925×
            }
67025×
            if let Some(sha) = git_states.get(&state_ref) {
6714×
                report.skipped += 1;
6724×
                last_parent = Some(sha.clone());
6734×
                prev = Some((state_ref, state.heads.clone()));
6744×
                continue;
67521×
            }
67621×
            if let Some(m) = marks.get(&state_ref) {
67710×
                report.skipped += 1;
67810×
                last_parent = Some(format!(":{m}"));
67910×
                prev = Some((state_ref, state.heads.clone()));
68010×
                continue;
68111×
            }
68211×
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
68311×
            let added = self
68411×
                .negotiate(&prev_heads, &state.heads)
68511×
                .unwrap_or_default();
68611×
            let loaded = self.load_state(&state.heads)?;
68711×
            let snapshot = loaded.materialize();
68811×
            let (author, secs, mut message) = match added.as_slice() {
6898×
                [h] => {
6908×
                    let c = self.store.get_change(h)?;
6918×
                    let mut m = c.message.clone();
6928×
                    if !m.ends_with('\n') {
6938×
                        m.push('\n');
6948×
                    }
6958×
                    m.push_str(&format!(
6968×
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
6978×
                        c.change_id.to_hex(),
6988×
                        h.to_hex()
6998×
                    ));
7008×
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
701
                }
7023×
                [] => (
7030×
                    "oxy <oxy@localhost>".to_string(),
7040×
                    op.hlc.wall_ms / 1000,
7050×
                    format!("oxy: {}\n\n", op.command),
7060×
                ),
7073×
                many => {
7083×
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
70922×
                    for h in many {
71022×
                        let c = self.store.get_change(h)?;
71122×
                        m.push_str(&format!(
71222×
                            "- {} {}\n",
71322×
                            c.change_id.short(8),
71422×
                            c.message.lines().next().unwrap_or("")
71522×
                        ));
716
                    }
7173×
                    m.push_str(&format!(
718
                        "\nOxy-Changes: {}\n",
7193×
                        many.iter()
72022×
                            .map(|h| h.to_hex())
7213×
                            .collect::<Vec<_>>()
7223×
                            .join(" ")
723
                    ));
7243×
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
725
                }
726
            };
72711×
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
72811×
            if snapshot.is_conflicted() {
7290×
                message.push_str("Oxy-Conflicted: true\n");
73011×
            }
73111×
            let mark = next_mark;
73211×
            next_mark += 1;
73311×
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
73411×
            self.write_commit(
73511×
                &mut stream,
73611×
                "refs/oxy/export",
73711×
                mark,
73811×
                &author,
73911×
                secs,
74011×
                &message,
74111×
                &parents,
74211×
                &snapshot,
7430×
            )?;
74411×
            marks.insert(state_ref, mark);
74511×
            last_parent = Some(format!(":{mark}"));
74611×
            prev = Some((state_ref, state.heads.clone()));
74711×
            report.exported += 1;
748
        }
74912×
        if let Some(p) = &last_parent {
75012×
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
75112×
        }
752
        // Tags: a tag whose state was exported as a bookmark state points at
753
        // that commit; otherwise its state gets a commit of its own.
75412×
        for t in self.tags()? {
7550×
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
7560×
                (Some(sha), _) => sha.clone(),
7570×
                (None, Some(m)) => format!(":{m}"),
758
                (None, None) => {
7590×
                    let loaded = self.load_state(&t.heads)?;
7600×
                    let snapshot = loaded.materialize();
7610×
                    let mark = next_mark;
7620×
                    next_mark += 1;
7630×
                    let message = format!(
764
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
765
                        t.name,
7660×
                        if t.message.is_empty() {
7670×
                            String::new()
768
                        } else {
7690×
                            format!("{}\n\n", t.message)
770
                        },
7710×
                        t.state.to_hex()
772
                    );
7730×
                    self.write_commit(
7740×
                        &mut stream,
7750×
                        "refs/oxy/export",
7760×
                        mark,
7770×
                        "oxy <oxy@localhost>",
7780×
                        Hlc::now().wall_ms / 1000,
7790×
                        &message,
7800×
                        &[],
7810×
                        &snapshot,
7820×
                    )?;
7830×
                    marks.insert(t.state, mark);
7840×
                    report.exported += 1;
7850×
                    format!(":{mark}")
786
                }
787
            };
7880×
            stream.extend_from_slice(
7890×
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
790
            );
791
        }
79212×
        stream.extend_from_slice(b"done\n");
793
79412×
        let mut cmd = Command::new("git");
795
        // `--force`: the scratch ref may jump between unrelated states.
79612×
        cmd.arg("-C")
79712×
            .arg(git_dir)
79812×
            .args(["fast-import", "--quiet", "--done", "--force"])
79912×
            .arg(format!("--export-marks={}", git_marks.display()));
80012×
        if git_marks.exists() {
8016×
            cmd.arg(format!("--import-marks={}", git_marks.display()));
8026×
        }
80312×
        let mut child = cmd
80412×
            .stdin(Stdio::piped())
80512×
            .stdout(Stdio::null())
80612×
            .stderr(Stdio::piped())
80712×
            .spawn()
80812×
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
80912×
        child.stdin.take().unwrap().write_all(&stream)?;
81012×
        let out = child.wait_with_output()?;
81112×
        if !out.status.success() {
8120×
            return fail(format!(
813
                "git fast-import failed: {}",
8140×
                String::from_utf8_lossy(&out.stderr).trim()
815
            ));
81612×
        }
81712×
        let text: String = marks
81812×
            .iter()
81921×
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
82012×
            .collect();
82112×
        write_atomic(&oxy_marks_path, text.as_bytes())?;
82212×
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
82312×
        report.skipped_subrepos = self.git_export_skipped.replace(0);
82412×
        Ok(report)
82512×
    }
826
827
    /// Import branch `branch` of the Git repository at `git_dir` into this
828
    /// (empty) repository's bookmark (spec §23): one change per commit, its
829
    /// edits the difference between the union of its parents' states and its
830
    /// tree, so merge commits become resolutions. Submodules are skipped.
83113×
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
83213×
        self.import_git_with(git_dir, branch, &mut |_| {})
83313×
    }
834
835
    /// `import_git`, telling `progress` where it is every few hundred
836
    /// commits: the count so far, the merges, and the commit in hand, so a
837
    /// long import is never silent and a run that dies says where.
83813×
    pub fn import_git_with(
83913×
        &self,
84013×
        git_dir: &Path,
84113×
        branch: &str,
84213×
        progress: crate::store::Progress<'_>,
84313×
    ) -> Result<GitImportReport> {
84413×
        if !self.bookmark_heads()?.is_empty() {
8450×
            return fail("git import needs an empty bookmark; import into a fresh repository");
84613×
        }
84713×
        self.import_git_commits(
84813×
            git_dir,
84913×
            branch,
85013×
            &format!("oxy git import {} {branch}", git_dir.display()),
85113×
            progress,
852
        )
85313×
    }
854
855
    /// Import the commits of `branch` that the bookmark does not have yet,
856
    /// then move the bookmark to the union of its heads and theirs.
85716×
    fn import_git_commits(
85816×
        &self,
85916×
        git_dir: &Path,
86016×
        branch: &str,
86116×
        command: &str,
86216×
        progress: crate::store::Progress<'_>,
86316×
    ) -> Result<GitImportReport> {
86416×
        let batch = self.store.begin_batch()?;
86516×
        let result = self.import_git_commits_batched(git_dir, branch, command, progress);
86616×
        batch.finish()?;
86716×
        result
86816×
    }
869
87016×
    fn import_git_commits_batched(
87116×
        &self,
87216×
        git_dir: &Path,
87316×
        branch: &str,
87416×
        command: &str,
87516×
        progress: crate::store::Progress<'_>,
87616×
    ) -> Result<GitImportReport> {
87716×
        let commits = list_commits(git_dir, branch)?;
87816×
        let mut cat = CatFile::start(git_dir)?;
87916×
        let mut report = GitImportReport::default();
88016×
        let mut known = self.git_known(git_dir)?;
88116×
        let old_heads = self.bookmark_heads()?;
882
        // The bookmark's heads as changes arrive: a change stops being a
883
        // head when another depends on it, so no full state of every
884
        // imported change is needed at the end.
88516×
        let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect();
886
        // The state and Git tree of imported commits whose first-parent
887
        // children are still to come, so a child starts from its parent's
888
        // state instead of rebuilding it from history. The last child takes
889
        // it; earlier ones clone it. At most `max_kept` are kept (a later
890
        // child of an evicted one rebuilds).
891
        // OXY_IMPORT_KEEP overrides it, for measuring.
89216×
        let max_kept: usize = std::env::var("OXY_IMPORT_KEEP")
89316×
            .ok()
89416×
            .and_then(|v| v.parse().ok())
89516×
            .unwrap_or(8);
89616×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
89793×
        for gc in &commits {
89893×
            if let Some(p1) = gc.parents.first() {
89975×
                *waiting.entry(p1.as_str()).or_default() += 1;
90075×
            }
901
        }
902
        type Kept = (State, BTreeMap<String, (String, String)>);
90316×
        let mut kept: HashMap<String, Kept> = HashMap::new();
904
        // Every commit to import that has a parent, diffed against its first.
90516×
        let pairs: Vec<(String, String)> = commits
90616×
            .iter()
90793×
            .filter(|gc| {
90893×
                !known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha)
90993×
            })
91088×
            .filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone())))
91116×
            .collect();
91216×
        let mut diffs = DiffTree::start(git_dir, pairs)?;
91316×
        let mut rebuilt = 0usize;
91416×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
91516×
        let mut last: Option<String> = None;
91616×
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
91716×
        let mut cache_bytes: usize = 0;
918
        // Time spent per phase over all commits (`OXY_TIMINGS=1`).
91916×
        let mut spent = [std::time::Duration::ZERO; 6];
92016×
        let mut clock = std::time::Instant::now();
921
        // One line per commit on stderr with OXY_IMPORT_TRACE=1: where its
922
        // base came from, what a merge added, the graphs its state holds,
923
        // the kept states and the process's resident memory.
92416×
        let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some();
92516×
        let rss_mb = || -> u64 {
9260×
            std::fs::read_to_string("/proc/self/statm")
9270×
                .ok()
9280×
                .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
9290×
                .map(|pages| (pages * 4096) >> 20)
9300×
                .unwrap_or(0)
9310×
        };
93216×
        let mut done = 0usize;
933
        // Atoms a kept state's graphs may hold before they are shed;
934
        // OXY_IMPORT_KEPT_ATOMS overrides it, for measuring.
93516×
        let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS")
93616×
            .ok()
93716×
            .and_then(|v| v.parse().ok())
93816×
            .unwrap_or(KEPT_ATOMS);
939
        // Graphs turned back into history (see `State::shed_graphs`).
94016×
        let mut shed = 0usize;
941528×
        let mut lap = |i: usize, clock: &mut std::time::Instant| {
942528×
            let now = std::time::Instant::now();
943528×
            spent[i] += now - *clock;
944528×
            *clock = now;
945528×
        };
946
947
        // OXY_IMPORT_CHECKPOINT overrides it, for testing.
94816×
        let checkpoint_every: usize = std::env::var("OXY_IMPORT_CHECKPOINT")
94916×
            .ok()
95016×
            .and_then(|v| v.parse().ok())
95116×
            .filter(|n| *n > 0)
95216×
            .unwrap_or(CHECKPOINT_COMMITS);
953
        // OXY_IMPORT_STOP_AFTER ends the import cleanly after that many
954
        // commits, its timings reported, for measuring at depth.
95516×
        let stop_after: Option<usize> = std::env::var("OXY_IMPORT_STOP_AFTER")
95616×
            .ok()
95716×
            .and_then(|v| v.parse().ok());
958
        // Merges built from the paths they can change (oxygen#80): on VS
959
        // Code at 139k commits the same 400 commits came out identical to
960
        // whole-tree merges, with merges 3.2x faster. OXY_IMPORT_WHOLE_MERGES=1
961
        // builds them from the whole tree, for comparing.
96216×
        let partial_merges = std::env::var_os("OXY_IMPORT_WHOLE_MERGES").is_none_or(|v| v == "0");
96316×
        let total = commits.len();
964
        // The importing identity's own commits, claimed (`git.claim`,
965
        // oxygen#97): a commit whose Git author email is its email gets
966
        // its key as author; anyone else's keeps the zero key.
96716×
        let claim: Option<(KeyId, String)> = if self.config.git_claim {
9681×
            let Some(key) = self.config.author_key else {
9690×
                return fail("git.claim authors your own commits with your key, and there is none: run `oxy identity create` first, or `oxy config git.claim false`");
970
            };
9711×
            Some((key, self.identity(&key)?.email.to_lowercase()))
972
        } else {
97315×
            None
974
        };
97593×
        for (index, gc) in commits.iter().enumerate() {
97693×
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
9775×
                continue;
97888×
            }
97988×
            if stop_after.is_some_and(|n| done >= n) {
9800×
                break;
98188×
            }
98288×
            let commit_started = std::time::Instant::now();
98388×
            if index % 500 == 0 {
98414×
                progress(&format!(
98514×
                    "{index} of {total} commits, {} merges; at {} {}",
98614×
                    report.merges,
98714×
                    &gc.sha[..12.min(gc.sha.len())],
98814×
                    gc.message
98914×
                        .lines()
99014×
                        .next()
99114×
                        .unwrap_or("")
99214×
                        .chars()
99314×
                        .take(60)
99414×
                        .collect::<String>()
99514×
                ));
99674×
            }
99788×
            let mut base_how = "root";
998
            // Base: union of every parent's state, starting from the first
999
            // parent's kept state when there is one; its tree tells which
1000
            // paths this commit leaves alone.
100188×
            let (mut base, prev_tree) = match gc.parents.first() {
100272×
                Some(p1) => {
100372×
                    let left = waiting.get_mut(p1.as_str()).map(|n| {
100472×
                        *n -= 1;
100572×
                        *n
100672×
                    });
100772×
                    let found = if left == Some(0) {
100871×
                        kept_order.retain(|k| k != p1);
100952×
                        kept.remove(p1.as_str())
1010
                    } else {
101120×
                        kept.get(p1.as_str()).cloned()
1012
                    };
101372×
                    let how = match (&found, left) {
101451×
                        (Some(_), Some(0)) => "kept",
101520×
                        (Some(_), _) => "cloned",
10161×
                        (None, _) => "rebuilt",
1017
                    };
101872×
                    if trace {
10190×
                        base_how = how;
102072×
                    }
102172×
                    match found {
102271×
                        Some((st, tree)) => (st, Some(tree)),
1023
                        None => {
1024
                            // History only: graphs are built for the files a
1025
                            // commit changes, so memory follows what changes,
1026
                            // not the whole tree.
10271×
                            let mut st = State::new_history_only();
10281×
                            self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
1029
                            // The parent's tree, so this commit still
1030
                            // renders only what it changes.
10311×
                            rebuilt += 1;
10321×
                            (st, Some(list_tree(git_dir, p1)?))
1033
                        }
1034
                    }
1035
                }
103616×
                None => (State::new_history_only(), None),
1037
            };
1038
            // Nodes the other parents' changes touch: the first parent's
1039
            // tree cannot vouch for them.
104088×
            let mut touched: HashSet<NodeId> = HashSet::new();
104188×
            let mut merged = 0usize;
1042
            // Where the first parent has each node, read before the merged
1043
            // changes move anything: a merge's partial build names the paths
1044
            // they touch in the first parent's tree as well as in the merged
1045
            // state (oxygen#80).
104688×
            let mut first_parent_view: Option<crate::tree::TreeView> = None;
104788×
            if gc.parents.len() > 1 {
104824×
                report.merges += 1;
104924×
                if prev_tree.is_some() && partial_merges {
105024×
                    first_parent_view = Some(base.tree().view());
105124×
                }
105224×
                let mut args: Vec<String> = gc.parents[1..].to_vec();
105324×
                args.push(format!("^{}", gc.parents[0]));
105424×
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
1055
                // A merge of a long-lived branch brings thousands of
1056
                // changes: added to built graphs, which kept states share,
1057
                // they were copied and applied whole (vscode's import passed
1058
                // 14 GB on such merges). Shed the graphs first, so the
1059
                // changes go in as skeletons and only what this commit
1060
                // touches is built again.
106124×
                if base.built_count() > 0 {
106221×
                    let mut count_args = vec!["rev-list", "--count"];
106321×
                    count_args.extend(refs.iter().copied());
106421×
                    let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0);
106521×
                    let shed_at = std::env::var("OXY_MERGE_SHED")
106621×
                        .ok()
106721×
                        .and_then(|v| v.parse().ok())
106821×
                        .unwrap_or(MERGE_SHED_COMMITS);
106921×
                    if others > shed_at {
10700×
                        shed += base.shed_graphs(|b| self.store_blob(b))?;
107121×
                    }
10723×
                }
107324×
                let before = base.len();
107424×
                self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?;
107524×
                merged = base.len() - before;
107664×
            }
107788×
            lap(0, &mut clock);
1078
            // The commit's tree: its first parent's with the diff applied,
1079
            // or listed whole when that tree is not kept.
108088×
            let diff = match gc.parents.first() {
108172×
                Some(_) => Some(diffs.diff(&gc.sha)?),
108216×
                None => None,
1083
            };
108488×
            let (tree, changed) = match (prev_tree, diff) {
108572×
                (Some(mut t), Some(diff)) => {
108672×
                    let mut changed: HashSet<String> = HashSet::new();
108790×
                    for (path, entry) in diff {
108890×
                        match entry {
108972×
                            Some(v) => {
109072×
                                t.insert(path.clone(), v);
109172×
                            }
109218×
                            None => {
109318×
                                t.remove(&path);
109418×
                            }
1095
                        }
109690×
                        changed.insert(path);
1097
                    }
109872×
                    (t, Some(changed))
1099
                }
110016×
                _ => (list_tree(git_dir, &gc.sha)?, None),
1101
            };
110288×
            lap(1, &mut clock);
1103
            // Text files with the same blob and mode as in the first
1104
            // parent's tree equal the base's rendering: they are neither
1105
            // rendered nor read nor compared (spec §12.3, as for a clean
1106
            // working copy), so a commit costs what it changes.
110788×
            let mut same: HashMap<&str, NodeId> = HashMap::new();
1108
            // Opaque files and symlinks likewise, when the base has one
1109
            // blob for them: they are neither read nor stored again.
111088×
            let mut same_opaque: HashSet<&str> = HashSet::new();
1111
            // An ordinary commit in a tree without submodules is built from
1112
            // the paths it changes alone (oxygen#25): with the `.oxyattributes`
1113
            // files that decide how they are stored, and the directories its
1114
            // removals may leave empty. A merge, or a commit whose parent's
1115
            // tree is not at hand, is built from its whole tree.
1116
            // A merge can differ from its first parent only at the paths
1117
            // Git's diff names and where the merged changes touched: those
1118
            // paths in the first parent's tree and in the merged state. With
1119
            // them added it is built like an ordinary commit, instead of
1120
            // from its whole tree (18 s for any merge at 118k commits of
1121
            // VS Code, oxygen#80). OXY_IMPORT_WHOLE_MERGES=1 takes the
1122
            // whole-tree path.
112388×
            let mut changed = changed;
1124
            // A tree conflict in the merged state (both sides placed a file
1125
            // at one path) is resolved by the whole-tree path.
112688×
            let mut merge_how = if gc.parents.len() > 1 {
112724×
                if first_parent_view.is_some() {
112824×
                    "partial"
1129
                } else {
11300×
                    "whole"
1131
                }
1132
            } else {
113364×
                "-"
1134
            };
1135
            // Only a conflict among what the merged changes touched; one
1136
            // elsewhere stays as it was in the first parent either way.
113788×
            if first_parent_view.is_some()
113824×
                && base.tree().view().conflicts.iter().any(|c| {
1139
                    use crate::tree::TreeConflict::*;
11407×
                    match c {
11415×
                        Name { nodes, .. } => nodes.iter().any(|n| touched.contains(n)),
11421×
                        MultiPlacement { node, .. } | Cycle { node } | Mode { node, .. } => {
11431×
                            touched.contains(node)
1144
                        }
11451×
                        Orphan { node, parent } => {
11461×
                            touched.contains(node) || touched.contains(parent)
1147
                        }
1148
                    }
11497×
                })
11507×
            {
11517×
                first_parent_view = None;
11527×
                merge_how = "conflicted";
115381×
            }
115488×
            if let (Some(ch), Some(fp)) = (changed.as_mut(), &first_parent_view) {
115517×
                let union = base.tree().view();
115634×
                for v in [fp, &union] {
1157139×
                    for (path, e) in v.entries.iter() {
1158139×
                        if touched.contains(&e.node) {
115939×
                            ch.insert(path.clone());
1160100×
                        }
1161
                    }
1162
                }
116371×
            }
116488×
            let partial = changed.is_some()
116572×
                && (gc.parents.len() == 1 || first_parent_view.is_some())
1166172×
                && !tree.values().any(|(mode, _)| mode == "160000");
116788×
            let mut rel: BTreeSet<&str> = BTreeSet::new();
1168
            // Text files whose graphs this commit builds, for the trace.
1169
            let need_n: usize;
117088×
            let base_snapshot = if let (true, Some(changed)) = (partial, &changed) {
117164×
                let view = base.tree().view();
117264×
                rel.extend(changed.iter().map(String::as_str));
117364×
                rel.extend(
117464×
                    tree.keys()
117564×
                        .map(String::as_str)
1176169×
                        .filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")),
1177
                );
117864×
                let mut dirs: BTreeSet<&str> = BTreeSet::new();
117989×
                for p in changed.iter().filter(|p| !tree.contains_key(*p)) {
118018×
                    let mut end = p.len();
118134×
                    while let Some(i) = p[..end].rfind('/') {
118216×
                        if !dirs.insert(&p[..i]) {
11830×
                            break;
118416×
                        }
118516×
                        end = i;
1186
                    }
1187
                }
118864×
                let need: Vec<NodeId> = rel
118964×
                    .iter()
119089×
                    .filter_map(|p| view.entries.get(*p))
119165×
                    .filter(|e| e.kind == NodeKind::File && !e.mode.opaque)
119264×
                    .map(|e| e.node)
119364×
                    .collect();
119464×
                crate::timing::add("render: same and need", clock.elapsed());
119564×
                need_n = need.len();
119664×
                let t = std::time::Instant::now();
119764×
                self.load_graphs_of(&mut base, &need)?;
119864×
                crate::timing::add("render: load graphs", t.elapsed());
119964×
                let t = std::time::Instant::now();
120064×
                let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied());
120164×
                crate::timing::add("render: materialize", t.elapsed());
120264×
                snap
1203
            } else {
120424×
                if let Some(changed) = &changed {
12058×
                    let view = base.tree().view();
120619×
                    for path in tree.keys() {
1207
                        // Submodule handling reads these two whatever changed.
120819×
                        if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules"
1209
                        {
121010×
                            continue;
12119×
                        }
12129×
                        if let Some(e) = view.entries.get(path) {
12135×
                            if touched.contains(&e.node) {
12140×
                                continue;
12155×
                            }
12165×
                            let opaque = e.kind == NodeKind::Symlink
12175×
                                || (e.kind == NodeKind::File && e.mode.opaque);
12185×
                            if e.kind == NodeKind::File && !e.mode.opaque {
12195×
                                same.insert(path.as_str(), e.node);
12205×
                            } else if opaque && base.live_blobs(&e.node).len() == 1 {
12210×
                                same_opaque.insert(path.as_str());
12220×
                            }
12234×
                        }
1224
                    }
122516×
                }
1226
                // Build the graphs of every text file the commit may change.
122724×
                let skip: HashSet<NodeId> = same.values().copied().collect();
122824×
                let need: Vec<NodeId> = base
122924×
                    .tree()
123024×
                    .view()
123124×
                    .entries
123224×
                    .values()
123324×
                    .filter(|e| {
123421×
                        e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node)
123521×
                    })
123624×
                    .map(|e| e.node)
123724×
                    .collect();
123824×
                crate::timing::add("render: same and need", clock.elapsed());
123924×
                need_n = need.len();
124024×
                let t = std::time::Instant::now();
124124×
                let snap = if need.len() > merge_batch() {
1242
                    // A merge onto a base with no built graphs: thousands
1243
                    // of files, whose graphs would not fit at once.
12445×
                    self.materialize_batched(&mut base, &need, &skip)?
1245
                } else {
124619×
                    let g = std::time::Instant::now();
124719×
                    self.load_graphs_of(&mut base, &need)?;
124819×
                    crate::timing::add("render: whole, load graphs", g.elapsed());
124919×
                    let m = std::time::Instant::now();
125019×
                    let snap = base.materialize_except(&skip);
125119×
                    crate::timing::add("render: whole, materialize", m.elapsed());
125219×
                    snap
1253
                };
125424×
                crate::timing::add("render: whole tree", t.elapsed());
125524×
                snap
1256
            };
1257
125888×
            lap(2, &mut clock);
1259
            // The commit's tree as in-memory entries.
126088×
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
126188×
            let mut gitlinks: Vec<(String, String)> = Vec::new();
126288×
            let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial {
126389×
                Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p)))
1264
            } else {
126524×
                Box::new(tree.iter())
1266
            };
1267118×
            for (path, (mode, sha)) in listed {
1268118×
                let (path, sha) = (path.clone(), sha.clone());
1269118×
                let (kind, exec) = match mode.as_str() {
1270118×
                    "100644" | "100664" => (NodeKind::File, false),
127113×
                    "100755" => (NodeKind::File, true),
12721×
                    "120000" => (NodeKind::Symlink, false),
12731×
                    "160000" => {
12741×
                        gitlinks.push((path, sha));
12751×
                        continue;
1276
                    }
12770×
                    _ => continue,
1278
                };
1279117×
                if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) {
12805×
                    let mut e = FsEntry::new(kind, exec, Vec::new());
12815×
                    e.unchanged = true;
12825×
                    entries.insert(path, e);
12835×
                    continue;
1284112×
                }
1285112×
                let content = match blob_cache.get(&sha) {
128636×
                    Some(c) => c.clone(),
1287
                    None => {
128876×
                        let c = cat.read(&sha)?;
128976×
                        if cache_bytes + c.len() > 64 * 1024 * 1024 {
12900×
                            blob_cache.clear();
12910×
                            cache_bytes = 0;
129276×
                        }
129376×
                        cache_bytes += c.len();
129476×
                        blob_cache.insert(sha.clone(), c.clone());
129576×
                        c
1296
                    }
1297
                };
1298112×
                entries.insert(path, FsEntry::new(kind, exec, content));
1299
            }
1300
1301
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
1302
            // pins, and `.gitmodules` also yields `.oxymodules`.
130388×
            if !gitlinks.is_empty() {
13041×
                report.submodules += gitlinks.len();
13051×
                let gm = entries
13061×
                    .get(".gitmodules")
13071×
                    .map(|e| {
13081×
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
13091×
                            &e.content,
13101×
                        ))
13111×
                    })
13121×
                    .unwrap_or_default();
13131×
                let mut modules = entries
13141×
                    .get(".oxymodules")
13151×
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
13161×
                    .unwrap_or_default();
13171×
                for (path, sha) in &gitlinks {
13181×
                    let m = gm.entries.get(path);
13191×
                    let branch = m
13201×
                        .and_then(|m| m.bookmark.clone())
13211×
                        .unwrap_or_else(|| "HEAD".into());
13221×
                    entries.insert(
13231×
                        path.clone(),
13241×
                        FsEntry::new(
13251×
                            NodeKind::Subrepo,
1326
                            false,
13271×
                            crate::subrepo::Pin::Git {
13281×
                                sha: sha.clone(),
13291×
                                branch,
13301×
                            }
13311×
                            .encode(),
1332
                        ),
1333
                    );
13341×
                    if let Some(m) = m {
13351×
                        modules.entries.insert(path.clone(), m.clone());
13361×
                    }
1337
                }
13381×
                if !modules.entries.is_empty() {
13391×
                    entries.insert(
13401×
                        ".oxymodules".into(),
13411×
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
13421×
                    );
13431×
                }
134487×
            }
134588×
            lap(3, &mut clock);
1346
            // New nodes' identifiers derive from the commit, so importing the
1347
            // same Git history twice gives the same changes (spec §23).
134888×
            let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes();
134988×
            let mut built = if partial {
1350
                // Whether the new tree has anything under `dir`.
135164×
                let dir_needed = |dir: &str| {
135216×
                    let prefix = format!("{dir}/");
135316×
                    tree.range(prefix.clone()..)
135416×
                        .next()
135516×
                        .is_some_and(|(k, _)| k.starts_with(&prefix))
135616×
                };
135764×
                self.build_from_entries_seeded(
135864×
                    &base,
135964×
                    &base_snapshot,
136064×
                    &entries,
136164×
                    seed,
136264×
                    Some(&dir_needed),
13630×
                )?
1364
            } else {
136524×
                self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)?
1366
            };
136788×
            lap(4, &mut clock);
1368
            // A file or submodule with several live blobs (branches that
1369
            // replaced it independently) is resolved to the commit's blob:
1370
            // Git's merge is the authority here, unlike a working copy,
1371
            // where a candidate on disk is not yet a decision (spec §23).
1372102×
            for (path, f) in &base_snapshot.files {
1373102×
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
1374
                else {
137598×
                    continue;
1376
                };
13774×
                if blobs.len() < 2 || f.kind != e.kind {
13783×
                    continue;
13791×
                }
13801×
                let chosen = self.store_blob(&e.content)?;
13812×
                for b in blobs {
13822×
                    built.edits.push(Edit::Replace {
13832×
                        node: f.node,
13842×
                        old: Some(*b),
13852×
                        new: Some(chosen),
13862×
                    });
13872×
                }
13881×
                built.resolves = true;
13891×
                built
13901×
                    .contributors
13911×
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
1392
            }
1393
            // It shares the base's tree view, which applying the change
1394
            // then updates in place rather than copying.
139588×
            drop(base_snapshot);
139688×
            drop(entries);
139788×
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
139888×
            let mut message = gc.message.clone();
139988×
            if !message.ends_with('\n') {
140088×
                message.push('\n');
140188×
            }
140288×
            message.push_str(&format!(
140388×
                "\nGit-Commit: {}\nGit-Author: {}\n",
140488×
                gc.sha, gc.author
140588×
            ));
140688×
            let mut change = Change {
1407
                version: crate::objects::CHANGE_VERSION,
140888×
                change_id: change_id_for(&gc.sha, &gc.message),
140988×
                deps: vec![],
141088×
                author: claim
141188×
                    .as_ref()
141288×
                    .filter(|(_, email)| git_email(&gc.author).is_some_and(|e| e == *email))
141388×
                    .map_or(ObjectRef::ZERO, |(key, _)| *key),
141488×
                hlc: Hlc {
141588×
                    wall_ms: gc.author_secs * 1000,
141688×
                    logical: 0,
141788×
                },
141888×
                message,
141988×
                tree_ops: built.tree_ops,
142088×
                edits: built.edits,
142188×
                kind: if built.resolves {
142212×
                    ChangeKind::Resolution
1423
                } else {
142476×
                    ChangeKind::Normal
1425
                },
1426
            };
142788×
            let t = std::time::Instant::now();
1428
            // A deletion depends on whoever inserted the live atoms after
1429
            // it, which only the file's graph knows: build the few the
1430
            // batched rendering left deferred.
143188×
            let need: Vec<NodeId> = change
143288×
                .edits
143388×
                .iter()
143493×
                .filter(|e| matches!(e, Edit::Delete { .. }))
143588×
                .map(|e| e.node())
143688×
                .filter(|n| !base.is_built(n))
143788×
                .collect();
143888×
            if !need.is_empty() {
14390×
                self.load_graphs_of(&mut base, &need)?;
144088×
            }
144188×
            deps.extend(referenced_changes(&change, &base));
144288×
            crate::timing::add("store: referenced", t.elapsed());
144388×
            change.deps = deps.into_iter().collect();
144488×
            change.normalize();
144588×
            let hash = self.store.put_change(&change)?;
144696×
            for d in &change.deps {
144796×
                heads_now.remove(d);
144896×
            }
144988×
            heads_now.insert(hash);
1450
            // Built graphs take its edits whole; files not built keep only
1451
            // where its text is, read back from the store.
145288×
            let t = std::time::Instant::now();
145388×
            let (skeleton, texts) = self.store.get_change_lazy(&hash)?;
145488×
            base.add_known_mixed(hash, change, skeleton, texts);
145588×
            crate::timing::add("store: add to state", t.elapsed());
145688×
            known.imported.insert(gc.sha.clone(), hash);
145788×
            if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) {
1458
                // A kept state holds its graphs until its children come:
1459
                // past a few thousand, they go back into its history.
1460
                // Past a few thousand graphs, or past a budget of atoms: a
1461
                // long-lived file's graph keeps every line it ever had, so a
1462
                // handful of them can hold gigabytes (#25).
146351×
                if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms {
14640×
                    shed += base.shed_graphs(|b| self.store_blob(b))?;
146551×
                }
146651×
                kept.insert(gc.sha.clone(), (base, tree));
146751×
                kept_order.push_back(gc.sha.clone());
146851×
                if kept_order.len() > max_kept {
14690×
                    if let Some(old) = kept_order.pop_front() {
14700×
                        kept.remove(&old);
14710×
                    }
147251×
                }
147337×
            }
147488×
            last = Some(gc.sha.clone());
147588×
            report.commits += 1;
147688×
            lap(5, &mut clock);
147788×
            done += 1;
147888×
            if done.is_multiple_of(checkpoint_every) {
14790×
                self.checkpoint_import(&heads_now, done)?;
148088×
            }
1481
            // A merge renders thousands of files on many threads and frees
1482
            // it all; the allocator keeps those pages unless asked to give
1483
            // them back, and the next merge piles on top (#25).
148488×
            let before_trim = if trace { rss_mb() } else { 0 };
148588×
            if gc.parents.len() > 1 {
148624×
                crate::alloc_stats::release_freed_memory();
148764×
            }
148888×
            if trace {
14890×
                let built = kept
14900×
                    .get(gc.sha.as_str())
14910×
                    .map(|(st, _)| st.built_count())
14920×
                    .unwrap_or(0);
14930×
                let (edits, most) = kept
14940×
                    .get(gc.sha.as_str())
14950×
                    .map(|(st, _)| st.deferred_edit_count())
14960×
                    .unwrap_or((0, 0));
14970×
                let atoms = kept
14980×
                    .get(gc.sha.as_str())
14990×
                    .map(|(st, _)| st.built_atoms())
15000×
                    .unwrap_or(0);
15010×
                eprintln!(
1502
                    "trace {done} {} parents={} base={base_how} merged={merged} built={built} atoms={atoms} kept={} shed={shed} rss_mb={} before_trim_mb={before_trim} deferred_edits={edits} most={most} need={need_n} merge={merge_how} ms={}",
15030×
                    &gc.sha[..12.min(gc.sha.len())],
15040×
                    gc.parents.len(),
15050×
                    kept.len(),
15060×
                    rss_mb(),
15070×
                    commit_started.elapsed().as_millis()
1508
                );
150988×
            }
1510
        }
151196×
        for (name, d) in [
151216×
            "git import: bases",
151316×
            "git import: tree",
151416×
            "git import: render base",
151516×
            "git import: read blobs",
151616×
            "git import: build change",
151716×
            "git import: store change",
151816×
        ]
151916×
        .iter()
152016×
        .zip(spent)
152196×
        {
152296×
            crate::timing::record(name, d);
152396×
        }
152416×
        crate::timing::report_totals();
152516×
        if crate::timing::enabled() {
15260×
            eprintln!(
15270×
                "timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed"
15280×
            );
152916×
        }
1530
1531
        // The bookmark: heads of the old state plus every new change.
153216×
        report.heads = old_heads.len();
153316×
        if last.is_none() {
15341×
            return Ok(report);
153515×
        }
153615×
        let heads: Vec<ChangeHash> = heads_now.into_iter().collect();
153715×
        report.heads = heads.len();
153815×
        let (op_ref, op) = self.head_op()?;
153915×
        let mut view = op.view.clone();
154015×
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
154115×
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
154215×
        view.bookmarks
154315×
            .insert(self.config.bookmark.clone(), state_ref);
154415×
        self.record_op(&[op_ref], command, view)?;
1545
        // The new state equals the tip's tree when the old one was itself a
1546
        // Git commit's tree (fetched or exported), or there was none.
154715×
        let old_known = old_heads.is_empty()
15482×
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
154915×
        if let (Some(tip), true) = (commits.last(), old_known) {
155015×
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
15510×
        }
1552
        // The working copy follows when it was clean on the old heads.
155315×
        if old_heads.is_empty() {
155414×
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
1555
        } else {
15561×
            let snap = self.snapshot(command)?;
15571×
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
15581×
            let mut base = snap.base.maximal(&snap.wc.deps);
15591×
            base.sort();
15601×
            let mut sorted_old = old_heads.clone();
15611×
            sorted_old.sort();
1562
            // An empty base too: an import that stopped after a checkpoint
1563
            // never checked anything out, and resuming it should.
15641×
            if clean && (base == sorted_old || base.is_empty()) {
15651×
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
15660×
            }
1567
        }
156815×
        Ok(report)
156916×
    }
1570
1571
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
1572
    /// an imported commit's change, or the whole state an exported commit
1573
    /// was made from (which may hold changes Git never saw).
15741×
    fn add_git_ancestors(
15751×
        &self,
15761×
        st: &mut State,
15771×
        git_dir: &Path,
15781×
        args: &[&str],
15791×
        known: &GitKnown,
15801×
    ) -> Result<()> {
15811×
        self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new())
15821×
    }
1583
1584
    /// `add_git_ancestors`, also collecting in `touched` every node the
1585
    /// changes it adds edit, place or remove.
158625×
    fn add_git_ancestors_touching(
158725×
        &self,
158825×
        st: &mut State,
158925×
        git_dir: &Path,
159025×
        args: &[&str],
159125×
        known: &GitKnown,
159225×
        touched: &mut HashSet<NodeId>,
159325×
    ) -> Result<()> {
159425×
        let mut full = vec!["rev-list"];
159525×
        full.extend(args);
159625×
        let out = git(git_dir, &full)?;
159732×
        let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> {
159832×
            if st.contains(h) {
15992×
                return Ok(());
160030×
            }
160130×
            if !st.is_history_only() {
16020×
                let c = self.store.get_change(h)?;
16030×
                touched.extend(c.edits.iter().map(|e| e.node()));
16040×
                touched.extend(c.tree_ops.iter().map(|o| o.node()));
16050×
                st.add_unchecked(c);
16060×
                return Ok(());
160730×
            }
1608
            // History only: the text of an edit waits unread unless its
1609
            // file's graph is built.
161030×
            let (skeleton, texts) = self.store.get_change_lazy(h)?;
161132×
            touched.extend(skeleton.edits.iter().map(|e| e.node()));
161230×
            touched.extend(skeleton.tree_ops.iter().map(|o| o.node()));
161330×
            let built = skeleton
161430×
                .edits
161530×
                .iter()
161632×
                .any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node()));
161730×
            if built {
16184×
                let full = self.store.get_change(h)?;
16194×
                st.add_known_mixed(*h, full, skeleton, texts);
162026×
            } else {
162126×
                st.add_known(*h, skeleton, texts);
162226×
            }
162330×
            Ok(())
162432×
        };
162530×
        for sha in out.lines() {
162630×
            if let Some(h) = known.imported.get(sha) {
162729×
                add(st, h)?;
16281×
            } else if let Some(state_ref) = known.exported.get(sha) {
16291×
                let heads = self.store.get_state(state_ref)?.heads;
16303×
                for h in self.negotiate(&[], &heads)? {
16313×
                    add(st, &h)?;
1632
                }
16330×
            }
1634
        }
163525×
        Ok(())
163625×
    }
1637
1638
    /// Recover an import that stopped before it moved the bookmark: its
1639
    /// unfinished pack indexed (`Store::adopt_unfinished_packs`), then every
1640
    /// change in the store that carries a `Git-Commit:` trailer, its heads
1641
    /// (those no other such change depends on) made the bookmark's heads,
1642
    /// so `oxy git fetch` carries on from there. Reads every object once.
1643
    /// Returns how many imported changes it found and the heads.
16440×
    pub fn recover_git_import(&self, progress: &dyn Fn(&str)) -> Result<(usize, usize)> {
1645
        // A stopped import's objects are in a pack it never indexed.
1646
        // OXY_RECOVER_MIN_AGE (seconds) overrides the five minutes it must
1647
        // have been left alone, for testing.
16480×
        let min_age = std::env::var("OXY_RECOVER_MIN_AGE")
16490×
            .ok()
16500×
            .and_then(|v| v.parse().ok())
16510×
            .unwrap_or(300);
16520×
        self.store
16530×
            .adopt_unfinished_packs(std::time::Duration::from_secs(min_age), progress)?;
16540×
        let all = self
16550×
            .store
16560×
            .list()
16570×
            .map_err(|e| RepoError::Msg(format!("listing the store: {e}")))?;
16580×
        let total = all.len();
16590×
        let mut found: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
16600×
        for (i, r) in all.iter().enumerate() {
16610×
            if i.is_multiple_of(100_000) {
16620×
                progress(&format!(
16630×
                    "{i} of {total} objects read, {} imported changes",
16640×
                    found.len()
16650×
                ));
16660×
            }
16670×
            let Ok(meta) = self.store.get_change_meta(r) else {
16680×
                continue;
1669
            };
16700×
            if meta.message.lines().any(|l| l.starts_with("Git-Commit: ")) {
16710×
                found.insert(*r, meta.deps.clone());
16720×
            }
1673
        }
16740×
        if found.is_empty() {
16750×
            return fail("no imported Git commit's change in this store");
16760×
        }
16770×
        let depended: HashSet<ChangeHash> = found.values().flatten().copied().collect();
16780×
        let mut heads: Vec<ChangeHash> = found
16790×
            .keys()
16800×
            .filter(|h| !depended.contains(h))
16810×
            .copied()
16820×
            .collect();
1683
        // The bookmark's present heads stay: a recovery only adds.
16840×
        heads.extend(self.bookmark_heads().unwrap_or_default());
16850×
        let st = self.load_state_history(&heads)?;
16860×
        let mut heads = st.maximal(&heads);
16870×
        heads.sort();
16880×
        heads.dedup();
16890×
        let (op_ref, op) = self.head_op()?;
16900×
        let mut view = op.view.clone();
16910×
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
16920×
        view.bookmarks
16930×
            .insert(self.config.bookmark.clone(), state_ref);
16940×
        self.record_op(&[op_ref], "oxy git recover", view)?;
16950×
        Ok((found.len(), heads.len()))
16960×
    }
1697
1698
    /// Point the bookmark at an import's heads so far (see
1699
    /// `CHECKPOINT_COMMITS`); the working copy is left alone until the end.
17000×
    fn checkpoint_import(&self, heads: &BTreeSet<ChangeHash>, done: usize) -> Result<()> {
17010×
        let heads: Vec<ChangeHash> = heads.iter().copied().collect();
17020×
        let (op_ref, op) = self.head_op()?;
17030×
        let mut view = op.view.clone();
17040×
        let state_ref = self.store.put_state(&StateObject::new(heads))?;
17050×
        view.bookmarks
17060×
            .insert(self.config.bookmark.clone(), state_ref);
17070×
        self.record_op(
17080×
            &[op_ref],
17090×
            &format!("oxy git import (checkpoint after {done} commits)"),
17100×
            view,
17110×
        )?;
17120×
        Ok(())
17130×
    }
1714
1715
    /// Commits this repository can relate to Oxygen history: imported
1716
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
171720×
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
171820×
        let imported = self.imported_commits()?;
171920×
        let marks_dir = self.git_marks_dir(git_dir)?;
172020×
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
172120×
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
172220×
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
17234×
            for line in text.lines() {
17244×
                if let Some((m, sha)) = line.split_once(' ') {
17254×
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
17264×
                        sha_of_mark.insert(m, sha.trim().to_string());
17274×
                    }
17280×
                }
1729
            }
173016×
        }
173120×
        let mut exported = HashMap::new();
173220×
        for (state_ref, m) in oxy_marks {
17334×
            if let Some(sha) = sha_of_mark.get(&m) {
17344×
                exported.insert(sha.clone(), state_ref);
17354×
            }
1736
        }
173720×
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
17387×
            exported.entry(sha).or_insert(state_ref);
17397×
        }
174020×
        Ok(GitKnown { imported, exported })
174120×
    }
1742
17438×
    fn git_author(&self, c: &Change) -> String {
17448×
        self.git_author_key(&c.author)
17458×
    }
1746
1747
    #[allow(clippy::too_many_arguments)]
174819×
    fn write_commit(
174919×
        &self,
175019×
        out: &mut Vec<u8>,
175119×
        reference: &str,
175219×
        mark: u64,
175319×
        author: &str,
175419×
        secs: u64,
175519×
        message: &str,
175619×
        parents: &[String],
175719×
        snapshot: &Snapshot,
175819×
    ) -> Result<()> {
175919×
        out.extend_from_slice(format!("commit {reference}\nmark :{mark}\nauthor {author} {secs} +0000\ncommitter {author} {secs} +0000\ndata {}\n{message}\n", message.len()).as_bytes());
176019×
        for (i, p) in parents.iter().enumerate() {
176112×
            out.extend_from_slice(
176212×
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
1763
            );
1764
        }
176519×
        out.extend_from_slice(b"deleteall\n");
176619×
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
176758×
        for (path, f) in &snapshot.files {
176858×
            if path == ".oxymodules" {
1769
                // Git reads `.gitmodules`; derive it unless the tree has one.
17701×
                if !has_gitmodules {
17710×
                    if let FileContent::Text { bytes, .. } = &f.content {
17720×
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
17730×
                            .to_gitmodules();
17740×
                        if !gm.is_empty() {
17750×
                            out.extend_from_slice(
17760×
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
17770×
                                    .as_bytes(),
17780×
                            );
17790×
                            out.extend_from_slice(gm.as_bytes());
17800×
                            out.push(b'\n');
17810×
                        }
17820×
                    }
17831×
                }
17841×
                continue;
178557×
            }
178657×
            if f.kind == NodeKind::Subrepo {
17871×
                if let FileContent::Opaque { blobs } = &f.content {
17881×
                    if let Some(b) = blobs.first() {
17891×
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
17901×
                            crate::subrepo::Pin::Git { sha, .. } => {
17911×
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
1792
                            }
17930×
                            crate::subrepo::Pin::Oxy { .. } => self
17940×
                                .git_export_skipped
17950×
                                .set(self.git_export_skipped.get() + 1),
1796
                        }
17970×
                    }
17980×
                }
17991×
                continue;
180056×
            }
180156×
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
180213×
                (NodeKind::Dir, _) => continue,
18030×
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
18040×
                    "120000",
18050×
                    blobs
18060×
                        .first()
18070×
                        .map(|b| self.read_blob(b))
18080×
                        .transpose()?
18090×
                        .unwrap_or_default(),
1810
                ),
181140×
                (_, FileContent::Text { bytes, .. }) => {
181240×
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
1813
                }
18143×
                (_, FileContent::Opaque { blobs }) => (
18153×
                    if f.mode.exec { "100755" } else { "100644" },
18163×
                    blobs
18173×
                        .first()
18183×
                        .map(|b| self.read_blob(b))
18193×
                        .transpose()?
18203×
                        .unwrap_or_default(),
1821
                ),
18220×
                (_, FileContent::Dir) => continue,
1823
            };
182443×
            out.extend_from_slice(
182543×
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
1826
            );
182743×
            out.extend_from_slice(&bytes);
182843×
            out.push(b'\n');
1829
        }
183019×
        out.push(b'\n');
183119×
        Ok(())
183219×
    }
1833
}
1834
1835
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
1836
#[derive(Debug, Clone, Default, PartialEq, Eq)]
1837
pub struct GitVerifyReport {
1838
    pub commits: usize,
1839
    /// Commits followed but not rebuilt (all but the last few, when asked).
1840
    pub skipped: usize,
1841
    pub files_compared: usize,
1842
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
1843
    pub mismatches: Vec<(String, String)>,
1844
    /// Commits of the branch after the last imported one: an import not
1845
    /// finished yet. Not checked.
1846
    pub not_yet: usize,
1847
}
1848
1849
impl Repo {
1850
    /// Check an import against its Git source: for every commit of
1851
    /// `branch`, the state formed by the changes imported for it and all
1852
    /// its ancestors must materialize to exactly that commit's tree, byte
1853
    /// for byte, with the same executable bits, symlink targets and
1854
    /// submodule pins. Reads only; stops listing after 50 differences.
185510×
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
185610×
        self.verify_git_import_last(git_dir, branch, None, 50)
185710×
    }
1858
1859
    /// [`Repo::verify_git_import`] of the last `last` commits only (all
1860
    /// when `None`): earlier ones are only followed, not rebuilt, for
1861
    /// looking again at where an import went wrong.
1862
    /// It stops after `max` differences (0: never), so one that repeats
1863
    /// through history does not hide the commits after it.
186410×
    pub fn verify_git_import_last(
186510×
        &self,
186610×
        git_dir: &Path,
186710×
        branch: &str,
186810×
        last: Option<usize>,
186910×
        max: usize,
187010×
    ) -> Result<GitVerifyReport> {
187110×
        let mut rep = GitVerifyReport::default();
187210×
        let mut commits = list_commits(git_dir, branch)?;
187310×
        let imported = self.imported_commits()?;
1874
        // An import still going (or stopped) has reached part of the
1875
        // branch: what follows its last imported commit is not checked,
1876
        // only counted, and --last counts back from there (oxygen#81).
187710×
        if let Some(end) = commits.iter().rposition(|c| imported.contains_key(&c.sha)) {
187810×
            let rest = commits.len() - end - 1;
187910×
            if rest > 0 {
18800×
                commits.truncate(end + 1);
188110×
            }
188210×
            rep.not_yet = rest;
18830×
        }
188410×
        let mut cat = CatFile::start(git_dir)?;
1885
        // Changes of each commit and all its ancestors, built up in topological order.
188610×
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
1887
        // Graphs (by key) and blobs already found equal to a Git blob.
188810×
        let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new();
188910×
        let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new();
1890
        // The state of a commit whose first-parent children are still to
1891
        // come, so a child adds its own changes instead of loading all its
1892
        // history again (as the import does).
189310×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
1894
        // Children still to come per commit, through any parent: a commit's
1895
        // closure is dropped after its last child, so only the open
1896
        // frontier is held. Kept for every commit, the closures grew with
1897
        // the square of the history and VS Code's verify ran out of memory
1898
        // (oxygen#81).
189910×
        let mut children: HashMap<&str, usize> = HashMap::new();
190063×
        for c in &commits {
190163×
            if let Some(p1) = c.parents.first() {
190251×
                *waiting.entry(p1.as_str()).or_default() += 1;
190351×
            }
190469×
            for p in &c.parents {
190569×
                *children.entry(p.as_str()).or_default() += 1;
190669×
            }
1907
        }
190810×
        let mut kept: HashMap<String, State> = HashMap::new();
190910×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
191063×
        for c in &commits {
191163×
            rep.commits += 1;
1912
            // The first parent's closure, taken over when this is its last
1913
            // child (no copy), then the other parents' added.
191463×
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
191569×
            for (i, p) in c.parents.iter().enumerate() {
191669×
                let left = children.get_mut(p.as_str()).map(|n| {
191769×
                    *n -= 1;
191869×
                    *n
191969×
                });
192069×
                let ps = if left == Some(0) {
192153×
                    closure.remove(p)
1922
                } else {
192316×
                    closure.get(p).cloned()
1924
                };
192569×
                if let Some(ps) = ps {
192669×
                    if i == 0 && set.is_empty() {
192751×
                        set = Arc::try_unwrap(ps).unwrap_or_else(|a| (*a).clone());
192818×
                    } else {
192918×
                        set.extend(ps.iter().copied());
193018×
                    }
19310×
                }
1932
            }
193363×
            match imported.get(&c.sha) {
193463×
                Some(h) => {
193563×
                    set.insert(*h);
193663×
                }
19370×
                None => {
19380×
                    rep.mismatches.push((
19390×
                        c.sha.clone(),
19400×
                        "no imported change carries this commit".into(),
19410×
                    ));
19420×
                }
1943
            }
194463×
            let set = Arc::new(set);
194563×
            if children.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
194653×
                closure.insert(c.sha.clone(), set.clone());
194753×
            }
194863×
            if max > 0 && rep.mismatches.len() >= max {
19490×
                break;
195063×
            }
195163×
            if last.is_some_and(|n| rep.commits + n <= commits.len()) {
19520×
                rep.skipped += 1;
19530×
                continue;
195463×
            }
195563×
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1956
            // History only: a file whose graph (by key) or blob was already
1957
            // found equal to this Git blob is not built, rendered or read
1958
            // again; the rest are.
195963×
            let from_parent = c.parents.first().and_then(|p1| {
196051×
                let left = waiting.get_mut(p1.as_str()).map(|n| {
196151×
                    *n -= 1;
196251×
                    *n
196351×
                });
196451×
                if left == Some(0) {
196553×
                    kept_order.retain(|k| k != p1);
196637×
                    kept.remove(p1.as_str())
1967
                } else {
196814×
                    kept.get(p1.as_str()).cloned()
1969
                }
197051×
            });
197163×
            let state = match from_parent {
197251×
                Some(mut st) => {
1973
                    // The changes the parent's state lacks. The state never
1974
                    // builds a graph (they are built beside it), so they
1975
                    // are read without their text.
1976223×
                    for h in set.iter() {
1977223×
                        if !st.contains(h) {
197872×
                            let (change, texts) = self.store.get_change_lazy(h)?;
197972×
                            st.add_known(*h, change, texts);
1980151×
                        }
1981
                    }
198251×
                    st
1983
                }
198412×
                None => self.load_state_history(&heads)?,
1985
            };
198663×
            let view = state.tree().view();
198763×
            let tree = list_tree(git_dir, &c.sha)?;
198863×
            let short = &c.sha[..12.min(c.sha.len())];
198963×
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
199063×
            let mut conflicted: Vec<String> =
199163×
                view.conflicts.iter().map(|c| format!("{c:?}")).collect();
199263×
            let mut need: Vec<NodeId> = Vec::new();
1993145×
            for (path, (mode, sha)) in &tree {
1994145×
                let Some(e) = view.entries.get(path) else {
19950×
                    continue;
1996
                };
1997145×
                if mode != "160000"
1998145×
                    && mode != "120000"
1999145×
                    && e.kind == NodeKind::File
2000145×
                    && !e.mode.opaque
2001
                {
2002134×
                    let known = state
2003134×
                        .graph_key(&e.node)
2004134×
                        .is_some_and(|k| verified_graphs.get(&k) == Some(sha));
2005134×
                    if !known {
200650×
                        need.push(e.node);
200784×
                    }
200811×
                }
2009
            }
2010
            // A graph's key is known only before it is built.
201163×
            let keys: HashMap<NodeId, [u8; 32]> = need
201263×
                .iter()
201363×
                .filter_map(|n| Some((*n, state.graph_key(n)?)))
201463×
                .collect();
201563×
            let need_set: HashSet<NodeId> = need.iter().copied().collect();
201663×
            let graphs = self.build_graphs_detached(&state, &need)?;
2017145×
            for (path, (mode, sha)) in &tree {
2018145×
                let Some(e) = view.entries.get(path) else {
20190×
                    differ(format!("{short}: {path} is missing"));
20200×
                    continue;
2021
                };
2022145×
                rep.files_compared += 1;
2023145×
                match mode.as_str() {
2024145×
                    "160000" => {
20250×
                        let blobs = state.live_blobs(&e.node);
20260×
                        match (e.kind, blobs.as_slice()) {
20270×
                            (NodeKind::Subrepo, [b]) => {
20280×
                                let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?;
20290×
                                if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
20300×
                                {
20310×
                                    differ(format!("{short}: {path} pins another commit"));
20320×
                                }
2033
                            }
20340×
                            (kind, _) => differ(format!(
20350×
                                "{short}: {path} is not one submodule pin: {kind:?} with {} pins",
20360×
                                blobs.len()
20370×
                            )),
2038
                        }
2039
                    }
2040145×
                    "120000" => {
20410×
                        let target = cat.read(sha)?;
20420×
                        let blobs = state.live_blobs(&e.node);
20430×
                        match (e.kind, blobs.as_slice()) {
20440×
                            (NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {}
20450×
                            _ => differ(format!("{short}: symlink {path} differs")),
2046
                        }
2047
                    }
2048
                    _ => {
2049145×
                        if e.mode.exec != (mode == "100755") {
20500×
                            differ(format!("{short}: {path} executable bit differs"));
2051145×
                        }
2052145×
                        if e.kind == NodeKind::File && !e.mode.opaque {
2053134×
                            if !need_set.contains(&e.node) {
2054
                                // Known equal: skipped when the graphs were chosen.
205584×
                                continue;
205650×
                            }
205750×
                            let (have, m) = match graphs.get(&e.node) {
205850×
                                Some(g) => state.render_graph(g),
20590×
                                None => (Vec::new(), Default::default()),
2060
                            };
206150×
                            if m.is_conflicted() {
2062
                                // Who conflicts: a copy of the state with this graph built.
20630×
                                let mut detail = state.clone();
20640×
                                self.load_graphs_of(&mut detail, &[e.node])?;
20650×
                                let who: Vec<String> = detail
20660×
                                    .conflict_regions(&e.node)
20670×
                                    .contributors
20680×
                                    .iter()
20690×
                                    .filter_map(|h| state.get(h))
20700×
                                    .map(|m| {
20710×
                                        let sha = m
20720×
                                            .message
20730×
                                            .lines()
20740×
                                            .rev()
20750×
                                            .find_map(|l| l.strip_prefix("Git-Commit: "))
20760×
                                            .unwrap_or("?");
20770×
                                        format!(
2078
                                            "{} {:?}",
20790×
                                            &sha[..12.min(sha.len())],
20800×
                                            m.message.lines().next().unwrap_or("")
2081
                                        )
20820×
                                    })
20830×
                                    .collect();
20840×
                                conflicted.push(format!("{path} between {}", who.join(" and ")));
208550×
                            }
208650×
                            let want = cat.read(sha)?;
208750×
                            if have != want {
20880×
                                differ(format!(
20890×
                                    "{short}: {path} differs: {}",
20900×
                                    first_difference(&have, &want)
20910×
                                ));
209250×
                            } else if !m.is_conflicted() {
209350×
                                if let Some(k) = keys.get(&e.node) {
209450×
                                    verified_graphs.insert(*k, sha.clone());
209550×
                                }
20960×
                            }
209750×
                            continue;
209811×
                        }
209911×
                        let blobs = state.live_blobs(&e.node);
210011×
                        let [b] = blobs.as_slice() else {
21010×
                            differ(format!("{short}: {path} is not one file"));
21020×
                            continue;
2103
                        };
210411×
                        if verified_blobs.get(b) == Some(sha) {
21056×
                            continue;
21065×
                        }
21075×
                        if self.read_blob(b)? != cat.read(sha)? {
21080×
                            differ(format!("{short}: {path} differs"));
21095×
                        } else {
21105×
                            verified_blobs.insert(*b, sha.clone());
21115×
                        }
2112
                    }
2113
                }
2114
            }
211563×
            if !conflicted.is_empty() {
21160×
                differ(format!(
21170×
                    "{short}: the state is conflicted: {}",
21180×
                    conflicted.join("; ")
21190×
                ));
212063×
            }
2121
            // Import records submodules in `.oxymodules` as well (spec §23),
2122
            // and export leaves it out again.
2123145×
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
2124186×
            for (path, e) in view.entries.iter() {
2125186×
                if e.kind != NodeKind::Dir
2126145×
                    && !tree.contains_key(path)
21270×
                    && !(has_submodules && path == ".oxymodules")
21280×
                {
21290×
                    differ(format!("{short}: {path} is extra"));
2130186×
                }
2131
            }
213263×
            if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
213337×
                kept.insert(c.sha.clone(), state);
213437×
                kept_order.push_back(c.sha.clone());
213537×
                if kept_order.len() > 8 {
21360×
                    if let Some(old) = kept_order.pop_front() {
21370×
                        kept.remove(&old);
21380×
                    }
213937×
                }
214026×
            }
214163×
            if max > 0 && rep.mismatches.len() >= max {
21420×
                break;
214363×
            }
2144
        }
214510×
        Ok(rep)
214610×
    }
2147
}
2148
2149
/// Where two versions of a file first part, for a verification report.
21500×
fn first_difference(have: &[u8], want: &[u8]) -> String {
21510×
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
21520×
        have.split(|b| *b == b'\n').collect(),
21530×
        want.split(|b| *b == b'\n').collect(),
2154
    );
21550×
    let i = h
21560×
        .iter()
21570×
        .zip(&w)
21580×
        .position(|(a, b)| a != b)
21590×
        .unwrap_or(h.len().min(w.len()));
21600×
    let show = |l: Option<&&[u8]>| {
21610×
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
21620×
            .unwrap_or_else(|| "(end)".into())
21630×
    };
21640×
    format!(
2165
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
21660×
        i + 1,
21670×
        show(h.get(i)),
21680×
        show(w.get(i)),
21690×
        h.len(),
21700×
        w.len()
2171
    )
21720×
}
2173
2174
/// What `git_export_graph` wrote.
2175
#[derive(Debug, Clone, Default, PartialEq, Eq)]
2176
pub struct GitGraphReport {
2177
    /// Changes written as commits this time (the rest were exported before).
2178
    pub commits: usize,
2179
    /// Branches and tags pointed at their commits.
2180
    pub branches: usize,
2181
    pub tags: usize,
2182
    /// Bookmarks or tags whose names Git does not take as refs.
2183
    pub skipped_refs: Vec<String>,
2184
    /// Subrepo nodes with Oxygen pins, which Git cannot represent.
2185
    pub skipped_subrepos: usize,
2186
}
2187
2188
/// A bookmark or tag name Git takes as a ref without escaping.
21897×
fn git_ref_ok(name: &str) -> bool {
21907×
    !name.is_empty()
21917×
        && !name.starts_with(['-', '/', '.'])
21927×
        && !name.ends_with(['/', '.'])
21937×
        && !name.contains("..")
21947×
        && !name.contains("//")
21957×
        && !name.ends_with(".lock")
21967×
        && name
21977×
            .bytes()
219822×
            .all(|b| b.is_ascii_alphanumeric() || b"-_./+".contains(&b))
21997×
}
2200
2201
impl Repo {
2202
    /// Export every bookmark and tag to the bare Git repository at
2203
    /// `git_dir` from the change graph (spec §23, oxygenhub D1), for a hub
2204
    /// to serve to Git clients. Unlike `git_export`, which follows one
2205
    /// checkout's operation log, this depends only on the changes, so the
2206
    /// same changes give the same Git commits wherever it runs:
2207
    ///
2208
    /// - each change is a commit whose tree is the state of the change and
2209
    ///   everything it depends on, whose parents are its dependencies'
2210
    ///   commits, with the change's author, time and message and its
2211
    ///   `Change-Id:` and `Oxy-Hash:` trailers (a change that depends on
2212
    ///   nothing is a root, so Git sees Oxygen's dependencies, not the order
2213
    ///   changes were made in);
2214
    /// - a bookmark with one head is a branch at that head's commit; with
2215
    ///   several, a merge of their commits whose tree is the bookmark's
2216
    ///   state, at the newest head's time;
2217
    /// - a tag points at its heads' commit, or such a merge.
2218
    ///
2219
    /// Commits already exported are remembered (marks), so a later run
2220
    /// writes only new changes. Branches for bookmarks that are gone are
2221
    /// deleted.
22223×
    pub fn git_export_graph(&self, git_dir: &Path) -> Result<GitGraphReport> {
22233×
        if !git_dir.join("HEAD").exists() {
22242×
            fs::create_dir_all(git_dir)?;
22252×
            git(git_dir, &["init", "--bare", "-q"])?;
22261×
        }
22273×
        let marks_dir = self.git_marks_dir(git_dir)?;
22283×
        let git_marks = marks_dir.join("git-marks");
22293×
        let graph_marks = marks_dir.join("graph-marks");
22303×
        let mut marks = Self::read_oxy_marks(&graph_marks)?;
22313×
        let mut next = marks.values().copied().max().unwrap_or(0) + 1;
22323×
        let mut report = GitGraphReport::default();
22333×
        let mut stream: Vec<u8> = Vec::new();
2234
22353×
        let mut refs: Vec<(String, Vec<ChangeHash>)> = Vec::new();
22364×
        for b in self.bookmarks()? {
22374×
            if git_ref_ok(&b.name) {
22384×
                refs.push((format!("refs/heads/{}", b.name), b.heads));
22394×
            } else {
22400×
                report.skipped_refs.push(b.name);
22410×
            }
2242
        }
22433×
        let tags = self.tags()?;
22443×
        for t in &tags {
22453×
            if git_ref_ok(&t.name) {
22463×
                refs.push((format!("refs/tags/{}", t.name), t.heads.clone()));
22473×
            } else {
22480×
                report.skipped_refs.push(t.name.clone());
22490×
            }
2250
        }
2251
2252
        // Every change the refs reach, dependencies before dependents: a
2253
        // depth-first walk in hash order, so the order is the same everywhere.
22543×
        let mut order: Vec<ChangeHash> = Vec::new();
22553×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
22563×
        let mut metas: HashMap<ChangeHash, crate::state::ChangeMeta> = HashMap::new();
22577×
        let mut roots: Vec<ChangeHash> = refs.iter().flat_map(|(_, h)| h.iter().copied()).collect();
22583×
        roots.sort();
22593×
        roots.dedup();
22607×
        for root in roots {
22617×
            if !seen.insert(root) {
22621×
                continue;
22636×
            }
22646×
            let mut stack: Vec<(ChangeHash, bool)> = vec![(root, false)];
226524×
            while let Some((h, done)) = stack.pop() {
226618×
                if done {
22679×
                    order.push(h);
22689×
                    continue;
22699×
                }
22709×
                stack.push((h, true));
22719×
                let meta = self.store.get_change_meta(&h)?;
22729×
                let mut deps = meta.deps.clone();
22739×
                deps.sort();
22749×
                for d in deps.into_iter().rev() {
22753×
                    if seen.insert(d) {
22763×
                        stack.push((d, false));
22773×
                    }
2278
                }
22799×
                metas.insert(h, meta);
2280
            }
2281
        }
2282
22839×
        for h in &order {
22849×
            if marks.contains_key(h) {
22853×
                continue;
22866×
            }
22876×
            let meta = &metas[h];
22886×
            let snapshot = self.load_state(&[*h])?.materialize();
22896×
            let mut message = meta.message.clone();
22906×
            if !message.ends_with('\n') {
22916×
                message.push('\n');
22926×
            }
22936×
            message.push_str(&format!(
22946×
                "\nChange-Id: {}\nOxy-Hash: {}\n",
22956×
                meta.change_id.to_hex(),
22966×
                h.to_hex()
22976×
            ));
22986×
            if snapshot.is_conflicted() {
22990×
                message.push_str("Oxy-Conflicted: true\n");
23006×
            }
23016×
            let mut deps = meta.deps.clone();
23026×
            deps.sort();
23036×
            let parents: Vec<String> = deps
23046×
                .iter()
23056×
                .filter_map(|d| marks.get(d))
23066×
                .map(|m| format!(":{m}"))
23076×
                .collect();
23086×
            let mark = next;
23096×
            next += 1;
23106×
            if parents.is_empty() {
23114×
                // Without `from`, fast-import would make the scratch ref's
23124×
                // tip its parent; a change that depends on nothing is a root.
23134×
                stream.extend_from_slice(b"reset refs/oxy/export\n\n");
23144×
            }
23156×
            self.write_commit(
23166×
                &mut stream,
23176×
                "refs/oxy/export",
23186×
                mark,
23196×
                &self.git_author_key(&meta.author),
23206×
                meta.hlc.wall_ms / 1000,
23216×
                &message,
23226×
                &parents,
23236×
                &snapshot,
23240×
            )?;
23256×
            marks.insert(*h, mark);
23266×
            report.commits += 1;
2327
        }
2328
23293×
        let mut wanted: HashSet<String> = HashSet::new();
23307×
        for (name, heads) in &refs {
23317×
            let mut heads = heads.clone();
23327×
            heads.sort();
23337×
            heads.dedup();
23347×
            let target = match heads.as_slice() {
23357×
                [] => continue,
23364×
                [one] => format!(":{}", marks[one]),
23373×
                many => {
2338
                    // A merge of the heads, named by them so it is made once.
23393×
                    let key = hash_object(
23403×
                        ObjectType::Chunk,
23413×
                        many.iter()
23426×
                            .map(|h| h.to_hex())
23433×
                            .collect::<Vec<_>>()
23443×
                            .join(" ")
23453×
                            .as_bytes(),
2346
                    );
23473×
                    if let Some(m) = marks.get(&key) {
23481×
                        format!(":{m}")
2349
                    } else {
23502×
                        let snapshot = self.load_state(many)?.materialize();
23514×
                        let newest = many.iter().map(|h| metas[h].hlc.wall_ms).max().unwrap_or(0);
23522×
                        let mut message = format!(
2353
                            "Merge of {} heads\n\nOxy-Heads: {}\n",
23542×
                            many.len(),
23552×
                            many.iter()
23564×
                                .map(|h| h.to_hex())
23572×
                                .collect::<Vec<_>>()
23582×
                                .join(" ")
2359
                        );
23602×
                        if snapshot.is_conflicted() {
23610×
                            message.push_str("Oxy-Conflicted: true\n");
23622×
                        }
23632×
                        let parents: Vec<String> =
23644×
                            many.iter().map(|h| format!(":{}", marks[h])).collect();
23652×
                        let mark = next;
23662×
                        next += 1;
23672×
                        self.write_commit(
23682×
                            &mut stream,
23692×
                            "refs/oxy/export",
23702×
                            mark,
23712×
                            "oxy <oxy@localhost>",
23722×
                            newest / 1000,
23732×
                            &message,
23742×
                            &parents,
23752×
                            &snapshot,
23760×
                        )?;
23772×
                        marks.insert(key, mark);
23782×
                        format!(":{mark}")
2379
                    }
2380
                }
2381
            };
23827×
            stream.extend_from_slice(format!("reset {name}\nfrom {target}\n\n").as_bytes());
23837×
            wanted.insert(name.clone());
23847×
            if name.starts_with("refs/tags/") {
23853×
                report.tags += 1;
23864×
            } else {
23874×
                report.branches += 1;
23884×
            }
2389
        }
23903×
        stream.extend_from_slice(b"done\n");
23913×
        run_fast_import(git_dir, &stream, &git_marks)?;
23923×
        let text: String = marks
23933×
            .iter()
239412×
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
23953×
            .collect();
23963×
        write_atomic(&graph_marks, text.as_bytes())?;
23973×
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
2398
        // Branches and tags of bookmarks and tags that are gone.
23993×
        let listed = git(
24003×
            git_dir,
24013×
            &[
24023×
                "for-each-ref",
24033×
                "--format=%(refname)",
24043×
                "refs/heads",
24053×
                "refs/tags",
24063×
            ],
24070×
        )?;
24083×
        for r in listed
24093×
            .lines()
24103×
            .map(str::trim)
24118×
            .filter(|r| !r.is_empty() && !wanted.contains(*r))
2412
        {
24131×
            git(git_dir, &["update-ref", "-d", r])?;
2414
        }
2415
        // HEAD names the main bookmark when there is one, so a clone checks it out.
24163×
        let main = ["main", "master", "trunk", "develop"]
24173×
            .into_iter()
24183×
            .find(|b| wanted.contains(&format!("refs/heads/{b}")));
24193×
        if let Some(b) = main {
24203×
            git(
24213×
                git_dir,
24223×
                &["symbolic-ref", "HEAD", &format!("refs/heads/{b}")],
24230×
            )?;
24240×
        }
24253×
        report.skipped_subrepos = self.git_export_skipped.replace(0);
24263×
        Ok(report)
24273×
    }
2428
2429
    /// `Name <email>` for a Git commit, from the author's identity.
243014×
    fn git_author_key(&self, key: &KeyId) -> String {
243114×
        match self.store.get_identity(key) {
243214×
            Ok(id) if !id.name.is_empty() => format!(
2433
                "{} <{}>",
243414×
                id.name.replace(['<', '>', '\n'], " "),
243514×
                id.email.replace(['<', '>', '\n', ' '], "")
2436
            ),
24370×
            _ => "oxy <oxy@localhost>".to_string(),
2438
        }
243914×
    }
2440
}
2441
2442
/// Feed a fast-import stream to `git fast-import` in `git_dir`, keeping its
2443
/// marks in `git_marks` so a later run can refer to commits it wrote.
24443×
fn run_fast_import(git_dir: &Path, stream: &[u8], git_marks: &Path) -> Result<()> {
24453×
    let mut cmd = Command::new("git");
2446
    // `--force`: a ref may move to an unrelated commit (a bookmark rewritten).
24473×
    cmd.arg("-C")
24483×
        .arg(git_dir)
24493×
        .args(["fast-import", "--quiet", "--done", "--force"])
24503×
        .arg(format!("--export-marks={}", git_marks.display()));
24513×
    if git_marks.exists() {
24521×
        cmd.arg(format!("--import-marks={}", git_marks.display()));
24532×
    }
24543×
    let mut child = cmd
24553×
        .stdin(Stdio::piped())
24563×
        .stdout(Stdio::null())
24573×
        .stderr(Stdio::piped())
24583×
        .spawn()
24593×
        .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
24603×
    child.stdin.take().unwrap().write_all(stream)?;
24613×
    let out = child.wait_with_output()?;
24623×
    if !out.status.success() {
24630×
        return fail(format!(
2464
            "git fast-import failed: {}",
24650×
            String::from_utf8_lossy(&out.stderr).trim()
2466
        ));
24673×
    }
24683×
    Ok(())
24693×
}
2470
2471
impl Repo {
2472
    /// Bring the side-by-side Git repository up to date (`git.colocate`):
2473
    /// a `.git` beside `.oxy`, made with `git init` when missing and told to
2474
    /// leave `.oxy/` alone, holding the current bookmark as exported by
2475
    /// `git_export_as` (one commit per state the bookmark passed through),
2476
    /// with HEAD on that branch and Git's index at its tree, so `git status`
2477
    /// shows only the working copy's uncommitted work. Files on disk are
2478
    /// never touched. Does nothing when the bookmark has not moved since the
2479
    /// last time; `Ok(true)` when it exported.
24804×
    pub fn git_colocate_sync(&self) -> Result<bool> {
24814×
        if self.bare {
24820×
            return fail("a bare repository has no working copy for a .git beside it");
24834×
        }
24844×
        let git_dir = self.root.join(".git");
24854×
        if git_dir.is_file() {
24860×
            return fail(".git is a file (a Git worktree or submodule link); remove it to keep a side-by-side Git repository here");
24874×
        }
24884×
        if !git_dir.join("HEAD").exists() {
24891×
            git(&self.root, &["init", "-q"])?;
24903×
        }
24914×
        let exclude = git_dir.join("info").join("exclude");
24924×
        let have = fs::read_to_string(&exclude).unwrap_or_default();
249330×
        if !have.lines().any(|l| l.trim() == "/.oxy/") {
24941×
            fs::create_dir_all(exclude.parent().expect("info/"))?;
24951×
            let sep = if have.is_empty() || have.ends_with('\n') {
24961×
                ""
2497
            } else {
24980×
                "\n"
2499
            };
25001×
            fs::write(
25011×
                &exclude,
25021×
                format!("{have}{sep}# Oxygen's own repository (oxy git colocate)\n/.oxy/\n"),
25030×
            )?;
25043×
        }
25054×
        let bookmark = self.config.bookmark.clone();
25064×
        let state = self
25074×
            .view()?
2508
            .bookmarks
25094×
            .get(&bookmark)
25104×
            .map(|s| s.to_hex())
25114×
            .unwrap_or_default();
25124×
        let stamp_file = self.oxy.join("git").join("colocate-stamp");
25134×
        let stamp = format!("{bookmark} {state}");
25144×
        if fs::read_to_string(&stamp_file).is_ok_and(|s| s.trim() == stamp) {
25152×
            return Ok(false);
25162×
        }
25172×
        if !state.is_empty() {
25182×
            self.git_export_as(&git_dir, &bookmark)?;
25192×
            git(
25202×
                &self.root,
25212×
                &["symbolic-ref", "HEAD", &format!("refs/heads/{bookmark}")],
25220×
            )?;
25232×
            git(&self.root, &["read-tree", "HEAD"])?;
25240×
        }
25252×
        fs::create_dir_all(stamp_file.parent().expect("git/"))?;
25262×
        fs::write(&stamp_file, stamp)?;
25272×
        Ok(!state.is_empty())
25284×
    }
2529
}