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