OXYGENHUB
◆ v0.7.0 oxygen / crates / oxy-core / src / repo / git.rs
90.9 KiB · Rust · last changed Windows paths print plainly (closes #143) 10 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
/// The email of a Git author `Name <email>`, lowercased.
201
fn git_email(author: &str) -> Option<String> {
202
    let (_, rest) = author.rsplit_once('<')?;
203
    let email = rest.strip_suffix('>')?.trim();
204
    (!email.is_empty()).then(|| email.to_lowercase())
205
}
206
207
/// One commit as `git log` describes it.
208
struct GitCommit {
209
    sha: String,
210
    parents: Vec<String>,
211
    author_secs: u64,
212
    author: String,
213
    message: String,
214
}
215
216
fn list_commits(git_dir: &Path, branch: &str) -> Result<Vec<GitCommit>> {
217
    let out = Command::new("git")
218
        .arg("-C")
219
        .arg(git_dir)
220
        .args([
221
            "log",
222
            "--reverse",
223
            "--topo-order",
224
            "--format=%H%x00%P%x00%at%x00%an <%ae>%x00%B%x1e",
225
            branch,
226
        ])
227
        .output()
228
        .map_err(|e| RepoError::Msg(format!("running git log: {e}")))?;
229
    if !out.status.success() {
230
        return fail(format!(
231
            "git log {branch} failed: {}",
232
            String::from_utf8_lossy(&out.stderr).trim()
233
        ));
234
    }
235
    let text = String::from_utf8_lossy(&out.stdout);
236
    let mut commits = Vec::new();
237
    for record in text.split('\x1e') {
238
        let record = record.trim_start_matches('\n');
239
        if record.trim().is_empty() {
240
            continue;
241
        }
242
        let f: Vec<&str> = record.splitn(5, '\0').collect();
243
        if f.len() != 5 {
244
            return fail("unexpected git log record");
245
        }
246
        commits.push(GitCommit {
247
            sha: f[0].to_string(),
248
            parents: f[1].split_whitespace().map(str::to_string).collect(),
249
            author_secs: f[2].parse().unwrap_or(0),
250
            author: f[3].to_string(),
251
            message: f[4].trim_end().to_string(),
252
        });
253
    }
254
    Ok(commits)
255
}
256
257
/// `path → (mode, blob sha)` for a commit's tree.
258
fn list_tree(git_dir: &Path, sha: &str) -> Result<BTreeMap<String, (String, String)>> {
259
    let text = git(git_dir, &["ls-tree", "-r", "-z", sha])?;
260
    let mut out = BTreeMap::new();
261
    for entry in text.split('\0') {
262
        if entry.is_empty() {
263
            continue;
264
        }
265
        let Some((meta, path)) = entry.split_once('\t') else {
266
            continue;
267
        };
268
        let m: Vec<&str> = meta.split(' ').collect();
269
        if m.len() == 3 {
270
            out.insert(path.to_string(), (m[0].to_string(), m[2].to_string()));
271
        }
272
    }
273
    Ok(out)
274
}
275
276
/// The ChangeId for a Git commit: its `Change-Id` trailer if it has a
277
/// 32-hex one, else BLAKE3-128 of the commit hash (spec §23).
278
fn change_id_for(sha: &str, message: &str) -> ChangeId {
279
    for line in message.lines().rev() {
280
        if let Some(v) = line.strip_prefix("Change-Id:") {
281
            if let Some(id) = ChangeId::from_hex(v.trim()) {
282
                return id;
283
            }
284
        }
285
    }
286
    let h = blake3::hash(sha.as_bytes());
287
    ChangeId(h.as_bytes()[..16].try_into().unwrap())
288
}
289
290
/// Git commits with a known Oxygen counterpart.
291
struct GitKnown {
292
    /// Imported commit → its change.
293
    imported: HashMap<String, ChangeHash>,
294
    /// Exported commit (or a fetched tip) → the bookmark state it equals.
295
    exported: HashMap<String, ObjectRef>,
296
}
297
298
#[derive(Debug, Clone, Default, PartialEq, Eq)]
299
pub struct GitExportReport {
300
    pub exported: usize,
301
    pub skipped: usize,
302
    /// Subrepo nodes with Oxygen pins, which Git cannot represent.
303
    pub skipped_subrepos: usize,
304
    pub branch: String,
305
    pub heads: usize,
306
}
307
308
/// A merge bringing more commits than this sheds its base's graphs first.
309
const MERGE_SHED_COMMITS: usize = 100;
310
311
/// The atoms a kept state's built graphs may hold before they go back into
312
/// its history (#25): about a few hundred megabytes.
313
const KEPT_ATOMS: usize = 1_500_000;
314
/// A kept state with more built graphs than this sheds them.
315
const KEPT_GRAPHS: usize = 2000;
316
/// An import moves its bookmark to the commits done so far every this
317
/// many commits, so one that stops part way resumes from there: imported
318
/// commits are found from the bookmark's history (`imported_commits`).
319
const CHECKPOINT_COMMITS: usize = 2000;
320
321
/// Text files of a merge rendered this many at a time (oxygen#25): a
322
/// batch's graphs are built beside the state and dropped once rendered,
323
/// so what is held for the whole tree is the renderings, not the graphs
324
/// with every deleted line of their history.
325
const MERGE_BATCH: usize = 500;
326
327
thread_local! {
328
    /// A smaller batch for this thread's imports: tests set 1, so a small
329
    /// merge takes the batched path.
330
    static MERGE_BATCH_OVERRIDE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
331
}
332
333
#[cfg(test)]
334
pub(crate) fn set_merge_batch_for_tests(n: Option<usize>) {
335
    MERGE_BATCH_OVERRIDE.with(|c| c.set(n));
336
}
337
338
fn merge_batch() -> usize {
339
    MERGE_BATCH_OVERRIDE
340
        .with(|c| c.get())
341
        .filter(|n| *n > 0)
342
        .or_else(|| {
343
            std::env::var("OXY_MERGE_BATCH")
344
                .ok()
345
                .and_then(|v| v.parse().ok())
346
        })
347
        .unwrap_or(MERGE_BATCH)
348
}
349
350
impl Repo {
351
    /// As `State::materialize_except`, for a tree whose graphs would not
352
    /// fit in memory at once. The few files the change builder reads
353
    /// graphs for (conflicted ones, and renderings whose lines are not
354
    /// one per live atom) are built in the state afterwards.
355
    fn materialize_batched(
356
        &self,
357
        base: &mut State,
358
        need: &[crate::ids::NodeId],
359
        skip: &HashSet<crate::ids::NodeId>,
360
    ) -> Result<crate::state::Snapshot> {
361
        use crate::graph::Materialized;
362
        use crate::state::{FileContent, FileState};
363
        use rayon::prelude::*;
364
        let view = base.tree().view();
365
        let mut rendered: HashMap<crate::ids::NodeId, (Vec<u8>, Materialized)> =
366
            HashMap::with_capacity(need.len());
367
        let mut keep_built: Vec<crate::ids::NodeId> = Vec::new();
368
        for batch in need.chunks(merge_batch()) {
369
            let t = std::time::Instant::now();
370
            let graphs = self.build_graphs_detached(base, batch)?;
371
            crate::timing::add("render: build graphs, batch", t.elapsed());
372
            let t = std::time::Instant::now();
373
            let batch_rendered: Vec<(crate::ids::NodeId, Vec<u8>, Materialized)> = graphs
374
                .par_iter()
375
                .map(|(node, g)| {
376
                    let (bytes, m) = base.render_graph(g);
377
                    (*node, bytes, m)
378
                })
379
                .collect();
380
            drop(graphs);
381
            crate::timing::add("render: render, batch", t.elapsed());
382
            for (node, bytes, m) in batch_rendered {
383
                if m.is_conflicted()
384
                    || m.live_atoms().len() != crate::diff::split_lines(&bytes).len()
385
                {
386
                    keep_built.push(node);
387
                }
388
                rendered.insert(node, (bytes, m));
389
            }
390
        }
391
        if !keep_built.is_empty() {
392
            self.load_graphs_of(base, &keep_built)?;
393
        }
394
        let mut files = BTreeMap::new();
395
        let mut unrendered = BTreeSet::new();
396
        for (path, e) in view.entries.iter() {
397
            let f = if e.kind == NodeKind::File && !e.mode.opaque {
398
                match rendered.remove(&e.node) {
399
                    Some((bytes, materialized)) => FileState {
400
                        node: e.node,
401
                        kind: e.kind,
402
                        mode: e.mode,
403
                        content: FileContent::Text {
404
                            bytes,
405
                            materialized,
406
                        },
407
                    },
408
                    None if skip.contains(&e.node) => {
409
                        unrendered.insert(path.clone());
410
                        FileState {
411
                            node: e.node,
412
                            kind: e.kind,
413
                            mode: e.mode,
414
                            content: FileContent::Text {
415
                                bytes: Vec::new(),
416
                                materialized: Materialized::default(),
417
                            },
418
                        }
419
                    }
420
                    None => {
421
                        // Neither asked for nor known unchanged: render it
422
                        // from a built graph, as the whole-tree path does.
423
                        self.load_graphs_of(base, &[e.node])?;
424
                        base.entry_state(e)
425
                    }
426
                }
427
            } else {
428
                base.entry_state(e)
429
            };
430
            files.insert(path.clone(), f);
431
        }
432
        Ok(crate::state::Snapshot {
433
            tree: view,
434
            files,
435
            unrendered,
436
        })
437
    }
438
}
439
440
fn git(dir: &Path, args: &[&str]) -> Result<String> {
441
    let out = Command::new("git")
442
        .arg("-C")
443
        .arg(dir)
444
        .args(args)
445
        .output()
446
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
447
    if !out.status.success() {
448
        return fail(format!(
449
            "git {} failed: {}",
450
            args.join(" "),
451
            String::from_utf8_lossy(&out.stderr).trim()
452
        ));
453
    }
454
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
455
}
456
457
impl Repo {
458
    fn git_marks_dir(&self, git_dir: &Path) -> Result<PathBuf> {
459
        let canonical =
460
            crate::portable::canonical(git_dir).unwrap_or_else(|_| git_dir.to_path_buf());
461
        let key = hash_object(ObjectType::Chunk, canonical.to_string_lossy().as_bytes()).short(16);
462
        let dir = self.oxy.join("git").join(key);
463
        fs::create_dir_all(&dir)?;
464
        Ok(dir)
465
    }
466
467
    /// `state ref → Git commit sha` for bookmark states that equal a Git
468
    /// commit's tree (recorded by import and fetch).
469
    fn read_git_states(path: &Path) -> Result<BTreeMap<ObjectRef, String>> {
470
        let mut out = BTreeMap::new();
471
        if let Ok(text) = fs::read_to_string(path) {
472
            for line in text.lines() {
473
                if let Some((h, sha)) = line.split_once(' ') {
474
                    if let Some(h) = ObjectRef::from_hex(h) {
475
                        out.insert(h, sha.trim().to_string());
476
                    }
477
                }
478
            }
479
        }
480
        Ok(out)
481
    }
482
483
    fn record_git_state(&self, git_dir: &Path, state: &ObjectRef, sha: &str) -> Result<()> {
484
        let path = self.git_marks_dir(git_dir)?.join("git-states");
485
        let mut states = Self::read_git_states(&path)?;
486
        states.insert(*state, sha.to_string());
487
        let text: String = states
488
            .iter()
489
            .map(|(h, s)| format!("{} {s}\n", h.to_hex()))
490
            .collect();
491
        write_atomic(&path, text.as_bytes())
492
    }
493
494
    /// The bare mirror this repository keeps for the Git remote `url`.
495
    fn git_mirror(&self, url: &str) -> Result<PathBuf> {
496
        let key = hash_object(ObjectType::Chunk, url.as_bytes()).short(16);
497
        let dir = self.oxy.join("git").join(key).join("mirror.git");
498
        if !dir.join("HEAD").exists() {
499
            fs::create_dir_all(&dir)?;
500
            git(&dir, &["init", "--bare", "-q"])?;
501
        }
502
        Ok(dir)
503
    }
504
505
    /// Git commits already imported into the bookmark, by sha.
506
    pub(crate) fn imported_commits(&self) -> Result<HashMap<String, ChangeHash>> {
507
        let mut map = HashMap::new();
508
        for e in self.log()? {
509
            if e.is_working_copy {
510
                continue;
511
            }
512
            if let Some(sha) = e
513
                .change
514
                .message
515
                .lines()
516
                .rev()
517
                .find_map(|l| l.strip_prefix("Git-Commit: "))
518
            {
519
                map.insert(sha.trim().to_string(), e.hash);
520
            }
521
        }
522
        Ok(map)
523
    }
524
525
    /// Bring the mirror's `branch` up to date with the Git remote `url`.
526
    /// A remote without that branch yet leaves the mirror as it is.
527
    fn git_mirror_fetch(&self, mirror: &Path, url: &str, branch: &str) -> Result<()> {
528
        let spec = format!("+refs/heads/{branch}:refs/heads/{branch}");
529
        match git(mirror, &["fetch", "-q", url, &spec]) {
530
            Ok(_) => Ok(()),
531
            Err(e) => {
532
                let ls = git(mirror, &["ls-remote", "--heads", url, branch]).unwrap_or_default();
533
                if ls.trim().is_empty() {
534
                    Ok(())
535
                } else {
536
                    Err(e)
537
                }
538
            }
539
        }
540
    }
541
542
    /// Fetch `branch` of the Git repository at `url` (a path or a Git URL)
543
    /// through a mirror and import the commits not yet in the bookmark
544
    /// (spec §23). Works on a repository that already has history: the
545
    /// new changes join the bookmark like a pull.
546
    pub fn git_fetch(&self, url: &str, branch: &str) -> Result<GitImportReport> {
547
        // A local path, made absolute: git runs it from inside the mirror.
548
        let local = crate::portable::canonical(Path::new(url))
549
            .ok()
550
            .filter(|_| !url.contains("://"));
551
        let absolute = local.as_ref().map(|p| p.to_string_lossy().into_owned());
552
        let url = absolute.as_deref().unwrap_or(url);
553
        let mirror = self.git_mirror(url)?;
554
        self.git_mirror_fetch(&mirror, url, branch)?;
555
        if git(
556
            &mirror,
557
            &[
558
                "rev-parse",
559
                "--verify",
560
                "-q",
561
                &format!("refs/heads/{branch}"),
562
            ],
563
        )
564
        .is_err()
565
        {
566
            return fail(format!("{url} has no branch {branch:?}"));
567
        }
568
        self.import_git_commits(
569
            &mirror,
570
            branch,
571
            &format!("oxy git fetch {url} {branch}"),
572
            &mut |_| {},
573
        )
574
    }
575
576
    /// Export the bookmark to `branch` of the Git repository at `url`
577
    /// through the mirror and push it. The remote's tip must already have
578
    /// been fetched (`git_fetch`), so the push fast-forwards.
579
    pub fn git_push(&self, url: &str, branch: &str) -> Result<GitExportReport> {
580
        let mirror = self.git_mirror(url)?;
581
        self.git_mirror_fetch(&mirror, url, branch)?;
582
        if let Ok(tip) = git(
583
            &mirror,
584
            &[
585
                "rev-parse",
586
                "--verify",
587
                "-q",
588
                &format!("refs/heads/{branch}"),
589
            ],
590
        ) {
591
            let known = self.git_known(&mirror)?;
592
            if !known.imported.contains_key(&tip) && !known.exported.contains_key(&tip) {
593
                return fail(format!(
594
                    "{url} {branch} has commits not yet fetched; run `oxy git fetch {url}` first"
595
                ));
596
            }
597
        }
598
        let report = self.git_export_as(&mirror, branch)?;
599
        let spec = format!("refs/heads/{branch}:refs/heads/{branch}");
600
        git(&mirror, &["push", "-q", url, &spec])?;
601
        Ok(report)
602
    }
603
604
    fn read_oxy_marks(path: &Path) -> Result<BTreeMap<ObjectRef, u64>> {
605
        let mut out = BTreeMap::new();
606
        if let Ok(text) = fs::read_to_string(path) {
607
            for line in text.lines() {
608
                if let Some((h, m)) = line.split_once(' ') {
609
                    if let (Some(h), Ok(m)) = (ObjectRef::from_hex(h), m.parse()) {
610
                        out.insert(h, m);
611
                    }
612
                }
613
            }
614
        }
615
        Ok(out)
616
    }
617
618
    /// Export the current bookmark to the Git repository at `git_dir`,
619
    /// creating a bare one if nothing is there. Each state the bookmark
620
    /// passed through (per the operation log) becomes one commit whose tree
621
    /// is that state, so the Git branch is a linear history of full trees.
622
    pub fn git_export(&self, git_dir: &Path) -> Result<GitExportReport> {
623
        let bookmark = self.config.bookmark.clone();
624
        self.git_export_as(git_dir, &bookmark)
625
    }
626
627
    /// `git_export` to the Git branch `branch`. A state that came from a
628
    /// Git commit (`oxy git fetch`) is not re-exported: later states chain
629
    /// onto that commit, so a push back to the Git remote fast-forwards.
630
    pub fn git_export_as(&self, git_dir: &Path, branch: &str) -> Result<GitExportReport> {
631
        if !git_dir.join("HEAD").exists() && !git_dir.join(".git").exists() {
632
            fs::create_dir_all(git_dir)?;
633
            git(git_dir, &["init", "--bare", "-q"])?;
634
        }
635
        let marks_dir = self.git_marks_dir(git_dir)?;
636
        let git_marks = marks_dir.join("git-marks");
637
        let oxy_marks_path = marks_dir.join("oxy-marks");
638
        let mut marks = Self::read_oxy_marks(&oxy_marks_path)?;
639
        let git_states = Self::read_git_states(&marks_dir.join("git-states"))?;
640
        let mut next_mark = marks.values().copied().max().unwrap_or(0) + 1;
641
642
        let bookmark = self.config.bookmark.clone();
643
        let mut stream: Vec<u8> = Vec::new();
644
        let mut report = GitExportReport {
645
            branch: branch.to_string(),
646
            heads: self.bookmark_heads()?.len(),
647
            ..Default::default()
648
        };
649
650
        // States along the bookmark, oldest first, skipping unchanged and pruned ones.
651
        let mut ops = self.op_log()?;
652
        ops.reverse();
653
        let mut prev: Option<(ObjectRef, Vec<ChangeHash>)> = None;
654
        // The fast-import parent of the next commit: `:mark` or a commit sha.
655
        let mut last_parent: Option<String> = None;
656
        for (_, op) in &ops {
657
            let Some(state_ref) = op.view.bookmarks.get(&bookmark).copied() else {
658
                continue;
659
            };
660
            if prev.as_ref().is_some_and(|(p, _)| *p == state_ref) {
661
                continue;
662
            }
663
            let Ok(state) = self.store.get_state(&state_ref) else {
664
                continue;
665
            };
666
            if state.heads.is_empty() {
667
                prev = Some((state_ref, vec![]));
668
                continue;
669
            }
670
            if let Some(sha) = git_states.get(&state_ref) {
671
                report.skipped += 1;
672
                last_parent = Some(sha.clone());
673
                prev = Some((state_ref, state.heads.clone()));
674
                continue;
675
            }
676
            if let Some(m) = marks.get(&state_ref) {
677
                report.skipped += 1;
678
                last_parent = Some(format!(":{m}"));
679
                prev = Some((state_ref, state.heads.clone()));
680
                continue;
681
            }
682
            let prev_heads = prev.as_ref().map(|(_, h)| h.clone()).unwrap_or_default();
683
            let added = self
684
                .negotiate(&prev_heads, &state.heads)
685
                .unwrap_or_default();
686
            let loaded = self.load_state(&state.heads)?;
687
            let snapshot = loaded.materialize();
688
            let (author, secs, mut message) = match added.as_slice() {
689
                [h] => {
690
                    let c = self.store.get_change(h)?;
691
                    let mut m = c.message.clone();
692
                    if !m.ends_with('\n') {
693
                        m.push('\n');
694
                    }
695
                    m.push_str(&format!(
696
                        "\nChange-Id: {}\nOxy-Hash: {}\n",
697
                        c.change_id.to_hex(),
698
                        h.to_hex()
699
                    ));
700
                    (self.git_author(&c), c.hlc.wall_ms / 1000, m)
701
                }
702
                [] => (
703
                    "oxy <oxy@localhost>".to_string(),
704
                    op.hlc.wall_ms / 1000,
705
                    format!("oxy: {}\n\n", op.command),
706
                ),
707
                many => {
708
                    let mut m = format!("oxy: {} ({} changes)\n\n", op.command, many.len());
709
                    for h in many {
710
                        let c = self.store.get_change(h)?;
711
                        m.push_str(&format!(
712
                            "- {} {}\n",
713
                            c.change_id.short(8),
714
                            c.message.lines().next().unwrap_or("")
715
                        ));
716
                    }
717
                    m.push_str(&format!(
718
                        "\nOxy-Changes: {}\n",
719
                        many.iter()
720
                            .map(|h| h.to_hex())
721
                            .collect::<Vec<_>>()
722
                            .join(" ")
723
                    ));
724
                    ("oxy <oxy@localhost>".to_string(), op.hlc.wall_ms / 1000, m)
725
                }
726
            };
727
            message.push_str(&format!("Oxy-State: {}\n", state_ref.to_hex()));
728
            if snapshot.is_conflicted() {
729
                message.push_str("Oxy-Conflicted: true\n");
730
            }
731
            let mark = next_mark;
732
            next_mark += 1;
733
            let parents: Vec<String> = last_parent.clone().into_iter().collect();
734
            self.write_commit(
735
                &mut stream,
736
                "refs/oxy/export",
737
                mark,
738
                &author,
739
                secs,
740
                &message,
741
                &parents,
742
                &snapshot,
743
            )?;
744
            marks.insert(state_ref, mark);
745
            last_parent = Some(format!(":{mark}"));
746
            prev = Some((state_ref, state.heads.clone()));
747
            report.exported += 1;
748
        }
749
        if let Some(p) = &last_parent {
750
            stream.extend_from_slice(format!("reset refs/heads/{branch}\nfrom {p}\n\n").as_bytes());
751
        }
752
        // Tags: a tag whose state was exported as a bookmark state points at
753
        // that commit; otherwise its state gets a commit of its own.
754
        for t in self.tags()? {
755
            let target = match (git_states.get(&t.state), marks.get(&t.state)) {
756
                (Some(sha), _) => sha.clone(),
757
                (None, Some(m)) => format!(":{m}"),
758
                (None, None) => {
759
                    let loaded = self.load_state(&t.heads)?;
760
                    let snapshot = loaded.materialize();
761
                    let mark = next_mark;
762
                    next_mark += 1;
763
                    let message = format!(
764
                        "oxy: tag {}\n\n{}Oxy-State: {}\n",
765
                        t.name,
766
                        if t.message.is_empty() {
767
                            String::new()
768
                        } else {
769
                            format!("{}\n\n", t.message)
770
                        },
771
                        t.state.to_hex()
772
                    );
773
                    self.write_commit(
774
                        &mut stream,
775
                        "refs/oxy/export",
776
                        mark,
777
                        "oxy <oxy@localhost>",
778
                        Hlc::now().wall_ms / 1000,
779
                        &message,
780
                        &[],
781
                        &snapshot,
782
                    )?;
783
                    marks.insert(t.state, mark);
784
                    report.exported += 1;
785
                    format!(":{mark}")
786
                }
787
            };
788
            stream.extend_from_slice(
789
                format!("reset refs/tags/{}\nfrom {target}\n\n", t.name).as_bytes(),
790
            );
791
        }
792
        stream.extend_from_slice(b"done\n");
793
794
        let mut cmd = Command::new("git");
795
        // `--force`: the scratch ref may jump between unrelated states.
796
        cmd.arg("-C")
797
            .arg(git_dir)
798
            .args(["fast-import", "--quiet", "--done", "--force"])
799
            .arg(format!("--export-marks={}", git_marks.display()));
800
        if git_marks.exists() {
801
            cmd.arg(format!("--import-marks={}", git_marks.display()));
802
        }
803
        let mut child = cmd
804
            .stdin(Stdio::piped())
805
            .stdout(Stdio::null())
806
            .stderr(Stdio::piped())
807
            .spawn()
808
            .map_err(|e| RepoError::Msg(format!("running git fast-import: {e}")))?;
809
        child.stdin.take().unwrap().write_all(&stream)?;
810
        let out = child.wait_with_output()?;
811
        if !out.status.success() {
812
            return fail(format!(
813
                "git fast-import failed: {}",
814
                String::from_utf8_lossy(&out.stderr).trim()
815
            ));
816
        }
817
        let text: String = marks
818
            .iter()
819
            .map(|(h, m)| format!("{} {m}\n", h.to_hex()))
820
            .collect();
821
        write_atomic(&oxy_marks_path, text.as_bytes())?;
822
        let _ = git(git_dir, &["update-ref", "-d", "refs/oxy/export"]);
823
        report.skipped_subrepos = self.git_export_skipped.replace(0);
824
        Ok(report)
825
    }
826
827
    /// Import branch `branch` of the Git repository at `git_dir` into this
828
    /// (empty) repository's bookmark (spec §23): one change per commit, its
829
    /// edits the difference between the union of its parents' states and its
830
    /// tree, so merge commits become resolutions. Submodules are skipped.
831
    pub fn import_git(&self, git_dir: &Path, branch: &str) -> Result<GitImportReport> {
832
        self.import_git_with(git_dir, branch, &mut |_| {})
833
    }
834
835
    /// `import_git`, telling `progress` where it is every few hundred
836
    /// commits: the count so far, the merges, and the commit in hand, so a
837
    /// long import is never silent and a run that dies says where.
838
    pub fn import_git_with(
839
        &self,
840
        git_dir: &Path,
841
        branch: &str,
842
        progress: crate::store::Progress<'_>,
843
    ) -> Result<GitImportReport> {
844
        if !self.bookmark_heads()?.is_empty() {
845
            return fail("git import needs an empty bookmark; import into a fresh repository");
846
        }
847
        self.import_git_commits(
848
            git_dir,
849
            branch,
850
            &format!("oxy git import {} {branch}", git_dir.display()),
851
            progress,
852
        )
853
    }
854
855
    /// Import the commits of `branch` that the bookmark does not have yet,
856
    /// then move the bookmark to the union of its heads and theirs.
857
    fn import_git_commits(
858
        &self,
859
        git_dir: &Path,
860
        branch: &str,
861
        command: &str,
862
        progress: crate::store::Progress<'_>,
863
    ) -> Result<GitImportReport> {
864
        let batch = self.store.begin_batch()?;
865
        let result = self.import_git_commits_batched(git_dir, branch, command, progress);
866
        batch.finish()?;
867
        result
868
    }
869
870
    fn import_git_commits_batched(
871
        &self,
872
        git_dir: &Path,
873
        branch: &str,
874
        command: &str,
875
        progress: crate::store::Progress<'_>,
876
    ) -> Result<GitImportReport> {
877
        let commits = list_commits(git_dir, branch)?;
878
        let mut cat = CatFile::start(git_dir)?;
879
        let mut report = GitImportReport::default();
880
        let mut known = self.git_known(git_dir)?;
881
        let old_heads = self.bookmark_heads()?;
882
        // The bookmark's heads as changes arrive: a change stops being a
883
        // head when another depends on it, so no full state of every
884
        // imported change is needed at the end.
885
        let mut heads_now: BTreeSet<ChangeHash> = old_heads.iter().copied().collect();
886
        // The state and Git tree of imported commits whose first-parent
887
        // children are still to come, so a child starts from its parent's
888
        // state instead of rebuilding it from history. The last child takes
889
        // it; earlier ones clone it. At most `max_kept` are kept (a later
890
        // child of an evicted one rebuilds).
891
        // OXY_IMPORT_KEEP overrides it, for measuring.
892
        let max_kept: usize = std::env::var("OXY_IMPORT_KEEP")
893
            .ok()
894
            .and_then(|v| v.parse().ok())
895
            .unwrap_or(8);
896
        let mut waiting: HashMap<&str, usize> = HashMap::new();
897
        for gc in &commits {
898
            if let Some(p1) = gc.parents.first() {
899
                *waiting.entry(p1.as_str()).or_default() += 1;
900
            }
901
        }
902
        type Kept = (State, BTreeMap<String, (String, String)>);
903
        let mut kept: HashMap<String, Kept> = HashMap::new();
904
        // Every commit to import that has a parent, diffed against its first.
905
        let pairs: Vec<(String, String)> = commits
906
            .iter()
907
            .filter(|gc| {
908
                !known.imported.contains_key(&gc.sha) && !known.exported.contains_key(&gc.sha)
909
            })
910
            .filter_map(|gc| Some((gc.sha.clone(), gc.parents.first()?.clone())))
911
            .collect();
912
        let mut diffs = DiffTree::start(git_dir, pairs)?;
913
        let mut rebuilt = 0usize;
914
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
915
        let mut last: Option<String> = None;
916
        let mut blob_cache: HashMap<String, Vec<u8>> = HashMap::new();
917
        let mut cache_bytes: usize = 0;
918
        // Time spent per phase over all commits (`OXY_TIMINGS=1`).
919
        let mut spent = [std::time::Duration::ZERO; 6];
920
        let mut clock = std::time::Instant::now();
921
        // One line per commit on stderr with OXY_IMPORT_TRACE=1: where its
922
        // base came from, what a merge added, the graphs its state holds,
923
        // the kept states and the process's resident memory.
924
        let trace = std::env::var_os("OXY_IMPORT_TRACE").is_some();
925
        let rss_mb = || -> u64 {
926
            std::fs::read_to_string("/proc/self/statm")
927
                .ok()
928
                .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
929
                .map(|pages| (pages * 4096) >> 20)
930
                .unwrap_or(0)
931
        };
932
        let mut done = 0usize;
933
        // Atoms a kept state's graphs may hold before they are shed;
934
        // OXY_IMPORT_KEPT_ATOMS overrides it, for measuring.
935
        let kept_atoms: usize = std::env::var("OXY_IMPORT_KEPT_ATOMS")
936
            .ok()
937
            .and_then(|v| v.parse().ok())
938
            .unwrap_or(KEPT_ATOMS);
939
        // Graphs turned back into history (see `State::shed_graphs`).
940
        let mut shed = 0usize;
941
        let mut lap = |i: usize, clock: &mut std::time::Instant| {
942
            let now = std::time::Instant::now();
943
            spent[i] += now - *clock;
944
            *clock = now;
945
        };
946
947
        // OXY_IMPORT_CHECKPOINT overrides it, for testing.
948
        let checkpoint_every: usize = std::env::var("OXY_IMPORT_CHECKPOINT")
949
            .ok()
950
            .and_then(|v| v.parse().ok())
951
            .filter(|n| *n > 0)
952
            .unwrap_or(CHECKPOINT_COMMITS);
953
        // OXY_IMPORT_STOP_AFTER ends the import cleanly after that many
954
        // commits, its timings reported, for measuring at depth.
955
        let stop_after: Option<usize> = std::env::var("OXY_IMPORT_STOP_AFTER")
956
            .ok()
957
            .and_then(|v| v.parse().ok());
958
        // Merges built from the paths they can change (oxygen#80): on VS
959
        // Code at 139k commits the same 400 commits came out identical to
960
        // whole-tree merges, with merges 3.2x faster. OXY_IMPORT_WHOLE_MERGES=1
961
        // builds them from the whole tree, for comparing.
962
        let partial_merges = std::env::var_os("OXY_IMPORT_WHOLE_MERGES").is_none_or(|v| v == "0");
963
        let total = commits.len();
964
        // The importing identity's own commits, claimed (`git.claim`,
965
        // oxygen#97): a commit whose Git author email is its email gets
966
        // its key as author; anyone else's keeps the zero key.
967
        let claim: Option<(KeyId, String)> = if self.config.git_claim {
968
            let Some(key) = self.config.author_key else {
969
                return fail("git.claim authors your own commits with your key, and there is none: run `oxy identity create` first, or `oxy config git.claim false`");
970
            };
971
            Some((key, self.identity(&key)?.email.to_lowercase()))
972
        } else {
973
            None
974
        };
975
        for (index, gc) in commits.iter().enumerate() {
976
            if known.imported.contains_key(&gc.sha) || known.exported.contains_key(&gc.sha) {
977
                continue;
978
            }
979
            if stop_after.is_some_and(|n| done >= n) {
980
                break;
981
            }
982
            let commit_started = std::time::Instant::now();
983
            if index % 500 == 0 {
984
                progress(&format!(
985
                    "{index} of {total} commits, {} merges; at {} {}",
986
                    report.merges,
987
                    &gc.sha[..12.min(gc.sha.len())],
988
                    gc.message
989
                        .lines()
990
                        .next()
991
                        .unwrap_or("")
992
                        .chars()
993
                        .take(60)
994
                        .collect::<String>()
995
                ));
996
            }
997
            let mut base_how = "root";
998
            // Base: union of every parent's state, starting from the first
999
            // parent's kept state when there is one; its tree tells which
1000
            // paths this commit leaves alone.
1001
            let (mut base, prev_tree) = match gc.parents.first() {
1002
                Some(p1) => {
1003
                    let left = waiting.get_mut(p1.as_str()).map(|n| {
1004
                        *n -= 1;
1005
                        *n
1006
                    });
1007
                    let found = if left == Some(0) {
1008
                        kept_order.retain(|k| k != p1);
1009
                        kept.remove(p1.as_str())
1010
                    } else {
1011
                        kept.get(p1.as_str()).cloned()
1012
                    };
1013
                    let how = match (&found, left) {
1014
                        (Some(_), Some(0)) => "kept",
1015
                        (Some(_), _) => "cloned",
1016
                        (None, _) => "rebuilt",
1017
                    };
1018
                    if trace {
1019
                        base_how = how;
1020
                    }
1021
                    match found {
1022
                        Some((st, tree)) => (st, Some(tree)),
1023
                        None => {
1024
                            // History only: graphs are built for the files a
1025
                            // commit changes, so memory follows what changes,
1026
                            // not the whole tree.
1027
                            let mut st = State::new_history_only();
1028
                            self.add_git_ancestors(&mut st, git_dir, &[p1.as_str()], &known)?;
1029
                            // The parent's tree, so this commit still
1030
                            // renders only what it changes.
1031
                            rebuilt += 1;
1032
                            (st, Some(list_tree(git_dir, p1)?))
1033
                        }
1034
                    }
1035
                }
1036
                None => (State::new_history_only(), None),
1037
            };
1038
            // Nodes the other parents' changes touch: the first parent's
1039
            // tree cannot vouch for them.
1040
            let mut touched: HashSet<NodeId> = HashSet::new();
1041
            let mut merged = 0usize;
1042
            // Where the first parent has each node, read before the merged
1043
            // changes move anything: a merge's partial build names the paths
1044
            // they touch in the first parent's tree as well as in the merged
1045
            // state (oxygen#80).
1046
            let mut first_parent_view: Option<crate::tree::TreeView> = None;
1047
            if gc.parents.len() > 1 {
1048
                report.merges += 1;
1049
                if prev_tree.is_some() && partial_merges {
1050
                    first_parent_view = Some(base.tree().view());
1051
                }
1052
                let mut args: Vec<String> = gc.parents[1..].to_vec();
1053
                args.push(format!("^{}", gc.parents[0]));
1054
                let refs: Vec<&str> = args.iter().map(String::as_str).collect();
1055
                // A merge of a long-lived branch brings thousands of
1056
                // changes: added to built graphs, which kept states share,
1057
                // they were copied and applied whole (vscode's import passed
1058
                // 14 GB on such merges). Shed the graphs first, so the
1059
                // changes go in as skeletons and only what this commit
1060
                // touches is built again.
1061
                if base.built_count() > 0 {
1062
                    let mut count_args = vec!["rev-list", "--count"];
1063
                    count_args.extend(refs.iter().copied());
1064
                    let others: usize = git(git_dir, &count_args)?.trim().parse().unwrap_or(0);
1065
                    let shed_at = std::env::var("OXY_MERGE_SHED")
1066
                        .ok()
1067
                        .and_then(|v| v.parse().ok())
1068
                        .unwrap_or(MERGE_SHED_COMMITS);
1069
                    if others > shed_at {
1070
                        shed += base.shed_graphs(|b| self.store_blob(b))?;
1071
                    }
1072
                }
1073
                let before = base.len();
1074
                self.add_git_ancestors_touching(&mut base, git_dir, &refs, &known, &mut touched)?;
1075
                merged = base.len() - before;
1076
            }
1077
            lap(0, &mut clock);
1078
            // The commit's tree: its first parent's with the diff applied,
1079
            // or listed whole when that tree is not kept.
1080
            let diff = match gc.parents.first() {
1081
                Some(_) => Some(diffs.diff(&gc.sha)?),
1082
                None => None,
1083
            };
1084
            let (tree, changed) = match (prev_tree, diff) {
1085
                (Some(mut t), Some(diff)) => {
1086
                    let mut changed: HashSet<String> = HashSet::new();
1087
                    for (path, entry) in diff {
1088
                        match entry {
1089
                            Some(v) => {
1090
                                t.insert(path.clone(), v);
1091
                            }
1092
                            None => {
1093
                                t.remove(&path);
1094
                            }
1095
                        }
1096
                        changed.insert(path);
1097
                    }
1098
                    (t, Some(changed))
1099
                }
1100
                _ => (list_tree(git_dir, &gc.sha)?, None),
1101
            };
1102
            lap(1, &mut clock);
1103
            // Text files with the same blob and mode as in the first
1104
            // parent's tree equal the base's rendering: they are neither
1105
            // rendered nor read nor compared (spec §12.3, as for a clean
1106
            // working copy), so a commit costs what it changes.
1107
            let mut same: HashMap<&str, NodeId> = HashMap::new();
1108
            // Opaque files and symlinks likewise, when the base has one
1109
            // blob for them: they are neither read nor stored again.
1110
            let mut same_opaque: HashSet<&str> = HashSet::new();
1111
            // An ordinary commit in a tree without submodules is built from
1112
            // the paths it changes alone (oxygen#25): with the `.oxyattributes`
1113
            // files that decide how they are stored, and the directories its
1114
            // removals may leave empty. A merge, or a commit whose parent's
1115
            // tree is not at hand, is built from its whole tree.
1116
            // A merge can differ from its first parent only at the paths
1117
            // Git's diff names and where the merged changes touched: those
1118
            // paths in the first parent's tree and in the merged state. With
1119
            // them added it is built like an ordinary commit, instead of
1120
            // from its whole tree (18 s for any merge at 118k commits of
1121
            // VS Code, oxygen#80). OXY_IMPORT_WHOLE_MERGES=1 takes the
1122
            // whole-tree path.
1123
            let mut changed = changed;
1124
            // A tree conflict in the merged state (both sides placed a file
1125
            // at one path) is resolved by the whole-tree path.
1126
            let mut merge_how = if gc.parents.len() > 1 {
1127
                if first_parent_view.is_some() {
1128
                    "partial"
1129
                } else {
1130
                    "whole"
1131
                }
1132
            } else {
1133
                "-"
1134
            };
1135
            // Only a conflict among what the merged changes touched; one
1136
            // elsewhere stays as it was in the first parent either way.
1137
            if first_parent_view.is_some()
1138
                && base.tree().view().conflicts.iter().any(|c| {
1139
                    use crate::tree::TreeConflict::*;
1140
                    match c {
1141
                        Name { nodes, .. } => nodes.iter().any(|n| touched.contains(n)),
1142
                        MultiPlacement { node, .. } | Cycle { node } | Mode { node, .. } => {
1143
                            touched.contains(node)
1144
                        }
1145
                        Orphan { node, parent } => {
1146
                            touched.contains(node) || touched.contains(parent)
1147
                        }
1148
                    }
1149
                })
1150
            {
1151
                first_parent_view = None;
1152
                merge_how = "conflicted";
1153
            }
1154
            if let (Some(ch), Some(fp)) = (changed.as_mut(), &first_parent_view) {
1155
                let union = base.tree().view();
1156
                for v in [fp, &union] {
1157
                    for (path, e) in v.entries.iter() {
1158
                        if touched.contains(&e.node) {
1159
                            ch.insert(path.clone());
1160
                        }
1161
                    }
1162
                }
1163
            }
1164
            let partial = changed.is_some()
1165
                && (gc.parents.len() == 1 || first_parent_view.is_some())
1166
                && !tree.values().any(|(mode, _)| mode == "160000");
1167
            let mut rel: BTreeSet<&str> = BTreeSet::new();
1168
            // Text files whose graphs this commit builds, for the trace.
1169
            let need_n: usize;
1170
            let base_snapshot = if let (true, Some(changed)) = (partial, &changed) {
1171
                let view = base.tree().view();
1172
                rel.extend(changed.iter().map(String::as_str));
1173
                rel.extend(
1174
                    tree.keys()
1175
                        .map(String::as_str)
1176
                        .filter(|p| *p == ".oxyattributes" || p.ends_with("/.oxyattributes")),
1177
                );
1178
                let mut dirs: BTreeSet<&str> = BTreeSet::new();
1179
                for p in changed.iter().filter(|p| !tree.contains_key(*p)) {
1180
                    let mut end = p.len();
1181
                    while let Some(i) = p[..end].rfind('/') {
1182
                        if !dirs.insert(&p[..i]) {
1183
                            break;
1184
                        }
1185
                        end = i;
1186
                    }
1187
                }
1188
                let need: Vec<NodeId> = rel
1189
                    .iter()
1190
                    .filter_map(|p| view.entries.get(*p))
1191
                    .filter(|e| e.kind == NodeKind::File && !e.mode.opaque)
1192
                    .map(|e| e.node)
1193
                    .collect();
1194
                crate::timing::add("render: same and need", clock.elapsed());
1195
                need_n = need.len();
1196
                let t = std::time::Instant::now();
1197
                self.load_graphs_of(&mut base, &need)?;
1198
                crate::timing::add("render: load graphs", t.elapsed());
1199
                let t = std::time::Instant::now();
1200
                let snap = base.materialize_paths(view, rel.iter().chain(dirs.iter()).copied());
1201
                crate::timing::add("render: materialize", t.elapsed());
1202
                snap
1203
            } else {
1204
                if let Some(changed) = &changed {
1205
                    let view = base.tree().view();
1206
                    for path in tree.keys() {
1207
                        // Submodule handling reads these two whatever changed.
1208
                        if changed.contains(path) || path == ".gitmodules" || path == ".oxymodules"
1209
                        {
1210
                            continue;
1211
                        }
1212
                        if let Some(e) = view.entries.get(path) {
1213
                            if touched.contains(&e.node) {
1214
                                continue;
1215
                            }
1216
                            let opaque = e.kind == NodeKind::Symlink
1217
                                || (e.kind == NodeKind::File && e.mode.opaque);
1218
                            if e.kind == NodeKind::File && !e.mode.opaque {
1219
                                same.insert(path.as_str(), e.node);
1220
                            } else if opaque && base.live_blobs(&e.node).len() == 1 {
1221
                                same_opaque.insert(path.as_str());
1222
                            }
1223
                        }
1224
                    }
1225
                }
1226
                // Build the graphs of every text file the commit may change.
1227
                let skip: HashSet<NodeId> = same.values().copied().collect();
1228
                let need: Vec<NodeId> = base
1229
                    .tree()
1230
                    .view()
1231
                    .entries
1232
                    .values()
1233
                    .filter(|e| {
1234
                        e.kind == NodeKind::File && !e.mode.opaque && !skip.contains(&e.node)
1235
                    })
1236
                    .map(|e| e.node)
1237
                    .collect();
1238
                crate::timing::add("render: same and need", clock.elapsed());
1239
                need_n = need.len();
1240
                let t = std::time::Instant::now();
1241
                let snap = if need.len() > merge_batch() {
1242
                    // A merge onto a base with no built graphs: thousands
1243
                    // of files, whose graphs would not fit at once.
1244
                    self.materialize_batched(&mut base, &need, &skip)?
1245
                } else {
1246
                    let g = std::time::Instant::now();
1247
                    self.load_graphs_of(&mut base, &need)?;
1248
                    crate::timing::add("render: whole, load graphs", g.elapsed());
1249
                    let m = std::time::Instant::now();
1250
                    let snap = base.materialize_except(&skip);
1251
                    crate::timing::add("render: whole, materialize", m.elapsed());
1252
                    snap
1253
                };
1254
                crate::timing::add("render: whole tree", t.elapsed());
1255
                snap
1256
            };
1257
1258
            lap(2, &mut clock);
1259
            // The commit's tree as in-memory entries.
1260
            let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1261
            let mut gitlinks: Vec<(String, String)> = Vec::new();
1262
            let listed: Box<dyn Iterator<Item = (&String, &(String, String))>> = if partial {
1263
                Box::new(rel.iter().filter_map(|p| tree.get_key_value(*p)))
1264
            } else {
1265
                Box::new(tree.iter())
1266
            };
1267
            for (path, (mode, sha)) in listed {
1268
                let (path, sha) = (path.clone(), sha.clone());
1269
                let (kind, exec) = match mode.as_str() {
1270
                    "100644" | "100664" => (NodeKind::File, false),
1271
                    "100755" => (NodeKind::File, true),
1272
                    "120000" => (NodeKind::Symlink, false),
1273
                    "160000" => {
1274
                        gitlinks.push((path, sha));
1275
                        continue;
1276
                    }
1277
                    _ => continue,
1278
                };
1279
                if same.contains_key(path.as_str()) || same_opaque.contains(path.as_str()) {
1280
                    let mut e = FsEntry::new(kind, exec, Vec::new());
1281
                    e.unchanged = true;
1282
                    entries.insert(path, e);
1283
                    continue;
1284
                }
1285
                let content = match blob_cache.get(&sha) {
1286
                    Some(c) => c.clone(),
1287
                    None => {
1288
                        let c = cat.read(&sha)?;
1289
                        if cache_bytes + c.len() > 64 * 1024 * 1024 {
1290
                            blob_cache.clear();
1291
                            cache_bytes = 0;
1292
                        }
1293
                        cache_bytes += c.len();
1294
                        blob_cache.insert(sha.clone(), c.clone());
1295
                        c
1296
                    }
1297
                };
1298
                entries.insert(path, FsEntry::new(kind, exec, content));
1299
            }
1300
1301
            // Submodules (spec §23): gitlinks become subrepo nodes with Git
1302
            // pins, and `.gitmodules` also yields `.oxymodules`.
1303
            if !gitlinks.is_empty() {
1304
                report.submodules += gitlinks.len();
1305
                let gm = entries
1306
                    .get(".gitmodules")
1307
                    .map(|e| {
1308
                        crate::subrepo::Modules::from_gitmodules(&String::from_utf8_lossy(
1309
                            &e.content,
1310
                        ))
1311
                    })
1312
                    .unwrap_or_default();
1313
                let mut modules = entries
1314
                    .get(".oxymodules")
1315
                    .map(|e| crate::subrepo::Modules::parse(&String::from_utf8_lossy(&e.content)))
1316
                    .unwrap_or_default();
1317
                for (path, sha) in &gitlinks {
1318
                    let m = gm.entries.get(path);
1319
                    let branch = m
1320
                        .and_then(|m| m.bookmark.clone())
1321
                        .unwrap_or_else(|| "HEAD".into());
1322
                    entries.insert(
1323
                        path.clone(),
1324
                        FsEntry::new(
1325
                            NodeKind::Subrepo,
1326
                            false,
1327
                            crate::subrepo::Pin::Git {
1328
                                sha: sha.clone(),
1329
                                branch,
1330
                            }
1331
                            .encode(),
1332
                        ),
1333
                    );
1334
                    if let Some(m) = m {
1335
                        modules.entries.insert(path.clone(), m.clone());
1336
                    }
1337
                }
1338
                if !modules.entries.is_empty() {
1339
                    entries.insert(
1340
                        ".oxymodules".into(),
1341
                        FsEntry::new(NodeKind::File, false, modules.to_text().into_bytes()),
1342
                    );
1343
                }
1344
            }
1345
            lap(3, &mut clock);
1346
            // New nodes' identifiers derive from the commit, so importing the
1347
            // same Git history twice gives the same changes (spec §23).
1348
            let seed = *blake3::hash(format!("oxy git import\0{}", gc.sha).as_bytes()).as_bytes();
1349
            let mut built = if partial {
1350
                // Whether the new tree has anything under `dir`.
1351
                let dir_needed = |dir: &str| {
1352
                    let prefix = format!("{dir}/");
1353
                    tree.range(prefix.clone()..)
1354
                        .next()
1355
                        .is_some_and(|(k, _)| k.starts_with(&prefix))
1356
                };
1357
                self.build_from_entries_seeded(
1358
                    &base,
1359
                    &base_snapshot,
1360
                    &entries,
1361
                    seed,
1362
                    Some(&dir_needed),
1363
                )?
1364
            } else {
1365
                self.build_from_entries_seeded(&base, &base_snapshot, &entries, seed, None)?
1366
            };
1367
            lap(4, &mut clock);
1368
            // A file or submodule with several live blobs (branches that
1369
            // replaced it independently) is resolved to the commit's blob:
1370
            // Git's merge is the authority here, unlike a working copy,
1371
            // where a candidate on disk is not yet a decision (spec §23).
1372
            for (path, f) in &base_snapshot.files {
1373
                let (FileContent::Opaque { blobs }, Some(e)) = (&f.content, entries.get(path))
1374
                else {
1375
                    continue;
1376
                };
1377
                if blobs.len() < 2 || f.kind != e.kind {
1378
                    continue;
1379
                }
1380
                let chosen = self.store_blob(&e.content)?;
1381
                for b in blobs {
1382
                    built.edits.push(Edit::Replace {
1383
                        node: f.node,
1384
                        old: Some(*b),
1385
                        new: Some(chosen),
1386
                    });
1387
                }
1388
                built.resolves = true;
1389
                built
1390
                    .contributors
1391
                    .extend(base.live_replaces(&f.node).into_iter().map(|(c, _)| c));
1392
            }
1393
            // It shares the base's tree view, which applying the change
1394
            // then updates in place rather than copying.
1395
            drop(base_snapshot);
1396
            drop(entries);
1397
            let mut deps: BTreeSet<ChangeHash> = built.contributors.iter().copied().collect();
1398
            let mut message = gc.message.clone();
1399
            if !message.ends_with('\n') {
1400
                message.push('\n');
1401
            }
1402
            message.push_str(&format!(
1403
                "\nGit-Commit: {}\nGit-Author: {}\n",
1404
                gc.sha, gc.author
1405
            ));
1406
            let mut change = Change {
1407
                version: crate::objects::CHANGE_VERSION,
1408
                change_id: change_id_for(&gc.sha, &gc.message),
1409
                deps: vec![],
1410
                author: claim
1411
                    .as_ref()
1412
                    .filter(|(_, email)| git_email(&gc.author).is_some_and(|e| e == *email))
1413
                    .map_or(ObjectRef::ZERO, |(key, _)| *key),
1414
                hlc: Hlc {
1415
                    wall_ms: gc.author_secs * 1000,
1416
                    logical: 0,
1417
                },
1418
                message,
1419
                tree_ops: built.tree_ops,
1420
                edits: built.edits,
1421
                kind: if built.resolves {
1422
                    ChangeKind::Resolution
1423
                } else {
1424
                    ChangeKind::Normal
1425
                },
1426
            };
1427
            let t = std::time::Instant::now();
1428
            // A deletion depends on whoever inserted the live atoms after
1429
            // it, which only the file's graph knows: build the few the
1430
            // batched rendering left deferred.
1431
            let need: Vec<NodeId> = change
1432
                .edits
1433
                .iter()
1434
                .filter(|e| matches!(e, Edit::Delete { .. }))
1435
                .map(|e| e.node())
1436
                .filter(|n| !base.is_built(n))
1437
                .collect();
1438
            if !need.is_empty() {
1439
                self.load_graphs_of(&mut base, &need)?;
1440
            }
1441
            deps.extend(referenced_changes(&change, &base));
1442
            crate::timing::add("store: referenced", t.elapsed());
1443
            change.deps = deps.into_iter().collect();
1444
            change.normalize();
1445
            let hash = self.store.put_change(&change)?;
1446
            for d in &change.deps {
1447
                heads_now.remove(d);
1448
            }
1449
            heads_now.insert(hash);
1450
            // Built graphs take its edits whole; files not built keep only
1451
            // where its text is, read back from the store.
1452
            let t = std::time::Instant::now();
1453
            let (skeleton, texts) = self.store.get_change_lazy(&hash)?;
1454
            base.add_known_mixed(hash, change, skeleton, texts);
1455
            crate::timing::add("store: add to state", t.elapsed());
1456
            known.imported.insert(gc.sha.clone(), hash);
1457
            if waiting.get(gc.sha.as_str()).is_some_and(|n| *n > 0) {
1458
                // A kept state holds its graphs until its children come:
1459
                // past a few thousand, they go back into its history.
1460
                // Past a few thousand graphs, or past a budget of atoms: a
1461
                // long-lived file's graph keeps every line it ever had, so a
1462
                // handful of them can hold gigabytes (#25).
1463
                if base.built_count() > KEPT_GRAPHS || base.built_atoms() > kept_atoms {
1464
                    shed += base.shed_graphs(|b| self.store_blob(b))?;
1465
                }
1466
                kept.insert(gc.sha.clone(), (base, tree));
1467
                kept_order.push_back(gc.sha.clone());
1468
                if kept_order.len() > max_kept {
1469
                    if let Some(old) = kept_order.pop_front() {
1470
                        kept.remove(&old);
1471
                    }
1472
                }
1473
            }
1474
            last = Some(gc.sha.clone());
1475
            report.commits += 1;
1476
            lap(5, &mut clock);
1477
            done += 1;
1478
            if done.is_multiple_of(checkpoint_every) {
1479
                self.checkpoint_import(&heads_now, done)?;
1480
            }
1481
            // A merge renders thousands of files on many threads and frees
1482
            // it all; the allocator keeps those pages unless asked to give
1483
            // them back, and the next merge piles on top (#25).
1484
            let before_trim = if trace { rss_mb() } else { 0 };
1485
            if gc.parents.len() > 1 {
1486
                crate::alloc_stats::release_freed_memory();
1487
            }
1488
            if trace {
1489
                let built = kept
1490
                    .get(gc.sha.as_str())
1491
                    .map(|(st, _)| st.built_count())
1492
                    .unwrap_or(0);
1493
                let (edits, most) = kept
1494
                    .get(gc.sha.as_str())
1495
                    .map(|(st, _)| st.deferred_edit_count())
1496
                    .unwrap_or((0, 0));
1497
                let atoms = kept
1498
                    .get(gc.sha.as_str())
1499
                    .map(|(st, _)| st.built_atoms())
1500
                    .unwrap_or(0);
1501
                eprintln!(
1502
                    "trace {done} {} parents={} base={base_how} merged={merged} built={built} atoms={atoms} kept={} shed={shed} rss_mb={} before_trim_mb={before_trim} deferred_edits={edits} most={most} need={need_n} merge={merge_how} ms={}",
1503
                    &gc.sha[..12.min(gc.sha.len())],
1504
                    gc.parents.len(),
1505
                    kept.len(),
1506
                    rss_mb(),
1507
                    commit_started.elapsed().as_millis()
1508
                );
1509
            }
1510
        }
1511
        for (name, d) in [
1512
            "git import: bases",
1513
            "git import: tree",
1514
            "git import: render base",
1515
            "git import: read blobs",
1516
            "git import: build change",
1517
            "git import: store change",
1518
        ]
1519
        .iter()
1520
        .zip(spent)
1521
        {
1522
            crate::timing::record(name, d);
1523
        }
1524
        crate::timing::report_totals();
1525
        if crate::timing::enabled() {
1526
            eprintln!(
1527
                "timing git import: {rebuilt} bases rebuilt from history, {shed} graphs shed"
1528
            );
1529
        }
1530
1531
        // The bookmark: heads of the old state plus every new change.
1532
        report.heads = old_heads.len();
1533
        if last.is_none() {
1534
            return Ok(report);
1535
        }
1536
        let heads: Vec<ChangeHash> = heads_now.into_iter().collect();
1537
        report.heads = heads.len();
1538
        let (op_ref, op) = self.head_op()?;
1539
        let mut view = op.view.clone();
1540
        let old_state_ref = view.bookmarks.get(&self.config.bookmark).copied();
1541
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
1542
        view.bookmarks
1543
            .insert(self.config.bookmark.clone(), state_ref);
1544
        self.record_op(&[op_ref], command, view)?;
1545
        // The new state equals the tip's tree when the old one was itself a
1546
        // Git commit's tree (fetched or exported), or there was none.
1547
        let old_known = old_heads.is_empty()
1548
            || old_state_ref.is_some_and(|s| known.exported.values().any(|e| *e == s));
1549
        if let (Some(tip), true) = (commits.last(), old_known) {
1550
            self.record_git_state(git_dir, &state_ref, &tip.sha)?;
1551
        }
1552
        // The working copy follows when it was clean on the old heads.
1553
        if old_heads.is_empty() {
1554
            self.checkout(&heads, true, &format!("{command} (checkout)"))?;
1555
        } else {
1556
            let snap = self.snapshot(command)?;
1557
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1558
            let mut base = snap.base.maximal(&snap.wc.deps);
1559
            base.sort();
1560
            let mut sorted_old = old_heads.clone();
1561
            sorted_old.sort();
1562
            // An empty base too: an import that stopped after a checkpoint
1563
            // never checked anything out, and resuming it should.
1564
            if clean && (base == sorted_old || base.is_empty()) {
1565
                self.checkout(&heads, false, &format!("{command} (checkout)"))?;
1566
            }
1567
        }
1568
        Ok(report)
1569
    }
1570
1571
    /// Add to `st` the changes of every Git commit `rev-list args` lists:
1572
    /// an imported commit's change, or the whole state an exported commit
1573
    /// was made from (which may hold changes Git never saw).
1574
    fn add_git_ancestors(
1575
        &self,
1576
        st: &mut State,
1577
        git_dir: &Path,
1578
        args: &[&str],
1579
        known: &GitKnown,
1580
    ) -> Result<()> {
1581
        self.add_git_ancestors_touching(st, git_dir, args, known, &mut HashSet::new())
1582
    }
1583
1584
    /// `add_git_ancestors`, also collecting in `touched` every node the
1585
    /// changes it adds edit, place or remove.
1586
    fn add_git_ancestors_touching(
1587
        &self,
1588
        st: &mut State,
1589
        git_dir: &Path,
1590
        args: &[&str],
1591
        known: &GitKnown,
1592
        touched: &mut HashSet<NodeId>,
1593
    ) -> Result<()> {
1594
        let mut full = vec!["rev-list"];
1595
        full.extend(args);
1596
        let out = git(git_dir, &full)?;
1597
        let mut add = |st: &mut State, h: &ChangeHash| -> Result<()> {
1598
            if st.contains(h) {
1599
                return Ok(());
1600
            }
1601
            if !st.is_history_only() {
1602
                let c = self.store.get_change(h)?;
1603
                touched.extend(c.edits.iter().map(|e| e.node()));
1604
                touched.extend(c.tree_ops.iter().map(|o| o.node()));
1605
                st.add_unchecked(c);
1606
                return Ok(());
1607
            }
1608
            // History only: the text of an edit waits unread unless its
1609
            // file's graph is built.
1610
            let (skeleton, texts) = self.store.get_change_lazy(h)?;
1611
            touched.extend(skeleton.edits.iter().map(|e| e.node()));
1612
            touched.extend(skeleton.tree_ops.iter().map(|o| o.node()));
1613
            let built = skeleton
1614
                .edits
1615
                .iter()
1616
                .any(|e| !matches!(e, Edit::Replace { .. }) && st.is_built(&e.node()));
1617
            if built {
1618
                let full = self.store.get_change(h)?;
1619
                st.add_known_mixed(*h, full, skeleton, texts);
1620
            } else {
1621
                st.add_known(*h, skeleton, texts);
1622
            }
1623
            Ok(())
1624
        };
1625
        for sha in out.lines() {
1626
            if let Some(h) = known.imported.get(sha) {
1627
                add(st, h)?;
1628
            } else if let Some(state_ref) = known.exported.get(sha) {
1629
                let heads = self.store.get_state(state_ref)?.heads;
1630
                for h in self.negotiate(&[], &heads)? {
1631
                    add(st, &h)?;
1632
                }
1633
            }
1634
        }
1635
        Ok(())
1636
    }
1637
1638
    /// Recover an import that stopped before it moved the bookmark: its
1639
    /// unfinished pack indexed (`Store::adopt_unfinished_packs`), then every
1640
    /// change in the store that carries a `Git-Commit:` trailer, its heads
1641
    /// (those no other such change depends on) made the bookmark's heads,
1642
    /// so `oxy git fetch` carries on from there. Reads every object once.
1643
    /// Returns how many imported changes it found and the heads.
1644
    pub fn recover_git_import(&self, progress: &dyn Fn(&str)) -> Result<(usize, usize)> {
1645
        // A stopped import's objects are in a pack it never indexed.
1646
        // OXY_RECOVER_MIN_AGE (seconds) overrides the five minutes it must
1647
        // have been left alone, for testing.
1648
        let min_age = std::env::var("OXY_RECOVER_MIN_AGE")
1649
            .ok()
1650
            .and_then(|v| v.parse().ok())
1651
            .unwrap_or(300);
1652
        self.store
1653
            .adopt_unfinished_packs(std::time::Duration::from_secs(min_age), progress)?;
1654
        let all = self
1655
            .store
1656
            .list()
1657
            .map_err(|e| RepoError::Msg(format!("listing the store: {e}")))?;
1658
        let total = all.len();
1659
        let mut found: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
1660
        for (i, r) in all.iter().enumerate() {
1661
            if i.is_multiple_of(100_000) {
1662
                progress(&format!(
1663
                    "{i} of {total} objects read, {} imported changes",
1664
                    found.len()
1665
                ));
1666
            }
1667
            let Ok(meta) = self.store.get_change_meta(r) else {
1668
                continue;
1669
            };
1670
            if meta.message.lines().any(|l| l.starts_with("Git-Commit: ")) {
1671
                found.insert(*r, meta.deps.clone());
1672
            }
1673
        }
1674
        if found.is_empty() {
1675
            return fail("no imported Git commit's change in this store");
1676
        }
1677
        let depended: HashSet<ChangeHash> = found.values().flatten().copied().collect();
1678
        let mut heads: Vec<ChangeHash> = found
1679
            .keys()
1680
            .filter(|h| !depended.contains(h))
1681
            .copied()
1682
            .collect();
1683
        // The bookmark's present heads stay: a recovery only adds.
1684
        heads.extend(self.bookmark_heads().unwrap_or_default());
1685
        let st = self.load_state_history(&heads)?;
1686
        let mut heads = st.maximal(&heads);
1687
        heads.sort();
1688
        heads.dedup();
1689
        let (op_ref, op) = self.head_op()?;
1690
        let mut view = op.view.clone();
1691
        let state_ref = self.store.put_state(&StateObject::new(heads.clone()))?;
1692
        view.bookmarks
1693
            .insert(self.config.bookmark.clone(), state_ref);
1694
        self.record_op(&[op_ref], "oxy git recover", view)?;
1695
        Ok((found.len(), heads.len()))
1696
    }
1697
1698
    /// Point the bookmark at an import's heads so far (see
1699
    /// `CHECKPOINT_COMMITS`); the working copy is left alone until the end.
1700
    fn checkpoint_import(&self, heads: &BTreeSet<ChangeHash>, done: usize) -> Result<()> {
1701
        let heads: Vec<ChangeHash> = heads.iter().copied().collect();
1702
        let (op_ref, op) = self.head_op()?;
1703
        let mut view = op.view.clone();
1704
        let state_ref = self.store.put_state(&StateObject::new(heads))?;
1705
        view.bookmarks
1706
            .insert(self.config.bookmark.clone(), state_ref);
1707
        self.record_op(
1708
            &[op_ref],
1709
            &format!("oxy git import (checkpoint after {done} commits)"),
1710
            view,
1711
        )?;
1712
        Ok(())
1713
    }
1714
1715
    /// Commits this repository can relate to Oxygen history: imported
1716
    /// ones by change, exported ones (through `git_dir`'s marks) by state.
1717
    fn git_known(&self, git_dir: &Path) -> Result<GitKnown> {
1718
        let imported = self.imported_commits()?;
1719
        let marks_dir = self.git_marks_dir(git_dir)?;
1720
        let oxy_marks = Self::read_oxy_marks(&marks_dir.join("oxy-marks"))?;
1721
        let mut sha_of_mark: HashMap<u64, String> = HashMap::new();
1722
        if let Ok(text) = fs::read_to_string(marks_dir.join("git-marks")) {
1723
            for line in text.lines() {
1724
                if let Some((m, sha)) = line.split_once(' ') {
1725
                    if let Ok(m) = m.trim_start_matches(':').parse::<u64>() {
1726
                        sha_of_mark.insert(m, sha.trim().to_string());
1727
                    }
1728
                }
1729
            }
1730
        }
1731
        let mut exported = HashMap::new();
1732
        for (state_ref, m) in oxy_marks {
1733
            if let Some(sha) = sha_of_mark.get(&m) {
1734
                exported.insert(sha.clone(), state_ref);
1735
            }
1736
        }
1737
        for (state_ref, sha) in Self::read_git_states(&marks_dir.join("git-states"))? {
1738
            exported.entry(sha).or_insert(state_ref);
1739
        }
1740
        Ok(GitKnown { imported, exported })
1741
    }
1742
1743
    fn git_author(&self, c: &Change) -> String {
1744
        match self.store.get_identity(&c.author) {
1745
            Ok(id) if !id.name.is_empty() => format!(
1746
                "{} <{}>",
1747
                id.name.replace(['<', '>', '\n'], " "),
1748
                id.email.replace(['<', '>', '\n', ' '], "")
1749
            ),
1750
            _ => "oxy <oxy@localhost>".to_string(),
1751
        }
1752
    }
1753
1754
    #[allow(clippy::too_many_arguments)]
1755
    fn write_commit(
1756
        &self,
1757
        out: &mut Vec<u8>,
1758
        reference: &str,
1759
        mark: u64,
1760
        author: &str,
1761
        secs: u64,
1762
        message: &str,
1763
        parents: &[String],
1764
        snapshot: &Snapshot,
1765
    ) -> Result<()> {
1766
        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());
1767
        for (i, p) in parents.iter().enumerate() {
1768
            out.extend_from_slice(
1769
                format!("{} {p}\n", if i == 0 { "from" } else { "merge" }).as_bytes(),
1770
            );
1771
        }
1772
        out.extend_from_slice(b"deleteall\n");
1773
        let has_gitmodules = snapshot.files.contains_key(".gitmodules");
1774
        for (path, f) in &snapshot.files {
1775
            if path == ".oxymodules" {
1776
                // Git reads `.gitmodules`; derive it unless the tree has one.
1777
                if !has_gitmodules {
1778
                    if let FileContent::Text { bytes, .. } = &f.content {
1779
                        let gm = crate::subrepo::Modules::parse(&String::from_utf8_lossy(bytes))
1780
                            .to_gitmodules();
1781
                        if !gm.is_empty() {
1782
                            out.extend_from_slice(
1783
                                format!("M 100644 inline .gitmodules\ndata {}\n", gm.len())
1784
                                    .as_bytes(),
1785
                            );
1786
                            out.extend_from_slice(gm.as_bytes());
1787
                            out.push(b'\n');
1788
                        }
1789
                    }
1790
                }
1791
                continue;
1792
            }
1793
            if f.kind == NodeKind::Subrepo {
1794
                if let FileContent::Opaque { blobs } = &f.content {
1795
                    if let Some(b) = blobs.first() {
1796
                        match crate::subrepo::Pin::decode(&self.read_blob(b)?)? {
1797
                            crate::subrepo::Pin::Git { sha, .. } => {
1798
                                out.extend_from_slice(format!("M 160000 {sha} {path}\n").as_bytes())
1799
                            }
1800
                            crate::subrepo::Pin::Oxy { .. } => self
1801
                                .git_export_skipped
1802
                                .set(self.git_export_skipped.get() + 1),
1803
                        }
1804
                    }
1805
                }
1806
                continue;
1807
            }
1808
            let (mode, bytes): (&str, Vec<u8>) = match (&f.kind, &f.content) {
1809
                (NodeKind::Dir, _) => continue,
1810
                (NodeKind::Symlink, FileContent::Opaque { blobs }) => (
1811
                    "120000",
1812
                    blobs
1813
                        .first()
1814
                        .map(|b| self.read_blob(b))
1815
                        .transpose()?
1816
                        .unwrap_or_default(),
1817
                ),
1818
                (_, FileContent::Text { bytes, .. }) => {
1819
                    (if f.mode.exec { "100755" } else { "100644" }, bytes.clone())
1820
                }
1821
                (_, FileContent::Opaque { blobs }) => (
1822
                    if f.mode.exec { "100755" } else { "100644" },
1823
                    blobs
1824
                        .first()
1825
                        .map(|b| self.read_blob(b))
1826
                        .transpose()?
1827
                        .unwrap_or_default(),
1828
                ),
1829
                (_, FileContent::Dir) => continue,
1830
            };
1831
            out.extend_from_slice(
1832
                format!("M {mode} inline {path}\ndata {}\n", bytes.len()).as_bytes(),
1833
            );
1834
            out.extend_from_slice(&bytes);
1835
            out.push(b'\n');
1836
        }
1837
        out.push(b'\n');
1838
        Ok(())
1839
    }
1840
}
1841
1842
/// What `verify_git_import` found (spec §23: import must reproduce every tree).
1843
#[derive(Debug, Clone, Default, PartialEq, Eq)]
1844
pub struct GitVerifyReport {
1845
    pub commits: usize,
1846
    /// Commits followed but not rebuilt (all but the last few, when asked).
1847
    pub skipped: usize,
1848
    pub files_compared: usize,
1849
    /// `(commit, what differs)`; empty when every commit's tree is reproduced.
1850
    pub mismatches: Vec<(String, String)>,
1851
    /// Commits of the branch after the last imported one: an import not
1852
    /// finished yet. Not checked.
1853
    pub not_yet: usize,
1854
}
1855
1856
impl Repo {
1857
    /// Check an import against its Git source: for every commit of
1858
    /// `branch`, the state formed by the changes imported for it and all
1859
    /// its ancestors must materialize to exactly that commit's tree, byte
1860
    /// for byte, with the same executable bits, symlink targets and
1861
    /// submodule pins. Reads only; stops listing after 50 differences.
1862
    pub fn verify_git_import(&self, git_dir: &Path, branch: &str) -> Result<GitVerifyReport> {
1863
        self.verify_git_import_last(git_dir, branch, None, 50)
1864
    }
1865
1866
    /// [`Repo::verify_git_import`] of the last `last` commits only (all
1867
    /// when `None`): earlier ones are only followed, not rebuilt, for
1868
    /// looking again at where an import went wrong.
1869
    /// It stops after `max` differences (0: never), so one that repeats
1870
    /// through history does not hide the commits after it.
1871
    pub fn verify_git_import_last(
1872
        &self,
1873
        git_dir: &Path,
1874
        branch: &str,
1875
        last: Option<usize>,
1876
        max: usize,
1877
    ) -> Result<GitVerifyReport> {
1878
        let mut rep = GitVerifyReport::default();
1879
        let mut commits = list_commits(git_dir, branch)?;
1880
        let imported = self.imported_commits()?;
1881
        // An import still going (or stopped) has reached part of the
1882
        // branch: what follows its last imported commit is not checked,
1883
        // only counted, and --last counts back from there (oxygen#81).
1884
        if let Some(end) = commits.iter().rposition(|c| imported.contains_key(&c.sha)) {
1885
            let rest = commits.len() - end - 1;
1886
            if rest > 0 {
1887
                commits.truncate(end + 1);
1888
            }
1889
            rep.not_yet = rest;
1890
        }
1891
        let mut cat = CatFile::start(git_dir)?;
1892
        // Changes of each commit and all its ancestors, built up in topological order.
1893
        let mut closure: HashMap<String, Arc<BTreeSet<ChangeHash>>> = HashMap::new();
1894
        // Graphs (by key) and blobs already found equal to a Git blob.
1895
        let mut verified_graphs: HashMap<[u8; 32], String> = HashMap::new();
1896
        let mut verified_blobs: HashMap<ObjectRef, String> = HashMap::new();
1897
        // The state of a commit whose first-parent children are still to
1898
        // come, so a child adds its own changes instead of loading all its
1899
        // history again (as the import does).
1900
        let mut waiting: HashMap<&str, usize> = HashMap::new();
1901
        // Children still to come per commit, through any parent: a commit's
1902
        // closure is dropped after its last child, so only the open
1903
        // frontier is held. Kept for every commit, the closures grew with
1904
        // the square of the history and VS Code's verify ran out of memory
1905
        // (oxygen#81).
1906
        let mut children: HashMap<&str, usize> = HashMap::new();
1907
        for c in &commits {
1908
            if let Some(p1) = c.parents.first() {
1909
                *waiting.entry(p1.as_str()).or_default() += 1;
1910
            }
1911
            for p in &c.parents {
1912
                *children.entry(p.as_str()).or_default() += 1;
1913
            }
1914
        }
1915
        let mut kept: HashMap<String, State> = HashMap::new();
1916
        let mut kept_order: std::collections::VecDeque<String> = std::collections::VecDeque::new();
1917
        for c in &commits {
1918
            rep.commits += 1;
1919
            // The first parent's closure, taken over when this is its last
1920
            // child (no copy), then the other parents' added.
1921
            let mut set: BTreeSet<ChangeHash> = BTreeSet::new();
1922
            for (i, p) in c.parents.iter().enumerate() {
1923
                let left = children.get_mut(p.as_str()).map(|n| {
1924
                    *n -= 1;
1925
                    *n
1926
                });
1927
                let ps = if left == Some(0) {
1928
                    closure.remove(p)
1929
                } else {
1930
                    closure.get(p).cloned()
1931
                };
1932
                if let Some(ps) = ps {
1933
                    if i == 0 && set.is_empty() {
1934
                        set = Arc::try_unwrap(ps).unwrap_or_else(|a| (*a).clone());
1935
                    } else {
1936
                        set.extend(ps.iter().copied());
1937
                    }
1938
                }
1939
            }
1940
            match imported.get(&c.sha) {
1941
                Some(h) => {
1942
                    set.insert(*h);
1943
                }
1944
                None => {
1945
                    rep.mismatches.push((
1946
                        c.sha.clone(),
1947
                        "no imported change carries this commit".into(),
1948
                    ));
1949
                }
1950
            }
1951
            let set = Arc::new(set);
1952
            if children.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
1953
                closure.insert(c.sha.clone(), set.clone());
1954
            }
1955
            if max > 0 && rep.mismatches.len() >= max {
1956
                break;
1957
            }
1958
            if last.is_some_and(|n| rep.commits + n <= commits.len()) {
1959
                rep.skipped += 1;
1960
                continue;
1961
            }
1962
            let heads: Vec<ChangeHash> = set.iter().copied().collect();
1963
            // History only: a file whose graph (by key) or blob was already
1964
            // found equal to this Git blob is not built, rendered or read
1965
            // again; the rest are.
1966
            let from_parent = c.parents.first().and_then(|p1| {
1967
                let left = waiting.get_mut(p1.as_str()).map(|n| {
1968
                    *n -= 1;
1969
                    *n
1970
                });
1971
                if left == Some(0) {
1972
                    kept_order.retain(|k| k != p1);
1973
                    kept.remove(p1.as_str())
1974
                } else {
1975
                    kept.get(p1.as_str()).cloned()
1976
                }
1977
            });
1978
            let state = match from_parent {
1979
                Some(mut st) => {
1980
                    // The changes the parent's state lacks. The state never
1981
                    // builds a graph (they are built beside it), so they
1982
                    // are read without their text.
1983
                    for h in set.iter() {
1984
                        if !st.contains(h) {
1985
                            let (change, texts) = self.store.get_change_lazy(h)?;
1986
                            st.add_known(*h, change, texts);
1987
                        }
1988
                    }
1989
                    st
1990
                }
1991
                None => self.load_state_history(&heads)?,
1992
            };
1993
            let view = state.tree().view();
1994
            let tree = list_tree(git_dir, &c.sha)?;
1995
            let short = &c.sha[..12.min(c.sha.len())];
1996
            let mut differ = |what: String| rep.mismatches.push((c.sha.clone(), what));
1997
            let mut conflicted: Vec<String> =
1998
                view.conflicts.iter().map(|c| format!("{c:?}")).collect();
1999
            let mut need: Vec<NodeId> = Vec::new();
2000
            for (path, (mode, sha)) in &tree {
2001
                let Some(e) = view.entries.get(path) else {
2002
                    continue;
2003
                };
2004
                if mode != "160000"
2005
                    && mode != "120000"
2006
                    && e.kind == NodeKind::File
2007
                    && !e.mode.opaque
2008
                {
2009
                    let known = state
2010
                        .graph_key(&e.node)
2011
                        .is_some_and(|k| verified_graphs.get(&k) == Some(sha));
2012
                    if !known {
2013
                        need.push(e.node);
2014
                    }
2015
                }
2016
            }
2017
            // A graph's key is known only before it is built.
2018
            let keys: HashMap<NodeId, [u8; 32]> = need
2019
                .iter()
2020
                .filter_map(|n| Some((*n, state.graph_key(n)?)))
2021
                .collect();
2022
            let need_set: HashSet<NodeId> = need.iter().copied().collect();
2023
            let graphs = self.build_graphs_detached(&state, &need)?;
2024
            for (path, (mode, sha)) in &tree {
2025
                let Some(e) = view.entries.get(path) else {
2026
                    differ(format!("{short}: {path} is missing"));
2027
                    continue;
2028
                };
2029
                rep.files_compared += 1;
2030
                match mode.as_str() {
2031
                    "160000" => {
2032
                        let blobs = state.live_blobs(&e.node);
2033
                        match (e.kind, blobs.as_slice()) {
2034
                            (NodeKind::Subrepo, [b]) => {
2035
                                let pin = crate::subrepo::Pin::decode(&self.read_blob(b)?)?;
2036
                                if !matches!(&pin, crate::subrepo::Pin::Git { sha: s, .. } if s == sha)
2037
                                {
2038
                                    differ(format!("{short}: {path} pins another commit"));
2039
                                }
2040
                            }
2041
                            (kind, _) => differ(format!(
2042
                                "{short}: {path} is not one submodule pin: {kind:?} with {} pins",
2043
                                blobs.len()
2044
                            )),
2045
                        }
2046
                    }
2047
                    "120000" => {
2048
                        let target = cat.read(sha)?;
2049
                        let blobs = state.live_blobs(&e.node);
2050
                        match (e.kind, blobs.as_slice()) {
2051
                            (NodeKind::Symlink, [b]) if self.read_blob(b)? == target => {}
2052
                            _ => differ(format!("{short}: symlink {path} differs")),
2053
                        }
2054
                    }
2055
                    _ => {
2056
                        if e.mode.exec != (mode == "100755") {
2057
                            differ(format!("{short}: {path} executable bit differs"));
2058
                        }
2059
                        if e.kind == NodeKind::File && !e.mode.opaque {
2060
                            if !need_set.contains(&e.node) {
2061
                                // Known equal: skipped when the graphs were chosen.
2062
                                continue;
2063
                            }
2064
                            let (have, m) = match graphs.get(&e.node) {
2065
                                Some(g) => state.render_graph(g),
2066
                                None => (Vec::new(), Default::default()),
2067
                            };
2068
                            if m.is_conflicted() {
2069
                                // Who conflicts: a copy of the state with this graph built.
2070
                                let mut detail = state.clone();
2071
                                self.load_graphs_of(&mut detail, &[e.node])?;
2072
                                let who: Vec<String> = detail
2073
                                    .conflict_regions(&e.node)
2074
                                    .contributors
2075
                                    .iter()
2076
                                    .filter_map(|h| state.get(h))
2077
                                    .map(|m| {
2078
                                        let sha = m
2079
                                            .message
2080
                                            .lines()
2081
                                            .rev()
2082
                                            .find_map(|l| l.strip_prefix("Git-Commit: "))
2083
                                            .unwrap_or("?");
2084
                                        format!(
2085
                                            "{} {:?}",
2086
                                            &sha[..12.min(sha.len())],
2087
                                            m.message.lines().next().unwrap_or("")
2088
                                        )
2089
                                    })
2090
                                    .collect();
2091
                                conflicted.push(format!("{path} between {}", who.join(" and ")));
2092
                            }
2093
                            let want = cat.read(sha)?;
2094
                            if have != want {
2095
                                differ(format!(
2096
                                    "{short}: {path} differs: {}",
2097
                                    first_difference(&have, &want)
2098
                                ));
2099
                            } else if !m.is_conflicted() {
2100
                                if let Some(k) = keys.get(&e.node) {
2101
                                    verified_graphs.insert(*k, sha.clone());
2102
                                }
2103
                            }
2104
                            continue;
2105
                        }
2106
                        let blobs = state.live_blobs(&e.node);
2107
                        let [b] = blobs.as_slice() else {
2108
                            differ(format!("{short}: {path} is not one file"));
2109
                            continue;
2110
                        };
2111
                        if verified_blobs.get(b) == Some(sha) {
2112
                            continue;
2113
                        }
2114
                        if self.read_blob(b)? != cat.read(sha)? {
2115
                            differ(format!("{short}: {path} differs"));
2116
                        } else {
2117
                            verified_blobs.insert(*b, sha.clone());
2118
                        }
2119
                    }
2120
                }
2121
            }
2122
            if !conflicted.is_empty() {
2123
                differ(format!(
2124
                    "{short}: the state is conflicted: {}",
2125
                    conflicted.join("; ")
2126
                ));
2127
            }
2128
            // Import records submodules in `.oxymodules` as well (spec §23),
2129
            // and export leaves it out again.
2130
            let has_submodules = tree.values().any(|(m, _)| m == "160000");
2131
            for (path, e) in view.entries.iter() {
2132
                if e.kind != NodeKind::Dir
2133
                    && !tree.contains_key(path)
2134
                    && !(has_submodules && path == ".oxymodules")
2135
                {
2136
                    differ(format!("{short}: {path} is extra"));
2137
                }
2138
            }
2139
            if waiting.get(c.sha.as_str()).is_some_and(|n| *n > 0) {
2140
                kept.insert(c.sha.clone(), state);
2141
                kept_order.push_back(c.sha.clone());
2142
                if kept_order.len() > 8 {
2143
                    if let Some(old) = kept_order.pop_front() {
2144
                        kept.remove(&old);
2145
                    }
2146
                }
2147
            }
2148
            if max > 0 && rep.mismatches.len() >= max {
2149
                break;
2150
            }
2151
        }
2152
        Ok(rep)
2153
    }
2154
}
2155
2156
/// Where two versions of a file first part, for a verification report.
2157
fn first_difference(have: &[u8], want: &[u8]) -> String {
2158
    let (h, w): (Vec<&[u8]>, Vec<&[u8]>) = (
2159
        have.split(|b| *b == b'\n').collect(),
2160
        want.split(|b| *b == b'\n').collect(),
2161
    );
2162
    let i = h
2163
        .iter()
2164
        .zip(&w)
2165
        .position(|(a, b)| a != b)
2166
        .unwrap_or(h.len().min(w.len()));
2167
    let show = |l: Option<&&[u8]>| {
2168
        l.map(|l| String::from_utf8_lossy(&l[..l.len().min(60)]).into_owned())
2169
            .unwrap_or_else(|| "(end)".into())
2170
    };
2171
    format!(
2172
        "line {}: has {:?}, Git has {:?} ({} lines, Git has {})",
2173
        i + 1,
2174
        show(h.get(i)),
2175
        show(w.get(i)),
2176
        h.len(),
2177
        w.len()
2178
    )
2179
}