OXYGENHUB
# a9f686edf60b oxygen / crates / oxy-core / src / repo / git.rs
44.9 KiB · Rust · last changed Git import verified commit by commit; two dependency bugs fixed 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 commit as `git log` describes it.
79
struct GitCommit {
80
    sha: String,
81
    parents: Vec<String>,
82
    author_secs: u64,
83
    author: String,
84
    message: String,
85
}
86
87
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> {
88
    let out = Command::new("git")
89
        .arg("-C")
90
        .arg(git_dir)
91
        .args([
92
            "log",
93
            "--reverse",
94
            "--topo-order",
95
            "--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e",
96
            branch,
97
        ])
98
        .output()
99
        .map_err(|e| RepoError::Msg(format!("running git log: {e}")))?;
100
    if !out.status.success() {
101
        return fail(format!(
102
            "git log {branch} failed: {}",
103
            String::from_utf8_lossy(&out.stderr).trim()
104
        ));
105
    }
106
    let text = String::from_utf8_lossy(&out.stdout);
107
    let mut commits = Vec::new();
108
    for record in text.split('\x1e') {
109
        let record = record.trim_start_matches('\n');
110
        if record.trim().is_empty() {
111
            continue;
112
        }
113
        let f: Vec<&str> = record.splitn(5, '\0').collect();
114
        if f.len() != 5 {
115
            return fail("unexpected git log record");
116
        }
117
        commits.push(GitCommit {
118
            sha: f[0].to_string(),
119
            parents: f[1].split_whitespace().map(str::to_string).collect(),
120
            author_secs: f[2].parse().unwrap_or(0),
121
            author: f[3].to_string(),
122
            message: f[4].trim_end().to_string(),
123
        });
124
    }
125
    Ok(commits)
126
}
127
128
/// `path → (mode, blob sha)` for a commit's tree.
129
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> {
130
    let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?;
131
    let mut out = BTreeMap::new();
132
    for entry in text.split('\0') {
133
        if entry.is_empty() {
134
            continue;
135
        }
136
        let Some((meta, path)) = entry.split_once('\t') else {
137
            continue;
138
        };
139
        let m: Vec<&str> = meta.split(' ').collect();
140
        if m.len() == 3 {
141
            out.insert(path.to_string(), (m[0].to_string(), m[2].to_string()));
142
        }
143
    }
144
    Ok(out)
145
}
146
147
/// The ChangeId for a Git commit: its `Change-Id` trailer if it has a
148
/// 32-hex one, else BLAKE3-128 of the commit hash (spec §23).
149
fn change_id_for(sha: &str, message: &str) -> ChangeId {
150
    for line in message.lines().rev() {
151
        if let Some(v) = line.strip_prefix("Change-Id:") {
152
            if let Some(id) = ChangeId::from_hex(v.trim()) {
153
                return id;
154
            }
155
        }
156
    }
157
    let h = blake3::hash(sha.as_bytes());
158
    ChangeId(h.as_bytes()[..16].try_into().unwrap())
159
}
160
161
/// Git commits with a known Oxygen counterpart.
162
struct GitKnown {
163
    /// Imported commit → its change.
164
    imported: HashMap<String, ChangeHash>,
165
    /// Exported commit (or a fetched tip) → the bookmark state it equals.
166
    exported: HashMap<String, ObjectRef>,
167
}
168
169
#[derive(Debug, Clone, Default, PartialEq, Eq)]
170
pub struct GitExportReport {
171
    pub exported: usize,
172
    pub skipped: usize,
173
    /// Subrepo nodes with Oxygen pins, which Git cannot represent.
174
    pub skipped_subrepos: usize,
175
    pub branch: String,
176
    pub heads: usize,
177
}
178
179
fn git(dir: &Path, args: &[&str]) -> Result<String> {
180
    let out = Command::new("git")
181
        .arg("-C")
182
        .arg(dir)
183
        .args(args)
184
        .output()
185
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
186
    if !out.status.success() {
187
        return fail(format!(
188
            "git {} failed: {}",
189
            args.join(" "),
190
            String::from_utf8_lossy(&out.stderr).trim()
191
        ));
192
    }
193
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
194
}
195
196
impl Repo {
197
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
198
        let canonical = git_dir
199
            .canonicalize()
200
            .unwrap_or_else(|_| git_dir.to_path_buf());
201
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
202
        let dir = self.oxy.join("git").join(key);
203
        fs::create_dir_all(&dir)?;
204
        Ok(dir)
205
    }
206
207
    /// `state ref → Git commit sha` for bookmark states that equal a Git
