OXYGENHUB
# ce118287d9da oxygen / crates / oxy-core / src / repo / git.rs
82.7 KiB · Rust · last changed git import: build a merge from the paths it can change 1 month ago source blame history raw
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 {
31
    fn start(git_dir: &Path) -> Result<CatFile> {
32
        let mut child = Command::new("git")
33
            .arg("-C")
34
            .arg(git_dir)
35
            .args(["cat-file", "--batch"])
36
            .stdin(Stdio::piped())
37
            .stdout(Stdio::piped())
38
            .stderr(Stdio::null())
39
            .spawn()
40
            .map_err(|e| RepoError::Msg(format!("running git cat-file: {e}")))?;
41
        let stdin = child.stdin.take().unwrap();
42
        let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
43
        Ok(CatFile {
44
            child,
45
            stdin,
46
            stdout,
47
        })
48
    }
49
50
    fn read(&mut self, sha: &str) -> Result<Vec<u8>> {
51
        use std::io::{BufRead, Read};
52
        writeln!(self.stdin, "{sha}")?;
53
        self.stdin.flush()?;
54
        let mut header = String::new();
55
        self.stdout.read_line(&mut header)?;
56
        let parts: Vec<&str> = header.trim_end().split(' ').collect();
57
        if parts.len() != 3 {
58
            return fail(format!("git cat-file: object {sha} not found"));
59
        }
60
        let size: usize = parts[2]
61
            .parse()
62
            .map_err(|_| RepoError::Msg("git cat-file: bad size".into()))?;
63
        let mut body = vec![0u8; size];
64
        self.stdout.read_exact(&mut body)?;
65
        let mut nl = [0u8; 1];
66
        self.stdout.read_exact(&mut nl)?;
67
        Ok(body)
68
    }
69
}
70
71
impl Drop for CatFile {
72
    fn drop(&mut self) {
73
        let _ = self.child.kill();
74
        let _ = self.child.wait();
75
    }
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 {
95
    fn start(git_dir: &Path, pairs: Vec<(String, String)>) -> Result<DiffTree> {
96
        let mut child = Command::new("git")
97
            .arg("-C")
98
            .arg(git_dir)
99
            .args([
100
                "diff-tree",
101
                "--stdin",
102
                "--always",
103
                "-r",
104
                "-z",
105
                "--no-renames",
106
            ])
107
            .stdin(Stdio::piped())
108
            .stdout(Stdio::piped())
109
            .stderr(Stdio::null())
110
            .spawn()
111
            .map_err(|e| RepoError::Msg(format!("running git diff-tree: {e}")))?;
112
        let mut stdin = child.stdin.take().unwrap();
113
        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.
115
        let feeder = std::thread::spawn(move || {
116
            let mut w = std::io::BufWriter::new(&mut stdin);
117
            for (c, p) in pairs {
118
                if writeln!(w, "{c} {p}").is_err() {
119
                    return;
120
                }
121
            }
122
            let _ = w.flush();
123
        });
124
        Ok(DiffTree {
125
            child,
126
            stdout,
127
            feeder: Some(feeder),
128
            next: None,
129
        })
130
    }
131
132
    fn field(&mut self) -> Result<Option<String>> {
133
        use std::io::BufRead;
134
        let mut buf = Vec::new();
135
        if self.stdout.read_until(0, &mut buf)? == 0 {
136
            return Ok(None);
137
        }
138
        if buf.last() == Some(&0) {
139
            buf.pop();
140
        }
141
        Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
142
    }
143
144
    /// The diff of `sha` against the parent it was fed with.
145
    fn diff(&mut self, sha: &str) -> Result<TreeDiff> {
146
        let header = match self.next.take() {
147
            Some(h) => Some(h),
148
            None => self.field()?,
149
        };
150
        if header.as_deref() != Some(sha) {
151
            return fail(format!("git diff-tree: expected {sha}, got {header:?}"));
152
        }
153
        let mut out = Vec::new();
154
        while let Some(f) = self.field()? {
155
            let Some(meta) = f.strip_prefix(':') else {
156
                self.next = Some(f);
157
                break;
158
            };
159
            let Some(path) = self.field()? else {
160
                return fail("git diff-tree: record without a path");
161
            };
162
            // `oldmode newmode oldsha newsha status`
163
            let m: Vec<&str> = meta.split(' ').collect();
164
            if m.len() != 5 {
165
                return fail(format!("git diff-tree: bad record {f:?}"));
166
            }
167
            let entry = if m[4].starts_with('D') {
168
                None
169
            } else {
170
                Some((m[1].to_string(), m[3].to_string()))
171
            };
172
            out.push((path, entry));
173
        }
174
        Ok(out)
175
    }
176
}
177
178
impl Drop for DiffTree {
179
    fn drop(&mut self) {
180
        let _ = self.child.kill();
181
        let _ = self.child.wait();
182
        if let Some(f) = self.feeder.take() {
183
            let _ = f.join();
184
        }
185
    }
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
197
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> {
198
    let out = Command::new("git")
199
        .arg("-C")
200
        .arg(git_dir)
201
        .args([
202
            "log",
203
            "--reverse",
204
            "--topo-order",
205
            "--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e",
206
            branch,
207
        ])
208
        .output()
209
        .map_err(|e| RepoError::Msg(format!("running git log: {e}")))?;
210
    if !out.status.success() {
211
        return fail(format!(
212
            "git log {branch} failed: {}",
213
            String::from_utf8_lossy(&out.stderr).trim()
214
        ));
215
    }
216
    let text = String::from_utf8_lossy(&out.stdout);
217
    let mut commits = Vec::new();
218
    for record in text.split('\x1e') {
219
        let record = record.trim_start_matches('\n');
220
        if record.trim().is_empty() {
221
            continue;
222
        }
223
        let f: Vec<&str> = record.splitn(5, '\0').collect();
224
        if f.len() != 5 {
225
            return fail("unexpected git log record");
226
        }
227
        commits.push(GitCommit {
228
            sha: f[0].to_string(),
229
            parents: f[1].split_whitespace().map(str::to_string).collect(),
230
            author_secs: f[2].parse().unwrap_or(0),
231
            author: f[3].to_string(),
232
            message: f[4].trim_end().to_string(),
233
        });
234
    }
235
    Ok(commits)
236
}
237
238
/// `path → (mode, blob sha)` for a commit's tree.
239
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> {
240
    let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?;
241
    let mut out = BTreeMap::new();
242
    for entry in text.split('\0') {
243
        if entry.is_empty() {
244
            continue;
245
        }
246
        let Some((meta, path)) = entry.split_once('\t') else {
247
            continue;
248
        };
249
        let m: Vec<&str> = meta.split(' ').collect();
250
        if m.len() == 3 {
251
            out.insert(path.to_string(), (m[0].to_string(), m[2].to_string()));
252
        }
253
    }
254
    Ok(out)
255
}
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).
259
fn change_id_for(sha: &str, message: &str) -> ChangeId {
260
    for line in message.lines().rev() {
261
        if let Some(v) = line.strip_prefix("Change-Id:") {
262
            if let Some(id) = ChangeId::from_hex(v.trim()) {
263
                return id;
264
            }
265
        }
266
    }
267
    let h = blake3::hash(sha.as_bytes());
268
    ChangeId(h.as_bytes()[..16].try_into().unwrap())
269
}
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
/// An import moves its bookmark to the commits done so far every this
298
/// many commits, so one that stops part way resumes from there: imported
299
/// commits are found from the bookmark's history (`imported_commits`).
300
const CHECKPOINT_COMMITS: usize = 2000;
301
302
/// Text files of a merge rendered this many at a time (oxygen#25): a
303
/// batch's graphs are built beside the state and dropped once rendered,
304
/// so what is held for the whole tree is the renderings, not the graphs
305
/// with every deleted line of their history.
306
const MERGE_BATCH: usize = 500;
307
308
thread_local! {
309
    /// A smaller batch for this thread's imports: tests set 1, so a small
310
    /// merge takes the batched path.
311
    static MERGE_BATCH_OVERRIDE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
312
}
313
314
#[cfg(test)]
315
pub(crate) fn set_merge_batch_for_tests(n: Option<usize>) {
316
    MERGE_BATCH_OVERRIDE.with(|c| c.set(n));
317
}
318
319
fn merge_batch() -> usize {
320
    MERGE_BATCH_OVERRIDE
321
        .with(|c| c.get())
322
        .filter(|n| *n > 0)
323
        .unwrap_or(MERGE_BATCH)
324
}
325
326
impl Repo {
327
    /// As `State::materialize_except`, for a tree whose graphs would not
328
    /// fit in memory at once. The few files the change builder reads
329
    /// graphs for (conflicted ones, and renderings whose lines are not
330
    /// one per live atom) are built in the state afterwards.
331
    fn materialize_batched(
332
        &self,
333
        base: &mut State,
334
        need: &[crate::ids::NodeId],
335
        skip: &HashSet<crate::ids::NodeId>,
336
    ) -> Result<crate::state::Snapshot> {
337
        use crate::graph::Materialized;
338
        use crate::state::{FileContent, FileState};
339
        use rayon::prelude::*;
340
        let view = base.tree().view();
341
        let mut rendered: HashMap<crate::ids::NodeId, (Vec<u8>, Materialized)> =
342
            HashMap::with_capacity(need.len());
343
        let mut keep_built: Vec<crate::ids::NodeId> = Vec::new();
344
        for batch in need.chunks(merge_batch()) {
345
            let t = std::time::Instant::now();
346
            let graphs = self.build_graphs_detached(base, batch)?;
347
            crate::timing::add("render: build graphs, batch", t.elapsed());
348
            let t = std::time::Instant::now();
349
            let batch_rendered: Vec<(crate::ids::NodeId, Vec<u8>, Materialized)> = graphs
350
                .par_iter()
351
                .map(|(node, g)| {
352
                    let (bytes, m) = base.render_graph(g);
353
                    (*node, bytes, m)
354
                })
355
                .collect();
356
            drop(graphs);
357
            crate::timing::add("render: render, batch", t.elapsed());
358
            for (node, bytes, m) in batch_rendered {
359
                if m.is_conflicted()
360
                    || m.live_atoms().len() != crate::diff::split_lines(&bytes).len()
361
                {
362
                    keep_built.push(node);
363
                }
364
                rendered.insert(node, (bytes, m));
365
            }
366
        }
367
        if !keep_built.is_empty() {
368
            self.load_graphs_of(base, &keep_built)?;
369
        }
370
        let mut files = BTreeMap::new();
371
        let mut unrendered = BTreeSet::new();
372
        for (path, e) in view.entries.iter() {
373
            let f = if e.kind == NodeKind::File && !e.mode.opaque {
374
                match rendered.remove(&e.node) {
375
                    Some((bytes, materialized)) => FileState {
376
                        node: e.node,
377
                        kind: e.kind,
378
                        mode: e.mode,
379
                        content: FileContent::Text {
380
                            bytes,
381
                            materialized,
382
                        },
383
                    },
384
                    None if skip.contains(&e.node) => {
385
                        unrendered.insert(path.clone());
386
                        FileState {
387
                            node: e.node,
388
                            kind: e.kind,
389
                            mode: e.mode,
390
                            content: FileContent::Text {
391
                                bytes: Vec::new(),
392
                                materialized: Materialized::default(),
393
                            },
394
                        }
395
                    }
396
                    None => {
397
                        // Neither asked for nor known unchanged: render it
398
                        // from a built graph, as the whole-tree path does.
399
                        self.load_graphs_of(base, &[e.node])?;
400
                        base.entry_state(e)
401
                    }
402
                }
403
            } else {
404
                base.entry_state(e)
405
            };
406
            files.insert(path.clone(), f);
407
        }
408
        Ok(crate::state::Snapshot {
409
            tree: view,
410
            files,
411
            unrendered,
412
        })
413
    }
414
}
415
416
fn git(dir: &Path, args: &[&str]) -> Result<String> {
417
    let out = Command::new("git")
418
        .arg("-C")
419
        .arg(dir)
420
        .args(args)
421
        .output()
422
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
423
    if !out.status.success() {
424
        return fail(format!(
425
            "git {} failed: {}",
426
            args.join(" "),
427
            String::from_utf8_lossy(&out.stderr).trim()
428
        ));
429
    }
430
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
431
}
432
433
impl Repo {
434
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
435
        let canonical = git_dir
436
            .canonicalize()
437
            .unwrap_or_else(|_| git_dir.to_path_buf());
438
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
439
        let dir = self.oxy.join("git").join(key);
440
        fs::create_dir_all(&dir)?;
441
        Ok(dir)
442
    }
443
444
    /// `state ref → Git commit sha` for bookmark states that equal a Git
445
    /// commit's tree (recorded by import and fetch).
446
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
447
        let mut out = BTreeMap::new();
448
        if let Ok(text) = fs::read_to_string(path) {
449
            for line in text.lines() {
450
                if let Some((h, sha)) = line.split_once(' ') {
451
                    if let Some(h) = ObjectRef::from_hex(h) {
452
                        out.insert(h, sha.trim().to_string());
453
                    }
454
                }
455
            }
456
        }
457
        Ok(out)
458
    }
