OXYGENHUB

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

1368 of 1713 lines run, 97 of 286 functions · run #370 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
440158×
fn git(dir: &Path, args: &[&str]) -> Result<String> {
441158×
    let out = Command::new("git")
442158×
        .arg("-C")
443158×
        .arg(dir)
444158×
        .args(args)
445158×
        .output()
446158×
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
447158×
    if !out.status.success() {
4480×
        return fail(format!(
449
            "git {} failed: {}",
4500×
            args.join(" "),
4510×
            String::from_utf8_lossy(&out.stderr).trim()
452
        ));
453158×
    }
454158×
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
455158×
}
456
457
impl Repo {
45845×
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
45945×
        let canonical = git_dir
46045×
            .canonicalize()
46145×
            .unwrap_or_else(|_| git_dir.to_path_buf());
46245×
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
46345×
        let dir = self.oxy.join("git").join(key);
46445×
        fs::create_dir_all(&dir)?;
46545×
        Ok(dir)
46645×
    }
467
468
    /// `state ref → Git commit sha` for bookmark states that equal a Git
469
    /// commit's tree (recorded by import and fetch).
47045×
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
47145×
        let mut out = BTreeMap::new();
47245×
        if let Ok(text) = fs::read_to_string(path) {
47312×
            for line in text.lines() {
47412×
                if let Some((h, sha)) = line.split_once(' ') {
47512×
                    if let Some(h) = ObjectRef::from_hex(h) {
47612×
                        out.insert(h, sha.trim().to_string());
47712×
                    }
4780×
                }
479
            }
48035×
        }
48145×
        Ok(out)
48245×
    }
483
48415×
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
48515×
        let path = self.git_marks_dir(git_dir)?.join("git-states");
48615×
        let mut states = Self::read_git_states(&path)?;
48715×
        states.insert(*state, sha.to_string());
48815×
        let text: String = states
48915×
            .iter()
49016×
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
49115×
            .collect();
49215×
        write_atomic(&path, text.as_bytes())
49315×
    }
494
495
    /// The bare mirror this repository keeps for the Git remote `url`.
4967×
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
4977×
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
4987×
        let dir = self.oxy.join("git").join(key).join("mirror.git");
4997×
        if !dir.join("HEAD").exists() {
5001×
            fs::create_dir_all(&dir)?;
5011×
            git(&dir, &["init", "--bare", "-q"])?;
5026×
        }
5037×
        Ok(dir)
5047×
    }
505
506
    /// Git commits already imported into the bookmark, by sha.
50730×
    pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
50830×
        let mut map = HashMap::new();
509112×
        for e in self.log()? {
510112×
            if e.is_working_copy {
51130×
                continue;
51282×
            }
51382×
            if let Some(sha) = e
51482×
                .change
51582×
                .message
51682×
                .lines()
51782×
                .rev()
518158×
                .find_map(|l| l.strip_prefix("Git-Commit: "))
51976×
            {
52076×
                map.insert(sha.trim().to_string(), e.hash);
52176×
            }
522
        }
52330×
        Ok(map)
52430×
    }
525
526
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
527
    /// A remote without that branch yet leaves the mirror as it is.
5287×
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
5297×
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
5307×
        match git(mirror, &["fetch", "-q", url, &spec]) {
5317×
            Ok(_) => Ok(()),
5320×
            Err(e) => {
5330×
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
5340×
                if ls.trim().is_empty() {
5350×
                    Ok(())
536
                } else {
5370×
                    Err(e)
538
                }
539
            }
540
        }
5417×
    }
542
543
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
544
    /// through a mirror and import the commits not yet in the bookmark
545
    /// (spec §23). Works on a repository that already has history: the
546
    /// new changes join the bookmark like a pull.
5473×
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
548
        // A local path, made absolute: git runs it from inside the mirror.
5493×
        let local = Path::new(url)
5503×
            .canonicalize()
5513×
            .ok()
5523×
            .filter(|_| !url.contains("://"));
5533×
        let absolute = local.as_ref().map(|p| p.to_string_lossy().into_owned());
5543×
        let url = absolute.as_deref().unwrap_or(url);
5553×
        let mirror = self.git_mirror(url)?;
5563×
        self.git_mirror_fetch(&mirror, url, branch)?;
5573×
        if git(
5583×
            &mirror,
5593×
            &[
5603×
                "rev-parse",
5613×
                "--verify",
5623×
                "-q",
5633×
                &format!("refs/heads/{branch}"),
5643×
            ],
5653×
        )
5663×
        .is_err()
567
        {
5680×
            return fail(format!("{url} has no branch {branch:?}"));
5693×
        }
5703×
        self.import_git_commits(
5713×
            &mirror,
5723×
            branch,
5733×
            &format!("oxy git fetch {url} {branch}"),
5741×
            &mut |_| {},
575
        )
5763×
    }
577
578
    /// Export the bookmark to `branch` of the Git repository at `url`
579
    /// through the mirror and push it. The remote's tip must already have
580
    /// been fetched (`git_fetch`), so the push fast-forwards.
5814×
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
5824×
        let mirror = self.git_mirror(url)?;
5834×
        self.git_mirror_fetch(&mirror, url, branch)?;
5844×
        if let Ok(tip) = git(
5854×
            &mirror,
5864×
            &[
5874×
                "rev-parse",
5884×
                "--verify",
5894×
                "-q",
5904×
                &format!("refs/heads/{branch}"),
5914×
            ],
5924×
        ) {
5934×
            let known = self.git_known(&mirror)?;
5944×
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
5951×
                return fail(format!(
596
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
597
                ));
5983×
            }
5990×
        }
6003×
        let report = self.git_export_as(&mirror, branch)?;
6013×
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
6023×
        git(&mirror, &["push", "-q", url, &spec])?;
6033×
        Ok(report)
6044×
    }
605
60630×
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
60730×
        let mut out = BTreeMap::new();
60830×
        if let Ok(text) = fs::read_to_string(path) {
60913×
            for line in text.lines() {
61013×
                if let Some((h, m)) = line.split_once(' ') {
61113×
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
61213×
                        out.insert(h, m);
61313×
                    }
6140×
                }
615
            }
61621×
        }
61730×
        Ok(out)
61830×
    }
619
620
    /// Export the current bookmark to the Git repository at `git_dir`,
621
    /// creating a bare one if nothing is there. Each state the bookmark
622
    /// passed through (per the operation log) becomes one commit whose tree
623
    /// is that state, so the Git branch is a linear history of full trees.
6247×
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
6257×
        let bookmark = self.config.bookmark.clone();
6267×
        self.git_export_as(git_dir, &bookmark)
6277×
    }
628
629
    /// `git_export` to the Git branch `branch`. A state that came from a
630
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
631
    /// onto that commit, so a push back to the Git remote fast-forwards.
63210×
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
63310×
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
6344×
            fs::create_dir_all(git_dir)?;
6354×
            git(git_dir, &["init", "--bare", "-q"])?;
6366×
        }
63710×
        let marks_dir = self.git_marks_dir(git_dir)?;
63810×
        let git_marks = marks_dir.join("git-marks");
63910×
        let oxy_marks_path = marks_dir.join("oxy-marks");
64010×
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
64110×
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
64210×
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
643
64410×
        let bookmark = self.config.bookmark.clone();
64510×
        let mut stream: Vec<u8> = Vec::new();
64610×
        let mut report = GitExportReport {
64710×
            branch: branch.to_string(),
64810×
            heads: self.bookmark_heads()?.len(),
64910×
            ..Default::default()
650
        };
651
652
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
65310×
        let mut ops = self.op_log()?;
65410×
        ops.reverse();
65510×
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
656
        // The fast-import parent of the next commit: `:mark` or a commit sha.
65710×
        let mut last_parent: Option<String> = None;
65844×
        for (_, op) in &ops {
65944×
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
6600×
                continue;
661
            };
66244×
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
66312×
                continue;
66432×
            }
66532×
            let Ok(state) = self.store.get_state(&state_ref) else {
6660×
                continue;
667
            };
66832×
            if state.heads.is_empty() {
66910×
                prev = Some((state_ref, vec![]));
67010×
                continue;
67122×
            }
67222×
            if let Some(sha) = git_states.get(&state_ref) {
6734×
                report.skipped += 1;
6744×
                last_parent = Some(sha.clone());
6754×
                prev = Some((state_ref, state.heads.clone()));
6764×
                continue;
67718×
            }
67818×
            if let Some(m) = marks.get(&state_ref) {
6799×
                report.skipped += 1;
6809×
                last_parent = Some(format!(":{m}"));
6819×
                prev = Some((state_ref, state.heads.clone()));
6829×
                continue;
6839×
            }
6849×
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
6859×
            let added = self
6869×
                .negotiate(&prev_heads, &state.heads)
6879×
                .unwrap_or_default();
6889×
            let loaded = self.load_state(&state.heads)?;