208
    /// commit's tree (recorded by import and fetch).
209
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
210
        let mut out = BTreeMap::new();
211
        if let Ok(text) = fs::read_to_string(path) {
212
            for line in text.lines() {
213
                if let Some((h, sha)) = line.split_once(' ') {
214
                    if let Some(h) = ObjectRef::from_hex(h) {
215
                        out.insert(h, sha.trim().to_string());
216
                    }
217
                }
218
            }
219
        }
220
        Ok(out)
221
    }
222
223
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
224
        let path = self.git_marks_dir(git_dir)?.join("git-states");
225
        let mut states = Self::read_git_states(&path)?;
226
        states.insert(*state, sha.to_string());
227
        let text: String = states
228
            .iter()
229
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
230
            .collect();
231
        write_atomic(&path, text.as_bytes())
232
    }
233
234
    /// The bare mirror this repository keeps for the Git remote `url`.
235
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
236
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
237
        let dir = self.oxy.join("git").join(key).join("mirror.git");
238
        if !dir.join("HEAD").exists() {
239
            fs::create_dir_all(&dir)?;
240
            git(&dir, &["init", "--bare", "-q"])?;
241
        }
242
        Ok(dir)
243
    }
244
245
    /// Git commits already imported into the bookmark, by sha.
246
    fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
247
        let mut map = HashMap::new();
248
        for e in self.log()? {
249
            if e.is_working_copy {
250
                continue;
251
            }
252
            if let Some(sha) = e
253
                .change
254
                .message
255
                .lines()
256
                .rev()
257
                .find_map(|l| l.strip_prefix("Git-Commit: "))
258
            {
259
                map.insert(sha.trim().to_string(), e.hash);
260
            }
261
        }
262
        Ok(map)
263
    }
264
265
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
266
    /// A remote without that branch yet leaves the mirror as it is.
267
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
268
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
269
        match git(mirror, &["fetch", "-q", url, &spec]) {
270
            Ok(_) => Ok(()),
271
            Err(e) => {
272
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
273
                if ls.trim().is_empty() {
274
                    Ok(())
275
                } else {
276
                    Err(e)
277
                }
278
            }
279
        }
280
    }
281
282
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
283
    /// through a mirror and import the commits not yet in the bookmark
284
    /// (spec §23). Works on a repository that already has history: the
285
    /// new changes join the bookmark like a pull.
286
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
287
        let mirror = self.git_mirror(url)?;
288
        self.git_mirror_fetch(&mirror, url, branch)?;
289
        if git(
290
            &mirror,
291
            &[
292
                "rev-parse",
293
                "--verify",
294
                "-q",
295
                &format!("refs/heads/{branch}"),
296
            ],
297
        )
298
        .is_err()
299
        {
300
            return fail(format!("{url} has no branch {branch:?}"));
301
        }
302
        self.import_git_commits(&mirror, branch, &format!("oxy git fetch {url} {branch}"))
303
    }
304
305
    /// Export the bookmark to `branch` of the Git repository at `url`
306
    /// through the mirror and push it. The remote's tip must already have
307
    /// been fetched (`git_fetch`), so the push fast-forwards.
308
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
309
        let mirror = self.git_mirror(url)?;
310
        self.git_mirror_fetch(&mirror, url, branch)?;
311
        if let Ok(tip) = git(
312
            &mirror,
313
            &[
314
                "rev-parse",
315
                "--verify",
316
                "-q",
317
                &format!("refs/heads/{branch}"),
318
            ],
319
        ) {
320
            let known = self.git_known(&mirror)?;
321
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
322
                return fail(format!(
323
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
324
                ));
325
            }
326
        }
327
        let report = self.git_export_as(&mirror, branch)?;
328
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
329
        git(&mirror, &["push", "-q", url, &spec])?;
330
        Ok(report)
331
    }
332
333
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
334
        let mut out = BTreeMap::new();
335
        if let Ok(text) = fs::read_to_string(path) {
336
            for line in text.lines() {
337
                if let Some((h, m)) = line.split_once(' ') {
338
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
339
                        out.insert(h, m);
340
                    }
341
                }
342
            }
343
        }
344
        Ok(out)
345
    }
346
347
    /// Export the current bookmark to the Git repository at `git_dir`,
348
    /// creating a bare one if nothing is there. Each state the bookmark
349
    /// passed through (per the operation log) becomes one commit whose tree
350
    /// is that state, so the Git branch is a linear history of full trees.
351
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
352
        let bookmark = self.config.bookmark.clone();