459
460
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
461
        let path = self.git_marks_dir(git_dir)?.join("git-states");
462
        let mut states = Self::read_git_states(&path)?;
463
        states.insert(*state, sha.to_string());
464
        let text: String = states
465
            .iter()
466
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
467
            .collect();
468
        write_atomic(&path, text.as_bytes())
469
    }
470
471
    /// The bare mirror this repository keeps for the Git remote `url`.
472
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
473
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
474
        let dir = self.oxy.join("git").join(key).join("mirror.git");
475
        if !dir.join("HEAD").exists() {
476
            fs::create_dir_all(&dir)?;
477
            git(&dir, &["init", "--bare", "-q"])?;
478
        }
479
        Ok(dir)
480
    }
481
482
    /// Git commits already imported into the bookmark, by sha.
483
    pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
484
        let mut map = HashMap::new();
485
        for e in self.log()? {
486
            if e.is_working_copy {
487
                continue;
488
            }
489
            if let Some(sha) = e
490
                .change
491
                .message
492
                .lines()
493
                .rev()
494
                .find_map(|l| l.strip_prefix("Git-Commit: "))
495
            {
496
                map.insert(sha.trim().to_string(), e.hash);
497
            }
498
        }
499
        Ok(map)
500
    }
501
502
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
503
    /// A remote without that branch yet leaves the mirror as it is.
504
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
505
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
506
        match git(mirror, &["fetch", "-q", url, &spec]) {
507
            Ok(_) => Ok(()),
508
            Err(e) => {
509
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
510
                if ls.trim().is_empty() {
511
                    Ok(())
512
                } else {
513
                    Err(e)
514
                }
515
            }
516
        }
517
    }
518
519
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
520
    /// through a mirror and import the commits not yet in the bookmark
521
    /// (spec §23). Works on a repository that already has history: the
522
    /// new changes join the bookmark like a pull.
523
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
524
        // A local path, made absolute: git runs it from inside the mirror.
525
        let local = Path::new(url)
526
            .canonicalize()
527
            .ok()
528
            .filter(|_| !url.contains("://"));
529
        let absolute = local.as_ref().map(|p| p.to_string_lossy().into_owned());
530
        let url = absolute.as_deref().unwrap_or(url);
531
        let mirror = self.git_mirror(url)?;
532
        self.git_mirror_fetch(&mirror, url, branch)?;
533
        if git(
534
            &mirror,
535
            &[
536
                "rev-parse",
537
                "--verify",
538
                "-q",
539
                &format!("refs/heads/{branch}"),
540
            ],
541
        )
542
        .is_err()
543
        {
544
            return fail(format!("{url} has no branch {branch:?}"));
545
        }
546
        self.import_git_commits(
547
            &mirror,
548
            branch,
549
            &format!("oxy git fetch {url} {branch}"),
550
            &mut |_| {},
551
        )
552
    }
553
554
    /// Export the bookmark to `branch` of the Git repository at `url`
555
    /// through the mirror and push it. The remote's tip must already have
556
    /// been fetched (`git_fetch`), so the push fast-forwards.
557
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
558
        let mirror = self.git_mirror(url)?;
559
        self.git_mirror_fetch(&mirror, url, branch)?;
560
        if let Ok(tip) = git(
561
            &mirror,
562
            &[
563
                "rev-parse",
564
                "--verify",
565
                "-q",
566
                &format!("refs/heads/{branch}"),
567
            ],
568
        ) {
569
            let known = self.git_known(&mirror)?;
570
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
571
                return fail(format!(
572
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
573
                ));
574
            }
575
        }
576
        let report = self.git_export_as(&mirror, branch)?;
577
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
578
        git(&mirror, &["push", "-q", url, &spec])?;
579
        Ok(report)
580
    }
581
582
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
583
        let mut out = BTreeMap::new();
584
        if let Ok(text) = fs::read_to_string(path) {
585
            for line in text.lines() {
586
                if let Some((h, m)) = line.split_once(' ') {
587
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
588
                        out.insert(h, m);
589
                    }
590
                }
591
            }
592
        }
593
        Ok(out)
594
    }
595
596
    /// Export the current bookmark to the Git repository at `git_dir`,
597
    /// creating a bare one if nothing is there. Each state the bookmark
598
    /// passed through (per the operation log) becomes one commit whose tree
599
    /// is that state, so the Git branch is a linear history of full trees.
600
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
601
        let bookmark = self.config.bookmark.clone();
602
        self.git_export_as(git_dir, &bookmark)
603
    }
604
605
    /// `git_export` to the Git branch `branch`. A state that came from a
