crates/repo/src/git.rs 57.0 KiB raw
1
//! Git plumbing for reading and writing repository state.
2
3
use std::collections::BTreeMap;
4
use std::ffi::OsString;
5
use std::fs;
6
use std::io::{self, Read as _, Write as _};
7
use std::path::{Path, PathBuf};
8
use std::process::{Command, Output, Stdio};
9
use std::thread;
10
use std::time::{SystemTime, UNIX_EPOCH};
11
12
use self::refs::Qualified;
13
use crate::{
14
    AheadBehind, Branch, CommitTime, DiffRepository, DiffStat, MergeStatus, Oid, PatchId,
15
    ReadRepository, RepoError, Rev, WriteRepository,
16
};
17
18
/// Git reference names and refspecs.
19
pub mod refs;
20
21
/// Environment variable that disables Git's colored output.
22
const NO_COLOR: &str = "NO_COLOR";
23
/// Environment variable selecting the locale for Git's output.
24
///
25
/// Forced to `C` so translatable output that gets parsed here, such as
26
/// `--shortstat` summaries, stays in English regardless of the user's locale.
27
const LC_ALL: &str = "LC_ALL";
28
/// Maximum bytes read from a file head for shebang-style inference.
29
const HEAD_BYTES: usize = 64;
30
/// Pathspec separator that ends Git's option list.
31
const PATHSPEC_SEPARATOR: &str = "--";
32
/// Hexadecimal width of a SHA-1 object identifier.
33
const SHA1_HEX_LEN: usize = 40;
34
/// Object identifier of the empty tree in SHA-1 repositories.
35
const SHA1_EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
36
/// Hexadecimal width of a SHA-256 object identifier.
37
const SHA256_HEX_LEN: usize = 64;
38
/// Object identifier of the empty tree in SHA-256 repositories.
39
const SHA256_EMPTY_TREE: &str = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321";
40
41
/// Git repository command context.
42
#[derive(Clone, Debug)]
43
pub struct Repository {
44
    /// Working directory for worktree-aware invocations.
45
    cwd: PathBuf,
46
    /// Git repository directory used for plumbing invocations.
47
    git_dir: PathBuf,
48
    /// Hexadecimal width of object identifiers in this repository.
49
    object_id_width: usize,
50
    /// Revision and option arguments forwarded during context refetches.
51
    selector_args: Vec<OsString>,
52
}
53
54
impl Repository {
55
    /// Creates a repository context for `cwd` with selectors from raw diff args.
56
    pub fn new(
57
        cwd: impl Into<PathBuf>,
58
        diff_args: impl Into<Vec<OsString>>,
59
    ) -> Result<Self, RepoError> {
60
        let repository = Self::discover(cwd.into())?;
61
        let selector_args = repository.diff_selector_args(diff_args.into())?;
62
        Ok(repository.with_selector_args(selector_args))
63
    }
64
65
    /// Creates a repository command context with an explicit repository directory.
66
    pub fn from_git_dir(cwd: PathBuf, git_dir: PathBuf) -> Result<Self, RepoError> {
67
        let output = Command::new("git")
68
            .arg("--git-dir")
69
            .arg(&git_dir)
70
            .args(["rev-parse", "--show-object-format"])
71
            .current_dir(&cwd)
72
            .env(NO_COLOR, "1")
73
            .env(LC_ALL, "C")
74
            .output()?;
75
        if !output.status.success() {
76
            return Err(RepoError::git(&output));
77
        }
78
        let format = utf8(output.stdout)?;
79
        let object_id_width = object_id_width(format.trim())?;
80
81
        Ok(Self {
82
            cwd,
83
            git_dir,
84
            object_id_width,
85
            selector_args: Vec::new(),
86
        })
87
    }
88
89
    /// Creates a repository command context by resolving the repository for `cwd`.
90
    pub fn discover(cwd: PathBuf) -> Result<Self, RepoError> {
91
        let output = Command::new("git")
92
            .arg("rev-parse")
93
            .args(["--absolute-git-dir", "--show-object-format"])
94
            .current_dir(&cwd)
95
            .env(NO_COLOR, "1")
96
            .env(LC_ALL, "C")
97
            .output()?;
98
        if !output.status.success() {
99
            return Err(RepoError::git(&output));
100
        }
101
        let text = utf8(output.stdout)?;
102
        let mut lines = text.lines();
103
        let git_dir = PathBuf::from(lines.next().unwrap_or_default());
104
        let object_id_width = object_id_width(lines.next().unwrap_or_default())?;
105
        if git_dir.as_os_str().is_empty() || lines.next().is_some() {
106
            return Err(RepoError::Git(
107
                "git rev-parse returned invalid repository metadata".to_owned(),
108
            ));
109
        }
110
        Ok(Self {
111
            cwd,
112
            git_dir,
113
            object_id_width,
114
            selector_args: Vec::new(),
115
        })
116
    }
117
118
    /// Returns the absolute working-tree root, which diff paths are relative to.
119
    pub fn workdir(&self) -> Result<PathBuf, RepoError> {
120
        let output = self.command("rev-parse").arg("--show-toplevel").output()?;
121
        if !output.status.success() {
122
            return Err(RepoError::git(&output));
123
        }
124
        let text = utf8(output.stdout)?;
125
        let root = PathBuf::from(text.trim());
126
        if root.as_os_str().is_empty() {
127
            return Err(RepoError::Git(
128
                "git rev-parse --show-toplevel returned an empty path".to_owned(),
129
            ));
130
        }
131
        Ok(root)
132
    }
133
134
    /// Returns a copy with `selector_args` used for diff context refetches.
135
    pub fn with_selector_args(&self, selector_args: impl Into<Vec<OsString>>) -> Self {
136
        Self {
137
            cwd: self.cwd.clone(),
138
            git_dir: self.git_dir.clone(),
139
            object_id_width: self.object_id_width,
140
            selector_args: selector_args.into(),
141
        }
142
    }
143
144
    /// Runs `git diff` with raw command-line arguments.
145
    pub fn diff_output(&self, args: &[OsString]) -> Result<Output, RepoError> {
146
        self.command("diff")
147
            .arg("--full-index")
148
            .args(args)
149
            .output()
150
            .map_err(RepoError::Io)
151
    }
152
153
    /// Pairs corresponding commits between two versions of a review range.
154
    ///
155
    /// Git's range-diff matching is similarity based, so rewritten commits can
156
    /// be paired even when their object ids and exact patch ids changed.
157
    pub fn range_diff(
158
        &self,
159
        old_base: Oid,
160
        old_target: Oid,
161
        new_base: Oid,
162
        new_target: Oid,
163
    ) -> Result<BTreeMap<Oid, Oid>, RepoError> {
164
        let old_range = format!("{old_base}..{old_target}");
165
        let new_range = format!("{new_base}..{new_target}");
166
        let abbrev = format!("--abbrev={}", self.object_id_width);
167
        let output = self.run(
168
            "range-diff",
169
            &[
170
                "--no-color",
171
                "--no-dual-color",
172
                &abbrev,
173
                &old_range,
174
                &new_range,
175
            ],
176
            Opts::default(),
177
        )?;
178
        if !output.status.success() {
179
            return Err(RepoError::git(&output));
180
        }
181
        let stdout = utf8(output.stdout)?;
182
        let mut pairs = BTreeMap::new();
183
        for line in stdout.lines() {
184
            let mut fields = line.split_whitespace();
185
            let Some(_old_index) = fields.next() else {
186
                continue;
187
            };
188
            let Some(old) = fields.next() else {
189
                continue;
190
            };
191
            let Some(marker) = fields.next() else {
192
                continue;
193
            };
194
            let Some(_new_index) = fields.next() else {
195
                continue;
196
            };
197
            let Some(new) = fields.next() else {
198
                continue;
199
            };
200
            if !matches!(marker, "=" | "!") {
201
                continue;
202
            }
203
            let (Ok(old), Ok(new)) = (old.parse(), new.parse()) else {
204
                continue;
205
            };
206
            pairs.insert(old, new);
207
        }
208
        Ok(pairs)
209
    }
210
211
    /// Reads the first bytes of a Git blob object.
212
    pub fn head_line(&self, oid: Oid) -> Result<Option<String>, RepoError> {
213
        let mut child = self
214
            .command("show")
215
            .arg(oid.to_string())
216
            .stdout(Stdio::piped())
217
            .stderr(Stdio::null())
218
            .spawn()?;
219
        let Some(mut stdout) = child.stdout.take() else {
220
            return Ok(None);
221
        };
222
        let head = read_head(&mut stdout)?;
223
        let _ = child.kill();
224
        let _ = child.wait();
225
226
        Ok(head)
227
    }
228
229
    /// Returns a Git command configured for this repository.
230
    fn command(&self, subcommand: &str) -> Command {
231
        let mut command = Command::new("git");
232
        command
233
            .arg(subcommand)
234
            .current_dir(&self.cwd)
235
            .env("GIT_DIR", &self.git_dir)
236
            .env(NO_COLOR, "1")
237
            .env(LC_ALL, "C");
238
        command
239
    }
240
241
    /// Returns diff selectors without pathspec arguments.
242
    fn diff_selector_args(&self, args: Vec<OsString>) -> Result<Vec<OsString>, RepoError> {
243
        if let Some(separator) = args
244
            .iter()
245
            .position(|arg| arg.as_os_str() == PATHSPEC_SEPARATOR)
246
        {
247
            return Ok(args[..separator].to_vec());
248
        }
249
        let mut selectors = self.rev_parse(&["--flags", "--no-revs"], &args)?;
250
        let revisions = self.rev_parse(&["--revs-only", "--symbolic"], &args)?;
251
        selectors.extend(revisions);
252
253
        Ok(selectors)
254
    }
255
256
    /// Runs `git rev-parse` to classify diff arguments.
257
    fn rev_parse(&self, modes: &[&str], args: &[OsString]) -> Result<Vec<OsString>, RepoError> {
258
        let output = self.command("rev-parse").args(modes).args(args).output()?;
259
        if !output.status.success() {
260
            return Err(RepoError::git(&output));
261
        }
262
        Ok(String::from_utf8_lossy(&output.stdout)
263
            .lines()
264
            .filter(|line| !line.is_empty())
265
            .map(OsString::from)
266
            .collect())
267
    }
268
269
    /// Runs a Git subcommand with default options and returns stdout bytes on success.
270
    fn git(&self, subcommand: &str, args: &[&str]) -> Result<Vec<u8>, RepoError> {
271
        let output = self.run(subcommand, args, Opts::default())?;
272
        if output.status.success() {
273
            Ok(output.stdout)
274
        } else {
275
            Err(RepoError::git(&output))
276
        }
277
    }
278
279
    /// Returns the `git log`-style header for `commit`.
280
    pub fn commit_header(&self, commit: Oid) -> Result<Vec<u8>, RepoError> {
281
        let commit = commit.to_string();
282
        self.git("show", &["-s", "--format=medium", &commit])
283
    }
284
285
    /// Returns each commit's author name and newest author or committer timestamp.
286
    pub fn commit_metadata(&self, commits: &[Oid]) -> Result<Vec<(String, CommitTime)>, RepoError> {
287
        if commits.is_empty() {
288
            return Ok(Vec::new());
289
        }
290
        let mut args = vec![
291
            "--no-walk=unsorted".to_owned(),
292
            "--format=%H%x00%an%x00%at%x00%ct".to_owned(),
293
        ];
294
        args.extend(commits.iter().map(Oid::to_string));
295
        let args = args.iter().map(String::as_str).collect::<Vec<_>>();
296
        let text = self.git("log", &args).and_then(utf8)?;
297
        let mut metadata = BTreeMap::new();
298
299
        for line in text.lines() {
300
            let (id, author, recency) = Self::parse_commit_metadata(line)?;
301
            metadata.insert(id, (author, recency));
302
        }
303
        commits
304
            .iter()
305
            .map(|commit| {
306
                metadata
307
                    .get(commit)
308
                    .cloned()
309
                    .ok_or_else(|| RepoError::Git(format!("git log omitted metadata for {commit}")))
310
            })
311
            .collect()
312
    }
313
314
    /// Parses one fixed four-field commit metadata record from `git log`.
315
    fn parse_commit_metadata(line: &str) -> Result<(Oid, String, CommitTime), RepoError> {
316
        let mut fields = line.split('\0');
317
        let (Some(id), Some(author), Some(authored), Some(committed), None) = (
318
            fields.next(),
319
            fields.next(),
320
            fields.next(),
321
            fields.next(),
322
            fields.next(),
323
        ) else {
324
            return Err(RepoError::Git(
325
                "malformed commit metadata line from git log".to_owned(),
326
            ));
327
        };
328
        let id = id
329
            .parse::<Oid>()
330
            .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?;
331
        let authored = authored
332
            .parse::<i64>()
333
            .map_err(|_| RepoError::Git("invalid author timestamp from git log".to_owned()))?;
334
        let committed = committed
335
            .parse::<i64>()
336
            .map_err(|_| RepoError::Git("invalid commit timestamp from git log".to_owned()))?;
337
338
        Ok((
339
            id,
340
            author.to_owned(),
341
            CommitTime {
342
                seconds: authored.max(committed),
343
            },
344
        ))
345
    }
346
347
    /// Runs a Git subcommand with optional stdin, index, and environment overrides.
348
    fn run(&self, subcommand: &str, args: &[&str], opts: Opts<'_>) -> Result<Output, RepoError> {
349
        let mut command = self.command(subcommand);
350
        command.args(args);
351
352
        for (key, value) in opts.env {
353
            command.env(key, value);
354
        }
355
        if let Some(index) = opts.index {
356
            command.env("GIT_INDEX_FILE", index);
357
        }
358
        if let Some(stdin) = opts.stdin {
359
            command
360
                .stdin(Stdio::piped())
361
                .stdout(Stdio::piped())
362
                .stderr(Stdio::piped());
363
            let mut child = command.spawn()?;
364
            // Feed the payload from a worker thread. Commands such as `patch-id`
365
            // write results while they read, so writing a large payload inline
366
            // deadlocks as soon as their output fills the pipe buffer.
367
            let payload = stdin.to_vec();
368
            let writer = child.stdin.take().map(|mut pipe| {
369
                thread::spawn(move || {
370
                    let result = pipe.write_all(&payload);
371
                    drop(pipe);
372
                    result
373
                })
374
            });
375
            let output = child.wait_with_output().map_err(RepoError::Io)?;
376
            if let Some(writer) = writer {
377
                match writer.join() {
378
                    // A command that fails early closes its input; report its own
379
                    // failure rather than the resulting broken pipe.
380
                    Ok(Err(error)) if output.status.success() => return Err(RepoError::Io(error)),
381
                    Ok(_) => {}
382
                    Err(_) => {
383
                        return Err(RepoError::Git(format!(
384
                            "git {subcommand} input writer panicked"
385
                        )));
386
                    }
387
                }
388
            }
389
            Ok(output)
390
        } else {
391
            command.output().map_err(RepoError::Io)
392
        }
393
    }
394
}
395
396
impl ReadRepository for Repository {
397
    /// Resolves a revision reference to a commit id.
398
    fn commit_id(&self, rev: &Rev) -> Result<Oid, RepoError> {
399
        let revision = format!("{}^{{commit}}", rev.as_str());
400
        let bytes = self.git("rev-parse", &[&revision])?;
401
        Oid::try_from(bytes.as_slice())
402
            .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {}", rev.as_str())))
403
    }
404
405
    /// Returns the tree id for any commit or tree object.
406
    fn tree_id(&self, object: Oid) -> Result<Oid, RepoError> {
407
        let object = format!("{object}^{{tree}}");
408
        let bytes = self.git("rev-parse", &[&object])?;
409
        Oid::try_from(bytes.as_slice())
410
            .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {object}")))
411
    }
412
413
    /// Returns the current commit stored in `reference`, if the ref exists.
414
    fn optional_ref(&self, reference: &Qualified<'_>) -> Result<Option<Oid>, RepoError> {
415
        let output = self.run(
416
            "rev-parse",
417
            &["--verify", "--quiet", reference.as_str()],
418
            Opts::default(),
419
        )?;
420
        if !output.status.success() {
421
            return Ok(None);
422
        }
423
        let oid = Oid::try_from(output.stdout.as_slice())
424
            .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?;
425
426
        Ok(Some(oid))
427
    }
428
429
    /// Returns refs below `prefix`, sorted by refname.
430
    fn refs(&self, prefix: &Qualified<'_>) -> Result<Vec<(Qualified<'static>, Oid)>, RepoError> {
431
        let bytes = self.git(
432
            "for-each-ref",
433
            &["--format=%(refname) %(objectname)", prefix.as_str()],
434
        )?;
435
        let text = utf8(bytes)?;
436
        text.lines()
437
            .map(|line| {
438
                let (refname, object) = line
439
                    .split_once(' ')
440
                    .ok_or_else(|| RepoError::Git(format!("invalid for-each-ref line: {line}")))?;
441
                let refname = refs::RefString::try_from(refname.to_owned())
442
                    .map_err(|error| RepoError::Git(format!("invalid refname: {error}")))?;
443
                let reference = Qualified::from_refstr(refname.as_refstr())
444
                    .ok_or_else(|| RepoError::Git(format!("unqualified refname: {refname}")))?
445
                    .into_owned();
446
                let oid = object
447
                    .parse()
448
                    .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?;
449
450
                Ok((reference, oid))
451
            })
452
            .collect()
453
    }
454
455
    /// Returns local branches, sorted by branch name.
456
    ///
457
    /// Tip commit times come from the same `for-each-ref` invocation, so
458
    /// callers can order branches without a subprocess per branch.
459
    fn branches(&self) -> Result<Vec<Branch>, RepoError> {
460
        let bytes = self.git(
461
            "for-each-ref",
462
            &[
463
                "--format=%(refname:short)%00%(objectname)%00%(committerdate:unix)",
464
                "refs/heads",
465
            ],
466
        )?;
467
        let text = utf8(bytes)?;
468
        text.lines()
469
            .map(|line| {
470
                let mut fields = line.split('\0');
471
                let (Some(name), Some(head), Some(seconds)) =
472
                    (fields.next(), fields.next(), fields.next())
473
                else {
474
                    return Err(RepoError::Git(format!("invalid branch line: {line}")));
475
                };
476
                let head = head
477
                    .parse()
478
                    .map_err(|_| RepoError::Git(format!("invalid branch head: {head}")))?;
479
                let seconds = seconds
480
                    .parse()
481
                    .map_err(|_| RepoError::Git(format!("invalid branch time: {seconds}")))?;
482
483
                Ok(Branch {
484
                    name: name.to_owned(),
485
                    head,
486
                    time: CommitTime { seconds },
487
                })
488
            })
489
            .collect()
490
    }
491
492
    /// Returns a Git configuration value, if set.
493
    fn config(&self, key: &str) -> Result<Option<String>, RepoError> {
494
        let output = self.run("config", &["--get", key], Opts::default())?;
495
        if !output.status.success() {
496
            return Ok(None);
497
        }
498
        let value = utf8(output.stdout)?;
499
        let value = value.trim().to_owned();
500
501
        Ok((!value.is_empty()).then_some(value))
502
    }
503
504
    /// Returns the repository trunk branch among `branches`.
505
    fn trunk(&self, branches: &[Branch]) -> Result<Option<Branch>, RepoError> {
506
        let remote = self.remote_default_branch()?;
507
        let configured = self.config("init.defaultBranch")?;
508
        Ok(remote
509
            .as_deref()
510
            .into_iter()
511
            .chain(configured.as_deref())
512
            .chain([refs::name::str::MAIN, refs::name::str::MASTER])
513
            .find_map(|name| branches.iter().find(|branch| branch.name == name))
514
            .cloned())
515
    }
516
517
    /// Returns the best common ancestor of two revisions.
518
    fn merge_base(&self, left: &Rev, right: &Rev) -> Result<Oid, RepoError> {
519
        let bytes = self.git("merge-base", &[left.as_str(), right.as_str()])?;
520
        let text = utf8(bytes)?;
521
        text.trim()
522
            .parse()
523
            .map_err(|_| RepoError::Git("invalid merge base".to_owned()))
524
    }
525
526
    /// Returns the branch point for `target` and its upstream or the trunk.
527
    fn branch_base(&self, target: &Rev) -> Result<Option<Oid>, RepoError> {
528
        let target_id = self.commit_id(target)?;
529
        let contains = format!("--contains={target_id}");
530
        let bytes = self.git(
531
            "for-each-ref",
532
            &[
533
                &contains,
534
                "--format=%(objectname)%00%(upstream)",
535
                "refs/heads",
536
            ],
537
        )?;
538
        let text = utf8(bytes)?;
539
        let target_id = target_id.to_string();
540
        let refs = || text.lines().filter_map(|line| line.split_once('\0'));
541
        let has_exact_head = refs().any(|(head, _)| *head == target_id);
542
        let mut base = None;
543
        for (_, upstream) in refs()
544
            .filter(|(_, upstream)| !upstream.is_empty())
545
            .filter(|(head, _)| !has_exact_head || *head == target_id)
546
        {
547
            let revision = format!("{upstream}^{{commit}}");
548
            let output = self.run(
549
                "rev-parse",
550
                &["--verify", "--quiet", &revision],
551
                Opts::default(),
552
            )?;
553
            if !output.status.success() {
554
                continue;
555
            }
556
            let upstream = Oid::try_from(output.stdout.as_slice())
557
                .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {upstream}")))?;
558
            base = Some(Rev::from(upstream));
559
            break;
560
        }
561
        let base = if let Some(base) = base {
562
            base
563
        } else {
564
            let branches = self.branches()?;
565
            let Some(trunk) = self.trunk(&branches)? else {
566
                return Ok(None);
567
            };
568
            Rev::from(trunk.head)
569
        };
570
        let base = self.merge_base(&base, target)?;
571
        Ok(Some(base))
572
    }
573
574
    /// Returns ahead and behind counts for `target` relative to `base`.
575
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError> {
576
        let range = format!("{}...{}", base.as_str(), target.as_str());
577
        let bytes = self.git("rev-list", &["--left-right", "--count", &range])?;
578
        let text = utf8(bytes)?;
579
        let mut fields = text.split_whitespace();
580
        let behind = fields
581
            .next()
582
            .ok_or_else(|| RepoError::Git("missing behind count".to_owned()))?
583
            .parse()
584
            .map_err(|_| RepoError::Git("invalid behind count".to_owned()))?;
585
        let ahead = fields
586
            .next()
587
            .ok_or_else(|| RepoError::Git("missing ahead count".to_owned()))?
588
            .parse()
589
            .map_err(|_| RepoError::Git("invalid ahead count".to_owned()))?;
590
591
        Ok(AheadBehind { ahead, behind })
592
    }
593
594
    /// Returns whether `target` would merge into `base` with conflicts.
595
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError> {
596
        let output = self.run(
597
            "merge-tree",
598
            &["--write-tree", base.as_str(), target.as_str()],
599
            Opts::default(),
600
        )?;
601
        if output.status.success() {
602
            return Ok(MergeStatus::Clean);
603
        }
604
        if output.status.code() == Some(1) {
605
            return Ok(MergeStatus::Conflicts);
606
        }
607
        Err(RepoError::git(&output))
608
    }
609
610
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
611
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError> {
612
        let commit = commit.to_string();
613
        let bytes = self.git("show", &["-s", "--format=%P", &commit])?;
614
        let text = utf8(bytes)?;
615
        let parents = text.split_whitespace().collect::<Vec<_>>();
616
617
        match parents.as_slice() {
618
            [parent] => parent
619
                .parse()
620
                .map_err(|_| RepoError::Git(format!("{commit} parent is not a valid hash"))),
621
            _ => Err(RepoError::Git(format!(
622
                "{commit} does not have exactly one parent"
623
            ))),
624
        }
625
    }
626
627
    /// Returns the full commit message for `commit`.
628
    fn commit_message(&self, commit: Oid) -> Result<String, RepoError> {
629
        let commit = commit.to_string();
630
        self.git("show", &["-s", "--format=%B", &commit])
631
            .and_then(utf8)
632
    }
633
634
    /// Returns the committer timestamp for `commit`.
635
    fn commit_time(&self, commit: Oid) -> Result<CommitTime, RepoError> {
636
        let commit = commit.to_string();
637
        let text = self.git("show", &["-s", "--format=%ct", &commit])?;
638
        let seconds = utf8(text)?
639
            .trim()
640
            .parse()
641
            .map_err(|_| RepoError::Git("invalid commit timestamp".to_owned()))?;
642
643
        Ok(CommitTime { seconds })
644
    }
645
646
    /// Returns each commit's aggregated diff size, in the given order.
647
    ///
648
    /// All stats come from one `git log --shortstat` invocation so callers can
649
    /// size a whole review range without a subprocess per commit. Merge commits
650
    /// are compared to their first parent, matching [`Self::commit_diff`].
651
    fn commit_stats(&self, commits: &[Oid]) -> Result<Vec<DiffStat>, RepoError> {
652
        if commits.is_empty() {
653
            return Ok(Vec::new());
654
        }
655
        let mut args = vec![
656
            "--no-walk=unsorted".to_owned(),
657
            "--first-parent".to_owned(),
658
            "--format=%H".to_owned(),
659
            "--shortstat".to_owned(),
660
        ];
661
        args.extend(commits.iter().map(Oid::to_string));
662
        let args = args.iter().map(String::as_str).collect::<Vec<_>>();
663
        let text = self.git("log", &args).and_then(utf8)?;
664
665
        let mut stats = BTreeMap::new();
666
        let mut current = None;
667
        for line in text.lines() {
668
            if let Ok(oid) = line.trim().parse::<Oid>() {
669
                current = Some(oid);
670
            } else if let Some(oid) = current
671
                && line.contains("changed")
672
            {
673
                stats.insert(oid, DiffStat::from_shortstat(line));
674
            }
675
        }
676
        Ok(commits
677
            .iter()
678
            .map(|commit| stats.get(commit).copied().unwrap_or_default())
679
            .collect())
680
    }
681
682
    /// Reads a blob object's bytes.
683
    fn cat_blob(&self, blob: Oid) -> Result<Vec<u8>, RepoError> {
684
        let blob = blob.to_string();
685
        self.git("cat-file", &["blob", &blob])
686
    }
687
688
    /// Produces a unified diff between two objects as text.
689
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError> {
690
        let from = from.to_string();
691
        let to = to.to_string();
692
        let bytes = self.git(
693
            "diff",
694
            &[
695
                "--no-ext-diff",
696
                "--no-textconv",
697
                "--no-color",
698
                "--full-index",
699
                &from,
700
                &to,
701
            ],
702
        )?;
703
        utf8(bytes)
704
    }
705
706
    /// Computes a stable Git patch id for `patch` text.
707
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError> {
708
        if patch.trim().is_empty() {
709
            return Ok(PatchId::default());
710
        }
711
        let output = self.run(
712
            "patch-id",
713
            &["--stable"],
714
            Opts {
715
                stdin: Some(patch.as_bytes()),
716
                ..Opts::default()
717
            },
718
        )?;
719
        if !output.status.success() {
720
            return Err(RepoError::git(&output));
721
        }
722
        let stdout = utf8(output.stdout)?;
723
        let id = stdout.split_once(' ').map_or(stdout.trim(), |(id, _)| id);
724
725
        Ok(PatchId(id.to_owned()))
726
    }
727
728
    /// Computes stable Git patch ids for many patches in one invocation.
729
    ///
730
    /// The patches are streamed to a single `git patch-id` process, separated
731
    /// by synthetic `commit` headers whose ids map output rows back to input
732
    /// positions. Every input patch must produce one output row.
733
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError> {
734
        if patches.is_empty() {
735
            return Ok(Vec::new());
736
        }
737
        let width = self.object_id_width;
738
        let mut stream = String::new();
739
        for (index, patch) in patches.iter().enumerate() {
740
            stream.push_str(&format!("commit {index:0width$x}\n"));
741
            stream.push_str(patch);
742
            if !patch.ends_with('\n') {
743
                stream.push('\n');
744
            }
745
        }
746
        let output = self.run(
747
            "patch-id",
748
            &["--stable"],
749
            Opts {
750
                stdin: Some(stream.as_bytes()),
751
                ..Opts::default()
752
            },
753
        )?;
754
        if !output.status.success() {
755
            return Err(RepoError::git(&output));
756
        }
757
        let stdout = utf8(output.stdout)?;
758
        let mut by_commit = BTreeMap::new();
759
        for line in stdout.lines() {
760
            if let Some((id, commit)) = line.split_once(' ') {
761
                by_commit.insert(commit.trim().to_owned(), PatchId(id.to_owned()));
762
            }
763
        }
764
        let mut ids = Vec::with_capacity(patches.len());
765
        for index in 0..patches.len() {
766
            let commit = format!("{index:0width$x}");
767
            let id = by_commit.remove(&commit).ok_or_else(|| {
768
                RepoError::Git(format!("git patch-id returned no id for patch {index}"))
769
            })?;
770
            ids.push(id);
771
        }
772
        Ok(ids)
773
    }
774
775
    /// Computes a three-way merge tree and returns the resulting tree id.
776
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError> {
777
        let merge_base = merge_base.to_string();
778
        let ours = ours.to_string();
779
        let theirs = theirs.to_string();
780
        let output = self.run(
781
            "merge-tree",
782
            &["--write-tree", "--merge-base", &merge_base, &ours, &theirs],
783
            Opts::default(),
784
        )?;
785
        if output.status.success() {
786
            let stdout = String::from_utf8_lossy(&output.stdout);
787
            // On success `--write-tree` prints the created tree id as the first
788
            // line. Conflict details only appear on failing output.
789
            return stdout
790
                .lines()
791
                .next()
792
                .map(str::trim)
793
                .filter(|line| !line.is_empty())
794
                .and_then(|line| line.parse().ok())
795
                .ok_or_else(|| RepoError::Git("git merge-tree did not return a tree".to_owned()));
796
        }
797
        let message = RepoError::git(&output).to_string();
798
        if output.status.code() == Some(1) {
799
            Err(RepoError::MergeConflict(message))
800
        } else {
801
            Err(RepoError::Git(message))
802
        }
803
    }
804
805
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
806
    fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError> {
807
        let range = format!("{}..{}", base.as_str(), target.as_str());
808
        let bytes = self.git("log", &["--reverse", "--format=%H%x00%s", &range])?;
809
        let text = utf8(bytes)?;
810
        let mut commits = Vec::new();
811
812
        for line in text.lines() {
813
            let Some((id, summary)) = line.split_once('\0') else {
814
                return Err(RepoError::Git(
815
                    "malformed commit line from git log".to_owned(),
816
                ));
817
            };
818
            let id = id
819
                .trim()
820
                .parse()
821
                .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?;
822
            commits.push((id, summary.to_owned()));
823
        }
824
        Ok(commits)
825
    }
826
827
    /// Returns the unified diff for `commit` against its first parent.
828
    ///
829
    /// Root commits are compared against the empty tree.
830
    fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError> {
831
        let commit = commit.to_string();
832
        let parents = self.git("show", &["-s", "--format=%P", &commit])?;
833
        let parents = utf8(parents)?;
834
        let empty_tree = match self.object_id_width {
835
            SHA1_HEX_LEN => SHA1_EMPTY_TREE,
836
            SHA256_HEX_LEN => SHA256_EMPTY_TREE,
837
            _ => unreachable!("commit_diff: unsupported object identifier width"),
838
        };
839
        let parent = parents.split_whitespace().next().unwrap_or(empty_tree);
840
841
        self.git(
842
            "diff",
843
            &[
844
                "--no-ext-diff",
845
                "--no-textconv",
846
                "--full-index",
847
                "--find-copies-harder",
848
                parent,
849
                &commit,
850
            ],
851
        )
852
    }
853
}
854
855
impl WriteRepository for Repository {
856
    /// Writes `bytes` as a blob object and returns its id.
857
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError> {
858
        let output = self.run(
859
            "hash-object",
860
            &["-w", "--stdin"],
861
            Opts {
862
                stdin: Some(bytes),
863
                ..Opts::default()
864
            },
865
        )?;
866
        if !output.status.success() {
867
            return Err(RepoError::git(&output));
868
        }
869
        Oid::try_from(output.stdout.as_slice())
870
            .map_err(|_| RepoError::Git("invalid oid from hash-object".to_owned()))
871
    }
872
873
    /// Applies a Git-format patch to a temporary index and returns its tree id.
874
    ///
875
    /// The temporary index is seeded from `base`, patched with
876
    /// `git apply --cached`, then written with `git write-tree`. This keeps
877
    /// acceptance updates isolated from the user's working tree and real index.
878
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
879
        if patch.trim().is_empty() {
880
            return self.tree_id(base);
881
        }
882
        let index = TempIndex::new()?;
883
        let index_path = index.path();
884
        let base = base.to_string();
885
886
        // `read-tree` initializes the temporary index to the exact tree being
887
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
888
        let output = self.run(
889
            "read-tree",
890
            &[&base],
891
            Opts {
892
                index: Some(index_path),
893
                ..Opts::default()
894
            },
895
        )?;
896
        if !output.status.success() {
897
            return Err(RepoError::git(&output));
898
        }
899
        // `--recount` lets single-hunk patches keep working after context
900
        // filtering changes hunk line counts.
901
        let output = self.run(
902
            "apply",
903
            &["--cached", "--recount", "--whitespace=nowarn", "--binary"],
904
            Opts {
905
                index: Some(index_path),
906
                stdin: Some(patch.as_bytes()),
907
                ..Opts::default()
908
            },
909
        )?;
910
        if !output.status.success() {
911
            return Err(RepoError::patch_apply(&output));
912
        }
913
        let output = self.run(
914
            "write-tree",
915
            &[],
916
            Opts {
917
                index: Some(index_path),
918
                ..Opts::default()
919
            },
920
        )?;
921
        if !output.status.success() {
922
            return Err(RepoError::git(&output));
923
        }
924
        Oid::try_from(output.stdout.as_slice())
925
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
926
    }