353
        self.git_export_as(git_dir, &bookmark)
354
    }
355
356
    /// `git_export` to the Git branch `branch`. A state that came from a
357
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
358
    /// onto that commit, so a push back to the Git remote fast-forwards.
359
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
360
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
361
            fs::create_dir_all(git_dir)?;
362
            git(git_dir, &["init", "--bare", "-q"])?;
363
        }
364
        let marks_dir = self.git_marks_dir(git_dir)?;
365
        let git_marks = marks_dir.join("git-marks");
366
        let oxy_marks_path = marks_dir.join("oxy-marks");
367
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
368
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
369
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
370
371
        let bookmark = self.config.bookmark.clone();
372
        let mut stream: Vec<u8> = Vec::new();
373
        let mut report = GitExportReport {
374
            branch: branch.to_string(),
375
            heads: self.bookmark_heads()?.len(),
376
            ..Default::default()
377
        };
378
379
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
380
        let mut ops = self.op_log()?;
381
        ops.reverse();
382
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
383
        // The fast-import parent of the next commit: `:mark` or a commit sha.
384
        let mut last_parent: Option<String> = None;
385
        for (_, op) in &ops {
386
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
387
                continue;
388
            };
389
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
390
                continue;
391
            }
392
            let Ok(state) = self.store.get_state(&state_ref) else {
393
                continue;
394
            };
395
            if state.heads.is_empty() {
396
                prev = Some((state_ref, vec![]));
397
                continue;
398
            }
399
            if let Some(sha) = git_states.get(&state_ref) {
400
                report.skipped += 1;
401
                last_parent = Some(sha.clone());
402
                prev = Some((state_ref, state.heads.clone()));
403
                continue;
404
            }
405
            if let Some(m) = marks.get(&state_ref) {
406
                report.skipped += 1;
407
                last_parent = Some(format!(":{m}"));
408
                prev = Some((state_ref, state.heads.clone()));
409
                continue;
410
            }
411
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
412
            let added = self
413
                .negotiate(&prev_heads, &state.heads)
414
                .unwrap_or_default();
415
            let loaded = self.load_state(&state.heads)?;
416
            let snapshot = loaded.materialize();
417
            let (author, secs, mut message) = match added.as_slice() {
418
                [h] => {
419
                    let c = self.store.get_change(h)?;
420
                    let mut m = c.message.clone();
421
                    if !m.ends_with('\n') {
422
                        m.push('\n');
423
                    }
424
                    m.push_str(&format!(
425
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
426
                        c.change_id.to_hex(),
427
                        h.to_hex()
428
                    ));
429
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
430
                }
431
                [] => (
432
                    "oxy <oxy@localhost>".to_string(),
433
                    op.hlc.wall_ms / 1000,
434
                    format!("oxy: {}\n\n", op.command),
435
                ),
436
                many => {
437
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
438
                    for h in many {
439
                        let c = self.store.get_change(h)?;
440
                        m.push_str(&format!(
441
                            "- {} {}\n",
442
                            c.change_id.short(8),
443
                            c.message.lines().next().unwrap_or("")
444
                        ));
445
                    }
446
                    m.push_str(&format!(
447
                        "\nOxy-Changes: {}\n",
448
                        many.iter()
449
                            .map(|h| h.to_hex())
450
                            .collect::<Vec<_>>()
451
                            .join(" ")
452
                    ));
453
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
454
                }
455
            };
456
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
457
            if snapshot.is_conflicted() {
458
                message.push_str("Oxy-Conflicted: true\n");
459
            }
460
            let mark = next_mark;
461
            next_mark += 1;
462
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
463
            self.write_commit(
464
                &mut stream,
465
                "refs/oxy/export",
466
                mark,
467
                &author,
468
                secs,
469
                &message,
470
                &parents,
471
                &snapshot,
472
            )?;
473
            marks.insert(state_ref, mark);
474
            last_parent = Some(format!(":{mark}"));
475
            prev = Some((state_ref, state.heads.clone()));
476
            report.exported += 1;
477
        }
478
        if let Some(p) = &last_parent {
479
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
480
        }
481
        // Tags: a tag whose state was exported as a bookmark state points at
482
        // that commit; otherwise its state gets a commit of its own.
