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