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