483
        for t in self.tags()? {
484
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
485
                (Some(sha), _) => sha.clone(),
486
                (None, Some(m)) => format!(":{m}"),
487
                (None, None) => {
488
                    let loaded = self.load_state(&t.heads)?;
489
                    let snapshot = loaded.materialize();
490
                    let mark = next_mark;
491
                    next_mark += 1;
492
                    let message = format!(
493
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
494
                        t.name,
495
                        if t.message.is_empty() {
496
                            String::new()
497
                        } else {
498
                            format!("{}\n\n", t.message)
499
                        },
500
                        t.state.to_hex()
501
                    );
502
                    self.write_commit(
503
                        &mut stream,
504
                        "refs/oxy/export",
505
                        mark,
506
                        "oxy <oxy@localhost>",
507
                        Hlc::now().wall_ms / 1000,
508
                        &message,
509
                        &[],
510
                        &snapshot,
511
                    )?;
512
                    marks.insert(t.state, mark);
513
                    report.exported += 1;
514
                    format!(":{mark}")
515
                }
516
            };
517
            stream.extend_from_slice(
518
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
519
            );
520
        }
521
        stream.extend_from_slice(b"done\n");
522
523
        let mut cmd = Command::new("git");
524
        // `--force`: the scratch ref may jump between unrelated states.
525
        cmd.arg("-C")
526
            .arg(git_dir)
527
            .args(["fast-import", "--quiet", "--done", "--force"])
528
            .arg(format!("--export-marks={}", git_marks.display()));
529
        if git_marks.exists() {
530
            cmd.arg(format!("--import-marks={}", git_marks.display()));
531
        }
532
        let mut child = cmd
533
            .stdin(Stdio::piped())
534
            .stdout(Stdio::null())
535
            .stderr(Stdio::piped())
536
            .spawn()
537
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
538
        child.stdin.take().unwrap().write_all(&stream)?;
539
        let out = child.wait_with_output()?;
540
        if !out.status.success() {
541
            return fail(format!(
542
                "git fast-import failed: {}",
543
                String::from_utf8_lossy(&out.stderr).trim()
544
            ));
545
        }
546
        let text: String = marks
547
            .iter()
548
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
549
            .collect();
550
        write_atomic(&oxy_marks_path, text.as_bytes())?;
551
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
552
        report.skipped_subrepos = self.git_export_skipped.replace(0);
553
        Ok(report)
554
    }
555
556
    /// Import branch `branch` of the Git repository at `git_dir` into this
557
    /// (empty) repository's bookmark (spec §23): one change per commit, its
558
    /// edits the difference between the union of its parents' states and its
559
    /// tree, so merge commits become resolutions. Submodules are skipped.
560
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
561
        if !self.bookmark_heads()?.is_empty() {
562
            return fail("git import needs an empty bookmark; import into a fresh repository");
563
        }
564
        self.import_git_commits(
565
            git_dir,
566
            branch,
567
            &format!("oxy git import {} {branch}", git_dir.display()),
568
        )
569
    }
570
571
    /// Import the commits of `branch` that the bookmark does not have yet,
572
    /// then move the bookmark to the union of its heads and theirs.
573
    fn import_git_commits(
574
        &self,
575
        git_dir: &Path,
576
        branch: &str,
577
        command: &str,
578
    ) -> Result<GitImportReport> {
579
        let batch = self.store.begin_batch()?;
580
        let result = self.import_git_commits_batched(git_dir, branch, command);
581
        batch.finish()?;
582
        result
583
    }