927
928
    /// Creates a commit with `tree` and `parent`.
929
    fn commit(
930
        &self,
931
        tree: Oid,
932
        parent: Oid,
933
        author: &str,
934
        email: &str,
935
        message: &str,
936
    ) -> Result<Oid, RepoError> {
937
        let tree = tree.to_string();
938
        let parent = parent.to_string();
939
        let output = self.run(
940
            "commit-tree",
941
            &[&tree, "-p", &parent, "-m", message],
942
            Opts {
943
                env: &[
944
                    ("GIT_AUTHOR_NAME", author),
945
                    ("GIT_AUTHOR_EMAIL", email),
946
                    ("GIT_COMMITTER_NAME", author),
947
                    ("GIT_COMMITTER_EMAIL", email),
948
                ],
949
                ..Opts::default()
950
            },
951
        )?;
952
        if !output.status.success() {
953
            return Err(RepoError::git(&output));
954
        }
955
        Oid::try_from(output.stdout.as_slice())
956
            .map_err(|_| RepoError::Git("invalid oid from commit-tree".to_owned()))
957
    }
958
959
    /// Moves `updated` to `commit` and deletes `deleted` in one transaction.
960
    fn update_ref_and_delete(
961
        &self,
962
        updated: &Qualified<'_>,
963
        commit: Oid,
964
        deleted: &Qualified<'_>,
965
    ) -> Result<(), RepoError> {
966
        let transaction = format!(
967
            "update {} {}\ndelete {}\n",
968
            updated.as_str(),
969
            commit,
970
            deleted.as_str()
971
        );
972
        let output = self.run(
973
            "update-ref",
974
            &["--stdin"],
975
            Opts {
976
                stdin: Some(transaction.as_bytes()),
977
                ..Opts::default()
978
            },
979
        )?;
980
        if !output.status.success() {
981
            return Err(RepoError::git(&output));
982
        }
983
        Ok(())
984
    }
