OXYGENHUB

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

1262 of 1526 lines run, 85 of 240 functions · run #250 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 {
3122×
    fn start(git_dir: &Path) -> Result<CatFile> {
3222×
        let mut child = Command::new("git")
3322×
            .arg("-C")
3422×
            .arg(git_dir)
3522×
            .args(["cat-file", "--batch"])
3622×
            .stdin(Stdio::piped())
3722×
            .stdout(Stdio::piped())
3822×
            .stderr(Stdio::null())
3922×
            .spawn()
4022×
            .map_err(|e| RepoError::Msg(format!("running git cat-file: {e}")))?;
4122×
        let stdin = child.stdin.take().unwrap();
4222×
        let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
4322×
        Ok(CatFile {
4422×
            child,
4522×
            stdin,
4622×
            stdout,
4722×
        })
4822×
    }
49
50123×
    fn read(&mut self, sha: &str) -> Result<Vec<u8>> {
51
        use std::io::{BufRead, Read};
52123×
        writeln!(self.stdin, "{sha}")?;
53123×
        self.stdin.flush()?;
54123×
        let mut header = String::new();
55123×
        self.stdout.read_line(&mut header)?;
56123×
        let parts: Vec<&str> = header.trim_end().split(' ').collect();
57123×
        if parts.len() != 3 {
580×
            return fail(format!("git cat-file: object {sha} not found"));
59123×
        }
60123×
        let size: usize = parts[2]
61123×
            .parse()
62123×
            .map_err(|_| RepoError::Msg("git cat-file: bad size".into()))?;
63123×
        let mut body = vec![0u8; size];
64123×
        self.stdout.read_exact(&mut body)?;
65123×
        let mut nl = [0u8; 1];
66123×
        self.stdout.read_exact(&mut nl)?;
67123×
        Ok(body)
68123×
    }
69
}
70
71
impl Drop for CatFile {
7222×
    fn drop(&mut self) {
7322×
        let _ = self.child.kill();
7422×
        let _ = self.child.wait();
7522×
    }
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 {
9514×
    fn start(git_dir: &Path, pairs: Vec<(String, String)>) -> Result<DiffTree> {
9614×
        let mut child = Command::new("git")
9714×
            .arg("-C")
9814×
            .arg(git_dir)
9914×
            .args([
10014×
                "diff-tree",
10114×
                "--stdin",
10214×
                "--always",
10314×
                "-r",
10414×
                "-z",
10514×
                "--no-renames",
10614×
            ])
10714×
            .stdin(Stdio::piped())
10814×
            .stdout(Stdio::piped())
10914×
            .stderr(Stdio::null())
11014×
            .spawn()
11114×
            .map_err(|e| RepoError::Msg(format!("running git diff-tree: {e}")))?;
11214×
        let mut stdin = child.stdin.take().unwrap();
11314×
        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.
11514×
        let feeder = std::thread::spawn(move || {
11614×
            let mut w = std::io::BufWriter::new(&mut stdin);
11766×
            for (c, p) in pairs {
11866×
                if writeln!(w, "{c} {p}").is_err() {
1190×
                    return;
12066×
                }
121
            }
12214×
            let _ = w.flush();
12314×
        });
12414×
        Ok(DiffTree {
12514×
            child,
12614×
            stdout,
12714×
            feeder: Some(feeder),
12814×
            next: None,
12914×
        })
13014×
    }
131
132243×
    fn field(&mut self) -> Result<Option<String>> {
133
        use std::io::BufRead;
134243×
        let mut buf = Vec::new();
135243×
        if self.stdout.read_until(0, &mut buf)? == 0 {
13613×
            return Ok(None);
137230×
        }
138230×
        if buf.last() == Some(&0) {
139230×
            buf.pop();
140230×
        }
141230×
        Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
142243×
    }
143
144
    /// The diff of `sha` against the parent it was fed with.
14566×
    fn diff(&mut self, sha: &str) -> Result<TreeDiff> {
14666×
        let header = match self.next.take() {
14753×
            Some(h) => Some(h),
14813×
            None => self.field()?,
149
        };
15066×
        if header.as_deref() != Some(sha) {
1510×
            return fail(format!("git diff-tree: expected {sha}, got {header:?}"));
15266×
        }
15366×
        let mut out = Vec::new();
154148×
        while let Some(f) = self.field()? {
155135×
            let Some(meta) = f.strip_prefix(':') else {
15653×
                self.next = Some(f);
15753×
                break;
158
            };
15982×
            let Some(path) = self.field()? else {
1600×
                return fail("git diff-tree: record without a path");
161
            };
162
            // `oldmode newmode oldsha newsha status`
16382×
            let m: Vec<&str> = meta.split(' ').collect();
16482×
            if m.len() != 5 {
1650×
                return fail(format!("git diff-tree: bad record {f:?}"));
16682×
            }
16782×
            let entry = if m[4].starts_with('D') {
16814×
                None
169
            } else {
17068×
                Some((m[1].to_string(), m[3].to_string()))
171
            };
17282×
            out.push((path, entry));
173
        }
17466×
        Ok(out)
17566×
    }
176
}
177
178
impl Drop for DiffTree {
17914×
    fn drop(&mut self) {
18014×
        let _ = self.child.kill();
18114×
        let _ = self.child.wait();
18214×
        if let Some(f) = self.feeder.take() {
18314×
            let _ = f.join();
18414×
        }
18514×
    }
186
}
187
188
/// One commit as `git log` describes it.
189
struct GitCommit {
190
    sha: String,
191
    parents: Vec<String>,
192
    author_secs: u64,
193
    author: String,
194
    message: String,
195
}
196
19722×
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> {
19822×
    let out = Command::new("git")
19922×
        .arg("-C")
20022×
        .arg(git_dir)
20122×
        .args([
20222×
            "log",
20322×
            "--reverse",
20422×
            "--topo-order",
20522×
            "--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e",
20622×
            branch,
20722×
        ])
20822×
        .output()
20922×
        .map_err(|e| RepoError::Msg(format!("running git log: {e}")))?;
21022×
    if !out.status.success() {
2110×
        return fail(format!(
212
            "git log {branch} failed: {}",
2130×
            String::from_utf8_lossy(&out.stderr).trim()
214
        ));
21522×
    }
21622×
    let text = String::from_utf8_lossy(&out.stdout);
21722×
    let mut commits = Vec::new();
218162×
    for record in text.split('\x1e') {
219162×
        let record = record.trim_start_matches('\n');
220162×
        if record.trim().is_empty() {
22122×
            continue;
222140×
        }
223140×
        let f: Vec<&str> = record.splitn(5, '\0').collect();
224140×
        if f.len() != 5 {
2250×
            return fail("unexpected git log record");
226140×
        }
227140×
        commits.push(GitCommit {
228140×
            sha: f[0].to_string(),
229140×
            parents: f[1].split_whitespace().map(str::to_string).collect(),
230140×
            author_secs: f[2].parse().unwrap_or(0),
231140×
            author: f[3].to_string(),
232140×
            message: f[4].trim_end().to_string(),
233140×
        });
234
    }
23522×
    Ok(commits)
23622×
}
237
238
/// `path → (mode, blob sha)` for a commit's tree.
23970×
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> {
24070×
    let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?;
24170×
    let mut out = BTreeMap::new();
242229×
    for entry in text.split('\0') {
243229×
        if entry.is_empty() {
24470×
            continue;
245159×
        }
246159×
        let Some((meta, path)) = entry.split_once('\t') else {
2470×
            continue;
248
        };
249159×
        let m: Vec<&str> = meta.split(' ').collect();
250159×
        if m.len() == 3 {
251159×
            out.insert(path.to_string(), (m[0].to_string(), m[2].to_string()));
252159×
        }
253
    }
25470×
    Ok(out)
25570×
}
256
257
/// The ChangeId for a Git commit: its `Change-Id` trailer if it has a
258
/// 32-hex one, else BLAKE3-128 of the commit hash (spec §23).
25980×
fn change_id_for(sha: &str, message: &str) -> ChangeId {
26080×
    for line in message.lines().rev() {
26180×
        if let Some(v) = line.strip_prefix("Change-Id:") {
2624×
            if let Some(id) = ChangeId::from_hex(v.trim()) {
2634×
                return id;
2640×
            }
26576×
        }
266
    }
26776×
    let h = blake3::hash(sha.as_bytes());
26876×
    ChangeId(h.as_bytes()[..16].try_into().unwrap())
26980×
}
270
271
/// Git commits with a known Oxygen counterpart.
272
struct GitKnown {
273
    /// Imported commit → its change.
274
    imported: HashMap<String, ChangeHash>,
275
    /// Exported commit (or a fetched tip) → the bookmark state it equals.
276
    exported: HashMap<String, ObjectRef>,
277
}
278
279
#[derive(Debug, Clone, Default, PartialEq, Eq)]
280
pub struct GitExportReport {
281
    pub exported: usize,
282
    pub skipped: usize,
283
    /// Subrepo nodes with Oxygen pins, which Git cannot represent.
284
    pub skipped_subrepos: usize,
285
    pub branch: String,
286
    pub heads: usize,
287
}
288
289
/// A merge bringing more commits than this sheds its base's graphs first.
290
const MERGE_SHED_COMMITS: usize = 100;
291
292
/// The atoms a kept state's built graphs may hold before they go back into
293
/// its history (#25): about a few hundred megabytes.
294
const KEPT_ATOMS: usize = 1_500_000;
295
/// A kept state with more built graphs than this sheds them.
296
const KEPT_GRAPHS: usize = 2000;
297
298
/// Text files of a merge rendered this many at a time (oxygen#25): a
299
/// batch's graphs are built beside the state and dropped once rendered,
300
/// so what is held for the whole tree is the renderings, not the graphs
301
/// with every deleted line of their history.
302
const MERGE_BATCH: usize = 500;
303
304
thread_local! {
305
    /// A smaller batch for this thread's imports: tests set 1, so a small
306
    /// merge takes the batched path.
307
    static MERGE_BATCH_OVERRIDE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
308
}
309
310
#[cfg(test)]
3114×
pub(crate) fn set_merge_batch_for_tests(n: Option<usize>) {
3124×
    MERGE_BATCH_OVERRIDE.with(|c| c.set(n));
3134×
}
314
31545×
fn merge_batch() -> usize {
31645×
    MERGE_BATCH_OVERRIDE
31745×
        .with(|c| c.get())
31845×
        .filter(|n| *n > 0)
31945×
        .or_else(|| {
32019×
            std::env::var("OXY_MERGE_BATCH")
32119×
                .ok()
32219×
                .and_then(|v| v.parse().ok())
32319×
        })
32445×
        .unwrap_or(MERGE_BATCH)
32545×
}
326
327
impl Repo {
328
    /// As `State::materialize_except`, for a tree whose graphs would not
329
    /// fit in memory at once. The few files the change builder reads
330
    /// graphs for (conflicted ones, and renderings whose lines are not
331
    /// one per live atom) are built in the state afterwards.
3327×
    fn materialize_batched(
3337×
        &self,
3347×
        base: &mut State,
3357×
        need: &[crate::ids::NodeId],
3367×
        skip: &HashSet<crate::ids::NodeId>,
3377×
    ) -> Result<crate::state::Snapshot> {
338
        use crate::graph::Materialized;
339
        use crate::state::{FileContent, FileState};
340
        use rayon::prelude::*;
3417×
        let view = base.tree().view();
3427×
        let mut rendered: HashMap<crate::ids::NodeId, (Vec<u8>, Materialized)> =
3437×
            HashMap::with_capacity(need.len());
3447×
        let mut keep_built: Vec<crate::ids::NodeId> = Vec::new();
34518×
        for batch in need.chunks(merge_batch()) {
34618×
            let t = std::time::Instant::now();
34718×
            let graphs = self.build_graphs_detached(base, batch)?;
34818×
            crate::timing::add("render: build graphs, batch", t.elapsed());
34918×
            let t = std::time::Instant::now();
35018×
            let batch_rendered: Vec<(crate::ids::NodeId, Vec<u8>, Materialized)> = graphs
35118×
                .par_iter()
35218×
                .map(|(node, g)| {
35318×
                    let (bytes, m) = base.render_graph(g);
35418×
                    (*node, bytes, m)
35518×
                })
35618×
                .collect();
35718×
            drop(graphs);
35818×
            crate::timing::add("render: render, batch", t.elapsed());
35918×
            for (node, bytes, m) in batch_rendered {
36018×
                if m.is_conflicted()
36118×
                    || m.live_atoms().len() != crate::diff::split_lines(&bytes).len()
3620×
                {
3630×
                    keep_built.push(node);
36418×
                }
36518×
                rendered.insert(node, (bytes, m));
366
            }
367
        }
3687×
        if !keep_built.is_empty() {
3690×
            self.load_graphs_of(base, &keep_built)?;
3707×
        }
3717×
        let mut files = BTreeMap::new();
3727×
        let mut unrendered = BTreeSet::new();
37322×
        for (path, e) in view.entries.iter() {
37422×
            let f = if e.kind == NodeKind::File && !e.mode.opaque {
37522×
                match rendered.remove(&e.node) {
37618×
                    Some((bytes, materialized)) => FileState {
37718×
                        node: e.node,
37818×
                        kind: e.kind,
37918×
                        mode: e.mode,
38018×
                        content: FileContent::Text {
38118×
                            bytes,
38218×
                            materialized,
38318×
                        },
38418×
                    },
3854×
                    None if skip.contains(&e.node) => {
3864×
                        unrendered.insert(path.clone());
3874×
                        FileState {
3884×
                            node: e.node,
3894×
                            kind: e.kind,
3904×
                            mode: e.mode,
3914×
                            content: FileContent::Text {
3924×
                                bytes: Vec::new(),
3934×
                                materialized: Materialized::default(),
3944×
                            },
3954×
                        }
396
                    }
397
                    None => {
398
                        // Neither asked for nor known unchanged: render it
399
                        // from a built graph, as the whole-tree path does.
4000×
                        self.load_graphs_of(base, &[e.node])?;
4010×
                        base.entry_state(e)
402
                    }
403
                }
404
            } else {
4050×
                base.entry_state(e)
406
            };
40722×
            files.insert(path.clone(), f);
408
        }
4097×
        Ok(crate::state::Snapshot {
4107×
            tree: view,
4117×
            files,
4127×
            unrendered,
4137×
        })
4147×
    }
415
}
416
417145×
fn git(dir: &Path, args: &[&str]) -> Result<String> {
418145×
    let out = Command::new("git")
419145×
        .arg("-C")
420145×
        .arg(dir)
421145×
        .args(args)
422145×
        .output()
423145×
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
424145×
    if !out.status.success() {
4250×
        return fail(format!(
426
            "git {} failed: {}",
4270×
            args.join(" "),
4280×
            String::from_utf8_lossy(&out.stderr).trim()
429
        ));
430145×
    }
431145×
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
432145×
}
433
434
impl Repo {
43541×
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
43641×
        let canonical = git_dir
43741×
            .canonicalize()
43841×
            .unwrap_or_else(|_| git_dir.to_path_buf());
43941×
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
44041×
        let dir = self.oxy.join("git").join(key);
44141×
        fs::create_dir_all(&dir)?;
44241×
        Ok(dir)
44341×
    }
444
445
    /// `state ref → Git commit sha` for bookmark states that equal a Git
446
    /// commit's tree (recorded by import and fetch).
44741×
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
44841×
        let mut out = BTreeMap::new();
44941×
        if let Ok(text) = fs::read_to_string(path) {
45012×
            for line in text.lines() {
45112×
                if let Some((h, sha)) = line.split_once(' ') {
45212×
                    if let Some(h) = ObjectRef::from_hex(h) {
45312×
                        out.insert(h, sha.trim().to_string());
45412×
                    }
4550×
                }
456
            }
45731×
        }
45841×
        Ok(out)
45941×
    }