584
585
    fn import_git_commits_batched(
586
        &self,
587
        git_dir: &Path,
588
        branch: &str,
589
        command: &str,
590
    ) -> Result<GitImportReport> {
591
        let commits = list_commits(git_dir, branch)?;
592
        let mut cat = CatFile::start(git_dir)?;
593
        let mut report = GitImportReport::default();
594
        let mut known = self.git_known(git_dir)?;
595
        let old_heads = self.bookmark_heads()?;
596
        let mut new_changes: Vec<Change> = Vec::new();
597
        // The state after the most recently imported commit, reused when the
598
        // next commit's first parent is that commit.
599
        let mut last: Option<(String, State)> = None;
600
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
601
        let mut cache_bytes: usize = 0;
602
603
        for gc in &commits {
604
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
605
                continue;
606
            }
607
            // Base: union of every parent's state.
608
            let mut base = match (&gc.parents.first(), &last) {
609
                (Some(p1), Some((sha, st))) if *p1 == sha => st.clone(),
610
                (Some(p1), _) => {
611
                    let mut st = State::new();
612
                    self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
613
                    st
614
                }
615
                (None, _) => State::new(),
616
            };
617
            if gc.parents.len() > 1 {
618
                report.merges += 1;
619
                let mut args: Vec<String> = gc.parents[1..].to_vec();
620
                args.push(format!("^{}", gc.parents[0]));
621
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
622
                self.add_git_ancestors(&mut base, git_dir, &refs, &known)?;
623
            }
624
            let base_snapshot = base.materialize();
625
626
            // The commit's tree as in-memory entries.
627
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
628
            let mut gitlinks: Vec<(String, String)> = Vec::new();
629
            for (path, (mode, sha)) in list_tree(git_dir, &gc.sha)? {
630
                let (kind, exec) = match mode.as_str() {
631
                    "100644" | "100664" => (NodeKind::File, false),
632
                    "100755" => (NodeKind::File, true),
633
                    "120000" => (NodeKind::Symlink, false),
634
                    "160000" => {
635
                        gitlinks.push((path, sha));
636
                        continue;
637
                    }
638
                    _ => continue,
639
                };
640
                let content = match blob_cache.get(&sha) {
641
                    Some(c) => c.clone(),
642
                    None => {
643
                        let c = cat.read(&sha)?;
644
                        if cache_bytes + c.len() > 256 * 1024 * 1024 {
645
                            blob_cache.clear();
646
                            cache_bytes = 0;
647
                        }
648
                        cache_bytes += c.len();
649
                        blob_cache.insert(sha.clone(), c.clone());
650
                        c
651
                    }
652
                };
653
                entries.insert(path, FsEntry::new(kind, exec, content));
654
            }
655
656
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
657
            // pins, and `.gitmodules` also yields `.oxymodules`.
658
            if !gitlinks.is_empty() {
659
                report.submodules += gitlinks.len();
660
                let gm = entries
661
                    .get(".gitmodules")
662
                    .map(|e| {
663
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
664
                            &e.content,
665
                        ))
666
                    })
667
                    .unwrap_or_default();
668
                let mut modules = entries
669
                    .get(".oxymodules")
670
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
671
                    .unwrap_or_default();
672
                for (path, sha) in &gitlinks {
673
                    let m = gm.entries.get(path);
674
                    let branch = m
675
                        .and_then(|m| m.bookmark.clone())
676
                        .unwrap_or_else(|| "HEAD".into());
677
                    entries.insert(
678
                        path.clone(),
679
                        FsEntry::new(
680
                            NodeKind::Subrepo,
681
                            false,
682
                            crate::subrepo::Pin::Git {
683
                                sha: sha.clone(),
684
                                branch,
685
                            }
686
                            .encode(),
687
                        ),
688
                    );
689
                    if let Some(m) = m {
690
                        modules.entries.insert(path.clone(), m.clone());
691
                    }
692
                }
693
                if !modules.entries.is_empty() {
694
                    entries.insert(
695
                        ".oxymodules".into(),
696
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
697
                    );
698
                }
699
            }
700
            let mut built =
701
                self.build_from_entries(&base, &base_snapshot, HashMap::new(), &entries)?;
702
            // A file or submodule with several live blobs (branches that
703
            // replaced it independently) is resolved to the commit's blob:
704
            // Git's merge is the authority here, unlike a working copy,
705
            // where a candidate on disk is not yet a decision (spec §23).
706
            for (path, f) in &base_snapshot.files {
707
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
708
                else {
709
                    continue;
710
                };
711
                if blobs.len() < 2 || f.kind != e.kind {
712
                    continue;
713
                }
714
                let chosen = self.store_blob(&e.content)?;
715
                for b in blobs {
716
                    built.edits.push(Edit::Replace {
717
                        node: f.node,
718
                        old: Some(*b),
719
                        new: Some(chosen),
720
                    });
721
                }
722
                built.resolves = true;
723
                built
724
                    .contributors
725
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
726
            }
727
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
728
            let mut message = gc.message.clone();
729
            if !message.ends_with('\n') {
730
                message.push('\n');
731
            }
732
            message.push_str(&format!(
733
                "\nGit-Commit: {}\nGit-Author: {}\n",
734
                gc.sha, gc.author
735
            ));
736
            let mut change = Change {
737
                change_id: change_id_for(&gc.sha, &gc.message),
738
                deps: vec![],
739
                author: ObjectRef::ZERO,
740
                hlc: Hlc {
741
                    wall_ms: gc.author_secs * 1000,
742
                    logical: 0,
743
                },
744
                message,
745
                tree_ops: built.tree_ops,
746
                edits: built.edits,
747
                kind: if built.resolves {
748
                    ChangeKind::Resolution
749
                } else {
750
                    ChangeKind::Normal
751
                },
752
            };
753
            deps.extend(referenced_changes(&change, &base));