6899×
            let snapshot = loaded.materialize();
6909×
            let (author, secs, mut message) = match added.as_slice() {
6916×
                [h] => {
6926×
                    let c = self.store.get_change(h)?;
6936×
                    let mut m = c.message.clone();
6946×
                    if !m.ends_with('\n') {
6956×
                        m.push('\n');
6966×
                    }
6976×
                    m.push_str(&format!(
6986×
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
6996×
                        c.change_id.to_hex(),
7006×
                        h.to_hex()
7016×
                    ));
7026×
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
703
                }
7043×
                [] => (
7050×
                    "oxy <oxy@localhost>".to_string(),
7060×
                    op.hlc.wall_ms / 1000,
7070×
                    format!("oxy: {}\n\n", op.command),
7080×
                ),
7093×
                many => {
7103×
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
71122×
                    for h in many {
71222×
                        let c = self.store.get_change(h)?;
71322×
                        m.push_str(&format!(
71422×
                            "- {} {}\n",
71522×
                            c.change_id.short(8),
71622×
                            c.message.lines().next().unwrap_or("")
71722×
                        ));
718
                    }
7193×
                    m.push_str(&format!(
720
                        "\nOxy-Changes: {}\n",
7213×
                        many.iter()
72222×
                            .map(|h| h.to_hex())
7233×
                            .collect::<Vec<_>>()
7243×
                            .join(" ")
725
                    ));
7263×
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
727
                }
728
            };
7299×
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
7309×
            if snapshot.is_conflicted() {
7310×
                message.push_str("Oxy-Conflicted: true\n");
7329×
            }
7339×
            let mark = next_mark;
7349×
            next_mark += 1;
7359×
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
7369×
            self.write_commit(
7379×
                &mut stream,
7389×
                "refs/oxy/export",
7399×
                mark,
7409×
                &author,
7419×
                secs,
7429×
                &message,
7439×
                &parents,
7449×
                &snapshot,
7450×
            )?;
7469×
            marks.insert(state_ref, mark);
7479×
            last_parent = Some(format!(":{mark}"));
7489×
            prev = Some((state_ref, state.heads.clone()));
7499×
            report.exported += 1;
750
        }
75110×
        if let Some(p) = &last_parent {
75210×
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
75310×
        }
754
        // Tags: a tag whose state was exported as a bookmark state points at
755
        // that commit; otherwise its state gets a commit of its own.
75610×
        for t in self.tags()? {
7570×
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
7580×
                (Some(sha), _) => sha.clone(),
7590×
                (None, Some(m)) => format!(":{m}"),
760
                (None, None) => {
7610×
                    let loaded = self.load_state(&t.heads)?;
7620×
                    let snapshot = loaded.materialize();
7630×
                    let mark = next_mark;
7640×
                    next_mark += 1;
7650×
                    let message = format!(
766
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
767
                        t.name,
7680×
                        if t.message.is_empty() {
7690×
                            String::new()
770
                        } else {
7710×
                            format!("{}\n\n", t.message)
772
                        },
7730×
                        t.state.to_hex()
774
                    );
7750×
                    self.write_commit(
7760×
                        &mut stream,
7770×
                        "refs/oxy/export",
7780×
                        mark,
7790×
                        "oxy <oxy@localhost>",
7800×
                        Hlc::now().wall_ms / 1000,
7810×
                        &message,
7820×
                        &[],
7830×
                        &snapshot,
7840×
                    )?;
7850×
                    marks.insert(t.state, mark);
7860×
                    report.exported += 1;
7870×
                    format!(":{mark}")
788
                }
789
            };
7900×
            stream.extend_from_slice(
7910×
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
792
            );
793
        }
79410×
        stream.extend_from_slice(b"done\n");
795
79610×
        let mut cmd = Command::new("git");
797
        // `--force`: the scratch ref may jump between unrelated states.
79810×
        cmd.arg("-C")
79910×
            .arg(git_dir)
80010×
            .args(["fast-import", "--quiet", "--done", "--force"])
80110×
            .arg(format!("--export-marks={}", git_marks.display()));
80210×
        if git_marks.exists() {
8035×
            cmd.arg(format!("--import-marks={}", git_marks.display()));
8045×
        }
80510×
        let mut child = cmd
80610×
            .stdin(Stdio::piped())
80710×
            .stdout(Stdio::null())
80810×
            .stderr(Stdio::piped())
80910×
            .spawn()
81010×
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
81110×
        child.stdin.take().unwrap().write_all(&stream)?;
81210×
        let out = child.wait_with_output()?;
81310×
        if !out.status.success() {
8140×
            return fail(format!(
815
                "git fast-import failed: {}",
8160×
                String::from_utf8_lossy(&out.stderr).trim()
817
            ));
81810×
        }
81910×
        let text: String = marks
82010×
            .iter()
82118×
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
82210×
            .collect();
82310×
        write_atomic(&oxy_marks_path, text.as_bytes())?;
82410×
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
82510×
        report.skipped_subrepos = self.git_export_skipped.replace(0);
82610×
        Ok(report)
82710×
    }
828
829
    /// Import branch `branch` of the Git repository at `git_dir` into this
830
    /// (empty) repository's bookmark (spec §23): one change per commit, its
831
    /// edits the difference between the union of its parents' states and its
832
    /// tree, so merge commits become resolutions. Submodules are skipped.
83313×
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
83413×
        self.import_git_with(git_dir, branch, &mut |_| {})
83513×
    }
836
837
    /// `import_git`, telling `progress` where it is every few hundred
838
    /// commits: the count so far, the merges, and the commit in hand, so a
839
    /// long import is never silent and a run that dies says where.
84013×
    pub fn import_git_with(
84113×
        &self,
84213×
        git_dir: &Path,
84313×
        branch: &str,
84413×
        progress: crate::store::Progress<'_>,
84513×
    ) -> Result<GitImportReport> {
84613×
        if !self.bookmark_heads()?.is_empty() {
8470×
            return fail("git import needs an empty bookmark; import into a fresh repository");
84813×
        }
84913×
        self.import_git_commits(
85013×
            git_dir,
85113×
            branch,
85213×
            &format!("oxy git import {} {branch}", git_dir.display()),
85313×
            progress,
854
        )
85513×
    }
856
857
    /// Import the commits of `branch` that the bookmark does not have yet,
858
    /// then move the bookmark to the union of its heads and theirs.
85916×
    fn import_git_commits(
86016×
        &self,
86116×
        git_dir: &Path,
86216×
        branch: &str,
86316×
        command: &str,
86416×
        progress: crate::store::Progress<'_>,
86516×
    ) -> Result<GitImportReport> {
86616×
        let batch = self.store.begin_batch()?;
86716×
        let result = self.import_git_commits_batched(git_dir, branch, command, progress);
86816×
        batch.finish()?;
86916×
        result
87016×
    }
871
87216×
    fn import_git_commits_batched(
87316×
        &self,
87416×
        git_dir: &Path,
87516×
        branch: &str,
87616×
        command: &str,
87716×
        progress: crate::store::Progress<'_>,
87816×
    ) -> Result<GitImportReport> {
87916×
        let commits = list_commits(git_dir, branch)?;
88016×
        let mut cat = CatFile::start(git_dir)?;
88116×
        let mut report = GitImportReport::default();
88216×
        let mut known = self.git_known(git_dir)?;
88316×
        let old_heads = self.bookmark_heads()?;
884
        // The bookmark's heads as changes arrive: a change stops being a
885
        // head when another depends on it, so no full state of every
886
        // imported change is needed at the end.
88716×
        let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect();
888
        // The state and Git tree of imported commits whose first-parent
889
        // children are still to come, so a child starts from its parent's
890
        // state instead of rebuilding it from history. The last child takes
891
        // it; earlier ones clone it. At most `max_kept` are kept (a later
892
        // child of an evicted one rebuilds).
893
        // OXY_IMPORT_KEEP overrides it, for measuring.
89416×
        let max_kept: usize = std::env::var("OXY_IMPORT_KEEP")
89516×
            .ok()
89616×
            .and_then(|v| v.parse().ok())
89716×
            .unwrap_or(8);
89816×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
89993×
        for gc in &commits {
90093×
            if let Some(p1) = gc.parents.first() {
90175×
                *waiting.entry(p1.as_str()).or_default() += 1;
90275×
            }
903
        }
904
        type Kept = (State, BTreeMap<String, (String, String)>);
90516×
        let mut kept: HashMap<String, Kept> = HashMap::new();
906
        // Every commit to import that has a parent, diffed against its first.
90716×
        let pairs: Vec<(String, String)> = commits
90816×
            .iter()
90993×
            .filter(|gc| {
91093×
                !known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha)
91193×
            })
91288×
            .filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone())))
91316×
            .collect();
91416×
        let mut diffs = DiffTree::start(git_dir, pairs)?;