460
46113×
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
46213×
        let path = self.git_marks_dir(git_dir)?.join("git-states");
46313×
        let mut states = Self::read_git_states(&path)?;
46413×
        states.insert(*state, sha.to_string());
46513×
        let text: String = states
46613×
            .iter()
46714×
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
46813×
            .collect();
46913×
        write_atomic(&path, text.as_bytes())
47013×
    }
471
472
    /// The bare mirror this repository keeps for the Git remote `url`.
4737×
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
4747×
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
4757×
        let dir = self.oxy.join("git").join(key).join("mirror.git");
4767×
        if !dir.join("HEAD").exists() {
4771×
            fs::create_dir_all(&dir)?;
4781×
            git(&dir, &["init", "--bare", "-q"])?;
4796×
        }
4807×
        Ok(dir)
4817×
    }
482
483
    /// Git commits already imported into the bookmark, by sha.
48426×
    pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
48526×
        let mut map = HashMap::new();
486100×
        for e in self.log()? {
487100×
            if e.is_working_copy {
48826×
                continue;
48974×
            }
49074×
            if let Some(sha) = e
49174×
                .change
49274×
                .message
49374×
                .lines()
49474×
                .rev()
495142×
                .find_map(|l| l.strip_prefix("Git-Commit: "))
49668×
            {
49768×
                map.insert(sha.trim().to_string(), e.hash);
49868×
            }
499
        }
50026×
        Ok(map)
50126×
    }
502
503
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
504
    /// A remote without that branch yet leaves the mirror as it is.
5057×
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
5067×
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
5077×
        match git(mirror, &["fetch", "-q", url, &spec]) {
5087×
            Ok(_) => Ok(()),
5090×
            Err(e) => {
5100×
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
5110×
                if ls.trim().is_empty() {
5120×
                    Ok(())
513
                } else {
5140×
                    Err(e)
515
                }
516
            }
517
        }
5187×
    }
519
520
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
521
    /// through a mirror and import the commits not yet in the bookmark
522
    /// (spec §23). Works on a repository that already has history: the
523
    /// new changes join the bookmark like a pull.
5243×
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
5253×
        let mirror = self.git_mirror(url)?;
5263×
        self.git_mirror_fetch(&mirror, url, branch)?;
5273×
        if git(
5283×
            &mirror,
5293×
            &[
5303×
                "rev-parse",
5313×
                "--verify",
5323×
                "-q",
5333×
                &format!("refs/heads/{branch}"),
5343×
            ],
5353×
        )