754
            change.deps = deps.into_iter().collect();
755
            change.normalize();
756
            let hash = self.store.put_change(&change)?;
757
            new_changes.push(change.clone());
758
            base.add_unchecked(change);
759
            known.imported.insert(gc.sha.clone(), hash);
760
            last = Some((gc.sha.clone(), base));
761
            report.commits += 1;
762
        }
763
764
        // The bookmark: heads of the old state plus every new change.
765
        report.heads = old_heads.len();
766
        if last.is_none() {
767
            return Ok(report);
768
        }
769
        let mut all = self.load_state(&old_heads)?;
770
        for c in new_changes {
771
            all.add_unchecked(c);
772
        }
773
        let mut heads = all.heads();
774
        heads.sort();
775
        report.heads = heads.len();
776
        let (op_ref, op) = self.head_op()?;
777
        let mut view = op.view.clone();
778
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
779
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
780
        view.bookmarks
781
            .insert(self.config.bookmark.clone(), state_ref);
782
        self.record_op(&[op_ref], command, view)?;
783
        // The new state equals the tip's tree when the old one was itself a
784
        // Git commit's tree (fetched or exported), or there was none.
785
        let old_known = old_heads.is_empty()
786
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
787
        if let (Some(tip), true) = (commits.last(), old_known) {
788
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
789
        }
790
        // The working copy follows when it was clean on the old heads.
791
        if old_heads.is_empty() {
792
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
793
        } else {
794
            let snap = self.snapshot(command)?;
795
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
796
            let mut base = snap.base.maximal(&snap.wc.deps);
797
            base.sort();
798
            let mut sorted_old = old_heads.clone();
799
            sorted_old.sort();
800
            if clean && base == sorted_old {
801
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
802
            }
803
        }
804
        Ok(report)
805
    }
806
807
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
808
    /// an imported commit's change, or the whole state an exported commit
809
    /// was made from (which may hold changes Git never saw).
810
    fn add_git_ancestors(
811
        &self,
812
        st: &mut State,
813
        git_dir: &Path,
814
        args: &[&str],
815
        known: &GitKnown,
816
    ) -> Result<()> {
817
        let mut full = vec!["rev-list"];
818
        full.extend(args);
819
        let out = git(git_dir, &full)?;
820
        for sha in out.lines() {
821
            if let Some(h) = known.imported.get(sha) {
822
                st.add_unchecked(self.store.get_change(h)?);
823
            } else if let Some(state_ref) = known.exported.get(sha) {
824
                let heads = self.store.get_state(state_ref)?.heads;
825
                for h in self.negotiate(&[], &heads)? {
826
                    st.add_unchecked(self.store.get_change(&h)?);
827
                }
828
            }
829
        }
830
        Ok(())
831
    }
832
833
    /// Commits this repository can relate to Oxygen history: imported
834
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
835
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
836
        let imported = self.imported_commits()?;
837
        let marks_dir = self.git_marks_dir(git_dir)?;
838
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
839
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
840
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
841
            for line in text.lines() {
842
                if let Some((m, sha)) = line.split_once(' ') {
843
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
844
                        sha_of_mark.insert(m, sha.trim().to_string());
845
                    }
846
                }
847
            }
848
        }
849
        let mut exported = HashMap::new();
850
        for (state_ref, m) in oxy_marks {
851
            if let Some(sha) = sha_of_mark.get(&m) {
852
                exported.insert(sha.clone(), state_ref);
853
            }
854
        }
855
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
856
            exported.entry(sha).or_insert(state_ref);
857
        }
858
        Ok(GitKnown { imported, exported })
859
    }
860
861
    fn git_author(&self, c: &Change) -> String {
862
        match self.store.get_identity(&c.author) {
863
            Ok(id) if !id.name.is_empty() => format!(
864
                "{} <{}>",
865
                id.name.replace(['<', '>', '\n'], " "),
866
                id.email.replace(['<', '>', '\n', ' '], "")
867
            ),
868
            _ => "oxy <oxy@localhost>".to_string(),
869
        }
870
    }
871
872
    #[allow(clippy::too_many_arguments)]
873
    fn write_commit(
874
        &self,
875
        out: &mut Vec<u8>,
876
        reference: &str,
877
        mark: u64,
878
        author: &str,
879
        secs: u64,
880
        message: &str,
881
        parents: &[String],
882
        snapshot: &Snapshot,
883
    ) -> Result<()> {
884
        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());
885
        for (i, p) in parents.iter().enumerate() {
886
            out.extend_from_slice(
887
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
888
            );
889
        }
