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