5363×
        .is_err()
537
        {
5380×
            return fail(format!("{url} has no branch {branch:?}"));
5393×
        }
5403×
        self.import_git_commits(
5413×
            &mirror,
5423×
            branch,
5433×
            &format!("oxy git fetch {url} {branch}"),
5441×
            &mut |_| {},
545
        )
5463×
    }
547
548
    /// Export the bookmark to `branch` of the Git repository at `url`
549
    /// through the mirror and push it. The remote's tip must already have
550
    /// been fetched (`git_fetch`), so the push fast-forwards.
5514×
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
5524×
        let mirror = self.git_mirror(url)?;
5534×
        self.git_mirror_fetch(&mirror, url, branch)?;
5544×
        if let Ok(tip) = git(
5554×
            &mirror,
5564×
            &[
5574×
                "rev-parse",
5584×
                "--verify",
5594×
                "-q",
5604×
                &format!("refs/heads/{branch}"),
5614×
            ],
5624×
        ) {
5634×
            let known = self.git_known(&mirror)?;
5644×
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
5651×
                return fail(format!(
566
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
567
                ));
5683×
            }
5690×
        }
5703×
        let report = self.git_export_as(&mirror, branch)?;
5713×
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
5723×
        git(&mirror, &["push", "-q", url, &spec])?;
5733×
        Ok(report)
5744×
    }
575
57628×
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
57728×
        let mut out = BTreeMap::new();
57828×
        if let Ok(text) = fs::read_to_string(path) {
57913×
            for line in text.lines() {
58013×
                if let Some((h, m)) = line.split_once(' ') {
58113×
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
58213×
                        out.insert(h, m);
58313×
                    }
5840×
                }
585
            }
58619×
        }
58728×
        Ok(out)
58828×
    }
589
590
    /// Export the current bookmark to the Git repository at `git_dir`,
591
    /// creating a bare one if nothing is there. Each state the bookmark
592
    /// passed through (per the operation log) becomes one commit whose tree
593
    /// is that state, so the Git branch is a linear history of full trees.
5947×
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
5957×
        let bookmark = self.config.bookmark.clone();
5967×
        self.git_export_as(git_dir, &bookmark)
5977×
    }
598
599
    /// `git_export` to the Git branch `branch`. A state that came from a
600
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
601
    /// onto that commit, so a push back to the Git remote fast-forwards.
60210×
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
60310×
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
6044×
            fs::create_dir_all(git_dir)?;
6054×
            git(git_dir, &["init", "--bare", "-q"])?;
6066×
        }
60710×
        let marks_dir = self.git_marks_dir(git_dir)?;
60810×
        let git_marks = marks_dir.join("git-marks");
60910×
        let oxy_marks_path = marks_dir.join("oxy-marks");
61010×
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
61110×
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
61210×
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
613
61410×
        let bookmark = self.config.bookmark.clone();
61510×
        let mut stream: Vec<u8> = Vec::new();
61610×
        let mut report = GitExportReport {
61710×
            branch: branch.to_string(),
61810×
            heads: self.bookmark_heads()?.len(),
61910×
            ..Default::default()
620
        };
621
622
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
62310×
        let mut ops = self.op_log()?;
62410×
        ops.reverse();
62510×
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
626
        // The fast-import parent of the next commit: `:mark` or a commit sha.
62710×
        let mut last_parent: Option<String> = None;
62844×
        for (_, op) in &ops {
62944×
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
6300×
                continue;
631
            };
63244×
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
63312×
                continue;
63432×
            }
63532×
            let Ok(state) = self.store.get_state(&state_ref) else {
6360×
                continue;
637
            };
63832×
            if state.heads.is_empty() {
63910×
                prev = Some((state_ref, vec![]));
64010×
                continue;
64122×
            }
64222×
            if let Some(sha) = git_states.get(&state_ref) {
6434×
                report.skipped += 1;
6444×
                last_parent = Some(sha.clone());
6454×
                prev = Some((state_ref, state.heads.clone()));
6464×
                continue;
64718×
            }
64818×
            if let Some(m) = marks.get(&state_ref) {
6499×
                report.skipped += 1;
6509×
                last_parent = Some(format!(":{m}"));
6519×
                prev = Some((state_ref, state.heads.clone()));
6529×
                continue;
6539×
            }
6549×
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
6559×
            let added = self
6569×
                .negotiate(&prev_heads, &state.heads)
6579×
                .unwrap_or_default();
6589×
            let loaded = self.load_state(&state.heads)?;
6599×
            let snapshot = loaded.materialize();
6609×
            let (author, secs, mut message) = match added.as_slice() {
6616×
                [h] => {
6626×
                    let c = self.store.get_change(h)?;
6636×
                    let mut m = c.message.clone();
6646×
                    if !m.ends_with('\n') {
6656×
                        m.push('\n');
6666×
                    }
6676×
                    m.push_str(&format!(
6686×
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
6696×
                        c.change_id.to_hex(),
6706×
                        h.to_hex()
6716×
                    ));
6726×
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
673
                }
6743×
                [] => (
6750×
                    "oxy <oxy@localhost>".to_string(),
6760×
                    op.hlc.wall_ms / 1000,
6770×
                    format!("oxy: {}\n\n", op.command),
6780×
                ),
6793×
                many => {
6803×
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
68122×
                    for h in many {
68222×
                        let c = self.store.get_change(h)?;
68322×
                        m.push_str(&format!(
68422×
                            "- {} {}\n",
68522×
                            c.change_id.short(8),
68622×
                            c.message.lines().next().unwrap_or("")
68722×
                        ));
688
                    }
6893×
                    m.push_str(&format!(
690
                        "\nOxy-Changes: {}\n",
6913×
                        many.iter()
69222×
                            .map(|h| h.to_hex())
6933×
                            .collect::<Vec<_>>()
6943×
                            .join(" ")
695
                    ));
6963×
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
697
                }
698
            };
6999×
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
7009×
            if snapshot.is_conflicted() {
7010×
                message.push_str("Oxy-Conflicted: true\n");
7029×
            }
7039×
            let mark = next_mark;
7049×
            next_mark += 1;
7059×
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
7069×
            self.write_commit(
7079×
                &mut stream,
7089×
                "refs/oxy/export",
7099×
                mark,
7109×
                &author,
7119×
                secs,
7129×
                &message,
7139×
                &parents,
7149×
                &snapshot,
7150×
            )?;
7169×
            marks.insert(state_ref, mark);
7179×
            last_parent = Some(format!(":{mark}"));
7189×
            prev = Some((state_ref, state.heads.clone()));
7199×
            report.exported += 1;
720
        }
72110×
        if let Some(p) = &last_parent {
72210×
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
72310×
        }
724
        // Tags: a tag whose state was exported as a bookmark state points at
725
        // that commit; otherwise its state gets a commit of its own.
72610×
        for t in self.tags()? {
7270×
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
7280×
                (Some(sha), _) => sha.clone(),
7290×
                (None, Some(m)) => format!(":{m}"),
730
                (None, None) => {
7310×
                    let loaded = self.load_state(&t.heads)?;
7320×
                    let snapshot = loaded.materialize();
7330×
                    let mark = next_mark;
7340×
                    next_mark += 1;
7350×
                    let message = format!(
736
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
737
                        t.name,
7380×
                        if t.message.is_empty() {
7390×
                            String::new()
740
                        } else {
7410×
                            format!("{}\n\n", t.message)
742
                        },
7430×
                        t.state.to_hex()
744
                    );
7450×
                    self.write_commit(
7460×
                        &mut stream,
7470×
                        "refs/oxy/export",
7480×
                        mark,
7490×
                        "oxy <oxy@localhost>",
7500×
                        Hlc::now().wall_ms / 1000,
7510×
                        &message,
7520×
                        &[],
7530×
                        &snapshot,
7540×
                    )?;
7550×
                    marks.insert(t.state, mark);
7560×
                    report.exported += 1;
7570×
                    format!(":{mark}")
758
                }
759
            };
7600×
            stream.extend_from_slice(
7610×
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
762
            );
763
        }
76410×
        stream.extend_from_slice(b"done\n");
765
76610×
        let mut cmd = Command::new("git");
767
        // `--force`: the scratch ref may jump between unrelated states.
76810×
        cmd.arg("-C")
76910×
            .arg(git_dir)
77010×
            .args(["fast-import", "--quiet", "--done", "--force"])
77110×
            .arg(format!("--export-marks={}", git_marks.display()));
77210×
        if git_marks.exists() {
7735×
            cmd.arg(format!("--import-marks={}", git_marks.display()));
7745×
        }
77510×
        let mut child = cmd
77610×
            .stdin(Stdio::piped())
77710×
            .stdout(Stdio::null())
77810×
            .stderr(Stdio::piped())
77910×
            .spawn()
78010×
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
78110×
        child.stdin.take().unwrap().write_all(&stream)?;
78210×
        let out = child.wait_with_output()?;
78310×
        if !out.status.success() {
7840×
            return fail(format!(
785
                "git fast-import failed: {}",
7860×
                String::from_utf8_lossy(&out.stderr).trim()
787
            ));
78810×
        }
78910×
        let text: String = marks
