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