985
986
    /// Moves `reference` to point at `commit`.
987
    fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError> {
988
        let commit = commit.to_string();
989
        let output = self.run(
990
            "update-ref",
991
            &[reference.as_str(), &commit],
992
            Opts::default(),
993
        )?;
994
        if !output.status.success() {
995
            return Err(RepoError::git(&output));
996
        }
997
        Ok(())
998
    }
999
1000
    /// Moves `reference` to `commit` only when it still points to `expected`.
1001
    fn compare_and_update_ref(
1002
        &self,
1003
        reference: &Qualified<'_>,
1004
        commit: Oid,
1005
        expected: Option<Oid>,
1006
    ) -> Result<bool, RepoError> {
1007
        let commit = commit.to_string();
1008
        let expected_arg =
1009
            expected.map_or_else(|| "0".repeat(self.object_id_width), |oid| oid.to_string());
1010
        let output = self.run(
1011
            "update-ref",
1012
            &[reference.as_str(), &commit, &expected_arg],
1013
            Opts::default(),
1014
        )?;
1015
        if output.status.success() {
1016
            return Ok(true);
1017
        }
1018
        if self.optional_ref(reference)? != expected {
1019
            return Ok(false);
1020
        }
1021
        Err(RepoError::git(&output))
1022
    }