606
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
607
    /// onto that commit, so a push back to the Git remote fast-forwards.
608
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
609
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
610
            fs::create_dir_all(git_dir)?;
611
            git(git_dir, &["init", "--bare", "-q"])?;
612
        }
613
        let marks_dir = self.git_marks_dir(git_dir)?;
614
        let git_marks = marks_dir.join("git-marks");
615
        let oxy_marks_path = marks_dir.join("oxy-marks");
616
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
617
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
618
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
619
620
        let bookmark = self.config.bookmark.clone();
621
        let mut stream: Vec<u8> = Vec::new();
622
        let mut report = GitExportReport {
623
            branch: branch.to_string(),
624
            heads: self.bookmark_heads()?.len(),
625
            ..Default::default()
626
        };
627
628
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
629
        let mut ops = self.op_log()?;
630
        ops.reverse();
631
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
632
        // The fast-import parent of the next commit: `:mark` or a commit sha.
633
        let mut last_parent: Option<String> = None;
634
        for (_, op) in &ops {
635
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
636
                continue;
637
            };
638
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
639
                continue;
640
            }
641
            let Ok(state) = self.store.get_state(&state_ref) else {
642
                continue;
643
            };
644
            if state.heads.is_empty() {
645
                prev = Some((state_ref, vec![]));
646
                continue;
647
            }
648
            if let Some(sha) = git_states.get(&state_ref) {
649
                report.skipped += 1;
650
                last_parent = Some(sha.clone());
651
                prev = Some((state_ref, state.heads.clone()));
652
                continue;
653
            }
654
            if let Some(m) = marks.get(&state_ref) {
655
                report.skipped += 1;
656
                last_parent = Some(format!(":{m}"));
657
                prev = Some((state_ref, state.heads.clone()));
658
                continue;
659
            }
660
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
661
            let added = self
662
                .negotiate(&prev_heads, &state.heads)
663
                .unwrap_or_default();
664
            let loaded = self.load_state(&state.heads)?;
665
            let snapshot = loaded.materialize();
666
            let (author, secs, mut message) = match added.as_slice() {
667
                [h] => {
668
                    let c = self.store.get_change(h)?;
669
                    let mut m = c.message.clone();
670
                    if !m.ends_with('\n') {
671
                        m.push('\n');
672
                    }
673
                    m.push_str(&format!(
674
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
675
                        c.change_id.to_hex(),
676
                        h.to_hex()
677
                    ));
678
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
679
                }
680
                [] => (
681
                    "oxy <oxy@localhost>".to_string(),
682
                    op.hlc.wall_ms / 1000,
683
                    format!("oxy: {}\n\n", op.command),
684
                ),
685
                many => {
686
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
687
                    for h in many {
688
                        let c = self.store.get_change(h)?;
689
                        m.push_str(&format!(
690
                            "- {} {}\n",
691
                            c.change_id.short(8),
692
                            c.message.lines().next().unwrap_or("")
693
                        ));
694
                    }
695
                    m.push_str(&format!(
696
                        "\nOxy-Changes: {}\n",
697
                        many.iter()
698
                            .map(|h| h.to_hex())
699
                            .collect::<Vec<_>>()
700
                            .join(" ")
701
                    ));
702
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
703
                }
704
            };
705
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
706
            if snapshot.is_conflicted() {
707
                message.push_str("Oxy-Conflicted: true\n");
708
            }
709
            let mark = next_mark;
710
            next_mark += 1;
711
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
712
            self.write_commit(
713
                &mut stream,
714
                "refs/oxy/export",
715
                mark,
716
                &author,
717
                secs,
718
                &message,
719
                &parents,
720
                &snapshot,
721
            )?;
722
            marks.insert(state_ref, mark);
723
            last_parent = Some(format!(":{mark}"));
724
            prev = Some((state_ref, state.heads.clone()));
725
            report.exported += 1;
726
        }
727
        if let Some(p) = &last_parent {
728
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
729
        }
730
        // Tags: a tag whose state was exported as a bookmark state points at
731
        // that commit; otherwise its state gets a commit of its own.
732
        for t in self.tags()? {
733
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
734
                (Some(sha), _) => sha.clone(),
735
                (None, Some(m)) => format!(":{m}"),
736
                (None, None) => {
737
                    let loaded = self.load_state(&t.heads)?;
738
                    let snapshot = loaded.materialize();
739
                    let mark = next_mark;
740
                    next_mark += 1;
741
                    let message = format!(
742
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
743
                        t.name,
744
                        if t.message.is_empty() {
745
                            String::new()
746
                        } else {
747
                            format!("{}\n\n", t.message)
748
                        },
749
                        t.state.to_hex()
750
                    );
751
                    self.write_commit(
752
                        &mut stream,
753
                        "refs/oxy/export",
754
                        mark,
755
                        "oxy <oxy@localhost>",
756
                        Hlc::now().wall_ms / 1000,
757
                        &message,
758
                        &[],
759
                        &snapshot,
760
                    )?;
761
                    marks.insert(t.state, mark);
762
                    report.exported += 1;
763
                    format!(":{mark}")
764
                }
765
            };
766
            stream.extend_from_slice(
767
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
768
            );
769
        }
770
        stream.extend_from_slice(b"done\n");
771
772
        let mut cmd = Command::new("git");
773
        // `--force`: the scratch ref may jump between unrelated states.
774
        cmd.arg("-C")
775
            .arg(git_dir)
776
            .args(["fast-import", "--quiet", "--done", "--force"])
777
            .arg(format!("--export-marks={}", git_marks.display()));
778
        if git_marks.exists() {
779
            cmd.arg(format!("--import-marks={}", git_marks.display()));
780
        }
781
        let mut child = cmd
782
            .stdin(Stdio::piped())
783
            .stdout(Stdio::null())
784
            .stderr(Stdio::piped())
785
            .spawn()
786
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
787
        child.stdin.take().unwrap().write_all(&stream)?;
788
        let out = child.wait_with_output()?;
789
        if !out.status.success() {
790
            return fail(format!(
791
                "git fast-import failed: {}",
792
                String::from_utf8_lossy(&out.stderr).trim()
793
            ));
794
        }
795
        let text: String = marks
796
            .iter()
797
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
798
            .collect();
799
        write_atomic(&oxy_marks_path, text.as_bytes())?;
800
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
801
        report.skipped_subrepos = self.git_export_skipped.replace(0);
802
        Ok(report)
803
    }
804
805
    /// Import branch `branch` of the Git repository at `git_dir` into this
806
    /// (empty) repository's bookmark (spec §23): one change per commit, its
807
    /// edits the difference between the union of its parents' states and its
808
    /// tree, so merge commits become resolutions. Submodules are skipped.
809
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
810
        self.import_git_with(git_dir, branch, &mut |_| {})
811
    }
812
813
    /// `import_git`, telling `progress` where it is every few hundred
814
    /// commits: the count so far, the merges, and the commit in hand, so a
815
    /// long import is never silent and a run that dies says where.
816
    pub fn import_git_with(
817
        &self,
818
        git_dir: &Path,
819
        branch: &str,
820
        progress: crate::store::Progress<'_>,
821
    ) -> Result<GitImportReport> {
822
        if !self.bookmark_heads()?.is_empty() {
823
            return fail("git import needs an empty bookmark; import into a fresh repository");
824
        }
825
        self.import_git_commits(
826
            git_dir,
827
            branch,
828
            &format!("oxy git import {} {branch}", git_dir.display()),
829
            progress,
830
        )
831
    }
832
833
    /// Import the commits of `branch` that the bookmark does not have yet,
834
    /// then move the bookmark to the union of its heads and theirs.
835
    fn import_git_commits(
836
        &self,
837
        git_dir: &Path,
838
        branch: &str,
839
        command: &str,
840
        progress: crate::store::Progress<'_>,
841
    ) -> Result<GitImportReport> {
842
        let batch = self.store.begin_batch()?;
843
        let result = self.import_git_commits_batched(git_dir, branch, command, progress);
844
        batch.finish()?;
845
        result
846
    }
