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