1023
}
1024
1025
impl Repository {
1026
    /// Returns the default branch reported by `origin/HEAD`, if present.
1027
    fn remote_default_branch(&self) -> Result<Option<String>, RepoError> {
1028
        let output = self.run(
1029
            "symbolic-ref",
1030
            &["--quiet", "--short", "refs/remotes/origin/HEAD"],
1031
            Opts::default(),
1032
        )?;
1033
        if !output.status.success() {
1034
            return Ok(None);
1035
        }
1036
        let name = utf8(output.stdout)?;
1037
        let name = name
1038
            .trim()
1039
            .strip_prefix("origin/")
1040
            .unwrap_or_else(|| name.trim())
1041
            .to_owned();
1042
1043
        Ok((!name.is_empty()).then_some(name))
1044
    }
1045
}
1046
1047
impl DiffRepository for Repository {
1048
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
1049
        let context = OsString::from(format!("-U{context_lines}"));
1050
        let output = self
1051
            .command("diff")
1052
            .args(&self.selector_args)
1053
            .arg("--no-ext-diff")
1054
            .arg("--no-textconv")
1055
            .arg("--full-index")
1056
            .arg(context)
1057
            .arg("--")
1058
            .args(paths)
1059
            .output()?;
1060
        if !output.status.success() {
1061
            return Err(RepoError::git(&output));
1062
        }
1063
        Ok(output.stdout)
1064
    }