91516×
        let mut rebuilt = 0usize;
91616×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
91716×
        let mut last: Option<String> = None;
91816×
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
91916×
        let mut cache_bytes: usize = 0;
920
        // Time spent per phase over all commits (`OXY_TIMINGS=1`).
92116×
        let mut spent = [std::time::Duration::ZERO; 6];
92216×
        let mut clock = std::time::Instant::now();
923
        // One line per commit on stderr with OXY_IMPORT_TRACE=1: where its
924
        // base came from, what a merge added, the graphs its state holds,
925
        // the kept states and the process's resident memory.
92616×
        let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some();
92716×
        let rss_mb = || -> u64 {
9280×
            std::fs::read_to_string("/proc/self/statm")
9290×
                .ok()
9300×
                .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
9310×
                .map(|pages| (pages * 4096) >> 20)
9320×
                .unwrap_or(0)
9330×
        };
93416×
        let mut done = 0usize;
935
        // Atoms a kept state's graphs may hold before they are shed;
936
        // OXY_IMPORT_KEPT_ATOMS overrides it, for measuring.
93716×
        let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS")
93816×
            .ok()
93916×
            .and_then(|v| v.parse().ok())
94016×
            .unwrap_or(KEPT_ATOMS);
941
        // Graphs turned back into history (see `State::shed_graphs`).
94216×
        let mut shed = 0usize;
943528×
        let mut lap = |i: usize, clock: &mut std::time::Instant| {
944528×
            let now = std::time::Instant::now();
945528×
            spent[i] += now - *clock;
946528×
            *clock = now;
947528×
        };
948
949
        // OXY_IMPORT_CHECKPOINT overrides it, for testing.
95016×
        let checkpoint_every: usize = std::env::var("OXY_IMPORT_CHECKPOINT")
95116×
            .ok()
95216×
            .and_then(|v| v.parse().ok())
95316×
            .filter(|n| *n > 0)
95416×
            .unwrap_or(CHECKPOINT_COMMITS);
955
        // OXY_IMPORT_STOP_AFTER ends the import cleanly after that many
956
        // commits, its timings reported, for measuring at depth.
95716×
        let stop_after: Option<usize> = std::env::var("OXY_IMPORT_STOP_AFTER")
95816×
            .ok()
95916×
            .and_then(|v| v.parse().ok());
960
        // Merges built from the paths they can change (oxygen#80): on VS
961
        // Code at 139k commits the same 400 commits came out identical to
962
        // whole-tree merges, with merges 3.2x faster. OXY_IMPORT_WHOLE_MERGES=1
963
        // builds them from the whole tree, for comparing.
96416×
        let partial_merges = std::env::var_os("OXY_IMPORT_WHOLE_MERGES").is_none_or(|v| v == "0");
96516×
        let total = commits.len();
966
        // The importing identity's own commits, claimed (`git.claim`,
967
        // oxygen#97): a commit whose Git author email is its email gets
968
        // its key as author; anyone else's keeps the zero key.