79010×
            .iter()
79118×
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
79210×
            .collect();
79310×
        write_atomic(&oxy_marks_path, text.as_bytes())?;
79410×
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
79510×
        report.skipped_subrepos = self.git_export_skipped.replace(0);
79610×
        Ok(report)
79710×
    }
798
799
    /// Import branch `branch` of the Git repository at `git_dir` into this
800
    /// (empty) repository's bookmark (spec §23): one change per commit, its
801
    /// edits the difference between the union of its parents' states and its
802
    /// tree, so merge commits become resolutions. Submodules are skipped.
80311×
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
80411×
        self.import_git_with(git_dir, branch, &mut |_| {})
80511×
    }
806
807
    /// `import_git`, telling `progress` where it is every few hundred
808
    /// commits: the count so far, the merges, and the commit in hand, so a
809
    /// long import is never silent and a run that dies says where.
81011×
    pub fn import_git_with(
81111×
        &self,
81211×
        git_dir: &Path,
81311×
        branch: &str,
81411×
        progress: crate::store::Progress<'_>,
81511×
    ) -> Result<GitImportReport> {
81611×
        if !self.bookmark_heads()?.is_empty() {
8170×
            return fail("git import needs an empty bookmark; import into a fresh repository");
81811×
        }
81911×
        self.import_git_commits(
82011×
            git_dir,
82111×
            branch,
82211×
            &format!("oxy git import {} {branch}", git_dir.display()),
82311×
            progress,
824
        )
82511×
    }
826
827
    /// Import the commits of `branch` that the bookmark does not have yet,
828
    /// then move the bookmark to the union of its heads and theirs.
82914×
    fn import_git_commits(
83014×
        &self,
83114×
        git_dir: &Path,
83214×
        branch: &str,
83314×
        command: &str,
83414×
        progress: crate::store::Progress<'_>,
83514×
    ) -> Result<GitImportReport> {
83614×
        let batch = self.store.begin_batch()?;
83714×
        let result = self.import_git_commits_batched(git_dir, branch, command, progress);
83814×
        batch.finish()?;
83914×
        result
84014×
    }
841
84214×
    fn import_git_commits_batched(
84314×
        &self,
84414×
        git_dir: &Path,
84514×
        branch: &str,
84614×
        command: &str,
84714×
        progress: crate::store::Progress<'_>,
84814×
    ) -> Result<GitImportReport> {
84914×
        let commits = list_commits(git_dir, branch)?;
85014×
        let mut cat = CatFile::start(git_dir)?;
85114×
        let mut report = GitImportReport::default();
85214×
        let mut known = self.git_known(git_dir)?;
85314×
        let old_heads = self.bookmark_heads()?;
854
        // The bookmark's heads as changes arrive: a change stops being a
855
        // head when another depends on it, so no full state of every
856
        // imported change is needed at the end.
85714×
        let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect();
858
        // The state and Git tree of imported commits whose first-parent
859
        // children are still to come, so a child starts from its parent's
860
        // state instead of rebuilding it from history. The last child takes
861
        // it; earlier ones clone it. At most `max_kept` are kept (a later
862
        // child of an evicted one rebuilds).
863
        // OXY_IMPORT_KEEP overrides it, for measuring.
86414×
        let max_kept: usize = std::env::var("OXY_IMPORT_KEEP")
86514×
            .ok()
86614×
            .and_then(|v| v.parse().ok())
86714×
            .unwrap_or(8);
86814×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
86985×
        for gc in &commits {
87085×
            if let Some(p1) = gc.parents.first() {
87169×
                *waiting.entry(p1.as_str()).or_default() += 1;
87269×
            }
873
        }
874
        type Kept = (State, BTreeMap<String, (String, String)>);
87514×
        let mut kept: HashMap<String, Kept> = HashMap::new();
876
        // Every commit to import that has a parent, diffed against its first.
87714×
        let pairs: Vec<(String, String)> = commits
87814×
            .iter()
87985×
            .filter(|gc| {
88085×
                !known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha)
88185×
            })
88280×
            .filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone())))
88314×
            .collect();
88414×
        let mut diffs = DiffTree::start(git_dir, pairs)?;
88514×
        let mut rebuilt = 0usize;
88614×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
88714×
        let mut last: Option<String> = None;
88814×
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
88914×
        let mut cache_bytes: usize = 0;
890
        // Time spent per phase over all commits (`OXY_TIMINGS=1`).
89114×
        let mut spent = [std::time::Duration::ZERO; 6];
89214×
        let mut clock = std::time::Instant::now();
893
        // One line per commit on stderr with OXY_IMPORT_TRACE=1: where its
894
        // base came from, what a merge added, the graphs its state holds,
895
        // the kept states and the process's resident memory.
89614×
        let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some();
89714×
        let rss_mb = || -> u64 {
8980×
            std::fs::read_to_string("/proc/self/statm")
8990×
                .ok()
9000×
                .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
9010×
                .map(|pages| (pages * 4096) >> 20)
9020×
                .unwrap_or(0)
9030×
        };
90414×
        let mut done = 0usize;
905
        // Atoms a kept state's graphs may hold before they are shed;
906
        // OXY_IMPORT_KEPT_ATOMS overrides it, for measuring.
90714×
        let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS")
90814×
            .ok()
90914×
            .and_then(|v| v.parse().ok())
91014×
            .unwrap_or(KEPT_ATOMS);
911
        // Graphs turned back into history (see `State::shed_graphs`).
91214×
        let mut shed = 0usize;
913480×
        let mut lap = |i: usize, clock: &mut std::time::Instant| {
914480×
            let now = std::time::Instant::now();
915480×
            spent[i] += now - *clock;
916480×
            *clock = now;
917480×
        };
918
91914×
        let total = commits.len();
92085×
        for (index, gc) in commits.iter().enumerate() {
92185×
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
9225×
                continue;
92380×
            }
92480×
            if index % 500 == 0 {
92512×
                progress(&format!(
92612×
                    "{index} of {total} commits, {} merges; at {} {}",
92712×
                    report.merges,
92812×
                    &gc.sha[..12.min(gc.sha.len())],
92912×
                    gc.message
93012×
                        .lines()
93112×
                        .next()
93212×
                        .unwrap_or("")
93312×
                        .chars()
93412×
                        .take(60)
93512×
                        .collect::<String>()
93612×
                ));
93768×
            }
93880×
            let mut base_how = "root";
939
            // Base: union of every parent's state, starting from the first
940
            // parent's kept state when there is one; its tree tells which
941
            // paths this commit leaves alone.
94280×
            let (mut base, prev_tree) = match gc.parents.first() {
94366×
                Some(p1) => {
94466×
                    let left = waiting.get_mut(p1.as_str()).map(|n| {
94566×
                        *n -= 1;
94666×
                        *n
94766×
                    });
94866×
                    let found = if left == Some(0) {
94965×
                        kept_order.retain(|k| k != p1);
95047×
                        kept.remove(p1.as_str())
951
                    } else {
95219×
                        kept.get(p1.as_str()).cloned()
953
                    };
95466×
                    let how = match (&found, left) {
95546×
                        (Some(_), Some(0)) => "kept",
95619×
                        (Some(_), _) => "cloned",
9571×
                        (None, _) => "rebuilt",
958
                    };
95966×
                    if trace {
9600×
                        base_how = how;
96166×
                    }
96266×
                    match found {
96365×
                        Some((st, tree)) => (st, Some(tree)),
964
                        None => {
965
                            // History only: graphs are built for the files a
966
                            // commit changes, so memory follows what changes,
967
                            // not the whole tree.
9681×
                            let mut st = State::new_history_only();
9691×
                            self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
970
                            // The parent's tree, so this commit still
971
                            // renders only what it changes.
9721×
                            rebuilt += 1;
9731×
                            (st, Some(list_tree(git_dir, p1)?))
974
                        }
975
                    }
976
                }
97714×
                None => (State::new_history_only(), None),
978
            };
979
            // Nodes the other parents' changes touch: the first parent's
980
            // tree cannot vouch for them.
98180×
            let mut touched: HashSet<NodeId> = HashSet::new();
98280×
            let mut merged = 0usize;
98380×
            if gc.parents.len() > 1 {
98423×
                report.merges += 1;
98523×
                let mut args: Vec<String> = gc.parents[1..].to_vec();
98623×
                args.push(format!("^{}", gc.parents[0]));
98723×
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
988
                // A merge of a long-lived branch brings thousands of
989
                // changes: added to built graphs, which kept states share,
990
                // they were copied and applied whole (vscode's import passed
991
                // 14 GB on such merges). Shed the graphs first, so the
992
                // changes go in as skeletons and only what this commit
993
                // touches is built again.
99423×
                if base.built_count() > 0 {
99519×
                    let mut count_args = vec!["rev-list", "--count"];
99619×
                    count_args.extend(refs.iter().copied());
99719×
                    let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0);
99819×
                    let shed_at = std::env::var("OXY_MERGE_SHED")
99919×
                        .ok()
100019×
                        .and_then(|v| v.parse().ok())
100119×
                        .unwrap_or(MERGE_SHED_COMMITS);
100219×
                    if others > shed_at {
10030×
                        shed += base.shed_graphs(|b| self.store_blob(b))?;
100419×
                    }
10054×
                }