847
848
    fn import_git_commits_batched(
849
        &self,
850
        git_dir: &Path,
851
        branch: &str,
852
        command: &str,
853
        progress: crate::store::Progress<'_>,
854
    ) -> Result<GitImportReport> {
855
        let commits = list_commits(git_dir, branch)?;
856
        let mut cat = CatFile::start(git_dir)?;
857
        let mut report = GitImportReport::default();
858
        let mut known = self.git_known(git_dir)?;
859
        let old_heads = self.bookmark_heads()?;
860
        // The bookmark's heads as changes arrive: a change stops being a
861
        // head when another depends on it, so no full state of every
862
        // imported change is needed at the end.
863
        let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect();
864
        // The state and Git tree of imported commits whose first-parent
865
        // children are still to come, so a child starts from its parent's
866
        // state instead of rebuilding it from history. The last child takes
867
        // it; earlier ones clone it. At most `max_kept` are kept (a later
868
        // child of an evicted one rebuilds).
869
        // OXY_IMPORT_KEEP overrides it, for measuring.
870
        let max_kept: usize = std::env::var("OXY_IMPORT_KEEP")
871
            .ok()
872
            .and_then(|v| v.parse().ok())
873
            .unwrap_or(8);
874
        let mut waiting: HashMap<&str, usize> = HashMap::new();
875
        for gc in &commits {
876
            if let Some(p1) = gc.parents.first() {
877
                *waiting.entry(p1.as_str()).or_default() += 1;
878
            }
879
        }
880
        type Kept = (State, BTreeMap<String, (String, String)>);
881
        let mut kept: HashMap<String, Kept> = HashMap::new();
882
        // Every commit to import that has a parent, diffed against its first.
883
        let pairs: Vec<(String, String)> = commits
884
            .iter()
885
            .filter(|gc| {
886
                !known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha)
887
            })
888
            .filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone())))
889
            .collect();
890
        let mut diffs = DiffTree::start(git_dir, pairs)?;
891
        let mut rebuilt = 0usize;
892
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
893
        let mut last: Option<String> = None;
894
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
895
        let mut cache_bytes: usize = 0;
896
        // Time spent per phase over all commits (`OXY_TIMINGS=1`).
897
        let mut spent = [std::time::Duration::ZERO; 6];
898
        let mut clock = std::time::Instant::now();
899
        // One line per commit on stderr with OXY_IMPORT_TRACE=1: where its
900
        // base came from, what a merge added, the graphs its state holds,
901
        // the kept states and the process's resident memory.
902
        let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some();
903
        let rss_mb = || -> u64 {
904
            std::fs::read_to_string("/proc/self/statm")
905
                .ok()
906
                .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
907
                .map(|pages| pages * 4096 >> 20)
908
                .unwrap_or(0)
909
        };
910
        let mut done = 0usize;
911
        // Atoms a kept state's graphs may hold before they are shed;
912
        // OXY_IMPORT_KEPT_ATOMS overrides it, for measuring.
913
        let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS")
914
            .ok()
915
            .and_then(|v| v.parse().ok())
916
            .unwrap_or(KEPT_ATOMS);
917
        // Graphs turned back into history (see `State::shed_graphs`).
918
        let mut shed = 0usize;
919
        let mut lap = |i: usize, clock: &mut std::time::Instant| {
920
            let now = std::time::Instant::now();
921
            spent[i] += now - *clock;
922
            *clock = now;
923
        };
924
925
        // OXY_IMPORT_CHECKPOINT overrides it, for testing.
926
        let checkpoint_every: usize = std::env::var("OXY_IMPORT_CHECKPOINT")
927
            .ok()
928
            .and_then(|v| v.parse().ok())
929
            .filter(|n| *n > 0)
930
            .unwrap_or(CHECKPOINT_COMMITS);
931
        // OXY_IMPORT_STOP_AFTER ends the import cleanly after that many
932
        // commits, its timings reported, for measuring at depth.
933
        let stop_after: Option<usize> = std::env::var("OXY_IMPORT_STOP_AFTER")
934
            .ok()
935
            .and_then(|v| v.parse().ok());
936
        let whole_merges = std::env::var_os("OXY_IMPORT_WHOLE_MERGES").filter(|v| v != "0");
937
        let total = commits.len();
938
        for (index, gc) in commits.iter().enumerate() {
939
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
940
                continue;
941
            }
942
            if stop_after.is_some_and(|n| done >= n) {
943
                break;
944
            }
945
            let commit_started = std::time::Instant::now();
946
            if index % 500 == 0 {
947
                progress(&format!(
948
                    "{index} of {total} commits, {} merges; at {} {}",
949
                    report.merges,
950
                    &gc.sha[..12.min(gc.sha.len())],
951
                    gc.message
952
                        .lines()
953
                        .next()
954
                        .unwrap_or("")
955
                        .chars()
956
                        .take(60)
957
                        .collect::<String>()
958
                ));
959
            }
960
            let mut base_how = "root";
961
            // Base: union of every parent's state, starting from the first
962
            // parent's kept state when there is one; its tree tells which
963
            // paths this commit leaves alone.
964
            let (mut base, prev_tree) = match gc.parents.first() {
965
                Some(p1) => {
966
                    let left = waiting.get_mut(p1.as_str()).map(|n| {
967
                        *n -= 1;
968
                        *n
969
                    });
970
                    let found = if left == Some(0) {
971
                        kept_order.retain(|k| k != p1);
972
                        kept.remove(p1.as_str())
973
                    } else {
974
                        kept.get(p1.as_str()).cloned()
975
                    };
976
                    let how = match (&found, left) {
977
                        (Some(_), Some(0)) => "kept",
978
                        (Some(_), _) => "cloned",
979
                        (None, _) => "rebuilt",
980
                    };
981
                    if trace {
982
                        base_how = how;
983
                    }
984
                    match found {
985
                        Some((st, tree)) => (st, Some(tree)),
986
                        None => {
987
                            // History only: graphs are built for the files a
988
                            // commit changes, so memory follows what changes,
989
                            // not the whole tree.
990
                            let mut st = State::new_history_only();
991
                            self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
992
                            // The parent's tree, so this commit still
993
                            // renders only what it changes.
994
                            rebuilt += 1;
995
                            (st, Some(list_tree(git_dir, p1)?))
996
                        }
997
                    }
998
                }
999
                None => (State::new_history_only(), None),
1000
            };
1001
            // Nodes the other parents' changes touch: the first parent's
1002
            // tree cannot vouch for them.
1003
            let mut touched: HashSet<NodeId> = HashSet::new();
1004
            let mut merged = 0usize;
1005
            // Where the first parent has each node, read before the merged
1006
            // changes move anything: a merge's partial build names the paths
1007
            // they touch in the first parent's tree as well as in the merged
1008
            // state (oxygen#80).
1009
            let mut first_parent_view: Option<crate::tree::TreeView> = None;
1010
            if gc.parents.len() > 1 {
1011
                report.merges += 1;
1012
                if prev_tree.is_some() && whole_merges.is_none() {
1013
                    first_parent_view = Some(base.tree().view());
1014
                }
1015
                let mut args: Vec<String> = gc.parents[1..].to_vec();
1016
                args.push(format!("^{}", gc.parents[0]));
1017
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
1018
                // A merge of a long-lived branch brings thousands of
1019
                // changes: added to built graphs, which kept states share,
1020
                // they were copied and applied whole (vscode's import passed
1021
                // 14 GB on such merges). Shed the graphs first, so the
1022
                // changes go in as skeletons and only what this commit
1023
                // touches is built again.
1024
                if base.built_count() > 0 {
1025
                    let mut count_args = vec!["rev-list", "--count"];
1026
                    count_args.extend(refs.iter().copied());
1027
                    let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0);
1028
                    if others > MERGE_SHED_COMMITS {
1029
                        shed += base.shed_graphs(|b| self.store_blob(b))?;
1030
                    }
1031
                }
1032
                let before = base.len();
1033
                self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?;
1034
                merged = base.len() - before;
1035
            }
1036
            lap(0, &mut clock);
1037
            // The commit's tree: its first parent's with the diff applied,
1038
            // or listed whole when that tree is not kept.
1039
            let diff = match gc.parents.first() {
1040
                Some(_) => Some(diffs.diff(&gc.sha)?),
1041
                None => None,
1042
            };
1043
            let (tree, changed) = match (prev_tree, diff) {
1044
                (Some(mut t), Some(diff)) => {
1045
                    let mut changed: HashSet<String> = HashSet::new();
1046
                    for (path, entry) in diff {
1047
                        match entry {
1048
                            Some(v) => {
1049
                                t.insert(path.clone(), v);
1050
                            }
1051
                            None => {
1052
                                t.remove(&path);
1053
                            }
1054
                        }
1055
                        changed.insert(path);
1056
                    }
1057
                    (t, Some(changed))
1058
                }
1059
                _ => (list_tree(git_dir, &gc.sha)?, None),
1060
            };
1061
            lap(1, &mut clock);
1062
            // Text files with the same blob and mode as in the first
1063
            // parent's tree equal the base's rendering: they are neither
1064
            // rendered nor read nor compared (spec §12.3, as for a clean
1065
            // working copy), so a commit costs what it changes.
1066
            let mut same: HashMap<&str, NodeId> = HashMap::new();
1067
            // Opaque files and symlinks likewise, when the base has one
1068
            // blob for them: they are neither read nor stored again.
1069
            let mut same_opaque: HashSet<&str> = HashSet::new();
1070
            // An ordinary commit in a tree without submodules is built from
1071
            // the paths it changes alone (oxygen#25): with the `.oxyattributes`
1072
            // files that decide how they are stored, and the directories its
1073
            // removals may leave empty. A merge, or a commit whose parent's
1074
            // tree is not at hand, is built from its whole tree.
