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