100623×
                let before = base.len();
100723×
                self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?;
100823×
                merged = base.len() - before;
100957×
            }
101080×
            lap(0, &mut clock);
1011
            // The commit's tree: its first parent's with the diff applied,
1012
            // or listed whole when that tree is not kept.
101380×
            let diff = match gc.parents.first() {
101466×
                Some(_) => Some(diffs.diff(&gc.sha)?),
101514×
                None => None,
1016
            };
101780×
            let (tree, changed) = match (prev_tree, diff) {
101866×
                (Some(mut t), Some(diff)) => {
101966×
                    let mut changed: HashSet<String> = HashSet::new();
102082×
                    for (path, entry) in diff {
102182×
                        match entry {
102268×
                            Some(v) => {
102368×
                                t.insert(path.clone(), v);
102468×
                            }
102514×
                            None => {
102614×
                                t.remove(&path);
102714×
                            }
1028
                        }
102982×
                        changed.insert(path);
1030
                    }
103166×
                    (t, Some(changed))
1032
                }
103314×
                _ => (list_tree(git_dir, &gc.sha)?, None),
1034
            };
103580×
            lap(1, &mut clock);
1036
            // Text files with the same blob and mode as in the first
1037
            // parent's tree equal the base's rendering: they are neither
1038
            // rendered nor read nor compared (spec §12.3, as for a clean
1039
            // working copy), so a commit costs what it changes.
104080×
            let mut same: HashMap<&str, NodeId> = HashMap::new();
1041
            // Opaque files and symlinks likewise, when the base has one
1042
            // blob for them: they are neither read nor stored again.
104380×
            let mut same_opaque: HashSet<&str> = HashSet::new();
1044
            // An ordinary commit in a tree without submodules is built from
1045
            // the paths it changes alone (oxygen#25): with the `.oxyattributes`
1046
            // files that decide how they are stored, and the directories its
1047
            // removals may leave empty. A merge, or a commit whose parent's
1048
            // tree is not at hand, is built from its whole tree.
104980×
            let partial = changed.is_some()
105066×
                && gc.parents.len() == 1
1051107×
                && !tree.values().any(|(mode, _)| mode == "160000");
105280×
            let mut rel: BTreeSet<&str> = BTreeSet::new();
105380×
            let base_snapshot = if let (true, Some(changed)) = (partial, &changed) {
105442×
                let view = base.tree().view();
105542×
                rel.extend(changed.iter().map(String::as_str));
105642×
                rel.extend(
105742×
                    tree.keys()
105842×
                        .map(String::as_str)
1059104×
                        .filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")),
1060
                );
106142×
                let mut dirs: BTreeSet<&str> = BTreeSet::new();
106261×
                for p in changed.iter().filter(|p| !tree.contains_key(*p)) {
106314×
                    let mut end = p.len();
106424×
                    while let Some(i) = p[..end].rfind('/') {
106510×
                        if !dirs.insert(&p[..i]) {
10660×
                            break;
106710×
                        }
106810×
                        end = i;
1069
                    }
1070
                }
107142×
                let need: Vec<NodeId> = rel
107242×
                    .iter()
107361×
                    .filter_map(|p| view.entries.get(*p))
107442×
                    .filter(|e| e.kind == NodeKind::File && !e.mode.opaque)
107542×
                    .map(|e| e.node)
107642×
                    .collect();
107742×
                crate::timing::add("render: same and need", clock.elapsed());
107842×
                let t = std::time::Instant::now();
107942×
                self.load_graphs_of(&mut base, &need)?;
108042×
                crate::timing::add("render: load graphs", t.elapsed());
108142×
                let t = std::time::Instant::now();
108242×
                let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied());
108342×
                crate::timing::add("render: materialize", t.elapsed());
108442×
                snap
1085
            } else {
108638×
                if let Some(changed) = &changed {
108724×
                    let view = base.tree().view();
108873×
                    for path in tree.keys() {
1089
                        // Submodule handling reads these two whatever changed.
109073×
                        if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules"
1091
                        {
109221×
                            continue;
109352×
                        }
109452×
                        if let Some(e) = view.entries.get(path) {
109548×
                            if touched.contains(&e.node) {
10968×
                                continue;
109740×
                            }
109840×
                            let opaque = e.kind == NodeKind::Symlink
109940×
                                || (e.kind == NodeKind::File && e.mode.opaque);
110040×
                            if e.kind == NodeKind::File && !e.mode.opaque {
110132×
                                same.insert(path.as_str(), e.node);
110232×
                            } else if opaque && base.live_blobs(&e.node).len() == 1 {
11038×
                                same_opaque.insert(path.as_str());
11048×
                            }
11054×
                        }
1106
                    }
110714×
                }
1108
                // Build the graphs of every text file the commit may change.
110938×
                let skip: HashSet<NodeId> = same.values().copied().collect();
111038×
                let need: Vec<NodeId> = base
111138×
                    .tree()
111238×
                    .view()
111338×
                    .entries
111438×
                    .values()
111588×
                    .filter(|e| {
111688×
                        e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node)
111788×
                    })
111838×
                    .map(|e| e.node)
111938×
                    .collect();
112038×
                crate::timing::add("render: same and need", clock.elapsed());
112138×
                let t = std::time::Instant::now();
112238×
                let snap = if need.len() > merge_batch() {
1123
                    // A merge onto a base with no built graphs: thousands
1124
                    // of files, whose graphs would not fit at once.
11257×
                    self.materialize_batched(&mut base, &need, &skip)?
1126
                } else {
112731×
                    self.load_graphs_of(&mut base, &need)?;
112831×
                    base.materialize_except(&skip)
1129
                };
113038×
                crate::timing::add("render: whole tree", t.elapsed());
113138×
                snap
1132
            };
1133
113480×
            lap(2, &mut clock);
1135
            // The commit's tree as in-memory entries.
113680×
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
113780×
            let mut gitlinks: Vec<(String, String)> = Vec::new();
113880×
            let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial {
113961×
                Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p)))
1140
            } else {
114138×
                Box::new(tree.iter())
1142
            };
1143145×
            for (path, (mode, sha)) in listed {
1144145×
                let (path, sha) = (path.clone(), sha.clone());
1145145×
                let (kind, exec) = match mode.as_str() {
1146145×
                    "100644" | "100664" => (NodeKind::File, false),
114721×
                    "100755" => (NodeKind::File, true),
11481×
                    "120000" => (NodeKind::Symlink, false),
11491×
                    "160000" => {
11501×
                        gitlinks.push((path, sha));
11511×
                        continue;
1152
                    }
11530×
                    _ => continue,
1154
                };
1155144×
                if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) {
115640×
                    let mut e = FsEntry::new(kind, exec, Vec::new());
115740×
                    e.unchanged = true;
115840×
                    entries.insert(path, e);
115940×
                    continue;
1160104×
                }
1161104×
                let content = match blob_cache.get(&sha) {
116232×
                    Some(c) => c.clone(),
1163
                    None => {
116472×
                        let c = cat.read(&sha)?;
116572×
                        if cache_bytes + c.len() > 64 * 1024 * 1024 {
11660×
                            blob_cache.clear();
11670×
                            cache_bytes = 0;
116872×
                        }
116972×
                        cache_bytes += c.len();
117072×
                        blob_cache.insert(sha.clone(), c.clone());
117172×
                        c
1172
                    }
1173
                };
1174104×
                entries.insert(path, FsEntry::new(kind, exec, content));
1175
            }
1176
1177
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
1178
            // pins, and `.gitmodules` also yields `.oxymodules`.
117980×
            if !gitlinks.is_empty() {
11801×
                report.submodules += gitlinks.len();
11811×
                let gm = entries
11821×
                    .get(".gitmodules")
11831×
                    .map(|e| {
11841×
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
11851×
                            &e.content,
11861×
                        ))
11871×
                    })
11881×
                    .unwrap_or_default();
11891×
                let mut modules = entries
11901×
                    .get(".oxymodules")
11911×
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
11921×
                    .unwrap_or_default();
11931×
                for (path, sha) in &gitlinks {
11941×
                    let m = gm.entries.get(path);
11951×
                    let branch = m
11961×
                        .and_then(|m| m.bookmark.clone())
11971×
                        .unwrap_or_else(|| "HEAD".into());
11981×
                    entries.insert(
11991×
                        path.clone(),
12001×
                        FsEntry::new(
12011×
                            NodeKind::Subrepo,
1202
                            false,
12031×
                            crate::subrepo::Pin::Git {
12041×
                                sha: sha.clone(),
12051×
                                branch,
12061×
                            }
12071×
                            .encode(),
1208
                        ),
1209
                    );
12101×
                    if let Some(m) = m {
12111×
                        modules.entries.insert(path.clone(), m.clone());
12121×
                    }
1213
                }
12141×
                if !modules.entries.is_empty() {
12151×
                    entries.insert(
12161×
                        ".oxymodules".into(),
12171×
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
12181×
                    );
12191×
                }
122079×
            }
122180×
            lap(3, &mut clock);
1222
            // New nodes' identifiers derive from the commit, so importing the
1223
            // same Git history twice gives the same changes (spec §23).