1075
            // A merge can differ from its first parent only at the paths
1076
            // Git's diff names and where the merged changes touched: those
1077
            // paths in the first parent's tree and in the merged state. With
1078
            // them added it is built like an ordinary commit, instead of
1079
            // from its whole tree (18 s for any merge at 118k commits of
1080
            // VS Code, oxygen#80). OXY_IMPORT_WHOLE_MERGES=1 restores the
1081
            // whole-tree path, for comparing.
1082
            let mut changed = changed;
1083
            // A tree conflict in the merged state (both sides placed a file
1084
            // at one path) is resolved by the whole-tree path.
1085
            let mut merge_how = if gc.parents.len() > 1 {
1086
                if first_parent_view.is_some() {
1087
                    "partial"
1088
                } else {
1089
                    "whole"
1090
                }
1091
            } else {
1092
                "-"
1093
            };
1094
            // Only a conflict among what the merged changes touched; one
1095
            // elsewhere stays as it was in the first parent either way.
1096
            if first_parent_view.is_some()
1097
                && base.tree().view().conflicts.iter().any(|c| {
1098
                    use crate::tree::TreeConflict::*;
1099
                    match c {
1100
                        Name { nodes, .. } => nodes.iter().any(|n| touched.contains(n)),
1101
                        MultiPlacement { node, .. } | Cycle { node } | Mode { node, .. } => {
1102
                            touched.contains(node)
1103
                        }
1104
                        Orphan { node, parent } => {
1105
                            touched.contains(node) || touched.contains(parent)
1106
                        }
1107
                    }
1108
                })
1109
            {
1110
                first_parent_view = None;
1111
                merge_how = "conflicted";
1112
            }
1113
            if let (Some(ch), Some(fp)) = (changed.as_mut(), &first_parent_view) {
1114
                let union = base.tree().view();
1115
                for v in [fp, &union] {
1116
                    for (path, e) in v.entries.iter() {
1117
                        if touched.contains(&e.node) {
1118
                            ch.insert(path.clone());
1119
                        }
1120
                    }
1121
                }
1122
            }
1123
            let partial = changed.is_some()
1124
                && (gc.parents.len() == 1 || first_parent_view.is_some())
1125
                && !tree.values().any(|(mode, _)| mode == "160000");
1126
            let mut rel: BTreeSet<&str> = BTreeSet::new();
1127
            // Text files whose graphs this commit builds, for the trace.
1128
            let need_n: usize;
1129
            let base_snapshot = if let (true, Some(changed)) = (partial, &changed) {
1130
                let view = base.tree().view();
1131
                rel.extend(changed.iter().map(String::as_str));
1132
                rel.extend(
1133
                    tree.keys()
1134
                        .map(String::as_str)
1135
                        .filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")),
1136
                );
1137
                let mut dirs: BTreeSet<&str> = BTreeSet::new();
1138
                for p in changed.iter().filter(|p| !tree.contains_key(*p)) {
1139
                    let mut end = p.len();
1140
                    while let Some(i) = p[..end].rfind('/') {
1141
                        if !dirs.insert(&p[..i]) {
1142
                            break;
1143
                        }
1144
                        end = i;
1145
                    }
1146
                }
1147
                let need: Vec<NodeId> = rel
1148
                    .iter()
1149
                    .filter_map(|p| view.entries.get(*p))
1150
                    .filter(|e| e.kind == NodeKind::File && !e.mode.opaque)
1151
                    .map(|e| e.node)
1152
                    .collect();
1153
                crate::timing::add("render: same and need", clock.elapsed());
1154
                need_n = need.len();
1155
                let t = std::time::Instant::now();
1156
                self.load_graphs_of(&mut base, &need)?;
1157
                crate::timing::add("render: load graphs", t.elapsed());
1158
                let t = std::time::Instant::now();
1159
                let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied());
1160
                crate::timing::add("render: materialize", t.elapsed());
1161
                snap
1162
            } else {
1163
                if let Some(changed) = &changed {
1164
                    let view = base.tree().view();
1165
                    for path in tree.keys() {
1166
                        // Submodule handling reads these two whatever changed.
1167
                        if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules"
1168
                        {
1169
                            continue;
1170
                        }
1171
                        if let Some(e) = view.entries.get(path) {
1172
                            if touched.contains(&e.node) {
1173
                                continue;
1174
                            }
1175
                            let opaque = e.kind == NodeKind::Symlink
1176
                                || (e.kind == NodeKind::File && e.mode.opaque);
1177
                            if e.kind == NodeKind::File && !e.mode.opaque {
1178
                                same.insert(path.as_str(), e.node);
1179
                            } else if opaque && base.live_blobs(&e.node).len() == 1 {
1180
                                same_opaque.insert(path.as_str());
1181
                            }
1182
                        }
1183
                    }
1184
                }
1185
                // Build the graphs of every text file the commit may change.
1186
                let skip: HashSet<NodeId> = same.values().copied().collect();
1187
                let need: Vec<NodeId> = base
1188
                    .tree()
1189
                    .view()
1190
                    .entries
1191
                    .values()
1192
                    .filter(|e| {
1193
                        e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node)
1194
                    })
1195
                    .map(|e| e.node)
1196
                    .collect();
1197
                crate::timing::add("render: same and need", clock.elapsed());
1198
                need_n = need.len();
1199
                let t = std::time::Instant::now();
1200
                let snap = if need.len() > merge_batch() {
1201
                    // A merge onto a base with no built graphs: thousands
1202
                    // of files, whose graphs would not fit at once.
1203
                    self.materialize_batched(&mut base, &need, &skip)?
1204
                } else {
1205
                    let g = std::time::Instant::now();
1206
                    self.load_graphs_of(&mut base, &need)?;
1207
                    crate::timing::add("render: whole, load graphs", g.elapsed());
1208
                    let m = std::time::Instant::now();
1209
                    let snap = base.materialize_except(&skip);
1210
                    crate::timing::add("render: whole, materialize", m.elapsed());
1211
                    snap
1212
                };
1213
                crate::timing::add("render: whole tree", t.elapsed());
1214
                snap
1215
            };
1216
1217
            lap(2, &mut clock);
1218
            // The commit's tree as in-memory entries.
1219
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1220
            let mut gitlinks: Vec<(String, String)> = Vec::new();
1221
            let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial {
1222
                Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p)))
1223
            } else {
1224
                Box::new(tree.iter())
1225
            };
1226
            for (path, (mode, sha)) in listed {
1227
                let (path, sha) = (path.clone(), sha.clone());
1228
                let (kind, exec) = match mode.as_str() {
1229
                    "100644" | "100664" => (NodeKind::File, false),
1230
                    "100755" => (NodeKind::File, true),
1231
                    "120000" => (NodeKind::Symlink, false),
1232
                    "160000" => {
1233
                        gitlinks.push((path, sha));
1234
                        continue;
1235
                    }
1236
                    _ => continue,
1237
                };
1238
                if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) {
1239
                    let mut e = FsEntry::new(kind, exec, Vec::new());
1240
                    e.unchanged = true;
1241
                    entries.insert(path, e);
1242
                    continue;
1243
                }
1244
                let content = match blob_cache.get(&sha) {
1245
                    Some(c) => c.clone(),
1246
                    None => {
1247
                        let c = cat.read(&sha)?;
1248
                        if cache_bytes + c.len() > 64 * 1024 * 1024 {
1249
                            blob_cache.clear();
1250
                            cache_bytes = 0;
1251
                        }
1252
                        cache_bytes += c.len();
1253
                        blob_cache.insert(sha.clone(), c.clone());
1254
                        c
1255
                    }
1256
                };
1257
                entries.insert(path, FsEntry::new(kind, exec, content));
1258
            }
1259
1260
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
1261
            // pins, and `.gitmodules` also yields `.oxymodules`.
1262
            if !gitlinks.is_empty() {
1263
                report.submodules += gitlinks.len();
1264
                let gm = entries
1265
                    .get(".gitmodules")
1266
                    .map(|e| {
1267
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
1268
                            &e.content,
1269
                        ))
1270
                    })
1271
                    .unwrap_or_default();
1272
                let mut modules = entries
1273
                    .get(".oxymodules")
1274
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
1275
                    .unwrap_or_default();
1276
                for (path, sha) in &gitlinks {
1277
                    let m = gm.entries.get(path);
1278
                    let branch = m
1279
                        .and_then(|m| m.bookmark.clone())
1280
                        .unwrap_or_else(|| "HEAD".into());
1281
                    entries.insert(
1282
                        path.clone(),
1283
                        FsEntry::new(
1284
                            NodeKind::Subrepo,
1285
                            false,
1286
                            crate::subrepo::Pin::Git {
1287
                                sha: sha.clone(),
1288
                                branch,
1289
                            }
1290
                            .encode(),
1291
                        ),
1292
                    );
1293
                    if let Some(m) = m {
1294
                        modules.entries.insert(path.clone(), m.clone());
1295
                    }
1296
                }