96916×
        let claim: Option<(KeyId, String)> = if self.config.git_claim {
9701×
            let Some(key) = self.config.author_key else {
9710×
                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`");
972
            };
9731×
            Some((key, self.identity(&key)?.email.to_lowercase()))
974
        } else {
97515×
            None
976
        };
97793×
        for (index, gc) in commits.iter().enumerate() {
97893×
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
9795×
                continue;
98088×
            }
98188×
            if stop_after.is_some_and(|n| done >= n) {
9820×
                break;
98388×
            }
98488×
            let commit_started = std::time::Instant::now();
98588×
            if index % 500 == 0 {
98614×
                progress(&format!(
98714×
                    "{index} of {total} commits, {} merges; at {} {}",
98814×
                    report.merges,
98914×
                    &gc.sha[..12.min(gc.sha.len())],
99014×
                    gc.message
99114×
                        .lines()
99214×
                        .next()
99314×
                        .unwrap_or("")
99414×
                        .chars()
99514×
                        .take(60)
99614×
                        .collect::<String>()
99714×
                ));
99874×
            }
99988×
            let mut base_how = "root";
1000
            // Base: union of every parent's state, starting from the first
1001
            // parent's kept state when there is one; its tree tells which
1002
            // paths this commit leaves alone.
100388×
            let (mut base, prev_tree) = match gc.parents.first() {
100472×
                Some(p1) => {
100572×
                    let left = waiting.get_mut(p1.as_str()).map(|n| {
100672×
                        *n -= 1;
100772×
                        *n
100872×
                    });
100972×
                    let found = if left == Some(0) {
101071×
                        kept_order.retain(|k| k != p1);
101152×
                        kept.remove(p1.as_str())
1012
                    } else {
101320×
                        kept.get(p1.as_str()).cloned()
1014
                    };
101572×
                    let how = match (&found, left) {
101651×
                        (Some(_), Some(0)) => "kept",
101720×
                        (Some(_), _) => "cloned",
10181×
                        (None, _) => "rebuilt",
1019
                    };
102072×
                    if trace {
10210×
                        base_how = how;
102272×
                    }
102372×
                    match found {
102471×
                        Some((st, tree)) => (st, Some(tree)),
1025
                        None => {
1026
                            // History only: graphs are built for the files a
1027
                            // commit changes, so memory follows what changes,
1028
                            // not the whole tree.
10291×
                            let mut st = State::new_history_only();
10301×
                            self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
1031
                            // The parent's tree, so this commit still
1032
                            // renders only what it changes.
10331×
                            rebuilt += 1;
10341×
                            (st, Some(list_tree(git_dir, p1)?))
1035
                        }
1036
                    }
1037
                }
103816×
                None => (State::new_history_only(), None),
1039
            };
1040
            // Nodes the other parents' changes touch: the first parent's
1041
            // tree cannot vouch for them.
104288×
            let mut touched: HashSet<NodeId> = HashSet::new();
104388×
            let mut merged = 0usize;
1044
            // Where the first parent has each node, read before the merged
1045
            // changes move anything: a merge's partial build names the paths
1046
            // they touch in the first parent's tree as well as in the merged
1047
            // state (oxygen#80).
104888×
            let mut first_parent_view: Option<crate::tree::TreeView> = None;
104988×
            if gc.parents.len() > 1 {
105024×
                report.merges += 1;
105124×
                if prev_tree.is_some() && partial_merges {
105224×
                    first_parent_view = Some(base.tree().view());
105324×
                }
105424×
                let mut args: Vec<String> = gc.parents[1..].to_vec();
105524×
                args.push(format!("^{}", gc.parents[0]));
105624×
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
1057
                // A merge of a long-lived branch brings thousands of
1058
                // changes: added to built graphs, which kept states share,
1059
                // they were copied and applied whole (vscode's import passed
1060
                // 14 GB on such merges). Shed the graphs first, so the
1061
                // changes go in as skeletons and only what this commit
1062
                // touches is built again.
106324×
                if base.built_count() > 0 {
106421×
                    let mut count_args = vec!["rev-list", "--count"];
106521×
                    count_args.extend(refs.iter().copied());
106621×
                    let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0);
106721×
                    let shed_at = std::env::var("OXY_MERGE_SHED")
106821×
                        .ok()
106921×
                        .and_then(|v| v.parse().ok())
107021×
                        .unwrap_or(MERGE_SHED_COMMITS);
107121×
                    if others > shed_at {
10720×
                        shed += base.shed_graphs(|b| self.store_blob(b))?;
107321×
                    }
10743×
                }
107524×
                let before = base.len();
107624×
                self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?;
107724×
                merged = base.len() - before;
107864×
            }
107988×
            lap(0, &mut clock);
1080
            // The commit's tree: its first parent's with the diff applied,
1081
            // or listed whole when that tree is not kept.
108288×
            let diff = match gc.parents.first() {
108372×
                Some(_) => Some(diffs.diff(&gc.sha)?),
108416×
                None => None,
1085
            };
108688×
            let (tree, changed) = match (prev_tree, diff) {
108772×
                (Some(mut t), Some(diff)) => {
108872×
                    let mut changed: HashSet<String> = HashSet::new();
108990×
                    for (path, entry) in diff {
109090×
                        match entry {
109172×
                            Some(v) => {
109272×
                                t.insert(path.clone(), v);
109372×
                            }
109418×
                            None => {
109518×
                                t.remove(&path);
109618×
                            }
1097
                        }
109890×
                        changed.insert(path);
1099
                    }
110072×
                    (t, Some(changed))
1101
                }
110216×
                _ => (list_tree(git_dir, &gc.sha)?, None),
1103
            };
110488×
            lap(1, &mut clock);
1105
            // Text files with the same blob and mode as in the first
1106
            // parent's tree equal the base's rendering: they are neither
1107
            // rendered nor read nor compared (spec §12.3, as for a clean
1108
            // working copy), so a commit costs what it changes.
110988×
            let mut same: HashMap<&str, NodeId> = HashMap::new();
1110
            // Opaque files and symlinks likewise, when the base has one
1111
            // blob for them: they are neither read nor stored again.
111288×
            let mut same_opaque: HashSet<&str> = HashSet::new();
1113
            // An ordinary commit in a tree without submodules is built from
1114
            // the paths it changes alone (oxygen#25): with the `.oxyattributes`
1115
            // files that decide how they are stored, and the directories its
1116
            // removals may leave empty. A merge, or a commit whose parent's
1117
            // tree is not at hand, is built from its whole tree.
1118
            // A merge can differ from its first parent only at the paths
1119
            // Git's diff names and where the merged changes touched: those
1120
            // paths in the first parent's tree and in the merged state. With
1121
            // them added it is built like an ordinary commit, instead of
1122
            // from its whole tree (18 s for any merge at 118k commits of
1123
            // VS Code, oxygen#80). OXY_IMPORT_WHOLE_MERGES=1 takes the
1124
            // whole-tree path.
112588×
            let mut changed = changed;
1126
            // A tree conflict in the merged state (both sides placed a file
1127
            // at one path) is resolved by the whole-tree path.
112888×
            let mut merge_how = if gc.parents.len() > 1 {
112924×
                if first_parent_view.is_some() {
113024×
                    "partial"
1131
                } else {
11320×
                    "whole"
1133
                }
1134
            } else {
113564×
                "-"
1136
            };
1137
            // Only a conflict among what the merged changes touched; one
1138
            // elsewhere stays as it was in the first parent either way.
113988×
            if first_parent_view.is_some()
114024×
                && base.tree().view().conflicts.iter().any(|c| {
1141
                    use crate::tree::TreeConflict::*;
11427×
                    match c {
11437×
                        Name { nodes, .. } => nodes.iter().any(|n| touched.contains(n)),
11441×
                        MultiPlacement { node, .. } | Cycle { node } | Mode { node, .. } => {
11451×
                            touched.contains(node)
1146
                        }
11471×
                        Orphan { node, parent } => {
11481×
                            touched.contains(node) || touched.contains(parent)
1149
                        }
1150
                    }
11517×
                })
11527×
            {
11537×
                first_parent_view = None;
11547×
                merge_how = "conflicted";
115581×
            }
115688×
            if let (Some(ch), Some(fp)) = (changed.as_mut(), &first_parent_view) {
115717×
                let union = base.tree().view();
115834×
                for v in [fp, &union] {
1159139×
                    for (path, e) in v.entries.iter() {
1160139×
                        if touched.contains(&e.node) {
116139×
                            ch.insert(path.clone());
1162100×
                        }
1163
                    }
1164
                }
116571×
            }
116688×
            let partial = changed.is_some()
116772×
                && (gc.parents.len() == 1 || first_parent_view.is_some())
1168172×
                && !tree.values().any(|(mode, _)| mode == "160000");
116988×
            let mut rel: BTreeSet<&str> = BTreeSet::new();
1170
            // Text files whose graphs this commit builds, for the trace.
1171
            let need_n: usize;
117288×
            let base_snapshot = if let (true, Some(changed)) = (partial, &changed) {
117364×
                let view = base.tree().view();
117464×
                rel.extend(changed.iter().map(String::as_str));
117564×
                rel.extend(
117664×
                    tree.keys()
117764×
                        .map(String::as_str)
1178169×
                        .filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")),
1179
                );
118064×
                let mut dirs: BTreeSet<&str> = BTreeSet::new();
118189×
                for p in changed.iter().filter(|p| !tree.contains_key(*p)) {
118218×
                    let mut end = p.len();
118334×
                    while let Some(i) = p[..end].rfind('/') {
118416×
                        if !dirs.insert(&p[..i]) {
11850×
                            break;
118616×
                        }
118716×
                        end = i;
1188
                    }
1189
                }
119064×
                let need: Vec<NodeId> = rel
119164×
                    .iter()
119289×
                    .filter_map(|p| view.entries.get(*p))
119365×
                    .filter(|e| e.kind == NodeKind::File && !e.mode.opaque)
119464×
                    .map(|e| e.node)
119564×
                    .collect();
119664×
                crate::timing::add("render: same and need", clock.elapsed());
119764×
                need_n = need.len();
119864×
                let t = std::time::Instant::now();
119964×
                self.load_graphs_of(&mut base, &need)?;
120064×
                crate::timing::add("render: load graphs", t.elapsed());
120164×
                let t = std::time::Instant::now();
120264×
                let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied());
120364×
                crate::timing::add("render: materialize", t.elapsed());
120464×
                snap
1205
            } else {
120624×
                if let Some(changed) = &changed {
12078×
                    let view = base.tree().view();
120819×
                    for path in tree.keys() {
1209
                        // Submodule handling reads these two whatever changed.
121019×
                        if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules"
1211
                        {
121210×
                            continue;
12139×
                        }
12149×
                        if let Some(e) = view.entries.get(path) {
12155×
                            if touched.contains(&e.node) {
12160×
                                continue;
12175×
                            }
12185×
                            let opaque = e.kind == NodeKind::Symlink
12195×
                                || (e.kind == NodeKind::File && e.mode.opaque);
12205×
                            if e.kind == NodeKind::File && !e.mode.opaque {
12215×
                                same.insert(path.as_str(), e.node);
12225×
                            } else if opaque && base.live_blobs(&e.node).len() == 1 {
12230×
                                same_opaque.insert(path.as_str());
12240×
                            }
12254×
                        }
1226
                    }
122716×
                }
1228
                // Build the graphs of every text file the commit may change.
122924×
                let skip: HashSet<NodeId> = same.values().copied().collect();
123024×
                let need: Vec<NodeId> = base
123124×
                    .tree()
123224×
                    .view()
123324×
                    .entries
123424×
                    .values()
123524×
                    .filter(|e| {
123621×
                        e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node)
123721×
                    })
123824×
                    .map(|e| e.node)
123924×
                    .collect();
124024×
                crate::timing::add("render: same and need", clock.elapsed());
124124×
                need_n = need.len();
124224×
                let t = std::time::Instant::now();
124324×
                let snap = if need.len() > merge_batch() {
1244
                    // A merge onto a base with no built graphs: thousands
1245
                    // of files, whose graphs would not fit at once.
12465×
                    self.materialize_batched(&mut base, &need, &skip)?
1247
                } else {
124819×
                    let g = std::time::Instant::now();
124919×
                    self.load_graphs_of(&mut base, &need)?;
125019×
                    crate::timing::add("render: whole, load graphs", g.elapsed());
125119×
                    let m = std::time::Instant::now();
125219×
                    let snap = base.materialize_except(&skip);
125319×
                    crate::timing::add("render: whole, materialize", m.elapsed());
125419×
                    snap
1255
                };
125624×
                crate::timing::add("render: whole tree", t.elapsed());
125724×
                snap
1258
            };
1259
126088×
            lap(2, &mut clock);
1261
            // The commit's tree as in-memory entries.
126288×
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
126388×
            let mut gitlinks: Vec<(String, String)> = Vec::new();
126488×
            let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial {
126589×
                Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p)))
1266
            } else {
126724×
                Box::new(tree.iter())
1268
            };
1269118×
            for (path, (mode, sha)) in listed {
1270118×
                let (path, sha) = (path.clone(), sha.clone());
1271118×
                let (kind, exec) = match mode.as_str() {
1272118×
                    "100644" | "100664" => (NodeKind::File, false),
127313×
                    "100755" => (NodeKind::File, true),
12741×
                    "120000" => (NodeKind::Symlink, false),
12751×
                    "160000" => {
12761×
                        gitlinks.push((path, sha));
12771×
                        continue;
1278
                    }
12790×
                    _ => continue,
1280
                };
1281117×
                if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) {
12825×
                    let mut e = FsEntry::new(kind, exec, Vec::new());
12835×
                    e.unchanged = true;
12845×
                    entries.insert(path, e);
12855×
                    continue;
1286112×
                }
1287112×
                let content = match blob_cache.get(&sha) {
128836×
                    Some(c) => c.clone(),
1289
                    None => {
129076×
                        let c = cat.read(&sha)?;
129176×
                        if cache_bytes + c.len() > 64 * 1024 * 1024 {
12920×
                            blob_cache.clear();
12930×
                            cache_bytes = 0;
129476×
                        }
129576×
                        cache_bytes += c.len();
129676×
                        blob_cache.insert(sha.clone(), c.clone());
129776×
                        c
1298
                    }
1299
                };
1300112×
                entries.insert(path, FsEntry::new(kind, exec, content));
1301
            }
1302
1303
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
1304
            // pins, and `.gitmodules` also yields `.oxymodules`.
130588×
            if !gitlinks.is_empty() {
13061×
                report.submodules += gitlinks.len();
13071×
                let gm = entries
13081×
                    .get(".gitmodules")
13091×
                    .map(|e| {
13101×
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
13111×
                            &e.content,
13121×
                        ))
13131×
                    })
13141×
                    .unwrap_or_default();
13151×
                let mut modules = entries
13161×
                    .get(".oxymodules")
13171×
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
13181×
                    .unwrap_or_default();
13191×
                for (path, sha) in &gitlinks {
13201×
                    let m = gm.entries.get(path);
13211×
                    let branch = m
13221×
                        .and_then(|m| m.bookmark.clone())
13231×
                        .unwrap_or_else(|| "HEAD".into());
13241×
                    entries.insert(
13251×
                        path.clone(),
13261×
                        FsEntry::new(
13271×
                            NodeKind::Subrepo,
1328
                            false,
13291×
                            crate::subrepo::Pin::Git {
13301×
                                sha: sha.clone(),
13311×
                                branch,
13321×
                            }
13331×
                            .encode(),
1334
                        ),
1335
                    );
13361×
                    if let Some(m) = m {
13371×
                        modules.entries.insert(path.clone(), m.clone());
13381×
                    }
1339
                }
13401×
                if !modules.entries.is_empty() {
13411×
                    entries.insert(
13421×
                        ".oxymodules".into(),
13431×
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
13441×
                    );
13451×
                }
134687×
            }
134788×
            lap(3, &mut clock);
1348
            // New nodes' identifiers derive from the commit, so importing the
1349
            // same Git history twice gives the same changes (spec §23).
135088×
            let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes();
135188×
            let mut built = if partial {
1352
                // Whether the new tree has anything under `dir`.
135364×
                let dir_needed = |dir: &str| {
135416×
                    let prefix = format!("{dir}/");
135516×
                    tree.range(prefix.clone()..)
135616×
                        .next()
135716×
                        .is_some_and(|(k, _)| k.starts_with(&prefix))
135816×
                };
135964×
                self.build_from_entries_seeded(
136064×
                    &base,
136164×
                    &base_snapshot,
136264×
                    &entries,
136364×
                    seed,
136464×
                    Some(&dir_needed),
13650×
                )?
1366
            } else {
136724×
                self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)?
1368
            };
136988×
            lap(4, &mut clock);
1370
            // A file or submodule with several live blobs (branches that
1371
            // replaced it independently) is resolved to the commit's blob:
1372
            // Git's merge is the authority here, unlike a working copy,
1373
            // where a candidate on disk is not yet a decision (spec §23).
1374102×
            for (path, f) in &base_snapshot.files {
1375102×
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
1376
                else {
137798×
                    continue;
1378
                };
13794×
                if blobs.len() < 2 || f.kind != e.kind {
13803×
                    continue;
13811×
                }
13821×
                let chosen = self.store_blob(&e.content)?;
13832×
                for b in blobs {
13842×
                    built.edits.push(Edit::Replace {
13852×
                        node: f.node,
13862×
                        old: Some(*b),
13872×
                        new: Some(chosen),
13882×
                    });
13892×
                }
13901×
                built.resolves = true;
13911×
                built
13921×
                    .contributors
13931×
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
1394
            }
1395
            // It shares the base's tree view, which applying the change
1396
            // then updates in place rather than copying.
139788×
            drop(base_snapshot);
139888×
            drop(entries);
139988×
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
140088×
            let mut message = gc.message.clone();
140188×
            if !message.ends_with('\n') {
140288×
                message.push('\n');
140388×
            }
140488×
            message.push_str(&format!(
140588×
                "\nGit-Commit: {}\nGit-Author: {}\n",
140688×
                gc.sha, gc.author
140788×
            ));
140888×
            let mut change = Change {
1409
                version: crate::objects::CHANGE_VERSION,
141088×
                change_id: change_id_for(&gc.sha, &gc.message),
141188×
                deps: vec![],
141288×
                author: claim
141388×
                    .as_ref()
141488×
                    .filter(|(_, email)| git_email(&gc.author).is_some_and(|e| e == *email))
141588×
                    .map_or(ObjectRef::ZERO, |(key, _)| *key),
141688×
                hlc: Hlc {
141788×
                    wall_ms: gc.author_secs * 1000,
141888×
                    logical: 0,
141988×
                },
142088×
                message,
142188×
                tree_ops: built.tree_ops,
142288×
                edits: built.edits,
142388×
                kind: if built.resolves {
142412×
                    ChangeKind::Resolution
1425
                } else {
142676×
                    ChangeKind::Normal
1427
                },
1428
            };
142988×
            let t = std::time::Instant::now();
1430
            // A deletion depends on whoever inserted the live atoms after
1431
            // it, which only the file's graph knows: build the few the
1432
            // batched rendering left deferred.
143388×
            let need: Vec<NodeId> = change
143488×
                .edits
143588×
                .iter()
143693×
                .filter(|e| matches!(e, Edit::Delete { .. }))
143788×
                .map(|e| e.node())
143888×
                .filter(|n| !base.is_built(n))
143988×
                .collect();
144088×
            if !need.is_empty() {
14410×
                self.load_graphs_of(&mut base, &need)?;
144288×
            }
144388×
            deps.extend(referenced_changes(&change, &base));
144488×
            crate::timing::add("store: referenced", t.elapsed());
144588×
            change.deps = deps.into_iter().collect();
144688×
            change.normalize();
144788×
            let hash = self.store.put_change(&change)?;
144896×
            for d in &change.deps {
144996×
                heads_now.remove(d);
145096×
            }
145188×
            heads_now.insert(hash);
1452
            // Built graphs take its edits whole; files not built keep only
1453
            // where its text is, read back from the store.
145488×
            let t = std::time::Instant::now();
145588×
            let (skeleton, texts) = self.store.get_change_lazy(&hash)?;
145688×
            base.add_known_mixed(hash, change, skeleton, texts);
145788×
            crate::timing::add("store: add to state", t.elapsed());
145888×
            known.imported.insert(gc.sha.clone(), hash);
145988×
            if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) {
1460
                // A kept state holds its graphs until its children come:
1461
                // past a few thousand, they go back into its history.
1462
                // Past a few thousand graphs, or past a budget of atoms: a
1463
                // long-lived file's graph keeps every line it ever had, so a
1464
                // handful of them can hold gigabytes (#25).
146551×
                if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms {
14660×
                    shed += base.shed_graphs(|b| self.store_blob(b))?;
146751×
                }
146851×
                kept.insert(gc.sha.clone(), (base, tree));
146951×
                kept_order.push_back(gc.sha.clone());
147051×
                if kept_order.len() > max_kept {
14710×
                    if let Some(old) = kept_order.pop_front() {
14720×
                        kept.remove(&old);
14730×
                    }
147451×
                }
147537×
            }
147688×
            last = Some(gc.sha.clone());
147788×
            report.commits += 1;
147888×
            lap(5, &mut clock);
147988×
            done += 1;
148088×
            if done.is_multiple_of(checkpoint_every) {
14810×
                self.checkpoint_import(&heads_now, done)?;
148288×
            }
1483
            // A merge renders thousands of files on many threads and frees
1484
            // it all; the allocator keeps those pages unless asked to give
1485
            // them back, and the next merge piles on top (#25).
148688×
            let before_trim = if trace { rss_mb() } else { 0 };
148788×
            if gc.parents.len() > 1 {
148824×
                crate::alloc_stats::release_freed_memory();
148964×
            }
149088×
            if trace {
14910×
                let built = kept
14920×
                    .get(gc.sha.as_str())
14930×
                    .map(|(st, _)| st.built_count())
14940×
                    .unwrap_or(0);
14950×
                let (edits, most) = kept
14960×
                    .get(gc.sha.as_str())
14970×
                    .map(|(st, _)| st.deferred_edit_count())
14980×
                    .unwrap_or((0, 0));
14990×
                let atoms = kept
15000×
                    .get(gc.sha.as_str())
15010×
                    .map(|(st, _)| st.built_atoms())
15020×
                    .unwrap_or(0);
15030×
                eprintln!(
1504
                    "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={}",
15050×
                    &gc.sha[..12.min(gc.sha.len())],
15060×
                    gc.parents.len(),
15070×
                    kept.len(),
15080×
                    rss_mb(),
15090×
                    commit_started.elapsed().as_millis()
1510
                );
151188×
            }
1512
        }
151396×
        for (name, d) in [
151416×
            "git import: bases",
151516×
            "git import: tree",
151616×
            "git import: render base",
151716×
            "git import: read blobs",
151816×
            "git import: build change",
151916×
            "git import: store change",
152016×
        ]
152116×
        .iter()
152216×
        .zip(spent)
152396×
        {
152496×
            crate::timing::record(name, d);
152596×
        }
152616×
        crate::timing::report_totals();
152716×
        if crate::timing::enabled() {
15280×
            eprintln!(
15290×
                "timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed"
15300×
            );
153116×
        }
1532
1533
        // The bookmark: heads of the old state plus every new change.
153416×
        report.heads = old_heads.len();
153516×
        if last.is_none() {
15361×
            return Ok(report);
153715×
        }
153815×
        let heads: Vec<ChangeHash> = heads_now.into_iter().collect();
153915×
        report.heads = heads.len();
154015×
        let (op_ref, op) = self.head_op()?;
154115×
        let mut view = op.view.clone();
154215×
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
154315×
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
154415×
        view.bookmarks
154515×
            .insert(self.config.bookmark.clone(), state_ref);
154615×
        self.record_op(&[op_ref], command, view)?;
1547
        // The new state equals the tip's tree when the old one was itself a
1548
        // Git commit's tree (fetched or exported), or there was none.
154915×
        let old_known = old_heads.is_empty()
15501×
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
155115×
        if let (Some(tip), true) = (commits.last(), old_known) {
155215×
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
15530×
        }
1554
        // The working copy follows when it was clean on the old heads.
155515×
        if old_heads.is_empty() {
155614×
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
1557
        } else {
15581×
            let snap = self.snapshot(command)?;
15591×
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
15601×
            let mut base = snap.base.maximal(&snap.wc.deps);
15611×
            base.sort();
15621×
            let mut sorted_old = old_heads.clone();
15631×
            sorted_old.sort();
1564
            // An empty base too: an import that stopped after a checkpoint
1565
            // never checked anything out, and resuming it should.
15661×
            if clean && (base == sorted_old || base.is_empty()) {
15671×
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
15680×
            }
1569
        }
157015×
        Ok(report)
157116×
    }
1572
1573
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
1574
    /// an imported commit's change, or the whole state an exported commit
1575
    /// was made from (which may hold changes Git never saw).
15761×
    fn add_git_ancestors(
15771×
        &self,
15781×
        st: &mut State,
15791×
        git_dir: &Path,
15801×
        args: &[&str],
15811×
        known: &GitKnown,
15821×
    ) -> Result<()> {
15831×
        self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new())
15841×
    }
1585
1586
    /// `add_git_ancestors`, also collecting in `touched` every node the
1587
    /// changes it adds edit, place or remove.
158825×
    fn add_git_ancestors_touching(
158925×
        &self,
159025×
        st: &mut State,
159125×
        git_dir: &Path,
159225×
        args: &[&str],
159325×
        known: &GitKnown,
159425×
        touched: &mut HashSet<NodeId>,
159525×
    ) -> Result<()> {
159625×
        let mut full = vec!["rev-list"];
159725×
        full.extend(args);
159825×
        let out = git(git_dir, &full)?;
159932×
        let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> {
160032×
            if st.contains(h) {
16012×
                return Ok(());
160230×
            }
160330×
            if !st.is_history_only() {
16040×
                let c = self.store.get_change(h)?;
16050×
                touched.extend(c.edits.iter().map(|e| e.node()));
16060×
                touched.extend(c.tree_ops.iter().map(|o| o.node()));
16070×
                st.add_unchecked(c);
16080×
                return Ok(());
160930×
            }
1610
            // History only: the text of an edit waits unread unless its
1611
            // file's graph is built.
161230×
            let (skeleton, texts) = self.store.get_change_lazy(h)?;
161332×
            touched.extend(skeleton.edits.iter().map(|e| e.node()));
161430×
            touched.extend(skeleton.tree_ops.iter().map(|o| o.node()));
161530×
            let built = skeleton
161630×
                .edits
161730×
                .iter()
161832×
                .any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node()));
161930×
            if built {
16204×
                let full = self.store.get_change(h)?;
16214×
                st.add_known_mixed(*h, full, skeleton, texts);
162226×
            } else {
162326×
                st.add_known(*h, skeleton, texts);
162426×
            }
162530×
            Ok(())
162632×
        };
162730×
        for sha in out.lines() {
162830×
            if let Some(h) = known.imported.get(sha) {
162929×
                add(st, h)?;
16301×
            } else if let Some(state_ref) = known.exported.get(sha) {
16311×
                let heads = self.store.get_state(state_ref)?.heads;
16323×
                for h in self.negotiate(&[], &heads)? {
16333×
                    add(st, &h)?;
1634
                }
16350×
            }
1636
        }
163725×
        Ok(())
163825×
    }
1639
1640
    /// Recover an import that stopped before it moved the bookmark: its
1641
    /// unfinished pack indexed (`Store::adopt_unfinished_packs`), then every
1642
    /// change in the store that carries a `Git-Commit:` trailer, its heads
1643
    /// (those no other such change depends on) made the bookmark's heads,
1644
    /// so `oxy git fetch` carries on from there. Reads every object once.
1645
    /// Returns how many imported changes it found and the heads.
16460×
    pub fn recover_git_import(&self, progress: &dyn Fn(&str)) -> Result<(usize, usize)> {
1647
        // A stopped import's objects are in a pack it never indexed.
1648
        // OXY_RECOVER_MIN_AGE (seconds) overrides the five minutes it must
1649
        // have been left alone, for testing.
16500×
        let min_age = std::env::var("OXY_RECOVER_MIN_AGE")
16510×
            .ok()
16520×
            .and_then(|v| v.parse().ok())
16530×
            .unwrap_or(300);
16540×
        self.store
16550×
            .adopt_unfinished_packs(std::time::Duration::from_secs(min_age), progress)?;
16560×
        let all = self
16570×
            .store
16580×
            .list()
16590×
            .map_err(|e| RepoError::Msg(format!("listing the store: {e}")))?;
16600×
        let total = all.len();
16610×
        let mut found: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
16620×
        for (i, r) in all.iter().enumerate() {
16630×
            if i.is_multiple_of(100_000) {
16640×
                progress(&format!(
16650×
                    "{i} of {total} objects read, {} imported changes",
16660×
                    found.len()
16670×
                ));
16680×
            }
16690×
            let Ok(meta) = self.store.get_change_meta(r) else {
16700×
                continue;
1671
            };
16720×
            if meta.message.lines().any(|l| l.starts_with("Git-Commit: ")) {
16730×
                found.insert(*r, meta.deps.clone());
16740×
            }
1675
        }
16760×
        if found.is_empty() {
16770×
            return fail("no imported Git commit's change in this store");
16780×
        }
16790×
        let depended: HashSet<ChangeHash> = found.values().flatten().copied().collect();
16800×
        let mut heads: Vec<ChangeHash> = found
16810×
            .keys()
16820×
            .filter(|h| !depended.contains(h))
16830×
            .copied()
16840×
            .collect();
1685
        // The bookmark's present heads stay: a recovery only adds.
16860×
        heads.extend(self.bookmark_heads().unwrap_or_default());
16870×
        let st = self.load_state_history(&heads)?;
16880×
        let mut heads = st.maximal(&heads);
16890×
        heads.sort();
16900×
        heads.dedup();
16910×
        let (op_ref, op) = self.head_op()?;
16920×
        let mut view = op.view.clone();
16930×
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
16940×
        view.bookmarks
16950×
            .insert(self.config.bookmark.clone(), state_ref);
16960×
        self.record_op(&[op_ref], "oxy git recover", view)?;
16970×
        Ok((found.len(), heads.len()))
16980×
    }
1699
1700
    /// Point the bookmark at an import's heads so far (see
1701
    /// `CHECKPOINT_COMMITS`); the working copy is left alone until the end.
17020×
    fn checkpoint_import(&self, heads: &BTreeSet<ChangeHash>, done: usize) -> Result<()> {
17030×
        let heads: Vec<ChangeHash> = heads.iter().copied().collect();
17040×
        let (op_ref, op) = self.head_op()?;
17050×
        let mut view = op.view.clone();
17060×
        let state_ref = self.store.put_state(&StateObject::new(heads))?;
17070×
        view.bookmarks
17080×
            .insert(self.config.bookmark.clone(), state_ref);
17090×
        self.record_op(
17100×
            &[op_ref],
17110×
            &format!("oxy git import (checkpoint after {done} commits)"),
17120×
            view,
17130×
        )?;
17140×
        Ok(())
17150×
    }
1716
1717
    /// Commits this repository can relate to Oxygen history: imported
1718
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
171920×
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
172020×
        let imported = self.imported_commits()?;
172120×
        let marks_dir = self.git_marks_dir(git_dir)?;
172220×
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
172320×
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
172420×
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
17254×
            for line in text.lines() {
17264×
                if let Some((m, sha)) = line.split_once(' ') {
17274×
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
17284×
                        sha_of_mark.insert(m, sha.trim().to_string());
17294×
                    }
17300×
                }
1731
            }
173216×
        }
173320×
        let mut exported = HashMap::new();
173420×
        for (state_ref, m) in oxy_marks {
17354×
            if let Some(sha) = sha_of_mark.get(&m) {
17364×
                exported.insert(sha.clone(), state_ref);
17374×
            }
1738
        }
173920×
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
17407×
            exported.entry(sha).or_insert(state_ref);
17417×
        }
174220×
        Ok(GitKnown { imported, exported })
174320×
    }
1744
17456×
    fn git_author(&self, c: &Change) -> String {
17466×
        match self.store.get_identity(&c.author) {
17476×
            Ok(id) if !id.name.is_empty() => format!(
1748
                "{} <{}>",
17496×
                id.name.replace(['<', '>', '\n'], " "),
17506×
                id.email.replace(['<', '>', '\n', ' '], "")
1751
            ),
17520×
            _ => "oxy <oxy@localhost>".to_string(),
1753
        }
17546×
    }
1755
1756
    #[allow(clippy::too_many_arguments)]
17579×
    fn write_commit(
17589×
        &self,
17599×
        out: &mut Vec<u8>,
17609×
        reference: &str,
17619×
        mark: u64,
17629×
        author: &str,
17639×
        secs: u64,
17649×
        message: &str,
17659×
        parents: &[String],
17669×
        snapshot: &Snapshot,
17679×
    ) -> Result<()> {
17689×
        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());
17699×
        for (i, p) in parents.iter().enumerate() {
17705×
            out.extend_from_slice(
17715×
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
1772
            );
1773
        }
17749×
        out.extend_from_slice(b"deleteall\n");
17759×
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
177638×
        for (path, f) in &snapshot.files {
177738×
            if path == ".oxymodules" {
1778
                // Git reads `.gitmodules`; derive it unless the tree has one.
17791×
                if !has_gitmodules {
17800×
                    if let FileContent::Text { bytes, .. } = &f.content {
17810×
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
17820×
                            .to_gitmodules();
17830×
                        if !gm.is_empty() {
17840×
                            out.extend_from_slice(
17850×
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
17860×
                                    .as_bytes(),
17870×
                            );
17880×
                            out.extend_from_slice(gm.as_bytes());
17890×
                            out.push(b'\n');
17900×
                        }
17910×
                    }
17921×
                }
17931×
                continue;
179437×
            }
179537×
            if f.kind == NodeKind::Subrepo {
17961×
                if let FileContent::Opaque { blobs } = &f.content {
17971×
                    if let Some(b) = blobs.first() {
17981×
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
17991×
                            crate::subrepo::Pin::Git { sha, .. } => {
18001×
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
1801
                            }
18020×
                            crate::subrepo::Pin::Oxy { .. } => self
18030×
                                .git_export_skipped
18040×
                                .set(self.git_export_skipped.get() + 1),
1805
                        }
18060×
                    }
18070×
                }
18081×
                continue;
180936×
            }
181036×
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
18119×
                (NodeKind::Dir, _) => continue,
18120×
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
18130×
                    "120000",
18140×
                    blobs
18150×
                        .first()
18160×
                        .map(|b| self.read_blob(b))
18170×
                        .transpose()?
18180×
                        .unwrap_or_default(),
1819
                ),
182024×
                (_, FileContent::Text { bytes, .. }) => {
182124×
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
1822
                }
18233×
                (_, FileContent::Opaque { blobs }) => (
18243×
                    if f.mode.exec { "100755" } else { "100644" },
18253×
                    blobs
18263×
                        .first()
18273×
                        .map(|b| self.read_blob(b))
18283×
                        .transpose()?
18293×
                        .unwrap_or_default(),
1830
                ),
18310×
                (_, FileContent::Dir) => continue,
1832
            };
183327×
            out.extend_from_slice(
183427×
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
1835
            );
183627×
            out.extend_from_slice(&bytes);
183727×
            out.push(b'\n');
1838
        }
18399×
        out.push(b'\n');
18409×
        Ok(())
18419×
    }
1842
}
1843
1844
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
1845
#[derive(Debug, Clone, Default, PartialEq, Eq)]
1846
pub struct GitVerifyReport {
1847
    pub commits: usize,
1848
    /// Commits followed but not rebuilt (all but the last few, when asked).
1849
    pub skipped: usize,
1850
    pub files_compared: usize,
1851
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
1852
    pub mismatches: Vec<(String, String)>,
1853
    /// Commits of the branch after the last imported one: an import not
1854
    /// finished yet. Not checked.
1855
    pub not_yet: usize,
1856
}
1857
1858
impl Repo {
1859
    /// Check an import against its Git source: for every commit of
1860
    /// `branch`, the state formed by the changes imported for it and all
1861
    /// its ancestors must materialize to exactly that commit's tree, byte
1862
    /// for byte, with the same executable bits, symlink targets and
1863
    /// submodule pins. Reads only; stops listing after 50 differences.
186410×
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
186510×
        self.verify_git_import_last(git_dir, branch, None, 50)
186610×
    }
1867
1868
    /// [`Repo::verify_git_import`] of the last `last` commits only (all
1869
    /// when `None`): earlier ones are only followed, not rebuilt, for
1870
    /// looking again at where an import went wrong.
1871
    /// It stops after `max` differences (0: never), so one that repeats
1872
    /// through history does not hide the commits after it.
187310×
    pub fn verify_git_import_last(
187410×
        &self,
187510×
        git_dir: &Path,
187610×
        branch: &str,
187710×
        last: Option<usize>,
187810×
        max: usize,
187910×
    ) -> Result<GitVerifyReport> {
188010×
        let mut rep = GitVerifyReport::default();
188110×
        let mut commits = list_commits(git_dir, branch)?;
188210×
        let imported = self.imported_commits()?;
1883
        // An import still going (or stopped) has reached part of the
1884
        // branch: what follows its last imported commit is not checked,
1885
        // only counted, and --last counts back from there (oxygen#81).
188610×
        if let Some(end) = commits.iter().rposition(|c| imported.contains_key(&c.sha)) {
188710×
            let rest = commits.len() - end - 1;
188810×
            if rest > 0 {
18890×
                commits.truncate(end + 1);
189010×
            }
189110×
            rep.not_yet = rest;
18920×
        }
189310×
        let mut cat = CatFile::start(git_dir)?;
1894
        // Changes of each commit and all its ancestors, built up in topological order.
189510×
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
1896
        // Graphs (by key) and blobs already found equal to a Git blob.
189710×
        let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new();
189810×
        let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new();
1899
        // The state of a commit whose first-parent children are still to
1900
        // come, so a child adds its own changes instead of loading all its
1901
        // history again (as the import does).
190210×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
1903
        // Children still to come per commit, through any parent: a commit's
1904
        // closure is dropped after its last child, so only the open
1905
        // frontier is held. Kept for every commit, the closures grew with
1906
        // the square of the history and VS Code's verify ran out of memory
1907
        // (oxygen#81).
190810×
        let mut children: HashMap<&str, usize> = HashMap::new();
190963×
        for c in &commits {
191063×
            if let Some(p1) = c.parents.first() {
191151×
                *waiting.entry(p1.as_str()).or_default() += 1;
191251×
            }
191369×
            for p in &c.parents {
191469×
                *children.entry(p.as_str()).or_default() += 1;
191569×
            }
1916
        }
191710×
        let mut kept: HashMap<String, State> = HashMap::new();
191810×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
191963×
        for c in &commits {
192063×
            rep.commits += 1;
1921
            // The first parent's closure, taken over when this is its last
1922
            // child (no copy), then the other parents' added.
192363×
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
192469×
            for (i, p) in c.parents.iter().enumerate() {
192569×
                let left = children.get_mut(p.as_str()).map(|n| {
192669×
                    *n -= 1;
192769×
                    *n
192869×
                });
192969×
                let ps = if left == Some(0) {
193053×
                    closure.remove(p)
1931
                } else {
193216×
                    closure.get(p).cloned()
1933
                };
193469×
                if let Some(ps) = ps {
193569×
                    if i == 0 && set.is_empty() {
193651×
                        set = Arc::try_unwrap(ps).unwrap_or_else(|a| (*a).clone());
193718×
                    } else {
193818×
                        set.extend(ps.iter().copied());
193918×
                    }
19400×
                }
1941
            }
194263×
            match imported.get(&c.sha) {
194363×
                Some(h) => {
194463×
                    set.insert(*h);
194563×
                }
19460×
                None => {
19470×
                    rep.mismatches.push((
19480×
                        c.sha.clone(),
19490×
                        "no imported change carries this commit".into(),
19500×
                    ));
19510×
                }
1952
            }
195363×
            let set = Arc::new(set);
195463×
            if children.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
195553×
                closure.insert(c.sha.clone(), set.clone());
195653×
            }
195763×
            if max > 0 && rep.mismatches.len() >= max {
19580×
                break;
195963×
            }
196063×
            if last.is_some_and(|n| rep.commits + n <= commits.len()) {
19610×
                rep.skipped += 1;
19620×
                continue;
196363×
            }
196463×
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1965
            // History only: a file whose graph (by key) or blob was already
1966
            // found equal to this Git blob is not built, rendered or read
1967
            // again; the rest are.
196863×
            let from_parent = c.parents.first().and_then(|p1| {
196951×
                let left = waiting.get_mut(p1.as_str()).map(|n| {
197051×
                    *n -= 1;
197151×
                    *n
197251×
                });
197351×
                if left == Some(0) {
197453×
                    kept_order.retain(|k| k != p1);
197537×
                    kept.remove(p1.as_str())
1976
                } else {
197714×
                    kept.get(p1.as_str()).cloned()
1978
                }
197951×
            });
198063×
            let state = match from_parent {
198151×
                Some(mut st) => {
1982
                    // The changes the parent's state lacks. The state never
1983
                    // builds a graph (they are built beside it), so they
1984
                    // are read without their text.
1985223×
                    for h in set.iter() {
1986223×
                        if !st.contains(h) {
198772×
                            let (change, texts) = self.store.get_change_lazy(h)?;
198872×
                            st.add_known(*h, change, texts);
1989151×
                        }
1990
                    }
199151×
                    st
1992
                }
199312×
                None => self.load_state_history(&heads)?,
1994
            };
199563×
            let view = state.tree().view();
199663×
            let tree = list_tree(git_dir, &c.sha)?;
199763×
            let short = &c.sha[..12.min(c.sha.len())];
199863×
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
199963×
            let mut conflicted: Vec<String> =
200063×
                view.conflicts.iter().map(|c| format!("{c:?}")).collect();
200163×
            let mut need: Vec<NodeId> = Vec::new();
2002145×
            for (path, (mode, sha)) in &tree {
2003145×
                let Some(e) = view.entries.get(path) else {
20040×
                    continue;
2005
                };
2006145×
                if mode != "160000"
2007145×
                    && mode != "120000"
2008145×
                    && e.kind == NodeKind::File
2009145×
                    && !e.mode.opaque
2010
                {
2011134×
                    let known = state
2012134×
                        .graph_key(&e.node)
2013134×
                        .is_some_and(|k| verified_graphs.get(&k) == Some(sha));
2014134×
                    if !known {
201550×
                        need.push(e.node);
201684×
                    }
201711×
                }
2018
            }
2019
            // A graph's key is known only before it is built.
202063×
            let keys: HashMap<NodeId, [u8; 32]> = need
202163×
                .iter()
202263×
                .filter_map(|n| Some((*n, state.graph_key(n)?)))
202363×
                .collect();
202463×
            let need_set: HashSet<NodeId> = need.iter().copied().collect();
202563×
            let graphs = self.build_graphs_detached(&state, &need)?;
2026145×
            for (path, (mode, sha)) in &tree {
2027145×
                let Some(e) = view.entries.get(path) else {
20280×
                    differ(format!("{short}: {path} is missing"));
20290×
                    continue;
2030
                };
2031145×
                rep.files_compared += 1;
2032145×
                match mode.as_str() {
2033145×
                    "160000" => {
20340×
                        let blobs = state.live_blobs(&e.node);
20350×
                        match (e.kind, blobs.as_slice()) {
20360×
                            (NodeKind::Subrepo, [b]) => {
20370×
                                let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?;
20380×
                                if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
20390×
                                {
20400×
                                    differ(format!("{short}: {path} pins another commit"));
20410×
                                }
2042
                            }
20430×
                            (kind, _) => differ(format!(
20440×
                                "{short}: {path} is not one submodule pin: {kind:?} with {} pins",
20450×
                                blobs.len()
20460×
                            )),
2047
                        }
2048
                    }
2049145×
                    "120000" => {
20500×
                        let target = cat.read(sha)?;
20510×
                        let blobs = state.live_blobs(&e.node);
20520×
                        match (e.kind, blobs.as_slice()) {
20530×
                            (NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {}
20540×
                            _ => differ(format!("{short}: symlink {path} differs")),
2055
                        }
2056
                    }
2057
                    _ => {
2058145×
                        if e.mode.exec != (mode == "100755") {
20590×
                            differ(format!("{short}: {path} executable bit differs"));
2060145×
                        }
2061145×
                        if e.kind == NodeKind::File && !e.mode.opaque {
2062134×
                            if !need_set.contains(&e.node) {
2063
                                // Known equal: skipped when the graphs were chosen.
206484×
                                continue;
206550×
                            }
206650×
                            let (have, m) = match graphs.get(&e.node) {
206750×
                                Some(g) => state.render_graph(g),
20680×
                                None => (Vec::new(), Default::default()),
2069
                            };
207050×
                            if m.is_conflicted() {
2071
                                // Who conflicts: a copy of the state with this graph built.
20720×
                                let mut detail = state.clone();
20730×
                                self.load_graphs_of(&mut detail, &[e.node])?;
20740×
                                let who: Vec<String> = detail
20750×
                                    .conflict_regions(&e.node)
20760×
                                    .contributors
20770×
                                    .iter()
20780×
                                    .filter_map(|h| state.get(h))
20790×
                                    .map(|m| {
20800×
                                        let sha = m
20810×
                                            .message
20820×
                                            .lines()
20830×
                                            .rev()
20840×
                                            .find_map(|l| l.strip_prefix("Git-Commit: "))
20850×
                                            .unwrap_or("?");
20860×
                                        format!(
2087
                                            "{} {:?}",
20880×
                                            &sha[..12.min(sha.len())],
20890×
                                            m.message.lines().next().unwrap_or("")
2090
                                        )
20910×
                                    })
20920×
                                    .collect();
20930×
                                conflicted.push(format!("{path} between {}", who.join(" and ")));
209450×
                            }
209550×
                            let want = cat.read(sha)?;
209650×
                            if have != want {
20970×
                                differ(format!(
20980×
                                    "{short}: {path} differs: {}",
20990×
                                    first_difference(&have, &want)
21000×
                                ));
210150×
                            } else if !m.is_conflicted() {
210250×
                                if let Some(k) = keys.get(&e.node) {
210350×
                                    verified_graphs.insert(*k, sha.clone());
210450×
                                }
21050×
                            }
210650×
                            continue;
210711×
                        }
210811×
                        let blobs = state.live_blobs(&e.node);
210911×
                        let [b] = blobs.as_slice() else {
21100×
                            differ(format!("{short}: {path} is not one file"));
21110×
                            continue;
2112
                        };
211311×
                        if verified_blobs.get(b) == Some(sha) {
21146×
                            continue;
21155×
                        }
21165×
                        if self.read_blob(b)? != cat.read(sha)? {
21170×
                            differ(format!("{short}: {path} differs"));
21185×
                        } else {
21195×
                            verified_blobs.insert(*b, sha.clone());
21205×
                        }
2121
                    }
2122
                }
2123
            }
212463×
            if !conflicted.is_empty() {
21250×
                differ(format!(
21260×
                    "{short}: the state is conflicted: {}",
21270×
                    conflicted.join("; ")
21280×
                ));
212963×
            }
2130
            // Import records submodules in `.oxymodules` as well (spec §23),
2131
            // and export leaves it out again.
2132145×
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
2133186×
            for (path, e) in view.entries.iter() {
2134186×
                if e.kind != NodeKind::Dir
2135145×
                    && !tree.contains_key(path)
21360×
                    && !(has_submodules && path == ".oxymodules")
21370×
                {
21380×
                    differ(format!("{short}: {path} is extra"));
2139186×
                }
2140
            }
214163×
            if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
214237×
                kept.insert(c.sha.clone(), state);
214337×
                kept_order.push_back(c.sha.clone());
214437×
                if kept_order.len() > 8 {
21450×
                    if let Some(old) = kept_order.pop_front() {
21460×
                        kept.remove(&old);
21470×
                    }
214837×
                }
214926×
            }
215063×
            if max > 0 && rep.mismatches.len() >= max {
21510×
                break;
215263×
            }
2153
        }
215410×
        Ok(rep)
215510×
    }
2156
}
2157
2158
/// Where two versions of a file first part, for a verification report.
21590×
fn first_difference(have: &[u8], want: &[u8]) -> String {
21600×
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
21610×
        have.split(|b| *b == b'\n').collect(),
21620×
        want.split(|b| *b == b'\n').collect(),
2163
    );
21640×
    let i = h
21650×
        .iter()
21660×
        .zip(&w)
21670×
        .position(|(a, b)| a != b)
21680×
        .unwrap_or(h.len().min(w.len()));
21690×
    let show = |l: Option<&&[u8]>| {
21700×
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
21710×
            .unwrap_or_else(|| "(end)".into())
21720×
    };
21730×
    format!(
2174
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
21750×
        i + 1,
21760×
        show(h.get(i)),
21770×
        show(w.get(i)),
21780×
        h.len(),
21790×
        w.len()
2180
    )
21810×
}