122480×
            let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes();
122580×
            let mut built = if partial {
1226
                // Whether the new tree has anything under `dir`.
122742×
                let dir_needed = |dir: &str| {
122810×
                    let prefix = format!("{dir}/");
122910×
                    tree.range(prefix.clone()..)
123010×
                        .next()
123110×
                        .is_some_and(|(k, _)| k.starts_with(&prefix))
123210×
                };
123342×
                self.build_from_entries_seeded(
123442×
                    &base,
123542×
                    &base_snapshot,
123642×
                    &entries,
123742×
                    seed,
123842×
                    Some(&dir_needed),
12390×
                )?
1240
            } else {
124138×
                self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)?
1242
            };
124380×
            lap(4, &mut clock);
1244
            // A file or submodule with several live blobs (branches that
1245
            // replaced it independently) is resolved to the commit's blob:
1246
            // Git's merge is the authority here, unlike a working copy,
1247
            // where a candidate on disk is not yet a decision (spec §23).
1248139×
            for (path, f) in &base_snapshot.files {
1249139×
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
1250
                else {
1251127×
                    continue;
1252
                };
125312×
                if blobs.len() < 2 || f.kind != e.kind {
125411×
                    continue;
12551×
                }
12561×
                let chosen = self.store_blob(&e.content)?;
12572×
                for b in blobs {
12582×
                    built.edits.push(Edit::Replace {
12592×
                        node: f.node,
12602×
                        old: Some(*b),
12612×
                        new: Some(chosen),
12622×
                    });
12632×
                }
12641×
                built.resolves = true;
12651×
                built
12661×
                    .contributors
12671×
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
1268
            }
1269
            // It shares the base's tree view, which applying the change
1270
            // then updates in place rather than copying.
127180×
            drop(base_snapshot);
127280×
            drop(entries);
127380×
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
127480×
            let mut message = gc.message.clone();
127580×
            if !message.ends_with('\n') {
127680×
                message.push('\n');
127780×
            }
127880×
            message.push_str(&format!(
127980×
                "\nGit-Commit: {}\nGit-Author: {}\n",
128080×
                gc.sha, gc.author
128180×
            ));
128280×
            let mut change = Change {
1283
                version: crate::objects::CHANGE_VERSION,
128480×
                change_id: change_id_for(&gc.sha, &gc.message),
128580×
                deps: vec![],
1286
                author: ObjectRef::ZERO,
128780×
                hlc: Hlc {
128880×
                    wall_ms: gc.author_secs * 1000,
128980×
                    logical: 0,
129080×
                },
129180×
                message,
129280×
                tree_ops: built.tree_ops,
129380×
                edits: built.edits,
129480×
                kind: if built.resolves {
129512×
                    ChangeKind::Resolution
1296
                } else {
129768×
                    ChangeKind::Normal
1298
                },
1299
            };
130080×
            let t = std::time::Instant::now();
1301
            // A deletion depends on whoever inserted the live atoms after
1302
            // it, which only the file's graph knows: build the few the
1303
            // batched rendering left deferred.
130480×
            let need: Vec<NodeId> = change
130580×
                .edits
130680×
                .iter()
130789×
                .filter(|e| matches!(e, Edit::Delete { .. }))
130880×
                .map(|e| e.node())
130980×
                .filter(|n| !base.is_built(n))
131080×
                .collect();
131180×
            if !need.is_empty() {
13120×
                self.load_graphs_of(&mut base, &need)?;
131380×
            }
131480×
            deps.extend(referenced_changes(&change, &base));
131580×
            crate::timing::add("store: referenced", t.elapsed());
131680×
            change.deps = deps.into_iter().collect();
131780×
            change.normalize();
131880×
            let hash = self.store.put_change(&change)?;
131988×
            for d in &change.deps {
132088×
                heads_now.remove(d);
132188×
            }
132280×
            heads_now.insert(hash);
1323
            // Built graphs take its edits whole; files not built keep only
1324
            // where its text is, read back from the store.
132580×
            let t = std::time::Instant::now();
132680×
            let (skeleton, texts) = self.store.get_change_lazy(&hash)?;
132780×
            base.add_known_mixed(hash, change, skeleton, texts);
132880×
            crate::timing::add("store: add to state", t.elapsed());
132980×
            known.imported.insert(gc.sha.clone(), hash);
133080×
            if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) {
1331
                // A kept state holds its graphs until its children come:
1332
                // past a few thousand, they go back into its history.
1333
                // Past a few thousand graphs, or past a budget of atoms: a
1334
                // long-lived file's graph keeps every line it ever had, so a
1335
                // handful of them can hold gigabytes (#25).
133646×
                if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms {
13370×
                    shed += base.shed_graphs(|b| self.store_blob(b))?;
133846×
                }
133946×
                kept.insert(gc.sha.clone(), (base, tree));
134046×
                kept_order.push_back(gc.sha.clone());
134146×
                if kept_order.len() > max_kept {
13420×
                    if let Some(old) = kept_order.pop_front() {
13430×
                        kept.remove(&old);
13440×
                    }
134546×
                }
134634×
            }
134780×
            last = Some(gc.sha.clone());
134880×
            report.commits += 1;
134980×
            lap(5, &mut clock);
135080×
            done += 1;
1351
            // A merge renders thousands of files on many threads and frees
1352
            // it all; the allocator keeps those pages unless asked to give
1353
            // them back, and the next merge piles on top (#25).
135480×
            let before_trim = if trace { rss_mb() } else { 0 };
135580×
            if gc.parents.len() > 1 {
135623×
                crate::alloc_stats::release_freed_memory();
135757×
            }
135880×
            if trace {
13590×
                let built = kept
13600×
                    .get(gc.sha.as_str())
13610×
                    .map(|(st, _)| st.built_count())
13620×
                    .unwrap_or(0);
13630×
                let (edits, most) = kept
13640×
                    .get(gc.sha.as_str())
13650×
                    .map(|(st, _)| st.deferred_edit_count())
13660×
                    .unwrap_or((0, 0));
13670×
                let atoms = kept
13680×
                    .get(gc.sha.as_str())
13690×
                    .map(|(st, _)| st.built_atoms())
13700×
                    .unwrap_or(0);
13710×
                eprintln!(
1372
                    "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}",
13730×
                    &gc.sha[..12.min(gc.sha.len())],
13740×
                    gc.parents.len(),
13750×
                    kept.len(),
13760×
                    rss_mb()
1377
                );
137880×
            }
1379
        }
138084×
        for (name, d) in [
138114×
            "git import: bases",
138214×
            "git import: tree",
138314×
            "git import: render base",
138414×
            "git import: read blobs",
138514×
            "git import: build change",
138614×
            "git import: store change",
138714×
        ]
138814×
        .iter()
138914×
        .zip(spent)
139084×
        {
139184×
            crate::timing::record(name, d);
139284×
        }
139314×
        crate::timing::report_totals();
139414×
        if crate::timing::enabled() {
13950×
            eprintln!(
13960×
                "timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed"
13970×
            );
139814×
        }
1399
1400
        // The bookmark: heads of the old state plus every new change.
140114×
        report.heads = old_heads.len();
140214×
        if last.is_none() {
14031×
            return Ok(report);
140413×
        }
140513×
        let heads: Vec<ChangeHash> = heads_now.into_iter().collect();
140613×
        report.heads = heads.len();
140713×
        let (op_ref, op) = self.head_op()?;
140813×
        let mut view = op.view.clone();
140913×
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
141013×
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
141113×
        view.bookmarks
141213×
            .insert(self.config.bookmark.clone(), state_ref);
141313×
        self.record_op(&[op_ref], command, view)?;
1414
        // The new state equals the tip's tree when the old one was itself a
1415
        // Git commit's tree (fetched or exported), or there was none.
141613×
        let old_known = old_heads.is_empty()
14171×
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
141813×
        if let (Some(tip), true) = (commits.last(), old_known) {
141913×
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
14200×
        }
1421
        // The working copy follows when it was clean on the old heads.
142213×
        if old_heads.is_empty() {
142312×
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
1424
        } else {
14251×
            let snap = self.snapshot(command)?;
14261×
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
14271×
            let mut base = snap.base.maximal(&snap.wc.deps);
14281×
            base.sort();
14291×
            let mut sorted_old = old_heads.clone();
14301×
            sorted_old.sort();
14311×
            if clean && base == sorted_old {
14321×
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
14330×
            }
1434
        }
143513×
        Ok(report)
143614×
    }
1437
1438
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
1439
    /// an imported commit's change, or the whole state an exported commit
1440
    /// was made from (which may hold changes Git never saw).
14411×
    fn add_git_ancestors(
14421×
        &self,
14431×
        st: &mut State,
14441×
        git_dir: &Path,
14451×
        args: &[&str],
14461×
        known: &GitKnown,
14471×
    ) -> Result<()> {
14481×
        self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new())
14491×
    }
1450
1451
    /// `add_git_ancestors`, also collecting in `touched` every node the
1452
    /// changes it adds edit, place or remove.