890
        out.extend_from_slice(b"deleteall\n");
891
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
892
        for (path, f) in &snapshot.files {
893
            if path == ".oxymodules" {
894
                // Git reads `.gitmodules`; derive it unless the tree has one.
895
                if !has_gitmodules {
896
                    if let FileContent::Text { bytes, .. } = &f.content {
897
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
898
                            .to_gitmodules();
899
                        if !gm.is_empty() {
900
                            out.extend_from_slice(
901
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
902
                                    .as_bytes(),
903
                            );
904
                            out.extend_from_slice(gm.as_bytes());
905
                            out.push(b'\n');
906
                        }
907
                    }
908
                }
909
                continue;
910
            }
911
            if f.kind == NodeKind::Subrepo {
912
                if let FileContent::Opaque { blobs } = &f.content {
913
                    if let Some(b) = blobs.first() {
914
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
915
                            crate::subrepo::Pin::Git { sha, .. } => {
916
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
917
                            }
918
                            crate::subrepo::Pin::Oxy { .. } => self
919
                                .git_export_skipped
920
                                .set(self.git_export_skipped.get() + 1),
921
                        }
922
                    }
923
                }
924
                continue;
925
            }
926
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
927
                (NodeKind::Dir, _) => continue,
928
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
929
                    "120000",
930
                    blobs
931
                        .first()
932
                        .map(|b| self.read_blob(b))
933
                        .transpose()?
934
                        .unwrap_or_default(),
935
                ),
936
                (_, FileContent::Text { bytes, .. }) => {
937
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
938
                }
939
                (_, FileContent::Opaque { blobs }) => (
940
                    if f.mode.exec { "100755" } else { "100644" },
941
                    blobs
942
                        .first()
943
                        .map(|b| self.read_blob(b))
944
                        .transpose()?
945
                        .unwrap_or_default(),
946
                ),
947
                (_, FileContent::Dir) => continue,
948
            };
949
            out.extend_from_slice(
950
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
951
            );
952
            out.extend_from_slice(&bytes);
953
            out.push(b'\n');
954
        }
955
        out.push(b'\n');
956
        Ok(())
957
    }