1297
                if !modules.entries.is_empty() {
1298
                    entries.insert(
1299
                        ".oxymodules".into(),
1300
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
1301
                    );
1302
                }
1303
            }
1304
            lap(3, &mut clock);
1305
            // New nodes' identifiers derive from the commit, so importing the
1306
            // same Git history twice gives the same changes (spec §23).
1307
            let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes();
1308
            let mut built = if partial {
1309
                // Whether the new tree has anything under `dir`.
1310
                let dir_needed = |dir: &str| {
1311
                    let prefix = format!("{dir}/");
1312
                    tree.range(prefix.clone()..)
1313
                        .next()
1314
                        .is_some_and(|(k, _)| k.starts_with(&prefix))
1315
                };
1316
                self.build_from_entries_seeded(
1317
                    &base,
1318
                    &base_snapshot,
1319
                    &entries,
1320
                    seed,
1321
                    Some(&dir_needed),
1322
                )?
1323
            } else {
1324
                self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)?
1325
            };
1326
            lap(4, &mut clock);
1327
            // A file or submodule with several live blobs (branches that
1328
            // replaced it independently) is resolved to the commit's blob:
1329
            // Git's merge is the authority here, unlike a working copy,
1330
            // where a candidate on disk is not yet a decision (spec §23).
1331
            for (path, f) in &base_snapshot.files {
1332
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
1333
                else {
1334
                    continue;
1335
                };
1336
                if blobs.len() < 2 || f.kind != e.kind {
1337
                    continue;
1338
                }
1339
                let chosen = self.store_blob(&e.content)?;
1340
                for b in blobs {
1341
                    built.edits.push(Edit::Replace {
1342
                        node: f.node,
1343
                        old: Some(*b),
1344
                        new: Some(chosen),
1345
                    });
1346
                }
1347
                built.resolves = true;
1348
                built
1349
                    .contributors
1350
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
1351
            }
1352
            // It shares the base's tree view, which applying the change
1353
            // then updates in place rather than copying.
1354
            drop(base_snapshot);
1355
            drop(entries);
1356
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
1357
            let mut message = gc.message.clone();
1358
            if !message.ends_with('\n') {
1359
                message.push('\n');
1360
            }
1361
            message.push_str(&format!(
1362
                "\nGit-Commit: {}\nGit-Author: {}\n",
1363
                gc.sha, gc.author
1364
            ));
1365
            let mut change = Change {
1366
                version: crate::objects::CHANGE_VERSION,
1367
                change_id: change_id_for(&gc.sha, &gc.message),
1368
                deps: vec![],
1369
                author: ObjectRef::ZERO,
1370
                hlc: Hlc {
1371
                    wall_ms: gc.author_secs * 1000,
1372
                    logical: 0,
1373
                },
1374
                message,
1375
                tree_ops: built.tree_ops,
1376
                edits: built.edits,
1377
                kind: if built.resolves {
1378
                    ChangeKind::Resolution
1379
                } else {
1380
                    ChangeKind::Normal
1381
                },
1382
            };
1383
            let t = std::time::Instant::now();
1384
            deps.extend(referenced_changes(&change, &base));
1385
            crate::timing::add("store: referenced", t.elapsed());
1386
            change.deps = deps.into_iter().collect();
1387
            change.normalize();
1388
            let hash = self.store.put_change(&change)?;
1389
            for d in &change.deps {
1390
                heads_now.remove(d);
1391
            }
1392
            heads_now.insert(hash);
1393
            // Built graphs take its edits whole; files not built keep only
1394
            // where its text is, read back from the store.
1395
            let t = std::time::Instant::now();
1396
            let (skeleton, texts) = self.store.get_change_lazy(&hash)?;
1397
            base.add_known_mixed(hash, change, skeleton, texts);
1398
            crate::timing::add("store: add to state", t.elapsed());
1399
            known.imported.insert(gc.sha.clone(), hash);
1400
            if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) {
1401
                // A kept state holds its graphs until its children come:
1402
                // past a few thousand, they go back into its history.
1403
                // Past a few thousand graphs, or past a budget of atoms: a
1404
                // long-lived file's graph keeps every line it ever had, so a
1405
                // handful of them can hold gigabytes (#25).
1406
                if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms {
1407
                    shed += base.shed_graphs(|b| self.store_blob(b))?;
1408
                }
1409
                kept.insert(gc.sha.clone(), (base, tree));
1410
                kept_order.push_back(gc.sha.clone());
1411
                if kept_order.len() > max_kept {
1412
                    if let Some(old) = kept_order.pop_front() {
1413
                        kept.remove(&old);
1414
                    }
1415
                }
1416
            }
1417
            last = Some(gc.sha.clone());
1418
            report.commits += 1;
1419
            lap(5, &mut clock);
1420
            done += 1;
1421
            if done.is_multiple_of(checkpoint_every) {
1422
                self.checkpoint_import(&heads_now, done)?;
1423
            }
1424
            // A merge renders thousands of files on many threads and frees
1425
            // it all; the allocator keeps those pages unless asked to give
1426
            // them back, and the next merge piles on top (#25).
1427
            let before_trim = if trace { rss_mb() } else { 0 };
1428
            if gc.parents.len() > 1 {
1429
                crate::alloc_stats::release_freed_memory();
1430
            }
1431
            if trace {
1432
                let built = kept
1433
                    .get(gc.sha.as_str())
1434
                    .map(|(st, _)| st.built_count())
1435
                    .unwrap_or(0);
1436
                let (edits, most) = kept
1437
                    .get(gc.sha.as_str())
1438
                    .map(|(st, _)| st.deferred_edit_count())
1439
                    .unwrap_or((0, 0));
1440
                let atoms = kept
1441
                    .get(gc.sha.as_str())
1442
                    .map(|(st, _)| st.built_atoms())
1443
                    .unwrap_or(0);
1444
                eprintln!(
1445
                    "trace {done} {} parents={} base={base_how} merged={merged} built={built} atoms={atoms} kept={} shed={shed} rss_mb={} before_trim_mb={before_trim} deferred_edits={edits} most={most} need={need_n} merge={merge_how} ms={}",
1446
                    &gc.sha[..12.min(gc.sha.len())],
1447
                    gc.parents.len(),
1448
                    kept.len(),
1449
                    rss_mb(),
1450
                    commit_started.elapsed().as_millis()
1451
                );
1452
            }
1453
        }
1454
        for (name, d) in [
1455
            "git import: bases",
1456
            "git import: tree",
1457
            "git import: render base",
1458
            "git import: read blobs",
1459
            "git import: build change",
1460
            "git import: store change",
1461
        ]
1462
        .iter()
1463
        .zip(spent)
1464
        {
1465
            crate::timing::record(name, d);
1466
        }
1467
        crate::timing::report_totals();
1468
        if crate::timing::enabled() {
1469
            eprintln!(
1470
                "timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed"
1471
            );
1472
        }
1473
1474
        // The bookmark: heads of the old state plus every new change.
1475
        report.heads = old_heads.len();
1476
        if last.is_none() {
1477
            return Ok(report);
1478
        }
1479
        let heads: Vec<ChangeHash> = heads_now.into_iter().collect();
1480
        report.heads = heads.len();
1481
        let (op_ref, op) = self.head_op()?;
1482
        let mut view = op.view.clone();
1483
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
1484
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
1485
        view.bookmarks
1486
            .insert(self.config.bookmark.clone(), state_ref);
1487
        self.record_op(&[op_ref], command, view)?;
1488
        // The new state equals the tip's tree when the old one was itself a
1489
        // Git commit's tree (fetched or exported), or there was none.
1490
        let old_known = old_heads.is_empty()
1491
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
1492
        if let (Some(tip), true) = (commits.last(), old_known) {
1493
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
1494
        }
1495
        // The working copy follows when it was clean on the old heads.
1496
        if old_heads.is_empty() {
1497
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
1498
        } else {
1499
            let snap = self.snapshot(command)?;
1500
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1501
            let mut base = snap.base.maximal(&snap.wc.deps);
1502
            base.sort();
1503
            let mut sorted_old = old_heads.clone();
1504
            sorted_old.sort();
1505
            // An empty base too: an import that stopped after a checkpoint
1506
            // never checked anything out, and resuming it should.
1507
            if clean && (base == sorted_old || base.is_empty()) {
1508
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
1509
            }
1510
        }
1511
        Ok(report)
1512
    }
1513
1514
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
1515
    /// an imported commit's change, or the whole state an exported commit
1516
    /// was made from (which may hold changes Git never saw).
1517
    fn add_git_ancestors(
1518
        &self,
1519
        st: &mut State,
1520
        git_dir: &Path,
1521
        args: &[&str],
1522
        known: &GitKnown,
1523
    ) -> Result<()> {
1524
        self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new())
1525
    }