145324×
    fn add_git_ancestors_touching(
145424×
        &self,
145524×
        st: &mut State,
145624×
        git_dir: &Path,
145724×
        args: &[&str],
145824×
        known: &GitKnown,
145924×
        touched: &mut HashSet<NodeId>,
146024×
    ) -> Result<()> {
146124×
        let mut full = vec!["rev-list"];
146224×
        full.extend(args);
146324×
        let out = git(git_dir, &full)?;
146431×
        let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> {
146531×
            if st.contains(h) {
14662×
                return Ok(());
146729×
            }
146829×
            if !st.is_history_only() {
14690×
                let c = self.store.get_change(h)?;
14700×
                touched.extend(c.edits.iter().map(|e| e.node()));
14710×
                touched.extend(c.tree_ops.iter().map(|o| o.node()));
14720×
                st.add_unchecked(c);
14730×
                return Ok(());
147429×
            }
1475
            // History only: the text of an edit waits unread unless its
1476
            // file's graph is built.
147729×
            let (skeleton, texts) = self.store.get_change_lazy(h)?;
147832×
            touched.extend(skeleton.edits.iter().map(|e| e.node()));
147929×
            touched.extend(skeleton.tree_ops.iter().map(|o| o.node()));
148029×
            let built = skeleton
148129×
                .edits
148229×
                .iter()
148332×
                .any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node()));
148429×
            if built {
14854×
                let full = self.store.get_change(h)?;
14864×
                st.add_known_mixed(*h, full, skeleton, texts);
148725×
            } else {
148825×
                st.add_known(*h, skeleton, texts);
148925×
            }
149029×
            Ok(())
149131×
        };
149229×
        for sha in out.lines() {
149329×
            if let Some(h) = known.imported.get(sha) {
149428×
                add(st, h)?;
14951×
            } else if let Some(state_ref) = known.exported.get(sha) {
14961×
                let heads = self.store.get_state(state_ref)?.heads;
14973×
                for h in self.negotiate(&[], &heads)? {
14983×
                    add(st, &h)?;
1499
                }
15000×
            }
1501
        }
150224×
        Ok(())
150324×
    }
1504
1505
    /// Commits this repository can relate to Oxygen history: imported
1506
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
150718×
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
150818×
        let imported = self.imported_commits()?;
150918×
        let marks_dir = self.git_marks_dir(git_dir)?;
151018×
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
151118×
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
151218×
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
15134×
            for line in text.lines() {
15144×
                if let Some((m, sha)) = line.split_once(' ') {
15154×
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
15164×
                        sha_of_mark.insert(m, sha.trim().to_string());
15174×
                    }
15180×
                }
1519
            }
152014×
        }
152118×
        let mut exported = HashMap::new();
152218×
        for (state_ref, m) in oxy_marks {
15234×
            if let Some(sha) = sha_of_mark.get(&m) {
15244×
                exported.insert(sha.clone(), state_ref);
15254×
            }
1526
        }
152718×
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
15287×
            exported.entry(sha).or_insert(state_ref);
15297×
        }
153018×
        Ok(GitKnown { imported, exported })
153118×
    }
1532
15336×
    fn git_author(&self, c: &Change) -> String {
15346×
        match self.store.get_identity(&c.author) {
15356×
            Ok(id) if !id.name.is_empty() => format!(
1536
                "{} <{}>",
15376×
                id.name.replace(['<', '>', '\n'], " "),
15386×
                id.email.replace(['<', '>', '\n', ' '], "")
1539
            ),
15400×
            _ => "oxy <oxy@localhost>".to_string(),
1541
        }
15426×
    }
1543
1544
    #[allow(clippy::too_many_arguments)]
15459×
    fn write_commit(
15469×
        &self,
15479×
        out: &mut Vec<u8>,
15489×
        reference: &str,
15499×
        mark: u64,
15509×
        author: &str,
15519×
        secs: u64,
15529×
        message: &str,
15539×
        parents: &[String],
15549×
        snapshot: &Snapshot,
15559×
    ) -> Result<()> {
15569×
        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());
15579×
        for (i, p) in parents.iter().enumerate() {
15585×
            out.extend_from_slice(
15595×
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
1560
            );
1561
        }
15629×
        out.extend_from_slice(b"deleteall\n");
15639×
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
156438×
        for (path, f) in &snapshot.files {
156538×
            if path == ".oxymodules" {
1566
                // Git reads `.gitmodules`; derive it unless the tree has one.
15671×
                if !has_gitmodules {
15680×
                    if let FileContent::Text { bytes, .. } = &f.content {
15690×
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
15700×
                            .to_gitmodules();
15710×
                        if !gm.is_empty() {
15720×
                            out.extend_from_slice(
15730×
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
15740×
                                    .as_bytes(),
15750×
                            );
15760×
                            out.extend_from_slice(gm.as_bytes());
15770×
                            out.push(b'\n');
15780×
                        }
15790×
                    }
15801×
                }
15811×
                continue;
158237×
            }
158337×
            if f.kind == NodeKind::Subrepo {
15841×
                if let FileContent::Opaque { blobs } = &f.content {
15851×
                    if let Some(b) = blobs.first() {
15861×
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
15871×
                            crate::subrepo::Pin::Git { sha, .. } => {
15881×
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
1589
                            }
15900×
                            crate::subrepo::Pin::Oxy { .. } => self
15910×
                                .git_export_skipped
15920×
                                .set(self.git_export_skipped.get() + 1),
1593
                        }
15940×
                    }
15950×
                }
15961×
                continue;
159736×
            }
159836×
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
15999×
                (NodeKind::Dir, _) => continue,
16000×
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
16010×
                    "120000",
16020×
                    blobs
16030×
                        .first()
16040×
                        .map(|b| self.read_blob(b))
16050×
                        .transpose()?
16060×
                        .unwrap_or_default(),
1607
                ),
160824×
                (_, FileContent::Text { bytes, .. }) => {
160924×
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
1610
                }
16113×
                (_, FileContent::Opaque { blobs }) => (
16123×
                    if f.mode.exec { "100755" } else { "100644" },
16133×
                    blobs
16143×
                        .first()
16153×
                        .map(|b| self.read_blob(b))
16163×
                        .transpose()?
16173×
                        .unwrap_or_default(),
1618
                ),
16190×
                (_, FileContent::Dir) => continue,
1620
            };
162127×
            out.extend_from_slice(
162227×
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
1623
            );
162427×
            out.extend_from_slice(&bytes);
162527×
            out.push(b'\n');
1626
        }
16279×
        out.push(b'\n');
16289×
        Ok(())
16299×
    }
1630
}
1631
1632
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
1633
#[derive(Debug, Clone, Default, PartialEq, Eq)]
1634
pub struct GitVerifyReport {
1635
    pub commits: usize,
1636
    /// Commits followed but not rebuilt (all but the last few, when asked).
1637
    pub skipped: usize,
1638
    pub files_compared: usize,
1639
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
1640
    pub mismatches: Vec<(String, String)>,
1641
}
1642
1643
impl Repo {
1644
    /// Check an import against its Git source: for every commit of
1645
    /// `branch`, the state formed by the changes imported for it and all
1646
    /// its ancestors must materialize to exactly that commit's tree, byte
1647
    /// for byte, with the same executable bits, symlink targets and
1648
    /// submodule pins. Reads only; stops listing after 50 differences.
16498×
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
16508×
        self.verify_git_import_last(git_dir, branch, None)
16518×
    }
1652
1653
    /// [`Repo::verify_git_import`] of the last `last` commits only (all
1654
    /// when `None`): earlier ones are only followed, not rebuilt, for
1655
    /// looking again at where an import went wrong.