1065
}
1066
1067
/// Optional execution context for a single Git invocation.
1068
#[derive(Clone, Copy, Debug, Default)]
1069
struct Opts<'a> {
1070
    /// Extra environment variables.
1071
    env: &'a [(&'a str, &'a str)],
1072
    /// Temporary index file written via `GIT_INDEX_FILE`.
1073
    index: Option<&'a Path>,
1074
    /// Stdin payload, if any.
1075
    stdin: Option<&'a [u8]>,
1076
}
1077
1078
/// Temporary index file path removed when dropped.
1079
#[derive(Debug)]
1080
struct TempIndex {
1081
    /// Directory holding the temporary index file.
1082
    dir: PathBuf,
1083
    /// Path passed through `GIT_INDEX_FILE`.
1084
    path: PathBuf,
1085
}
1086
1087
impl TempIndex {
1088
    /// Creates an empty temporary index path.
1089
    fn new() -> io::Result<Self> {
1090
        let suffix = SystemTime::now()
1091
            .duration_since(UNIX_EPOCH)
1092
            .unwrap_or_default()
1093
            .as_nanos();
1094
        let dir = std::env::temp_dir().join(format!(
1095
            "rustik-brain-index-{}-{suffix}",
1096
            std::process::id()
1097
        ));
1098
        fs::create_dir(&dir)?;
1099
        let path = dir.join("index");
1100
1101
        Ok(Self { dir, path })
1102
    }
1103
1104
    /// Returns the temporary index path.
1105
    fn path(&self) -> &Path {
1106
        &self.path
1107
    }
1108
}
1109
1110
impl Drop for TempIndex {
1111
    fn drop(&mut self) {
1112
        let _ = fs::remove_dir_all(&self.dir);
1113
    }
1114
}
1115
1116
/// Returns the hexadecimal object identifier width for a Git object format.
1117
fn object_id_width(format: &str) -> Result<usize, RepoError> {
1118
    match format {
1119
        "sha1" => Ok(SHA1_HEX_LEN),
1120
        "sha256" => Ok(SHA256_HEX_LEN),
1121
        format => Err(RepoError::Git(format!(
1122
            "unsupported Git object format: {format}"
1123
        ))),
1124
    }
1125
}
1126
1127
/// Converts bytes to a UTF-8 string.
1128
fn utf8(bytes: Vec<u8>) -> Result<String, RepoError> {
1129
    String::from_utf8(bytes).map_err(|e| RepoError::Git(e.to_string()))
1130
}
1131
1132
/// Reads a bounded file prefix and returns its first line.
1133
fn read_head(reader: &mut impl io::Read) -> Result<Option<String>, RepoError> {
1134
    let mut bytes = Vec::with_capacity(HEAD_BYTES);
1135
    let read = reader.take(HEAD_BYTES as u64).read_to_end(&mut bytes)?;
1136
1137
    if read == 0 {
1138
        return Ok(None);
1139
    }
1140
    if let Some(end) = bytes.iter().position(|byte| *byte == b'\n') {
1141
        bytes.truncate(end);
1142
    }
1143
    if bytes.last() == Some(&b'\r') {
1144
        bytes.pop();
1145
    }
1146
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
1147
}
1148
1149
#[cfg(test)]
1150
mod tests {
1151
    use super::*;
1152
1153
    /// Temporary Git repository removed when its test finishes.
1154
    struct TestRepository {
1155
        /// Repository working tree.
1156
        path: PathBuf,
1157
        /// Repository API under test.
1158
        repository: Repository,
1159
    }
1160
1161
    impl TestRepository {
1162
        /// Creates a repository with Git's default initial branch.
1163
        fn new() -> Self {
1164
            Self::init(&[])
1165
        }
1166
1167
        /// Creates a repository with `main` as its initial branch.
1168
        fn with_main_branch() -> Self {
1169
            Self::init(&["-b", "main"])
1170
        }
1171
1172
        /// Creates a repository with the requested object format.
1173
        fn with_object_format(object_format: &str) -> Self {
1174
            let format = format!("--object-format={object_format}");
1175
            Self::init(&[&format])
1176
        }
1177
1178
        /// Initializes a repository with additional `git init` arguments.
1179
        fn init(args: &[&str]) -> Self {
1180
            let nonce = SystemTime::now()
1181
                .duration_since(UNIX_EPOCH)
1182
                .unwrap()
1183
                .as_nanos();
1184
            let path = std::env::temp_dir()
1185
                .join(format!("rustik-repo-test-{}-{nonce}", std::process::id()));
1186
            let status = Command::new("git")
1187
                .args(["init", "-q"])
1188
                .args(args)
1189
                .arg(&path)
1190
                .status()
1191
                .unwrap();
1192
            assert!(status.success());
1193
            let repository = Repository::discover(path.clone()).unwrap();
1194
1195
            Self { path, repository }
1196
        }
1197
1198
        /// Returns the repository working tree.
1199
        fn path(&self) -> &Path {
1200
            &self.path
1201
        }
1202
1203
        /// Writes a working-tree file.
1204
        fn write(&self, path: &str, contents: &str) {
1205
            fs::write(self.path.join(path), contents).unwrap();
1206
        }
1207
1208
        /// Creates an empty commit.
1209
        fn commit_empty(&self, message: &str) {
1210
            self.git("commit", &["-q", "--allow-empty", "-m", message]);
1211
        }
1212
1213
        /// Commits the selected working-tree files.
1214
        fn commit(&self, paths: &[&str], message: &str) {
1215
            self.git("add", paths);
1216
            self.git("commit", &["-q", "-m", message]);
1217
        }
1218
1219
        /// Writes and commits one file.
1220
        fn commit_file(&self, path: &str, contents: &str, message: &str) {
1221
            self.write(path, contents);
1222
            self.commit(&[path], message);
1223
        }
1224
1225
        /// Runs a Git subcommand and requires success.
1226
        fn git(&self, subcommand: &str, args: &[&str]) {
1227
            let output = self
1228
                .repository
1229
                .run(
1230
                    subcommand,
1231
                    args,
1232
                    Opts {
1233
                        env: &[
1234
                            ("GIT_AUTHOR_NAME", "Rustik Test"),
1235
                            ("GIT_AUTHOR_EMAIL", "rustik@example.com"),
1236
                            ("GIT_COMMITTER_NAME", "Rustik Test"),
1237
                            ("GIT_COMMITTER_EMAIL", "rustik@example.com"),
1238
                        ],
1239
                        ..Opts::default()
1240
                    },
1241
                )
1242
                .unwrap();
1243
            assert!(output.status.success());
1244
        }
1245
    }
1246
1247
    impl std::ops::Deref for TestRepository {
1248
        type Target = Repository;
1249
1250
        fn deref(&self) -> &Self::Target {
1251
            &self.repository
1252
        }
1253
    }
1254
1255
    impl Drop for TestRepository {
1256
        fn drop(&mut self) {
1257
            fs::remove_dir_all(&self.path).unwrap();
1258
        }
1259
    }
1260
1261
    #[test]
1262
    fn branch_base_prefers_non_trunk_upstream() {
1263
        let repository = TestRepository::with_main_branch();
1264
        repository.commit_empty("main");
1265
        repository.git("switch", &["-q", "-c", "integration"]);
1266
        repository.commit_empty("integration");
1267
        repository.git("switch", &["-q", "-c", "feature"]);
1268
        repository.git("branch", &["--set-upstream-to=integration", "feature"]);
1269
        repository.commit_empty("feature");
1270
        repository.git("branch", &["aaa"]);
1271
        let feature = repository
1272
            .commit_id(&Rev::try_from("feature").unwrap())
1273
            .unwrap();
1274
        let target = Rev::from(feature);
1275
        let integration = Rev::try_from("integration").unwrap();
1276
1277
        assert_eq!(
1278
            repository.branch_base(&target).unwrap(),
1279
            Some(repository.commit_id(&integration).unwrap())
1280
        );
1281
    }
1282
1283
    #[test]
1284
    fn branch_base_ignores_missing_upstream() {
1285
        let repository = TestRepository::with_main_branch();
1286
        repository.commit_empty("main");
1287
        repository.git("switch", &["-q", "-c", "feature"]);
1288
        repository.commit_empty("feature");
1289
        repository.git("remote", &["add", "origin", "."]);
1290
        repository.git("update-ref", &["refs/remotes/origin/feature", "feature"]);
1291
        repository.git("branch", &["--set-upstream-to=origin/feature", "feature"]);
1292
        repository.git("update-ref", &["-d", "refs/remotes/origin/feature"]);
1293
        assert_eq!(
1294
            repository.config("branch.feature.remote").unwrap(),
1295
            Some("origin".to_owned())
1296
        );
1297
        assert_eq!(
1298
            repository.config("branch.feature.merge").unwrap(),
1299
            Some("refs/heads/feature".to_owned())
1300
        );
1301
        let feature = repository
1302
            .commit_id(&Rev::try_from("feature").unwrap())
1303
            .unwrap();
1304
        let target = Rev::from(feature);
1305
        let main = Rev::try_from("main").unwrap();
1306
1307
        assert_eq!(
1308
            repository.branch_base(&target).unwrap(),
1309
            Some(repository.commit_id(&main).unwrap())
1310
        );
1311
    }
1312
1313
    #[test]
1314
    fn branch_base_missing_exact_upstream_falls_back_to_trunk() {
1315
        let repository = TestRepository::with_main_branch();
1316
        repository.commit_empty("main");
1317
        repository.git("switch", &["-q", "-c", "integration"]);
1318
        repository.commit_empty("integration");
1319
        repository.git("switch", &["-q", "-c", "feature"]);
1320
        repository.commit_empty("feature");
1321
        repository.git("remote", &["add", "origin", "."]);
1322
        repository.git("update-ref", &["refs/remotes/origin/feature", "feature"]);
1323
        repository.git("branch", &["--set-upstream-to=origin/feature", "feature"]);
1324
        repository.git("update-ref", &["-d", "refs/remotes/origin/feature"]);
1325
        repository.git("switch", &["-q", "-c", "container"]);
1326
        repository.commit_empty("container");
1327
        repository.git("branch", &["--set-upstream-to=integration", "container"]);
1328
        let feature = repository
1329
            .commit_id(&Rev::try_from("feature").unwrap())
1330
            .unwrap();
1331
        let target = Rev::from(feature);
1332
        let main = Rev::try_from("main").unwrap();
1333
1334
        assert_eq!(
1335
            repository.branch_base(&target).unwrap(),
1336
            Some(repository.commit_id(&main).unwrap())
1337
        );
1338
    }
1339
1340
    #[test]
1341
    fn branch_base_exact_branch_without_upstream_falls_back_to_trunk() {
1342
        let repository = TestRepository::with_main_branch();
1343
        repository.commit_empty("main");
1344
        repository.git("switch", &["-q", "-c", "feature"]);
1345
        repository.commit_empty("feature");
1346
        repository.git("switch", &["-q", "-c", "container"]);
1347
        repository.commit_empty("container");
1348
        repository.git("remote", &["add", "origin", "."]);
1349
        repository.git(
1350
            "update-ref",
1351
            &["refs/remotes/origin/container", "container"],
1352
        );
1353
        repository.git(
1354
            "branch",
1355
            &["--set-upstream-to=origin/container", "container"],
1356
        );
1357
        let feature = repository
1358
            .commit_id(&Rev::try_from("feature").unwrap())
1359
            .unwrap();
1360
        let target = Rev::from(feature);
1361
        let main = Rev::try_from("main").unwrap();
1362
1363
        assert_eq!(
1364
            repository.branch_base(&target).unwrap(),
1365
            Some(repository.commit_id(&main).unwrap())
1366
        );
1367
    }
1368
1369
    #[test]
1370
    fn commit_stats_uses_merge_first_parent() {
1371
        let repository = TestRepository::with_main_branch();
1372
        repository.commit_file("base", "base\n", "base");
1373
        repository.git("switch", &["-q", "-c", "feature"]);
1374
        repository.commit_file("feature", "first\nsecond\n", "feature");
1375
        repository.git("switch", &["-q", "main"]);
1376
        repository.commit_file("main", "main\n", "main");
1377
        repository.git("merge", &["-q", "--no-ff", "feature", "-m", "merge"]);
1378
        let merge = repository
1379
            .commit_id(&Rev::try_from("HEAD").unwrap())
1380
            .unwrap();
1381
1382
        assert_eq!(
1383
            repository.commit_stats(&[merge]).unwrap(),
1384
            vec![DiffStat {
1385
                files_changed: 1,
1386
                insertions: 2,
1387
                deletions: 0,
1388
            }]
1389
        );
1390
    }
1391
1392
    #[test]
1393
    fn commit_diff_returns_root_commit_file() {
1394
        let repository = TestRepository::new();
1395
        repository.commit_file("root", "root\n", "root");
1396
        let root = repository
1397
            .commit_id(&Rev::try_from("HEAD").unwrap())
1398
            .unwrap();
1399
1400
        let diff = utf8(repository.commit_diff(root).unwrap()).unwrap();
1401
1402
        assert!(diff.starts_with("diff --git a/root b/root\nnew file mode"));
1403
        assert!(diff.contains("@@ -0,0 +1 @@\n+root\n"));
1404
    }
1405
1406
    #[test]
1407
    fn commit_diff_uses_builtin_diff_with_external_helper_configured() {
1408
        let repository = TestRepository::new();
1409
        repository.commit_file("file", "old\n", "base");
1410
        repository.commit_file("file", "new\n", "change");
1411
        repository.git(
1412
            "config",
1413
            &["diff.external", "printf 'external diff output\n'"],
1414
        );
1415
        let head = repository
1416
            .commit_id(&Rev::try_from("HEAD").unwrap())
1417
            .unwrap();
1418
1419
        let diff = utf8(repository.commit_diff(head).unwrap()).unwrap();
1420
1421
        assert!(diff.starts_with("diff --git a/file b/file\n"));
1422
        assert!(diff.contains("@@ -1 +1 @@\n-old\n+new\n"));
1423
    }
1424
1425
    #[test]
1426
    fn context_diff_uses_builtin_diff_with_external_helper_configured() {
1427
        let repository = TestRepository::new();
1428
        repository.commit_file("file", "old\n", "base");
1429
        repository.write("file", "new\n");
1430
        repository.git(
1431
            "config",
1432
            &["diff.external", "printf 'external diff output\n'"],
1433
        );
1434
1435
        let diff =
1436
            utf8(DiffRepository::diff(&*repository, 3, &[Path::new("file")]).unwrap()).unwrap();
1437
1438
        assert!(
1439
            diff.starts_with("diff --git a/file b/file\n"),
1440
            "external helper replaced context diff:\n{diff}"
1441
        );
1442
        assert!(diff.contains("@@ -1 +1 @@\n-old\n+new\n"));
1443
    }
1444
1445
    #[test]
1446
    fn context_diff_reports_git_stderr() {
1447
        let repository = TestRepository::new();
1448
        let selected_repository = repository
1449
            .repository
1450
            .with_selector_args(vec![OsString::from("invalid revision")]);
1451
1452
        let error = DiffRepository::diff(&selected_repository, 3, &[]).unwrap_err();
1453
1454
        assert!(error.to_string().starts_with("git: "));
1455
        assert!(error.to_string().contains("invalid revision"));
1456
    }
1457
1458
    #[test]
1459
    fn machine_readable_diffs_ignore_textconv_drivers() {
1460
        let repository = TestRepository::new();
1461
        let repository_path = repository.path();
1462
        repository.write(".gitattributes", "file diff=fixture\n");
1463
        repository.write("file", "old\n");
1464
        repository.commit(&[".gitattributes", "file"], "base");
1465
        repository.commit_file("file", "new\n", "change");
1466
        repository.git(
1467
            "config",
1468
            &["diff.fixture.textconv", "printf 'textconv helper output\n'"],
1469
        );
1470
        let base = repository
1471
            .commit_id(&Rev::try_from("HEAD^").unwrap())
1472
            .unwrap();
1473
        let head = repository
1474
            .commit_id(&Rev::try_from("HEAD").unwrap())
1475
            .unwrap();
1476
        let selected_repository = Repository::new(
1477
            repository_path.to_owned(),
1478
            vec![OsString::from("HEAD^"), OsString::from("HEAD")],
1479
        )
1480
        .unwrap();
1481
1482
        let initial = utf8(repository.commit_diff(head).unwrap()).unwrap();
1483
        let projected = ReadRepository::diff(&*repository, base, head).unwrap();
1484
        let refetched =
1485
            utf8(DiffRepository::diff(&selected_repository, 3, &[Path::new("file")]).unwrap())
1486
                .unwrap();
1487
1488
        for (path, diff) in [
1489
            ("initial", &initial),
1490
            ("projected", &projected),
1491
            ("refetched", &refetched),
1492
        ] {
1493
            assert!(
1494
                diff.starts_with("diff --git a/file b/file\n"),
1495
                "textconv replaced {path} diff:\n{diff}"
1496
            );
1497
            assert!(
1498
                diff.contains("@@ -1 +1 @@\n-old\n+new\n"),
1499
                "textconv changed {path} diff:\n{diff}"
1500
            );
1501
        }
1502
    }
1503
1504
    #[test]
1505
    fn trunk_ignores_stale_remote_default() {
1506
        let repository = TestRepository::with_main_branch();
1507
        repository.commit_empty("main");
1508
        repository.git("switch", &["-q", "-c", "integration"]);
1509
        repository.commit_empty("integration");
1510
        repository.git(
1511
            "symbolic-ref",
1512
            &[
1513
                "refs/remotes/origin/HEAD",
1514
                "refs/remotes/origin/integration",
1515
            ],
1516
        );
1517
        let branches = repository.branches().unwrap();
1518
        assert_eq!(
1519
            repository.trunk(&branches).unwrap().unwrap().name,
1520
            "integration"
1521
        );
1522
1523
        repository.git(
1524
            "symbolic-ref",
1525
            &["refs/remotes/origin/HEAD", "refs/remotes/origin/master"],
1526
        );
1527
1528
        assert_eq!(repository.trunk(&branches).unwrap().unwrap().name, "main");
1529
    }
1530
1531
    #[test]
1532
    fn commit_metadata_parses_four_fields() {
1533
        let record = [
1534
            "0123456789abcdef0123456789abcdef01234567",
1535
            "Alice",
1536
            "-10",
1537
            "20",
1538
        ]
1539
        .join("\0");
1540
        let (id, author, recency) = Repository::parse_commit_metadata(&record).unwrap();
1541
1542
        assert_eq!(
1543
            id,
1544
            "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
1545
        );
1546
        assert_eq!(author, "Alice");
1547
        assert_eq!(recency, CommitTime { seconds: 20 });
1548
    }
1549
1550
    #[test]
1551
    fn commit_metadata_rejects_extra_fields() {
1552
        let record = [
1553
            "0123456789abcdef0123456789abcdef01234567",
1554
            "Alice",
1555
            "10",
1556
            "20",
1557
            "extra",
1558
        ]
1559
        .join("\0");
1560
        let error = Repository::parse_commit_metadata(&record).unwrap_err();
1561
1562
        assert_eq!(
1563
            error.to_string(),
1564
            "git: malformed commit metadata line from git log"
1565
        );
1566
    }
1567
1568
    #[test]
1569
    fn patch_ids_map_sha1_and_sha256_streams() {
1570
        let patches = [
1571
            "diff --git a/a b/a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(),
1572
            "diff --git a/b b/b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(),
1573
        ];
1574
1575
        for object_format in ["sha1", "sha256"] {
1576
            let repository = TestRepository::with_object_format(object_format);
1577
            let ids = repository.patch_ids(&patches).unwrap();
1578
1579
            assert_eq!(ids.len(), patches.len());
1580
            assert!(ids.iter().all(|id| !id.as_str().is_empty()));
1581
            assert_ne!(ids[0], ids[1]);
1582
            assert!(repository.patch_ids(&[String::new()]).is_err());
1583
        }
1584
    }
1585
1586
    #[test]
1587
    fn patch_ids_streams_a_payload_larger_than_the_pipe_buffer() {
1588
        let repository = TestRepository::with_object_format("sha1");
1589
        let patches = (0..2000)
1590
            .map(|index| {
1591
                format!(
1592
                    "diff --git a/f{index} b/f{index}\n--- a/f{index}\n+++ b/f{index}\n\
1593
                     @@ -1 +1 @@\n-old{index}\n+new{index}\n"
1594
                )
1595
            })
1596
            .collect::<Vec<_>>();
1597
1598
        let ids = repository.patch_ids(&patches).unwrap();
1599
1600
        assert_eq!(ids.len(), patches.len());
1601
        assert_ne!(ids[0], ids[1]);
1602
    }
1603
1604
    #[test]
1605
    fn range_diff_pairs_rewritten_commits() {
1606
        let repository = TestRepository::with_main_branch();
1607
        repository.commit_file("file", "base\n", "base");
1608
        let base = repository
1609
            .commit_id(&Rev::try_from("HEAD").unwrap())
1610
            .unwrap();
1611
        repository.git("switch", &["-q", "-c", "old"]);
1612
        repository.commit_file("file", "base\nold\nshared\n", "change");
1613
        let old = repository
1614
            .commit_id(&Rev::try_from("HEAD").unwrap())
1615
            .unwrap();
1616
        repository.git("switch", &["-q", "main"]);
1617
        repository.commit_file("other", "upstream\n", "upstream");
1618
        let new_base = repository
1619
            .commit_id(&Rev::try_from("HEAD").unwrap())
1620
            .unwrap();
1621
        repository.git("switch", &["-q", "-c", "new"]);
1622
        let old_arg = old.to_string();
1623
        repository.git("cherry-pick", &[&old_arg]);
1624
        let new = repository
1625
            .commit_id(&Rev::try_from("HEAD").unwrap())
1626
            .unwrap();
1627
1628
        let pairs = repository.range_diff(base, old, new_base, new).unwrap();
1629
1630
        assert_eq!(pairs.get(&old), Some(&new));
1631
    }
1632
}