1526
1527
    /// `add_git_ancestors`, also collecting in `touched` every node the
1528
    /// changes it adds edit, place or remove.
1529
    fn add_git_ancestors_touching(
1530
        &self,
1531
        st: &mut State,
1532
        git_dir: &Path,
1533
        args: &[&str],
1534
        known: &GitKnown,
1535
        touched: &mut HashSet<NodeId>,
1536
    ) -> Result<()> {
1537
        let mut full = vec!["rev-list"];
1538
        full.extend(args);
1539
        let out = git(git_dir, &full)?;
1540
        let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> {
1541
            if st.contains(h) {
1542
                return Ok(());
1543
            }
1544
            if !st.is_history_only() {
1545
                let c = self.store.get_change(h)?;
1546
                touched.extend(c.edits.iter().map(|e| e.node()));
1547
                touched.extend(c.tree_ops.iter().map(|o| o.node()));
1548
                st.add_unchecked(c);
1549
                return Ok(());
1550
            }
1551
            // History only: the text of an edit waits unread unless its
1552
            // file's graph is built.
1553
            let (skeleton, texts) = self.store.get_change_lazy(h)?;
1554
            touched.extend(skeleton.edits.iter().map(|e| e.node()));
1555
            touched.extend(skeleton.tree_ops.iter().map(|o| o.node()));
1556
            let built = skeleton
1557
                .edits
1558
                .iter()
1559
                .any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node()));
1560
            if built {
1561
                let full = self.store.get_change(h)?;
1562
                st.add_known_mixed(*h, full, skeleton, texts);
1563
            } else {
1564
                st.add_known(*h, skeleton, texts);
1565
            }
1566
            Ok(())
1567
        };
1568
        for sha in out.lines() {
1569
            if let Some(h) = known.imported.get(sha) {
1570
                add(st, h)?;
1571
            } else if let Some(state_ref) = known.exported.get(sha) {
1572
                let heads = self.store.get_state(state_ref)?.heads;
1573
                for h in self.negotiate(&[], &heads)? {
1574
                    add(st, &h)?;
1575
                }
1576
            }
1577
        }
1578
        Ok(())
1579
    }
1580
1581
    /// Point the bookmark at an import's heads so far (see
1582
    /// `CHECKPOINT_COMMITS`); the working copy is left alone until the end.
1583
    fn checkpoint_import(&self, heads: &BTreeSet<ChangeHash>, done: usize) -> Result<()> {
1584
        let heads: Vec<ChangeHash> = heads.iter().copied().collect();
1585
        let (op_ref, op) = self.head_op()?;
1586
        let mut view = op.view.clone();
1587
        let state_ref = self.store.put_state(&StateObject::new(heads))?;
1588
        view.bookmarks
1589
            .insert(self.config.bookmark.clone(), state_ref);
1590
        self.record_op(
1591
            &[op_ref],
1592
            &format!("oxy git import (checkpoint after {done} commits)"),
1593
            view,
1594
        )?;
1595
        Ok(())
1596
    }
1597
1598
    /// Commits this repository can relate to Oxygen history: imported
1599
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
1600
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
1601
        let imported = self.imported_commits()?;
1602
        let marks_dir = self.git_marks_dir(git_dir)?;
1603
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
1604
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
1605
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
1606
            for line in text.lines() {
1607
                if let Some((m, sha)) = line.split_once(' ') {
1608
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
1609
                        sha_of_mark.insert(m, sha.trim().to_string());
1610
                    }
1611
                }
1612
            }
1613
        }
1614
        let mut exported = HashMap::new();
1615
        for (state_ref, m) in oxy_marks {
1616
            if let Some(sha) = sha_of_mark.get(&m) {
1617
                exported.insert(sha.clone(), state_ref);
1618
            }
1619
        }
1620
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
1621
            exported.entry(sha).or_insert(state_ref);
1622
        }
1623
        Ok(GitKnown { imported, exported })
1624
    }
1625
1626
    fn git_author(&self, c: &Change) -> String {
1627
        match self.store.get_identity(&c.author) {
1628
            Ok(id) if !id.name.is_empty() => format!(
1629
                "{} <{}>",
1630
                id.name.replace(['<', '>', '\n'], " "),
1631
                id.email.replace(['<', '>', '\n', ' '], "")
1632
            ),
1633
            _ => "oxy <oxy@localhost>".to_string(),
1634
        }
1635
    }
1636
1637
    #[allow(clippy::too_many_arguments)]
1638
    fn write_commit(
1639
        &self,
1640
        out: &mut Vec<u8>,
1641
        reference: &str,
1642
        mark: u64,
1643
        author: &str,
1644
        secs: u64,
1645
        message: &str,
1646
        parents: &[String],
1647
        snapshot: &Snapshot,
1648
    ) -> Result<()> {
1649
        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());
1650
        for (i, p) in parents.iter().enumerate() {
1651
            out.extend_from_slice(
1652
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
1653
            );
1654
        }
1655
        out.extend_from_slice(b"deleteall\n");
1656
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
1657
        for (path, f) in &snapshot.files {
1658
            if path == ".oxymodules" {
1659
                // Git reads `.gitmodules`; derive it unless the tree has one.
1660
                if !has_gitmodules {
1661
                    if let FileContent::Text { bytes, .. } = &f.content {
1662
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
1663
                            .to_gitmodules();
1664
                        if !gm.is_empty() {
1665
                            out.extend_from_slice(
1666
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
1667
                                    .as_bytes(),
1668
                            );
1669
                            out.extend_from_slice(gm.as_bytes());
1670
                            out.push(b'\n');
1671
                        }
1672
                    }
1673
                }
1674
                continue;
1675
            }
1676
            if f.kind == NodeKind::Subrepo {
1677
                if let FileContent::Opaque { blobs } = &f.content {
1678
                    if let Some(b) = blobs.first() {
1679
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
1680
                            crate::subrepo::Pin::Git { sha, .. } => {
1681
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
1682
                            }
1683
                            crate::subrepo::Pin::Oxy { .. } => self
1684
                                .git_export_skipped
1685
                                .set(self.git_export_skipped.get() + 1),
1686
                        }
1687
                    }
1688
                }
1689
                continue;
1690
            }
1691
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
1692
                (NodeKind::Dir, _) => continue,
1693
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
1694
                    "120000",
1695
                    blobs
1696
                        .first()
1697
                        .map(|b| self.read_blob(b))
1698
                        .transpose()?
1699
                        .unwrap_or_default(),
1700
                ),
1701
                (_, FileContent::Text { bytes, .. }) => {
1702
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
1703
                }
1704
                (_, FileContent::Opaque { blobs }) => (
1705
                    if f.mode.exec { "100755" } else { "100644" },
1706
                    blobs
1707
                        .first()
1708
                        .map(|b| self.read_blob(b))
1709
                        .transpose()?
1710
                        .unwrap_or_default(),
1711
                ),
1712
                (_, FileContent::Dir) => continue,
1713
            };
1714
            out.extend_from_slice(
1715
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
1716
            );
1717
            out.extend_from_slice(&bytes);
1718
            out.push(b'\n');
1719
        }
1720
        out.push(b'\n');
1721
        Ok(())
1722
    }
