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