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