1723
}
1724
1725
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
1726
#[derive(Debug, Clone, Default, PartialEq, Eq)]
1727
pub struct GitVerifyReport {
1728
    pub commits: usize,
1729
    pub files_compared: usize,
1730
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
1731
    pub mismatches: Vec<(String, String)>,
1732
}
1733
1734
impl Repo {
1735
    /// Check an import against its Git source: for every commit of
1736
    /// `branch`, the state formed by the changes imported for it and all
1737
    /// its ancestors must materialize to exactly that commit's tree, byte
1738
    /// for byte, with the same executable bits, symlink targets and
1739
    /// submodule pins. Reads only; stops listing after 50 differences.
1740
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
1741
        let commits = list_commits(git_dir, branch)?;
1742
        let imported = self.imported_commits()?;
1743
        let mut cat = CatFile::start(git_dir)?;
1744
        let mut rep = GitVerifyReport::default();
1745
        // Changes of each commit and all its ancestors, built up in topological order.
1746
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
1747
        // Graphs (by key) and blobs already found equal to a Git blob.
1748
        let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new();
1749
        let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new();
1750
        // The state of a commit whose first-parent children are still to
1751
        // come, so a child adds its own changes instead of loading all its
1752
        // history again (as the import does).
1753
        let mut waiting: HashMap<&str, usize> = HashMap::new();
1754
        for c in &commits {
1755
            if let Some(p1) = c.parents.first() {
1756
                *waiting.entry(p1.as_str()).or_default() += 1;
1757
            }
1758
        }
1759
        let mut kept: HashMap<String, State> = HashMap::new();
1760
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
1761
        for c in &commits {
1762
            rep.commits += 1;
1763
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
1764
            for p in &c.parents {
1765
                if let Some(ps) = closure.get(p) {
1766
                    set.extend(ps.iter().copied());
1767
                }
1768
            }
1769
            match imported.get(&c.sha) {
1770
                Some(h) => {
1771
                    set.insert(*h);
1772
                }
1773
                None => {
1774
                    rep.mismatches.push((
1775
                        c.sha.clone(),
1776
                        "no imported change carries this commit".into(),
1777
                    ));
1778
                }
1779
            }
1780
            let set = Arc::new(set);
1781
            closure.insert(c.sha.clone(), set.clone());
1782
            if rep.mismatches.len() >= 50 {
1783
                break;
1784
            }
1785
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1786
            // History only: a file whose graph (by key) or blob was already
1787
            // found equal to this Git blob is not built, rendered or read
1788
            // again; the rest are.
1789
            let from_parent = c.parents.first().and_then(|p1| {
1790
                let left = waiting.get_mut(p1.as_str()).map(|n| {
1791
                    *n -= 1;
1792
                    *n
1793
                });
1794
                if left == Some(0) {
1795
                    kept_order.retain(|k| k != p1);
1796
                    kept.remove(p1.as_str())
1797
                } else {
1798
                    kept.get(p1.as_str()).cloned()
1799
                }
1800
            });
1801
            let state = match from_parent {
1802
                Some(mut st) => {
1803
                    // The changes the parent's state lacks. The state never
1804
                    // builds a graph (they are built beside it), so they
1805
                    // are read without their text.
1806
                    for h in set.iter() {
1807
                        if !st.contains(h) {
1808
                            let (change, texts) = self.store.get_change_lazy(h)?;
1809
                            st.add_known(*h, change, texts);
1810
                        }
1811
                    }
1812
                    st
1813
                }
1814
                None => self.load_state_history(&heads)?,
1815
            };
1816
            let view = state.tree().view();
1817
            let tree = list_tree(git_dir, &c.sha)?;
1818
            let short = &c.sha[..12.min(c.sha.len())];
1819
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
1820
            let mut conflicted: Vec<String> =
1821
                view.conflicts.iter().map(|c| format!("{c:?}")).collect();
1822
            let mut need: Vec<NodeId> = Vec::new();
1823
            for (path, (mode, sha)) in &tree {
1824
                let Some(e) = view.entries.get(path) else {
1825
                    continue;
1826
                };
1827
                if mode != "160000"
1828
                    && mode != "120000"
1829
                    && e.kind == NodeKind::File
1830
                    && !e.mode.opaque
1831
                {
1832
                    let known = state
1833
                        .graph_key(&e.node)
1834
                        .is_some_and(|k| verified_graphs.get(&k) == Some(sha));
1835
                    if !known {
1836
                        need.push(e.node);
1837
                    }
1838
                }
1839
            }
1840
            // A graph's key is known only before it is built.
1841
            let keys: HashMap<NodeId, [u8; 32]> = need
1842
                .iter()
1843
                .filter_map(|n| Some((*n, state.graph_key(n)?)))
1844
                .collect();
1845
            let need_set: HashSet<NodeId> = need.iter().copied().collect();
1846
            let graphs = self.build_graphs_detached(&state, &need)?;
1847
            for (path, (mode, sha)) in &tree {
1848
                let Some(e) = view.entries.get(path) else {
1849
                    differ(format!("{short}: {path} is missing"));
1850
                    continue;
1851
                };
1852
                rep.files_compared += 1;
1853
                match mode.as_str() {
1854
                    "160000" => {
1855
                        let blobs = state.live_blobs(&e.node);
1856
                        match (e.kind, blobs.as_slice()) {
1857
                            (NodeKind::Subrepo, [b]) => {
1858
                                let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?;
1859
                                if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
1860
                                {
1861
                                    differ(format!("{short}: {path} pins another commit"));
1862
                                }
1863
                            }
1864
                            (kind, _) => differ(format!(
1865
                                "{short}: {path} is not one submodule pin: {kind:?} with {} pins",
1866
                                blobs.len()
1867
                            )),
1868
                        }
1869
                    }
1870
                    "120000" => {
1871
                        let target = cat.read(sha)?;
1872
                        let blobs = state.live_blobs(&e.node);
1873
                        match (e.kind, blobs.as_slice()) {
1874
                            (NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {}
1875
                            _ => differ(format!("{short}: symlink {path} differs")),
1876
                        }
1877
                    }
1878
                    _ => {
1879
                        if e.mode.exec != (mode == "100755") {
1880
                            differ(format!("{short}: {path} executable bit differs"));
1881
                        }
1882
                        if e.kind == NodeKind::File && !e.mode.opaque {
1883
                            if !need_set.contains(&e.node) {
1884
                                // Known equal: skipped when the graphs were chosen.
1885
                                continue;
1886
                            }
1887
                            let (have, m) = match graphs.get(&e.node) {
1888
                                Some(g) => state.render_graph(g),
1889
                                None => (Vec::new(), Default::default()),
1890
                            };
1891
                            if m.is_conflicted() {
1892
                                // Who conflicts: a copy of the state with this graph built.
1893
                                let mut detail = state.clone();
1894
                                self.load_graphs_of(&mut detail, &[e.node])?;
1895
                                let who: Vec<String> = detail
1896
                                    .conflict_regions(&e.node)
1897
                                    .contributors
1898
                                    .iter()
1899
                                    .filter_map(|h| state.get(h))
1900
                                    .map(|m| {
1901
                                        let sha = m
1902
                                            .message
1903
                                            .lines()
1904
                                            .rev()
1905
                                            .find_map(|l| l.strip_prefix("Git-Commit: "))
1906
                                            .unwrap_or("?");
1907
                                        format!(
1908
                                            "{} {:?}",
1909
                                            &sha[..12.min(sha.len())],
1910
                                            m.message.lines().next().unwrap_or("")
1911
                                        )
1912
                                    })
1913
                                    .collect();
1914
                                conflicted.push(format!("{path} between {}", who.join(" and ")));
1915
                            }
1916
                            let want = cat.read(sha)?;
1917
                            if have != want {
1918
                                differ(format!(
1919
                                    "{short}: {path} differs: {}",
1920
                                    first_difference(&have, &want)
1921
                                ));
1922
                            } else if !m.is_conflicted() {
1923
                                if let Some(k) = keys.get(&e.node) {
1924
                                    verified_graphs.insert(*k, sha.clone());
1925
                                }
1926
                            }
1927
                            continue;
1928
                        }
1929
                        let blobs = state.live_blobs(&e.node);
1930
                        let [b] = blobs.as_slice() else {
1931
                            differ(format!("{short}: {path} is not one file"));
1932
                            continue;
1933
                        };
1934
                        if verified_blobs.get(b) == Some(sha) {
1935
                            continue;
1936
                        }
1937
                        if self.read_blob(b)? != cat.read(sha)? {
1938
                            differ(format!("{short}: {path} differs"));
1939
                        } else {
1940
                            verified_blobs.insert(*b, sha.clone());
1941
                        }
1942
                    }
1943
                }
1944
            }
1945
            if !conflicted.is_empty() {
1946
                differ(format!(
1947
                    "{short}: the state is conflicted: {}",
1948
                    conflicted.join("; ")
1949
                ));
1950
            }
1951
            // Import records submodules in `.oxymodules` as well (spec §23),
1952
            // and export leaves it out again.
1953
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
1954
            for (path, e) in view.entries.iter() {
1955
                if e.kind != NodeKind::Dir
1956
                    && !tree.contains_key(path)
1957
                    && !(has_submodules && path == ".oxymodules")
1958
                {
1959
                    differ(format!("{short}: {path} is extra"));
1960
                }
1961
            }
1962
            if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
1963
                kept.insert(c.sha.clone(), state);
1964
                kept_order.push_back(c.sha.clone());
1965
                if kept_order.len() > 8 {
1966
                    if let Some(old) = kept_order.pop_front() {
1967
                        kept.remove(&old);
1968
                    }
1969
                }
1970
            }
1971
            if rep.mismatches.len() >= 50 {
1972
                break;
1973
            }
1974
        }
1975
        Ok(rep)
1976
    }
1977
}
1978
1979
/// Where two versions of a file first part, for a verification report.
1980
fn first_difference(have: &[u8], want: &[u8]) -> String {
1981
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
1982
        have.split(|b| *b == b'\n').collect(),
1983
        want.split(|b| *b == b'\n').collect(),
1984
    );
1985
    let i = h
1986
        .iter()
1987
        .zip(&w)
1988
        .position(|(a, b)| a != b)
1989
        .unwrap_or(h.len().min(w.len()));
1990
    let show = |l: Option<&&[u8]>| {
1991
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
1992
            .unwrap_or_else(|| "(end)".into())
1993
    };
1994
    format!(
1995
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
1996
        i + 1,
1997
        show(h.get(i)),
1998
        show(w.get(i)),
1999
        h.len(),
2000
        w.len()
2001
    )
2002
}