-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
repo.rs
2307 lines (2105 loc) · 82.5 KB
/
repo.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Operations on the Git repository. This module exists for a few reasons:
//!
//! - To ensure that every call to a Git operation has an associated `wrap_err`
//! for use with `Try`.
//! - To improve the interface in some cases. In particular, some operations in
//! `git2` return an `Error` with code `ENOTFOUND`, but we should really return
//! an `Option` in those cases.
//! - To make it possible to audit all the Git operations carried out in the
//! codebase.
//! - To collect some different helper Git functions.
use std::borrow::{Borrow, Cow};
use std::collections::{HashMap, HashSet};
use std::convert::{TryFrom, TryInto};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::SystemTime;
use chrono::{DateTime, Local, TimeZone, Utc};
use color_eyre::Help;
use cursive::theme::BaseColor;
use cursive::utils::markup::StyledString;
use eyre::{eyre, Context};
use itertools::Itertools;
use lazy_static::lazy_static;
use os_str_bytes::{OsStrBytes, OsStringBytes};
use regex::bytes::Regex;
use tracing::{instrument, warn};
use crate::core::config::get_main_branch_name;
use crate::core::effects::{Effects, OperationType};
use crate::core::eventlog::EventTransactionId;
use crate::core::formatting::{Glyphs, StyledStringBuilder};
use crate::core::node_descriptors::{
render_node_descriptors, CommitMessageDescriptor, CommitOidDescriptor, NodeObject, Redactor,
};
use crate::git::config::{Config, ConfigRead};
use crate::git::oid::{make_non_zero_oid, MaybeZeroOid, NonZeroOid};
use crate::git::run::GitRunInfo;
use crate::git::tree::{dehydrate_tree, get_changed_paths_between_trees, hydrate_tree, Tree};
/// Convert a `git2::Error` into an `eyre::Error` with an auto-generated message.
pub(super) fn wrap_git_error(error: git2::Error) -> eyre::Error {
eyre::eyre!("Git error {:?}: {}", error.code(), error.message())
}
/// Clean up a message, removing extraneous whitespace plus comment lines starting with
/// `comment_char`, and ensure that the message ends with a newline.
pub fn message_prettify(message: &str, comment_char: char) -> eyre::Result<String> {
let comment_char = u32::from(comment_char);
let comment_char = u8::try_from(comment_char).wrap_err("comment char was not ASCII")?;
let message = git2::message_prettify(message, Some(comment_char))?;
Ok(message)
}
/// A snapshot of information about a certain reference. Updates to the
/// reference after this value is obtained are not reflected.
///
/// `HEAD` is typically a symbolic reference, which means that it's a reference
/// that points to another reference. Usually, the other reference is a branch.
/// In this way, you can check out a branch and move the branch (e.g. by
/// committing) and `HEAD` is also effectively updated (you can traverse the
/// pointed-to reference and get the current commit OID).
///
/// There are a couple of interesting edge cases to worry about:
///
/// - `HEAD` is detached. This means that it's pointing directly to a commit and
/// is not a symbolic reference for the time being. This is uncommon in normal
/// Git usage, but very common in `git-branchless` usage.
/// - `HEAD` is unborn. This means that it doesn't even exist yet. This happens
/// when a repository has been freshly initialized, but no commits have been
/// made, for example.
#[derive(Debug, PartialEq, Eq)]
pub struct ResolvedReferenceInfo<'a> {
/// The OID of the commit that `HEAD` points to. If `HEAD` is unborn, then
/// this is `None`.
pub oid: Option<NonZeroOid>,
/// The name of the reference that `HEAD` points to symbolically. If `HEAD`
/// is detached, then this is `None`.
pub reference_name: Option<Cow<'a, OsStr>>,
}
impl<'a> ResolvedReferenceInfo<'a> {
/// Get the name of the branch, if any. Returns `None` if `HEAD` is
/// detached. The `refs/heads/` prefix, if any, is stripped.
pub fn get_branch_name(&self) -> eyre::Result<Option<OsString>> {
let reference_name: &OsStr = match &self.reference_name {
Some(reference_name) => reference_name,
None => return Ok(None),
};
let reference_name_bytes = reference_name.to_raw_bytes();
match reference_name_bytes.strip_prefix(b"refs/heads/") {
None => Ok(Some(reference_name.to_owned())),
Some(branch_name) => {
let branch_name = OsStringBytes::from_raw_vec(branch_name.to_vec())?;
Ok(Some(branch_name))
}
}
}
}
/// The parsed version of Git.
#[derive(Debug, PartialEq, PartialOrd, Eq)]
pub struct GitVersion(pub isize, pub isize, pub isize);
impl FromStr for GitVersion {
type Err = eyre::Error;
#[instrument]
fn from_str(output: &str) -> eyre::Result<GitVersion> {
let output = output.trim();
let words = output.split(&[' ', '-'][..]).collect::<Vec<&str>>();
let version_str = match &words.as_slice() {
[_git, _version, version_str, ..] => version_str,
_ => eyre::bail!("Could not parse Git version output: {:?}", output),
};
match version_str.split('.').collect::<Vec<&str>>().as_slice() {
[major, minor, patch, ..] => {
let major = major.parse()?;
let minor = minor.parse()?;
// Example version without a real patch number: `2.33.GIT`.
let patch: isize = patch.parse().unwrap_or_default();
Ok(GitVersion(major, minor, patch))
}
_ => eyre::bail!("Could not parse Git version string: {}", version_str),
}
}
}
/// Options for `Repo::cherry_pick_fast`.
#[derive(Clone, Debug)]
pub struct CherryPickFastOptions {
/// Detect if a commit is being applied onto a parent with the same tree,
/// and skip applying the patch in that case.
pub reuse_parent_tree_if_possible: bool,
}
/// An error raised when attempting the `Repo::cherry_pick_fast` operation.
#[derive(Debug)]
pub enum CherryPickFastError {
/// A merge conflict occurred, so the cherry-pick could not continue.
MergeConflict {
/// The paths that were in conflict.
conflicting_paths: HashSet<PathBuf>,
},
}
/// Options for `Repo::amend_fast`
#[derive(Debug)]
pub enum AmendFastOptions {
/// Amend a set of paths from the current state of the working copy.
FromWorkingCopy {
/// The status entries for the files to amend.
status_entries: Vec<StatusEntry>,
},
/// Amend a set of paths from the current state of the index.
FromIndex {
/// The paths to amend.
paths: Vec<PathBuf>,
},
}
impl AmendFastOptions {
/// Returns whether there are any paths to be amended.
pub fn is_empty(&self) -> bool {
match &self {
AmendFastOptions::FromIndex { paths } => paths.is_empty(),
AmendFastOptions::FromWorkingCopy { status_entries } => status_entries.is_empty(),
}
}
}
/// A snapshot of all the positions of references we care about in the repository.
#[derive(Debug)]
pub struct RepoReferencesSnapshot {
/// The location of the `HEAD` reference. This may be `None` if `HEAD` is unborn.
pub head_oid: Option<NonZeroOid>,
/// The location of the main branch.
pub main_branch_oid: NonZeroOid,
/// A mapping from commit OID to the branches which point to that commit.
pub branch_oid_to_names: HashMap<NonZeroOid, HashSet<OsString>>,
}
/// Wrapper around `git2::Repository`.
pub struct Repo {
pub(super) inner: git2::Repository,
}
impl std::fmt::Debug for Repo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<Git repository at: {:?}>", self.get_path())
}
}
impl Repo {
/// Get the Git repository associated with the given directory.
#[instrument]
pub fn from_dir(path: &Path) -> eyre::Result<Self> {
let repo = git2::Repository::discover(path).map_err(wrap_git_error)?;
Ok(Repo { inner: repo })
}
/// Get the Git repository associated with the current directory.
#[instrument]
pub fn from_current_dir() -> eyre::Result<Self> {
let path = std::env::current_dir().wrap_err("Getting working directory")?;
Repo::from_dir(&path)
}
/// Open a new copy of the repository.
pub fn try_clone(&self) -> eyre::Result<Self> {
let path = self.get_path();
let repo = git2::Repository::open(path)?;
Ok(Repo { inner: repo })
}
/// Get the path to the `.git` directory for the repository.
pub fn get_path(&self) -> &Path {
self.inner.path()
}
/// Get the path to the `packed-refs` file for the repository.
pub fn get_packed_refs_path(&self) -> PathBuf {
self.inner.path().join("packed-refs")
}
/// Get the path to the directory inside the `.git` directory which contains
/// state used for the current rebase (if any).
pub fn get_rebase_state_dir_path(&self) -> PathBuf {
self.inner.path().join("rebase-merge")
}
/// Get the path to the working copy for this repository. If the repository
/// is bare (has no working copy), returns `None`.
pub fn get_working_copy_path(&self) -> Option<&Path> {
self.inner.workdir()
}
/// Get the index file for this repository.
pub fn get_index(&self) -> eyre::Result<Index> {
Ok(Index {
inner: self.inner.index()?,
})
}
/// Get the configuration object for the repository.
///
/// **Warning**: This object should only be used for read operations. Write
/// operations should go to the `config` file under the `.git/branchless`
/// directory.
#[instrument]
pub fn get_readonly_config(&self) -> eyre::Result<impl ConfigRead> {
let config = self
.inner
.config()
.map_err(wrap_git_error)
.wrap_err("Creating `git2::Config` object")?;
Ok(Config::from(config))
}
/// Get the file where git-branchless-specific Git configuration is stored.
#[instrument]
pub fn get_config_path(&self) -> PathBuf {
self.get_path().join("branchless").join("config")
}
/// Get the directory where the DAG for the repository is stored.
#[instrument]
pub fn get_dag_dir(&self) -> PathBuf {
self.get_path().join("branchless").join("dag")
}
/// Get the directory to store man-pages. Note that this is the `man`
/// directory, and not a subsection thereof. `git-branchless` man-pages must
/// go into the `man/man1` directory to be found by `man`.
#[instrument]
pub fn get_man_dir(&self) -> PathBuf {
self.get_path().join("branchless").join("man")
}
/// Get a directory suitable for storing temporary files.
///
/// In particular, this directory is guaranteed to be on the same filesystem
/// as the Git repository itself, so you can move files between them
/// atomically. See
/// <https://github.com/arxanas/git-branchless/discussions/120>.
#[instrument]
pub fn get_tempfile_dir(&self) -> PathBuf {
self.get_path().join("branchless").join("tmp")
}
/// Get the connection to the SQLite database for this repository.
#[instrument]
pub fn get_db_conn(&self) -> eyre::Result<rusqlite::Connection> {
let dir = self.get_path().join("branchless");
std::fs::create_dir_all(&dir).wrap_err("Creating .git/branchless dir")?;
let path = dir.join("db.sqlite3");
let conn = rusqlite::Connection::open(&path)
.wrap_err_with(|| format!("Opening database connection at {:?}", &path))?;
Ok(conn)
}
/// Get a snapshot of information about a given reference.
#[instrument]
pub fn resolve_reference(&self, reference: &Reference) -> eyre::Result<ResolvedReferenceInfo> {
let oid = reference.peel_to_commit()?.map(|commit| commit.get_oid());
let reference_name: Option<OsString> = match reference.inner.kind() {
Some(git2::ReferenceType::Direct) => None,
Some(git2::ReferenceType::Symbolic) => match reference.inner.symbolic_target_bytes() {
Some(name) => Some(OsStringBytes::from_raw_vec(name.to_vec())?),
None => eyre::bail!(
"Reference was resolved to OID: {:?}, but its name could not be decoded: {:?}",
oid,
reference.inner.name_bytes()
),
},
None => eyre::bail!("Unknown `HEAD` reference type"),
};
Ok(ResolvedReferenceInfo {
oid,
reference_name: reference_name.map(Cow::Owned),
})
}
/// Get the OID for the repository's `HEAD` reference.
#[instrument]
pub fn get_head_info(&self) -> eyre::Result<ResolvedReferenceInfo> {
match self.find_reference(OsStr::new("HEAD"))? {
Some(reference) => self.resolve_reference(&reference),
None => Ok(ResolvedReferenceInfo {
oid: None,
reference_name: None,
}),
}
}
/// Set the `HEAD` reference directly to the provided `oid`. Does not touch
/// the working copy.
#[instrument]
pub fn set_head(&self, oid: NonZeroOid) -> eyre::Result<()> {
self.inner.set_head_detached(oid.inner)?;
Ok(())
}
/// Detach `HEAD` by making it point directly to its current OID, rather
/// than to a branch. If `HEAD` is already detached, logs a warning.
#[instrument]
pub fn detach_head(&self, head_info: &ResolvedReferenceInfo) -> eyre::Result<()> {
match head_info.oid {
Some(oid) => self
.inner
.set_head_detached(oid.inner)
.map_err(wrap_git_error),
None => {
warn!("Attempted to detach `HEAD` while `HEAD` is unborn");
Ok(())
}
}
}
/// Get the `Reference` for the main branch for the repository.
pub fn get_main_branch_reference(&self) -> eyre::Result<Reference> {
let main_branch_name = get_main_branch_name(self)?;
match self.find_branch(&main_branch_name, git2::BranchType::Local)? {
Some(branch) => {
let upstream_branch = branch
.inner
.upstream()
.map(|branch| Branch { inner: branch })
.unwrap_or_else(|_| branch);
Ok(upstream_branch.into_reference())
}
None => match self.find_branch(&main_branch_name, git2::BranchType::Remote)? {
Some(branch) => Ok(branch.into_reference()),
None => {
let suggestion = format!(
r"
The main branch {:?} could not be found in your repository
at path: {:?}.
These branches exist: {:?}
Either create it, or update the main branch setting by running:
git config branchless.core.mainBranch <branch>
",
get_main_branch_name(self)?,
self.get_path(),
self.get_all_local_branches()?
.into_iter()
.map(|branch| {
branch
.into_reference()
.get_name()
.map(|s| format!("{:?}", s))
})
.collect::<eyre::Result<Vec<String>>>()?,
);
Err(eyre!("Could not find repository main branch")
.with_suggestion(|| suggestion))
}
},
}
}
/// Get the OID corresponding to the main branch.
#[instrument]
pub fn get_main_branch_oid(&self) -> eyre::Result<NonZeroOid> {
let main_branch_reference = self.get_main_branch_reference()?;
let commit = main_branch_reference.peel_to_commit()?;
match commit {
Some(commit) => Ok(commit.get_oid()),
None => eyre::bail!(
"Could not find commit pointed to by main branch: {:?}",
main_branch_reference.get_name()?
),
}
}
/// Get a mapping from OID to the names of branches which point to that OID.
///
/// The returned branch names include the `refs/heads/` prefix, so it must
/// be stripped if desired.
#[instrument]
pub fn get_branch_oid_to_names(&self) -> eyre::Result<HashMap<NonZeroOid, HashSet<OsString>>> {
let mut result: HashMap<NonZeroOid, HashSet<OsString>> = HashMap::new();
for branch in self.get_all_local_branches()? {
let reference = branch.into_reference();
let reference_name = reference.get_name()?;
let reference_info = self.resolve_reference(&reference)?;
if let Some(reference_oid) = reference_info.oid {
result
.entry(reference_oid)
.or_insert_with(HashSet::new)
.insert(reference_name);
}
}
// The main branch may be a remote branch, in which case it won't be
// returned in the iteration above.
let main_branch_name = self.get_main_branch_reference()?.get_name()?;
let main_branch_oid = self.get_main_branch_oid()?;
result
.entry(main_branch_oid)
.or_insert_with(HashSet::new)
.insert(main_branch_name);
Ok(result)
}
/// Get the positions of references in the repository.
pub fn get_references_snapshot(&self) -> eyre::Result<RepoReferencesSnapshot> {
let head_oid = self.get_head_info()?.oid;
let main_branch_oid = self.get_main_branch_oid()?;
let branch_oid_to_names = self.get_branch_oid_to_names()?;
Ok(RepoReferencesSnapshot {
head_oid,
main_branch_oid,
branch_oid_to_names,
})
}
/// Detect if an interactive rebase has started but not completed.
///
/// Git will send us spurious `post-rewrite` events marked as `amend` during an
/// interactive rebase, indicating that some of the commits have been rewritten
/// as part of the rebase plan, but not all of them. This function attempts to
/// detect when an interactive rebase is underway, and if the current
/// `post-rewrite` event is spurious.
///
/// There are two practical issues for users as a result of this Git behavior:
///
/// * During an interactive rebase, we may see many "processing 1 rewritten
/// commit" messages, and then a final "processing X rewritten commits" message
/// once the rebase has concluded. This is potentially confusing for users, since
/// the operation logically only rewrote the commits once, but we displayed the
/// message multiple times.
///
/// * During an interactive rebase, we may warn about abandoned commits, when the
/// next operation in the rebase plan fixes up the abandoned commit. This can
/// happen even if no conflict occurred and the rebase completed successfully
/// without any user intervention.
#[instrument]
pub fn is_rebase_underway(&self) -> eyre::Result<bool> {
use git2::RepositoryState::*;
match self.inner.state() {
Rebase | RebaseInteractive | RebaseMerge => Ok(true),
// Possibly some of these states should also be treated as `true`?
Clean | Merge | Revert | RevertSequence | CherryPick | CherryPickSequence | Bisect
| ApplyMailbox | ApplyMailboxOrRebase => Ok(false),
}
}
/// Get the type current multi-step operation (such as `rebase` or
/// `cherry-pick`) which is underway. Returns `None` if there is no such
/// operation.
pub fn get_current_operation_type(&self) -> Option<&str> {
use git2::RepositoryState::*;
match self.inner.state() {
Clean | Bisect => None,
Merge => Some("merge"),
Revert | RevertSequence => Some("revert"),
CherryPick | CherryPickSequence => Some("cherry-pick"),
Rebase | RebaseInteractive | RebaseMerge => Some("rebase"),
ApplyMailbox | ApplyMailboxOrRebase => Some("am"),
}
}
/// Find the merge-base between two commits. Returns `None` if a merge-base
/// could not be found.
#[instrument]
pub fn find_merge_base(
&self,
lhs: NonZeroOid,
rhs: NonZeroOid,
) -> eyre::Result<Option<NonZeroOid>> {
match self.inner.merge_base(lhs.inner, rhs.inner) {
Ok(merge_base_oid) => Ok(Some(make_non_zero_oid(merge_base_oid))),
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => Err(wrap_git_error(err)),
}
}
/// Get the patch for a commit, i.e. the diff between that commit and its
/// parent.
///
/// If the commit has more than one parent, returns `None`.
#[instrument]
pub fn get_patch_for_commit(
&self,
effects: &Effects,
commit: &Commit,
) -> eyre::Result<Option<Diff>> {
let (_effects, _progress) = effects.start_operation(OperationType::CalculateDiff);
let changed_paths = match self.get_paths_touched_by_commit(commit)? {
None => return Ok(None),
Some(changed_paths) => changed_paths,
};
let dehydrated_commit = self.dehydrate_commit(
commit,
changed_paths
.iter()
.map(|x| -> &Path { x })
.collect_vec()
.as_slice(),
true,
)?;
let parent = dehydrated_commit.get_only_parent();
let parent_tree = match &parent {
Some(parent) => Some(parent.get_tree()?.inner.clone()),
None => None,
};
let current_tree = dehydrated_commit.get_tree()?;
let diff = self
.inner
.diff_tree_to_tree(parent_tree.as_ref(), Some(¤t_tree.inner), None)
.wrap_err_with(|| format!("Calculating diff between: {:?}", commit))?;
Ok(Some(Diff { inner: diff }))
}
/// Returns the set of paths currently staged to the repository's index.
#[instrument]
pub fn get_staged_paths(&self) -> eyre::Result<HashSet<PathBuf>> {
let head_commit_oid = match self.get_head_info()?.oid {
Some(oid) => oid,
None => eyre::bail!("No HEAD to check for staged paths"),
};
let head_commit = self.find_commit_or_fail(head_commit_oid)?;
let head_tree = self.find_tree_or_fail(head_commit.get_tree()?.get_oid())?;
let diff = self.inner.diff_tree_to_index(
Some(&head_tree.inner),
Some(&self.get_index()?.inner),
None,
)?;
let paths = diff
.deltas()
.into_iter()
.flat_map(|delta| vec![delta.old_file().path(), delta.new_file().path()])
.flat_map(|p| p.map(PathBuf::from))
.collect();
Ok(paths)
}
/// Get the file paths which were added, removed, or changed by the given
/// commit.
///
/// If the commit has no parents, returns all of the file paths in that
/// commit's tree.
///
/// If the commit has more than one parent, returns `None`.
#[instrument]
pub fn get_paths_touched_by_commit(
&self,
commit: &Commit,
) -> eyre::Result<Option<HashSet<PathBuf>>> {
let parent_commits = commit.get_parents();
let parent_tree = match parent_commits.as_slice() {
[] => None,
[only_parent] => Some(only_parent.get_tree()?.inner),
[..] => return Ok(None),
};
let current_tree = commit.get_tree()?.inner;
let changed_paths =
get_changed_paths_between_trees(self, parent_tree.as_ref(), Some(¤t_tree))?;
Ok(Some(changed_paths))
}
/// Get the patch ID for this commit.
#[instrument]
pub fn get_patch_id(
&self,
effects: &Effects,
commit: &Commit,
) -> eyre::Result<Option<PatchId>> {
let patch = match self.get_patch_for_commit(effects, commit)? {
None => return Ok(None),
Some(diff) => diff,
};
let patch_id = {
let (_effects, _progress) = effects.start_operation(OperationType::CalculatePatchId);
patch.inner.patchid(None).wrap_err("Computing patch ID")?
};
Ok(Some(PatchId { patch_id }))
}
/// Attempt to parse the user-provided object descriptor.
pub fn revparse_single_commit(&self, spec: &str) -> eyre::Result<Option<Commit>> {
match self.inner.revparse_single(spec) {
Ok(object) => match object.into_commit() {
Ok(commit) => Ok(Some(Commit { inner: commit })),
Err(_) => Ok(None),
},
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => Err(wrap_git_error(err)),
}
}
/// Look up a single reference by name.
pub fn get_reference(&self, reference_name: &OsStr) -> eyre::Result<Option<Reference>> {
let reference_name = reference_name.to_str().ok_or_else(|| {
eyre::eyre!(
"Cannot convert reference name to string (libgit2 limitation): {:?}",
reference_name
)
})?;
match self.inner.find_reference(reference_name) {
Ok(reference) => Ok(Some(Reference { inner: reference })),
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => (Err(err.into())),
}
}
/// Find all references in the repository.
#[instrument]
pub fn get_all_references(&self) -> eyre::Result<Vec<Reference>> {
let mut all_references = Vec::new();
for reference in self
.inner
.references()
.map_err(wrap_git_error)
.wrap_err("Iterating through references")?
{
let reference = reference.wrap_err("Accessing individual reference")?;
all_references.push(Reference { inner: reference });
}
Ok(all_references)
}
/// Check if the repository has staged or unstaged changes. Untracked files
/// are not included. This operation may take a while.
#[instrument]
pub fn has_changed_files(
&self,
effects: &Effects,
git_run_info: &GitRunInfo,
) -> eyre::Result<bool> {
let exit_code = git_run_info.run(
effects,
// This is not a mutating operation, so we don't need a transaction ID.
None,
&["diff", "--quiet"],
)?;
if exit_code == 0 {
Ok(false)
} else {
Ok(true)
}
}
/// Returns the current status of the repo index and working copy.
pub fn get_status(
&self,
git_run_info: &GitRunInfo,
event_tx_id: Option<EventTransactionId>,
) -> eyre::Result<Vec<StatusEntry>> {
let output = git_run_info
.run_silent(
self,
event_tx_id,
&["status", "--porcelain=v2", "--untracked-files=no", "-z"],
Default::default(),
)?
.stdout;
let not_null_terminator = |c: &u8| *c != 0_u8;
let mut statuses = Vec::new();
let mut status_bytes = output.into_iter().peekable();
// Iterate over the status entries in the output.
// This takes some care, because NUL bytes are both used to delimit
// between entries, and as a separator between paths in the case
// of renames.
// See https://git-scm.com/docs/git-status#_porcelain_format_version_2
while let Some(line_prefix) = status_bytes.peek() {
let line = match line_prefix {
// Ordinary change entry.
b'1' => {
let line = status_bytes
.by_ref()
.take_while(not_null_terminator)
.collect_vec();
line
}
// Rename or copy change entry.
b'2' => {
let mut line = status_bytes
.by_ref()
.take_while(not_null_terminator)
.collect_vec();
line.push(0_u8); // Persist first null terminator in the line.
line.extend(status_bytes.by_ref().take_while(not_null_terminator));
line
}
_ => eyre::bail!("unknown status line prefix: {}", line_prefix),
};
let entry = line.as_slice().try_into()?;
statuses.push(entry);
}
Ok(statuses)
}
/// Create a new reference or update an existing one.
#[instrument]
pub fn create_reference(
&self,
name: &OsStr,
oid: NonZeroOid,
force: bool,
log_message: &str,
) -> eyre::Result<Reference> {
let name = match name.to_str() {
Some(name) => name,
None => eyre::bail!(
"Reference name is not a UTF-8 string (libgit2 limitation): {:?}",
name
),
};
let reference = self
.inner
.reference(name, oid.inner, force, log_message)
.map_err(wrap_git_error)?;
Ok(Reference { inner: reference })
}
/// Look up a reference with the given name. Returns `None` if not found.
#[instrument]
pub fn find_reference(&self, name: &OsStr) -> eyre::Result<Option<Reference>> {
let name = match name.to_str() {
Some(name) => name,
None => eyre::bail!(
"Reference name is not a UTF-8 string (libgit2 limitation): {:?}",
name
),
};
match self.inner.find_reference(name) {
Ok(reference) => Ok(Some(Reference { inner: reference })),
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => Err(wrap_git_error(err)),
}
}
/// Get all local branches in the repository.
#[instrument]
pub fn get_all_local_branches(&self) -> eyre::Result<Vec<Branch>> {
let mut all_branches = Vec::new();
for branch in self
.inner
.branches(Some(git2::BranchType::Local))
.map_err(wrap_git_error)
.wrap_err("Iterating over all local branches")?
{
let (branch, _branch_type) = branch.wrap_err("Accessing individual branch")?;
all_branches.push(Branch { inner: branch });
}
Ok(all_branches)
}
/// Look up the branch with the given name. Returns `None` if not found.
#[instrument]
pub fn find_branch(&self, name: &str, branch_type: BranchType) -> eyre::Result<Option<Branch>> {
match self.inner.find_branch(name, branch_type) {
Ok(branch) => Ok(Some(Branch { inner: branch })),
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => Err(wrap_git_error(err)),
}
}
/// Create a new branch or update an existing branch.
#[instrument]
pub fn create_branch(
&self,
name: &OsStr,
target: &Commit,
force: bool,
) -> eyre::Result<git2::Branch> {
let name = match name.to_str() {
Some(name) => name,
None => eyre::bail!(
"Branch name is not a UTF-8 string (libgit2 limitation): {:?}",
name
),
};
self.inner
.branch(name, &target.inner, force)
.map_err(wrap_git_error)
}
/// Look up a commit with the given OID. Returns `None` if not found.
#[instrument]
pub fn find_commit(&self, oid: NonZeroOid) -> eyre::Result<Option<Commit>> {
match self.inner.find_commit(oid.inner) {
Ok(commit) => Ok(Some(Commit { inner: commit })),
Err(err) if err.code() == git2::ErrorCode::NotFound => Ok(None),
Err(err) => Err(wrap_git_error(err)),
}
}
/// Like `find_commit`, but raises a generic error if the commit could not
/// be found.
#[instrument]
pub fn find_commit_or_fail(&self, oid: NonZeroOid) -> eyre::Result<Commit> {
match self.find_commit(oid) {
Ok(Some(commit)) => Ok(commit),
Ok(None) => eyre::bail!("Could not find commit with OID: {:?}", oid),
Err(err) => Err(err),
}
}
/// Look up the commit with the given OID and render a friendly description
/// of it, or render an error message if not found.
pub fn friendly_describe_commit_from_oid(
&self,
glyphs: &Glyphs,
oid: NonZeroOid,
) -> eyre::Result<StyledString> {
match self.find_commit(oid)? {
Some(commit) => Ok(commit.friendly_describe(glyphs)?),
None => {
let NonZeroOid { inner: oid } = oid;
Ok(StyledString::styled(
format!("<commit not available: {}>", oid),
BaseColor::Red.light(),
))
}
}
}
/// Create a new commit.
#[instrument]
pub fn create_commit(
&self,
update_ref: Option<&str>,
author: &Signature,
committer: &Signature,
message: &str,
tree: &Tree,
parents: Vec<&Commit>,
) -> eyre::Result<NonZeroOid> {
let parents = parents
.iter()
.map(|commit| &commit.inner)
.collect::<Vec<_>>();
let oid = self
.inner
.commit(
update_ref,
&author.inner,
&committer.inner,
message,
&tree.inner,
parents.as_slice(),
)
.map_err(wrap_git_error)?;
Ok(make_non_zero_oid(oid))
}
/// Cherry-pick a commit in memory and return the resulting index.
#[instrument]
pub fn cherry_pick_commit(
&self,
cherry_pick_commit: &Commit,
our_commit: &Commit,
mainline: u32,
) -> eyre::Result<Index> {
let index = self
.inner
.cherrypick_commit(&cherry_pick_commit.inner, &our_commit.inner, mainline, None)
.map_err(wrap_git_error)?;
Ok(Index { inner: index })
}
/// Cherry-pick a commit in memory and return the resulting tree.
///
/// The `libgit2` routines operate on entire `Index`es, which contain one
/// entry per file in the repository. When operating on a large repository,
/// this is prohibitively slow, as it takes several seconds just to write
/// the index to disk. To improve performance, we reduce the size of the
/// involved indexes by filtering out any unchanged entries from the input
/// trees, then call into `libgit2`, then add back the unchanged entries to
/// the output tree.
#[instrument]
pub fn cherry_pick_fast<'repo>(
&'repo self,
patch_commit: &'repo Commit,
target_commit: &'repo Commit,
options: &CherryPickFastOptions,
) -> eyre::Result<Result<Tree<'repo>, CherryPickFastError>> {
let CherryPickFastOptions {
reuse_parent_tree_if_possible,
} = options;
if *reuse_parent_tree_if_possible {
if let Some(only_parent) = patch_commit.get_only_parent() {
if only_parent.get_tree()?.get_oid() == target_commit.get_tree()?.get_oid() {
// If this patch is being applied to the same commit it was
// originally based on, then we can skip cherry-picking
// altogether, and use its tree directly. This is common e.g.
// when only rewording a commit message.
return Ok(Ok(patch_commit.get_tree()?));
}
};
}
let changed_pathbufs = self
.get_paths_touched_by_commit(patch_commit)?
.ok_or_else(|| {
eyre::eyre!("Could not get paths touched by commit: {:?}", &patch_commit)
})?
.into_iter()
.collect_vec();
let changed_paths = changed_pathbufs.iter().map(PathBuf::borrow).collect_vec();
let dehydrated_patch_commit =
self.dehydrate_commit(patch_commit, changed_paths.as_slice(), true)?;
let dehydrated_target_commit =
self.dehydrate_commit(target_commit, changed_paths.as_slice(), false)?;
let rebased_index =
self.cherry_pick_commit(&dehydrated_patch_commit, &dehydrated_target_commit, 0)?;
let rebased_tree = {
if rebased_index.has_conflicts() {
let conflicting_paths = {
let mut result = HashSet::new();
for conflict in rebased_index
.inner
.conflicts()
.wrap_err("Getting conflicting paths")?
{
let conflict = conflict.wrap_err("Getting conflicting path")?;
if let Some(ancestor) = conflict.ancestor {
result
.insert(PathBuf::from(OsStrBytes::from_raw_bytes(ancestor.path)?));
}
if let Some(our) = conflict.our {
result.insert(PathBuf::from(OsStrBytes::from_raw_bytes(our.path)?));
}
if let Some(their) = conflict.their {
result.insert(PathBuf::from(OsStrBytes::from_raw_bytes(their.path)?));
}
}
result
};
if conflicting_paths.is_empty() {
warn!("BUG: A merge conflict was detected, but there were no entries in `conflicting_paths`. Maybe the wrong index entry was used?")
}
return Ok(Err(CherryPickFastError::MergeConflict {