16568×
    pub fn verify_git_import_last(
16578×
        &self,
16588×
        git_dir: &Path,
16598×
        branch: &str,
16608×
        last: Option<usize>,
16618×
    ) -> Result<GitVerifyReport> {
16628×
        let commits = list_commits(git_dir, branch)?;
16638×
        let imported = self.imported_commits()?;
16648×
        let mut cat = CatFile::start(git_dir)?;
16658×
        let mut rep = GitVerifyReport::default();
1666
        // Changes of each commit and all its ancestors, built up in topological order.
16678×
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
1668
        // Graphs (by key) and blobs already found equal to a Git blob.
16698×
        let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new();
16708×
        let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new();
1671
        // The state of a commit whose first-parent children are still to
1672
        // come, so a child adds its own changes instead of loading all its
1673
        // history again (as the import does).
16748×
        let mut waiting: HashMap<&str, usize> = HashMap::new();
167555×
        for c in &commits {
167655×
            if let Some(p1) = c.parents.first() {
167745×
                *waiting.entry(p1.as_str()).or_default() += 1;
167845×
            }
1679
        }
16808×
        let mut kept: HashMap<String, State> = HashMap::new();
16818×
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
168255×
        for c in &commits {
168355×
            rep.commits += 1;
168455×
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
168562×
            for p in &c.parents {
168662×
                if let Some(ps) = closure.get(p) {
168762×
                    set.extend(ps.iter().copied());
168862×
                }
1689
            }
169055×
            match imported.get(&c.sha) {
169155×
                Some(h) => {
169255×
                    set.insert(*h);
169355×
                }
16940×
                None => {
16950×
                    rep.mismatches.push((
16960×
                        c.sha.clone(),
16970×
                        "no imported change carries this commit".into(),
16980×
                    ));
16990×
                }
1700
            }
170155×
            let set = Arc::new(set);
170255×
            closure.insert(c.sha.clone(), set.clone());
170355×
            if rep.mismatches.len() >= 50 {
17040×
                break;
170555×
            }
170655×
            if last.is_some_and(|n| rep.commits + n <= commits.len()) {
17070×
                rep.skipped += 1;
17080×
                continue;
170955×
            }
171055×
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1711
            // History only: a file whose graph (by key) or blob was already
1712
            // found equal to this Git blob is not built, rendered or read
1713
            // again; the rest are.
171455×
            let from_parent = c.parents.first().and_then(|p1| {
171545×
                let left = waiting.get_mut(p1.as_str()).map(|n| {
171645×
                    *n -= 1;
171745×
                    *n
171845×
                });
171945×
                if left == Some(0) {
172047×
                    kept_order.retain(|k| k != p1);
172132×
                    kept.remove(p1.as_str())
1722
                } else {
172313×
                    kept.get(p1.as_str()).cloned()
1724
                }
172545×
            });
172655×
            let state = match from_parent {
172745×
                Some(mut st) => {
1728
                    // The changes the parent's state lacks. The state never
1729
                    // builds a graph (they are built beside it), so they
1730
                    // are read without their text.
1731202×
                    for h in set.iter() {
1732202×
                        if !st.contains(h) {
173365×
                            let (change, texts) = self.store.get_change_lazy(h)?;
173465×
                            st.add_known(*h, change, texts);
1735137×
                        }
1736
                    }
173745×
                    st
1738
                }
173910×
                None => self.load_state_history(&heads)?,
1740
            };
174155×
            let view = state.tree().view();
174255×
            let tree = list_tree(git_dir, &c.sha)?;
174355×
            let short = &c.sha[..12.min(c.sha.len())];
174455×
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
174555×
            let mut conflicted: Vec<String> =
174655×
                view.conflicts.iter().map(|c| format!("{c:?}")).collect();
174755×
            let mut need: Vec<NodeId> = Vec::new();
1748131×
            for (path, (mode, sha)) in &tree {
1749131×
                let Some(e) = view.entries.get(path) else {
17500×
                    continue;
1751
                };
1752131×
                if mode != "160000"
1753131×
                    && mode != "120000"
1754131×
                    && e.kind == NodeKind::File
1755131×
                    && !e.mode.opaque
1756
                {
1757120×
                    let known = state
1758120×
                        .graph_key(&e.node)
1759120×
                        .is_some_and(|k| verified_graphs.get(&k) == Some(sha));
1760120×
                    if !known {
176146×
                        need.push(e.node);
176274×
                    }
176311×
                }
1764
            }
1765
            // A graph's key is known only before it is built.
176655×
            let keys: HashMap<NodeId, [u8; 32]> = need
176755×
                .iter()
176855×
                .filter_map(|n| Some((*n, state.graph_key(n)?)))
176955×
                .collect();
177055×
            let need_set: HashSet<NodeId> = need.iter().copied().collect();
177155×
            let graphs = self.build_graphs_detached(&state, &need)?;
1772131×
            for (path, (mode, sha)) in &tree {
1773131×
                let Some(e) = view.entries.get(path) else {
17740×
                    differ(format!("{short}: {path} is missing"));
17750×
                    continue;
1776
                };
1777131×
                rep.files_compared += 1;
1778131×
                match mode.as_str() {
1779131×
                    "160000" => {
17800×
                        let blobs = state.live_blobs(&e.node);
17810×
                        match (e.kind, blobs.as_slice()) {
17820×
                            (NodeKind::Subrepo, [b]) => {
17830×
                                let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?;
17840×
                                if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
17850×
                                {
17860×
                                    differ(format!("{short}: {path} pins another commit"));
17870×
                                }
1788
                            }
17890×
                            (kind, _) => differ(format!(
17900×
                                "{short}: {path} is not one submodule pin: {kind:?} with {} pins",
17910×
                                blobs.len()
17920×
                            )),
1793
                        }
1794
                    }
1795131×
                    "120000" => {
17960×
                        let target = cat.read(sha)?;
17970×
                        let blobs = state.live_blobs(&e.node);
17980×
                        match (e.kind, blobs.as_slice()) {
17990×
                            (NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {}
18000×
                            _ => differ(format!("{short}: symlink {path} differs")),
1801
                        }
1802
                    }
1803
                    _ => {
1804131×
                        if e.mode.exec != (mode == "100755") {
18050×
                            differ(format!("{short}: {path} executable bit differs"));
1806131×
                        }
1807131×
                        if e.kind == NodeKind::File && !e.mode.opaque {
1808120×
                            if !need_set.contains(&e.node) {
1809
                                // Known equal: skipped when the graphs were chosen.
181074×
                                continue;
181146×
                            }
181246×
                            let (have, m) = match graphs.get(&e.node) {
181346×
                                Some(g) => state.render_graph(g),
18140×
                                None => (Vec::new(), Default::default()),
1815
                            };
181646×
                            if m.is_conflicted() {
1817
                                // Who conflicts: a copy of the state with this graph built.
18180×
                                let mut detail = state.clone();
18190×
                                self.load_graphs_of(&mut detail, &[e.node])?;
18200×
                                let who: Vec<String> = detail
18210×
                                    .conflict_regions(&e.node)
18220×
                                    .contributors
18230×
                                    .iter()
18240×
                                    .filter_map(|h| state.get(h))
18250×
                                    .map(|m| {
18260×
                                        let sha = m
18270×
                                            .message
18280×
                                            .lines()
18290×
                                            .rev()
18300×
                                            .find_map(|l| l.strip_prefix("Git-Commit: "))
18310×
                                            .unwrap_or("?");
18320×
                                        format!(
1833
                                            "{} {:?}",
18340×
                                            &sha[..12.min(sha.len())],
18350×
                                            m.message.lines().next().unwrap_or("")
1836
                                        )
18370×
                                    })
18380×
                                    .collect();
18390×
                                conflicted.push(format!("{path} between {}", who.join(" and ")));
184046×
                            }
184146×
                            let want = cat.read(sha)?;
184246×
                            if have != want {
18430×
                                differ(format!(
18440×
                                    "{short}: {path} differs: {}",
18450×
                                    first_difference(&have, &want)
18460×
                                ));
184746×
                            } else if !m.is_conflicted() {
184846×
                                if let Some(k) = keys.get(&e.node) {
184946×
                                    verified_graphs.insert(*k, sha.clone());
185046×
                                }
18510×
                            }
185246×
                            continue;
185311×
                        }
185411×
                        let blobs = state.live_blobs(&e.node);
185511×
                        let [b] = blobs.as_slice() else {
18560×
                            differ(format!("{short}: {path} is not one file"));
18570×
                            continue;
1858
                        };
185911×
                        if verified_blobs.get(b) == Some(sha) {
18606×
                            continue;
18615×
                        }
18625×
                        if self.read_blob(b)? != cat.read(sha)? {
18630×
                            differ(format!("{short}: {path} differs"));
18645×
                        } else {
18655×
                            verified_blobs.insert(*b, sha.clone());
18665×
                        }
1867
                    }
1868
                }
1869
            }
187055×
            if !conflicted.is_empty() {
18710×
                differ(format!(
18720×
                    "{short}: the state is conflicted: {}",
18730×
                    conflicted.join("; ")
18740×
                ));
187555×
            }
1876
            // Import records submodules in `.oxymodules` as well (spec §23),
1877
            // and export leaves it out again.
1878131×
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
1879166×
            for (path, e) in view.entries.iter() {
1880166×
                if e.kind != NodeKind::Dir
1881131×
                    && !tree.contains_key(path)
18820×
                    && !(has_submodules && path == ".oxymodules")
18830×
                {
18840×
                    differ(format!("{short}: {path} is extra"));
1885166×
                }
1886
            }
188755×
            if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
188832×
                kept.insert(c.sha.clone(), state);
188932×
                kept_order.push_back(c.sha.clone());
189032×
                if kept_order.len() > 8 {
18910×
                    if let Some(old) = kept_order.pop_front() {
18920×
                        kept.remove(&old);
18930×
                    }
189432×
                }
189523×
            }
189655×
            if rep.mismatches.len() >= 50 {
18970×
                break;
189855×
            }
1899
        }
19008×
        Ok(rep)
19018×
    }
1902
}
1903
1904
/// Where two versions of a file first part, for a verification report.
19050×
fn first_difference(have: &[u8], want: &[u8]) -> String {
19060×
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
19070×
        have.split(|b| *b == b'\n').collect(),
19080×
        want.split(|b| *b == b'\n').collect(),
1909
    );
19100×
    let i = h
19110×
        .iter()
19120×
        .zip(&w)
19130×
        .position(|(a, b)| a != b)
19140×
        .unwrap_or(h.len().min(w.len()));
19150×
    let show = |l: Option<&&[u8]>| {
19160×
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
19170×
            .unwrap_or_else(|| "(end)".into())
19180×
    };
19190×
    format!(
1920
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
19210×
        i + 1,
19220×
        show(h.get(i)),
19230×
        show(w.get(i)),
19240×
        h.len(),
19250×
        w.len()
1926
    )
19270×
}