958
}
959
960
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
961
#[derive(Debug, Clone, Default, PartialEq, Eq)]
962
pub struct GitVerifyReport {
963
    pub commits: usize,
964
    pub files_compared: usize,
965
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
966
    pub mismatches: Vec<(String, String)>,
967
}
968
969
impl Repo {
970
    /// Check an import against its Git source: for every commit of
971
    /// `branch`, the state formed by the changes imported for it and all
972
    /// its ancestors must materialize to exactly that commit's tree, byte
973
    /// for byte, with the same executable bits, symlink targets and
974
    /// submodule pins. Reads only; stops listing after 50 differences.
975
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
976
        let commits = list_commits(git_dir, branch)?;
977
        let imported = self.imported_commits()?;
978
        let mut cat = CatFile::start(git_dir)?;
979
        let mut rep = GitVerifyReport::default();
980
        // Changes of each commit and all its ancestors, built up in topological order.
981
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
982
        for c in &commits {
983
            rep.commits += 1;
984
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
985
            for p in &c.parents {
986
                if let Some(ps) = closure.get(p) {
987
                    set.extend(ps.iter().copied());
988
                }
989
            }
990
            match imported.get(&c.sha) {
991
                Some(h) => {
992
                    set.insert(*h);
993
                }
994
                None => {
995
                    rep.mismatches.push((
996
                        c.sha.clone(),
997
                        "no imported change carries this commit".into(),
998
                    ));
999
                }
1000
            }
1001
            let set = Arc::new(set);
1002
            closure.insert(c.sha.clone(), set.clone());
1003
            if rep.mismatches.len() >= 50 {
1004
                break;
1005
            }
1006
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1007
            let state = self.load_state(&heads)?;
1008
            let snap = state.materialize();
1009
            let tree = list_tree(git_dir, &c.sha)?;
1010
            let short = &c.sha[..12.min(c.sha.len())];
1011
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
1012
            if snap.is_conflicted() {
1013
                // Name the changes behind each conflicted file, by their Git commits.
1014
                let mut detail = Vec::new();
1015
                for (path, f) in &snap.files {
1016
                    if !f.is_conflicted() {
1017
                        continue;
1018
                    }
1019
                    let who: Vec<String> = state
1020
                        .conflict_regions(&f.node)
1021
                        .contributors
1022
                        .iter()
1023
                        .filter_map(|h| state.get(h))
1024
                        .map(|m| {
1025
                            let sha = m
1026
                                .message
1027
                                .lines()
1028
                                .rev()
1029
                                .find_map(|l| l.strip_prefix("Git-Commit: "))
1030
                                .unwrap_or("?");
1031
                            format!(
1032
                                "{} {:?}",
1033
                                &sha[..12.min(sha.len())],
1034
                                m.message.lines().next().unwrap_or("")
1035
                            )
1036
                        })
1037
                        .collect();
1038
                    detail.push(format!("{path} between {}", who.join(" and ")));
1039
                }
1040
                differ(format!(
1041
                    "{short}: the state is conflicted: {}",
1042
                    detail.join("; ")
1043
                ));
1044
            }
1045
            for (path, (mode, sha)) in &tree {
1046
                let Some(f) = snap.files.get(path) else {
1047
                    differ(format!("{short}: {path} is missing"));
1048
                    continue;
1049
                };
1050
                rep.files_compared += 1;
1051
                match mode.as_str() {
1052
                    "160000" => match (&f.kind, &f.content) {
1053
                        (NodeKind::Subrepo, FileContent::Opaque { blobs }) if blobs.len() == 1 => {
1054
                            let pin = crate::subrepo::Pin::decode(&self.read_blob(&blobs[0])?)?;
1055
                            if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
1056
                            {
1057
                                differ(format!("{short}: {path} pins another commit"));
1058
                            }
1059
                        }
1060
                        (kind, content) => differ(format!(
1061
                            "{short}: {path} is not one submodule pin: {kind:?} with {}",
1062
                            match content {
1063
                                FileContent::Opaque { blobs } => format!("{} pins", blobs.len()),
1064
                                FileContent::Text { .. } => "text".into(),
1065
                                FileContent::Dir => "a directory".into(),
1066
                            }
1067
                        )),
1068
                    },
1069
                    "120000" => {
1070
                        let target = cat.read(sha)?;
1071
                        match (&f.kind, &f.content) {
1072
                            (NodeKind::Symlink, FileContent::Opaque { blobs })
1073
                                if blobs.len() == 1 && self.read_blob(&blobs[0])? == target => {}
1074
                            _ => differ(format!("{short}: symlink {path} differs")),
1075
                        }
1076
                    }
1077
                    _ => {
1078
                        let want = cat.read(sha)?;
1079
                        let have = match &f.content {
1080
                            FileContent::Text { bytes, .. } => bytes.clone(),
1081
                            FileContent::Opaque { blobs } if blobs.len() == 1 => {
1082
                                self.read_blob(&blobs[0])?
1083
                            }
1084
                            _ => {
1085
                                differ(format!("{short}: {path} is not one file"));
1086
                                continue;
1087
                            }
1088
                        };
1089
                        if have != want {
1090
                            differ(format!(
1091
                                "{short}: {path} differs: {}",
1092
                                first_difference(&have, &want)
1093
                            ));
1094
                        }
1095
                        if f.mode.exec != (mode == "100755") {
1096
                            differ(format!("{short}: {path} executable bit differs"));
1097
                        }
1098
                    }
1099
                }
1100
            }
1101
            // Import records submodules in `.oxymodules` as well (spec §23),
1102
            // and export leaves it out again.
1103
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
1104
            for (path, f) in &snap.files {
1105
                if f.kind != NodeKind::Dir
1106
                    && !tree.contains_key(path)
1107
                    && !(has_submodules && path == ".oxymodules")
1108
                {
1109
                    differ(format!("{short}: {path} is extra"));
1110
                }
1111
            }
1112
            if rep.mismatches.len() >= 50 {
1113
                break;
1114
            }
1115
        }
1116
        Ok(rep)
1117
    }
1118
}
1119
1120
/// Where two versions of a file first part, for a verification report.
1121
fn first_difference(have: &[u8], want: &[u8]) -> String {
1122
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
1123
        have.split(|b| *b == b'\n').collect(),
1124
        want.split(|b| *b == b'\n').collect(),
1125
    );
1126
    let i = h
1127
        .iter()
1128
        .zip(&w)
1129
        .position(|(a, b)| a != b)
1130
        .unwrap_or(h.len().min(w.len()));
1131
    let show = |l: Option<&&[u8]>| {
1132
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
1133
            .unwrap_or_else(|| "(end)".into())
1134
    };
1135
    format!(
1136
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
1137
        i + 1,
1138
        show(h.get(i)),
1139
        show(w.get(i)),
1140
        h.len(),
1141
        w.len()
1142
    )
1143
}