forked from rust-lang/git2-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepo.rs
4276 lines (3943 loc) · 147 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
use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::env;
use std::ffi::{CStr, CString, OsStr};
use std::iter::IntoIterator;
use std::mem;
use std::path::{Path, PathBuf};
use std::ptr;
use std::str;
use crate::build::{CheckoutBuilder, RepoBuilder};
use crate::diff::{
binary_cb_c, file_cb_c, hunk_cb_c, line_cb_c, BinaryCb, DiffCallbacks, FileCb, HunkCb, LineCb,
};
use crate::oid_array::OidArray;
use crate::stash::{stash_cb, StashApplyOptions, StashCbData, StashSaveOptions};
use crate::string_array::StringArray;
use crate::tagforeach::{tag_foreach_cb, TagForeachCB, TagForeachData};
use crate::util::{self, path_to_repo_path, Binding};
use crate::worktree::{Worktree, WorktreeAddOptions};
use crate::CherrypickOptions;
use crate::RevertOptions;
use crate::{mailmap::Mailmap, panic};
use crate::{
raw, AttrCheckFlags, Buf, Error, Object, Remote, RepositoryOpenFlags, RepositoryState, Revspec,
StashFlags,
};
use crate::{
AnnotatedCommit, MergeAnalysis, MergeOptions, MergePreference, SubmoduleIgnore,
SubmoduleStatus, SubmoduleUpdate,
};
use crate::{ApplyLocation, ApplyOptions, Rebase, RebaseOptions};
use crate::{Blame, BlameOptions, Reference, References, ResetType, Signature, Submodule};
use crate::{Blob, BlobWriter, Branch, BranchType, Branches, Commit, Config, Index, Oid, Tree};
use crate::{Describe, IntoCString, Reflog, RepositoryInitMode, RevparseMode};
use crate::{DescribeOptions, Diff, DiffOptions, Odb, PackBuilder, TreeBuilder};
use crate::{Note, Notes, ObjectType, Revwalk, Status, StatusOptions, Statuses, Tag, Transaction};
type MergeheadForeachCb<'a> = dyn FnMut(&Oid) -> bool + 'a;
type FetchheadForeachCb<'a> = dyn FnMut(&str, &[u8], &Oid, bool) -> bool + 'a;
struct FetchheadForeachCbData<'a> {
callback: &'a mut FetchheadForeachCb<'a>,
}
struct MergeheadForeachCbData<'a> {
callback: &'a mut MergeheadForeachCb<'a>,
}
extern "C" fn mergehead_foreach_cb(oid: *const raw::git_oid, payload: *mut c_void) -> c_int {
panic::wrap(|| unsafe {
let data = &mut *(payload as *mut MergeheadForeachCbData<'_>);
let res = {
let callback = &mut data.callback;
callback(&Binding::from_raw(oid))
};
if res {
0
} else {
1
}
})
.unwrap_or(1)
}
extern "C" fn fetchhead_foreach_cb(
ref_name: *const c_char,
remote_url: *const c_char,
oid: *const raw::git_oid,
is_merge: c_uint,
payload: *mut c_void,
) -> c_int {
panic::wrap(|| unsafe {
let data = &mut *(payload as *mut FetchheadForeachCbData<'_>);
let res = {
let callback = &mut data.callback;
assert!(!ref_name.is_null());
assert!(!remote_url.is_null());
assert!(!oid.is_null());
let ref_name = str::from_utf8(CStr::from_ptr(ref_name).to_bytes()).unwrap();
let remote_url = CStr::from_ptr(remote_url).to_bytes();
let oid = Binding::from_raw(oid);
let is_merge = is_merge == 1;
callback(&ref_name, remote_url, &oid, is_merge)
};
if res {
0
} else {
1
}
})
.unwrap_or(1)
}
/// An owned git repository, representing all state associated with the
/// underlying filesystem.
///
/// This structure corresponds to a `git_repository` in libgit2. Many other
/// types in git2-rs are derivative from this structure and are attached to its
/// lifetime.
///
/// When a repository goes out of scope it is freed in memory but not deleted
/// from the filesystem.
pub struct Repository {
raw: *mut raw::git_repository,
}
// It is the current belief that a `Repository` can be sent among threads, or
// even shared among threads in a mutex.
unsafe impl Send for Repository {}
/// Options which can be used to configure how a repository is initialized
pub struct RepositoryInitOptions {
flags: u32,
mode: u32,
workdir_path: Option<CString>,
description: Option<CString>,
template_path: Option<CString>,
initial_head: Option<CString>,
origin_url: Option<CString>,
}
impl Repository {
/// Attempt to open an already-existing repository at `path`.
///
/// The path can point to either a normal or bare repository.
pub fn open<P: AsRef<Path>>(path: P) -> Result<Repository, Error> {
crate::init();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_open(&mut ret, path));
Ok(Binding::from_raw(ret))
}
}
/// Attempt to open an already-existing bare repository at `path`.
///
/// The path can point to only a bare repository.
pub fn open_bare<P: AsRef<Path>>(path: P) -> Result<Repository, Error> {
crate::init();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_open_bare(&mut ret, path));
Ok(Binding::from_raw(ret))
}
}
/// Find and open an existing repository, respecting git environment
/// variables. This acts like `open_ext` with the
/// [FROM_ENV](RepositoryOpenFlags::FROM_ENV) flag, but additionally respects `$GIT_DIR`.
/// With `$GIT_DIR` unset, this will search for a repository starting in
/// the current directory.
pub fn open_from_env() -> Result<Repository, Error> {
crate::init();
let mut ret = ptr::null_mut();
let flags = raw::GIT_REPOSITORY_OPEN_FROM_ENV;
unsafe {
try_call!(raw::git_repository_open_ext(
&mut ret,
ptr::null(),
flags as c_uint,
ptr::null()
));
Ok(Binding::from_raw(ret))
}
}
/// Find and open an existing repository, with additional options.
///
/// If flags contains [NO_SEARCH](RepositoryOpenFlags::NO_SEARCH), the path must point
/// directly to a repository; otherwise, this may point to a subdirectory
/// of a repository, and `open_ext` will search up through parent
/// directories.
///
/// If flags contains [CROSS_FS](RepositoryOpenFlags::CROSS_FS), the search through parent
/// directories will not cross a filesystem boundary (detected when the
/// stat st_dev field changes).
///
/// If flags contains [BARE](RepositoryOpenFlags::BARE), force opening the repository as
/// bare even if it isn't, ignoring any working directory, and defer
/// loading the repository configuration for performance.
///
/// If flags contains [NO_DOTGIT](RepositoryOpenFlags::NO_DOTGIT), don't try appending
/// `/.git` to `path`.
///
/// If flags contains [FROM_ENV](RepositoryOpenFlags::FROM_ENV), `open_ext` will ignore
/// other flags and `ceiling_dirs`, and respect the same environment
/// variables git does. Note, however, that `path` overrides `$GIT_DIR`; to
/// respect `$GIT_DIR` as well, use `open_from_env`.
///
/// ceiling_dirs specifies a list of paths that the search through parent
/// directories will stop before entering. Use the functions in std::env
/// to construct or manipulate such a path list. (You can use `&[] as
/// &[&std::ffi::OsStr]` as an argument if there are no ceiling
/// directories.)
pub fn open_ext<P, O, I>(
path: P,
flags: RepositoryOpenFlags,
ceiling_dirs: I,
) -> Result<Repository, Error>
where
P: AsRef<Path>,
O: AsRef<OsStr>,
I: IntoIterator<Item = O>,
{
crate::init();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
let ceiling_dirs_os = env::join_paths(ceiling_dirs)?;
let ceiling_dirs = ceiling_dirs_os.into_c_string()?;
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_open_ext(
&mut ret,
path,
flags.bits() as c_uint,
ceiling_dirs
));
Ok(Binding::from_raw(ret))
}
}
/// Attempt to open an already-existing repository from a worktree.
pub fn open_from_worktree(worktree: &Worktree) -> Result<Repository, Error> {
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_open_from_worktree(
&mut ret,
worktree.raw()
));
Ok(Binding::from_raw(ret))
}
}
/// Attempt to open an already-existing repository at or above `path`
///
/// This starts at `path` and looks up the filesystem hierarchy
/// until it finds a repository.
pub fn discover<P: AsRef<Path>>(path: P) -> Result<Repository, Error> {
// TODO: this diverges significantly from the libgit2 API
crate::init();
let buf = Buf::new();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
unsafe {
try_call!(raw::git_repository_discover(
buf.raw(),
path,
1,
ptr::null()
));
}
Repository::open(util::bytes2path(&*buf))
}
/// Attempt to find the path to a git repo for a given path
///
/// This starts at `path` and looks up the filesystem hierarchy
/// until it finds a repository, stopping if it finds a member of ceiling_dirs
pub fn discover_path<P: AsRef<Path>, I, O>(path: P, ceiling_dirs: I) -> Result<PathBuf, Error>
where
O: AsRef<OsStr>,
I: IntoIterator<Item = O>,
{
crate::init();
let buf = Buf::new();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
let ceiling_dirs_os = env::join_paths(ceiling_dirs)?;
let ceiling_dirs = ceiling_dirs_os.into_c_string()?;
unsafe {
try_call!(raw::git_repository_discover(
buf.raw(),
path,
1,
ceiling_dirs
));
}
Ok(util::bytes2path(&*buf).to_path_buf())
}
/// Creates a new repository in the specified folder.
///
/// This by default will create any necessary directories to create the
/// repository, and it will read any user-specified templates when creating
/// the repository. This behavior can be configured through `init_opts`.
pub fn init<P: AsRef<Path>>(path: P) -> Result<Repository, Error> {
Repository::init_opts(path, &RepositoryInitOptions::new())
}
/// Creates a new `--bare` repository in the specified folder.
///
/// The folder must exist prior to invoking this function.
pub fn init_bare<P: AsRef<Path>>(path: P) -> Result<Repository, Error> {
Repository::init_opts(path, RepositoryInitOptions::new().bare(true))
}
/// Creates a new repository in the specified folder with the given options.
///
/// See `RepositoryInitOptions` struct for more information.
pub fn init_opts<P: AsRef<Path>>(
path: P,
opts: &RepositoryInitOptions,
) -> Result<Repository, Error> {
crate::init();
// Normal file path OK (does not need Windows conversion).
let path = path.as_ref().into_c_string()?;
let mut ret = ptr::null_mut();
unsafe {
let mut opts = opts.raw();
try_call!(raw::git_repository_init_ext(&mut ret, path, &mut opts));
Ok(Binding::from_raw(ret))
}
}
/// Clone a remote repository.
///
/// See the `RepoBuilder` struct for more information. This function will
/// delegate to a fresh `RepoBuilder`
pub fn clone<P: AsRef<Path>>(url: &str, into: P) -> Result<Repository, Error> {
crate::init();
RepoBuilder::new().clone(url, into.as_ref())
}
/// Clone a remote repository, initialize and update its submodules
/// recursively.
///
/// This is similar to `git clone --recursive`.
pub fn clone_recurse<P: AsRef<Path>>(url: &str, into: P) -> Result<Repository, Error> {
let repo = Repository::clone(url, into)?;
repo.update_submodules()?;
Ok(repo)
}
/// Attempt to wrap an object database as a repository.
pub fn from_odb(odb: Odb<'_>) -> Result<Repository, Error> {
crate::init();
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_wrap_odb(&mut ret, odb.raw()));
Ok(Binding::from_raw(ret))
}
}
/// Update submodules recursively.
///
/// Uninitialized submodules will be initialized.
fn update_submodules(&self) -> Result<(), Error> {
fn add_subrepos(repo: &Repository, list: &mut Vec<Repository>) -> Result<(), Error> {
for mut subm in repo.submodules()? {
subm.update(true, None)?;
list.push(subm.open()?);
}
Ok(())
}
let mut repos = Vec::new();
add_subrepos(self, &mut repos)?;
while let Some(repo) = repos.pop() {
add_subrepos(&repo, &mut repos)?;
}
Ok(())
}
/// Execute a rev-parse operation against the `spec` listed.
///
/// The resulting revision specification is returned, or an error is
/// returned if one occurs.
pub fn revparse(&self, spec: &str) -> Result<Revspec<'_>, Error> {
let mut raw = raw::git_revspec {
from: ptr::null_mut(),
to: ptr::null_mut(),
flags: 0,
};
let spec = CString::new(spec)?;
unsafe {
try_call!(raw::git_revparse(&mut raw, self.raw, spec));
let to = Binding::from_raw_opt(raw.to);
let from = Binding::from_raw_opt(raw.from);
let mode = RevparseMode::from_bits_truncate(raw.flags as u32);
Ok(Revspec::from_objects(from, to, mode))
}
}
/// Find a single object, as specified by a revision string.
pub fn revparse_single(&self, spec: &str) -> Result<Object<'_>, Error> {
let spec = CString::new(spec)?;
let mut obj = ptr::null_mut();
unsafe {
try_call!(raw::git_revparse_single(&mut obj, self.raw, spec));
assert!(!obj.is_null());
Ok(Binding::from_raw(obj))
}
}
/// Find a single object and intermediate reference by a revision string.
///
/// See `man gitrevisions`, or
/// <http://git-scm.com/docs/git-rev-parse.html#_specifying_revisions> for
/// information on the syntax accepted.
///
/// In some cases (`@{<-n>}` or `<branchname>@{upstream}`), the expression
/// may point to an intermediate reference. When such expressions are being
/// passed in, this intermediate reference is returned.
pub fn revparse_ext(&self, spec: &str) -> Result<(Object<'_>, Option<Reference<'_>>), Error> {
let spec = CString::new(spec)?;
let mut git_obj = ptr::null_mut();
let mut git_ref = ptr::null_mut();
unsafe {
try_call!(raw::git_revparse_ext(
&mut git_obj,
&mut git_ref,
self.raw,
spec
));
assert!(!git_obj.is_null());
Ok((Binding::from_raw(git_obj), Binding::from_raw_opt(git_ref)))
}
}
/// Tests whether this repository is a bare repository or not.
pub fn is_bare(&self) -> bool {
unsafe { raw::git_repository_is_bare(self.raw) == 1 }
}
/// Tests whether this repository is a shallow clone.
pub fn is_shallow(&self) -> bool {
unsafe { raw::git_repository_is_shallow(self.raw) == 1 }
}
/// Tests whether this repository is a worktree.
pub fn is_worktree(&self) -> bool {
unsafe { raw::git_repository_is_worktree(self.raw) == 1 }
}
/// Tests whether this repository is empty.
pub fn is_empty(&self) -> Result<bool, Error> {
let empty = unsafe { try_call!(raw::git_repository_is_empty(self.raw)) };
Ok(empty == 1)
}
/// Returns the path to the `.git` folder for normal repositories or the
/// repository itself for bare repositories.
pub fn path(&self) -> &Path {
unsafe {
let ptr = raw::git_repository_path(self.raw);
util::bytes2path(crate::opt_bytes(self, ptr).unwrap())
}
}
/// Returns the current state of this repository
pub fn state(&self) -> RepositoryState {
let state = unsafe { raw::git_repository_state(self.raw) };
macro_rules! check( ($($raw:ident => $real:ident),*) => (
$(if state == raw::$raw as c_int {
super::RepositoryState::$real
}) else *
else {
panic!("unknown repository state: {}", state)
}
) );
check!(
GIT_REPOSITORY_STATE_NONE => Clean,
GIT_REPOSITORY_STATE_MERGE => Merge,
GIT_REPOSITORY_STATE_REVERT => Revert,
GIT_REPOSITORY_STATE_REVERT_SEQUENCE => RevertSequence,
GIT_REPOSITORY_STATE_CHERRYPICK => CherryPick,
GIT_REPOSITORY_STATE_CHERRYPICK_SEQUENCE => CherryPickSequence,
GIT_REPOSITORY_STATE_BISECT => Bisect,
GIT_REPOSITORY_STATE_REBASE => Rebase,
GIT_REPOSITORY_STATE_REBASE_INTERACTIVE => RebaseInteractive,
GIT_REPOSITORY_STATE_REBASE_MERGE => RebaseMerge,
GIT_REPOSITORY_STATE_APPLY_MAILBOX => ApplyMailbox,
GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE => ApplyMailboxOrRebase
)
}
/// Get the path of the working directory for this repository.
///
/// If this repository is bare, then `None` is returned.
pub fn workdir(&self) -> Option<&Path> {
unsafe {
let ptr = raw::git_repository_workdir(self.raw);
if ptr.is_null() {
None
} else {
Some(util::bytes2path(CStr::from_ptr(ptr).to_bytes()))
}
}
}
/// Set the path to the working directory for this repository.
///
/// If `update_link` is true, create/update the gitlink file in the workdir
/// and set config "core.worktree" (if workdir is not the parent of the .git
/// directory).
pub fn set_workdir(&self, path: &Path, update_gitlink: bool) -> Result<(), Error> {
// Normal file path OK (does not need Windows conversion).
let path = path.into_c_string()?;
unsafe {
try_call!(raw::git_repository_set_workdir(
self.raw(),
path,
update_gitlink
));
}
Ok(())
}
/// Get the currently active namespace for this repository.
///
/// If there is no namespace, or the namespace is not a valid utf8 string,
/// `None` is returned.
pub fn namespace(&self) -> Option<&str> {
self.namespace_bytes().and_then(|s| str::from_utf8(s).ok())
}
/// Get the currently active namespace for this repository as a byte array.
///
/// If there is no namespace, `None` is returned.
pub fn namespace_bytes(&self) -> Option<&[u8]> {
unsafe { crate::opt_bytes(self, raw::git_repository_get_namespace(self.raw)) }
}
/// Set the active namespace for this repository.
pub fn set_namespace(&self, namespace: &str) -> Result<(), Error> {
self.set_namespace_bytes(namespace.as_bytes())
}
/// Set the active namespace for this repository as a byte array.
pub fn set_namespace_bytes(&self, namespace: &[u8]) -> Result<(), Error> {
unsafe {
let namespace = CString::new(namespace)?;
try_call!(raw::git_repository_set_namespace(self.raw, namespace));
Ok(())
}
}
/// Remove the active namespace for this repository.
pub fn remove_namespace(&self) -> Result<(), Error> {
unsafe {
try_call!(raw::git_repository_set_namespace(self.raw, ptr::null()));
Ok(())
}
}
/// Retrieves the Git merge message.
/// Remember to remove the message when finished.
pub fn message(&self) -> Result<String, Error> {
unsafe {
let buf = Buf::new();
try_call!(raw::git_repository_message(buf.raw(), self.raw));
Ok(str::from_utf8(&buf).unwrap().to_string())
}
}
/// Remove the Git merge message.
pub fn remove_message(&self) -> Result<(), Error> {
unsafe {
try_call!(raw::git_repository_message_remove(self.raw));
Ok(())
}
}
/// List all remotes for a given repository
pub fn remotes(&self) -> Result<StringArray, Error> {
let mut arr = raw::git_strarray {
strings: ptr::null_mut(),
count: 0,
};
unsafe {
try_call!(raw::git_remote_list(&mut arr, self.raw));
Ok(Binding::from_raw(arr))
}
}
/// Get the information for a particular remote
pub fn find_remote(&self, name: &str) -> Result<Remote<'_>, Error> {
let mut ret = ptr::null_mut();
let name = CString::new(name)?;
unsafe {
try_call!(raw::git_remote_lookup(&mut ret, self.raw, name));
Ok(Binding::from_raw(ret))
}
}
/// Add a remote with the default fetch refspec to the repository's
/// configuration.
pub fn remote(&self, name: &str, url: &str) -> Result<Remote<'_>, Error> {
let mut ret = ptr::null_mut();
let name = CString::new(name)?;
let url = CString::new(url)?;
unsafe {
try_call!(raw::git_remote_create(&mut ret, self.raw, name, url));
Ok(Binding::from_raw(ret))
}
}
/// Add a remote with the provided fetch refspec to the repository's
/// configuration.
pub fn remote_with_fetch(
&self,
name: &str,
url: &str,
fetch: &str,
) -> Result<Remote<'_>, Error> {
let mut ret = ptr::null_mut();
let name = CString::new(name)?;
let url = CString::new(url)?;
let fetch = CString::new(fetch)?;
unsafe {
try_call!(raw::git_remote_create_with_fetchspec(
&mut ret, self.raw, name, url, fetch
));
Ok(Binding::from_raw(ret))
}
}
/// Create an anonymous remote
///
/// Create a remote with the given URL and refspec in memory. You can use
/// this when you have a URL instead of a remote's name. Note that anonymous
/// remotes cannot be converted to persisted remotes.
pub fn remote_anonymous(&self, url: &str) -> Result<Remote<'_>, Error> {
let mut ret = ptr::null_mut();
let url = CString::new(url)?;
unsafe {
try_call!(raw::git_remote_create_anonymous(&mut ret, self.raw, url));
Ok(Binding::from_raw(ret))
}
}
/// Give a remote a new name
///
/// All remote-tracking branches and configuration settings for the remote
/// are updated.
///
/// A temporary in-memory remote cannot be given a name with this method.
///
/// No loaded instances of the remote with the old name will change their
/// name or their list of refspecs.
///
/// The returned array of strings is a list of the non-default refspecs
/// which cannot be renamed and are returned for further processing by the
/// caller.
pub fn remote_rename(&self, name: &str, new_name: &str) -> Result<StringArray, Error> {
let name = CString::new(name)?;
let new_name = CString::new(new_name)?;
let mut problems = raw::git_strarray {
count: 0,
strings: ptr::null_mut(),
};
unsafe {
try_call!(raw::git_remote_rename(
&mut problems,
self.raw,
name,
new_name
));
Ok(Binding::from_raw(problems))
}
}
/// Delete an existing persisted remote.
///
/// All remote-tracking branches and configuration settings for the remote
/// will be removed.
pub fn remote_delete(&self, name: &str) -> Result<(), Error> {
let name = CString::new(name)?;
unsafe {
try_call!(raw::git_remote_delete(self.raw, name));
}
Ok(())
}
/// Add a fetch refspec to the remote's configuration
///
/// Add the given refspec to the fetch list in the configuration. No loaded
/// remote instances will be affected.
pub fn remote_add_fetch(&self, name: &str, spec: &str) -> Result<(), Error> {
let name = CString::new(name)?;
let spec = CString::new(spec)?;
unsafe {
try_call!(raw::git_remote_add_fetch(self.raw, name, spec));
}
Ok(())
}
/// Add a push refspec to the remote's configuration.
///
/// Add the given refspec to the push list in the configuration. No
/// loaded remote instances will be affected.
pub fn remote_add_push(&self, name: &str, spec: &str) -> Result<(), Error> {
let name = CString::new(name)?;
let spec = CString::new(spec)?;
unsafe {
try_call!(raw::git_remote_add_push(self.raw, name, spec));
}
Ok(())
}
/// Set the remote's URL in the configuration
///
/// Remote objects already in memory will not be affected. This assumes
/// the common case of a single-url remote and will otherwise return an
/// error.
pub fn remote_set_url(&self, name: &str, url: &str) -> Result<(), Error> {
let name = CString::new(name)?;
let url = CString::new(url)?;
unsafe {
try_call!(raw::git_remote_set_url(self.raw, name, url));
}
Ok(())
}
/// Set the remote's URL for pushing in the configuration.
///
/// Remote objects already in memory will not be affected. This assumes
/// the common case of a single-url remote and will otherwise return an
/// error.
///
/// `None` indicates that it should be cleared.
pub fn remote_set_pushurl(&self, name: &str, pushurl: Option<&str>) -> Result<(), Error> {
let name = CString::new(name)?;
let pushurl = crate::opt_cstr(pushurl)?;
unsafe {
try_call!(raw::git_remote_set_pushurl(self.raw, name, pushurl));
}
Ok(())
}
/// Sets the current head to the specified object and optionally resets
/// the index and working tree to match.
///
/// A soft reset means the head will be moved to the commit.
///
/// A mixed reset will trigger a soft reset, plus the index will be
/// replaced with the content of the commit tree.
///
/// A hard reset will trigger a mixed reset and the working directory will
/// be replaced with the content of the index. (Untracked and ignored files
/// will be left alone, however.)
///
/// The `target` is a commit-ish to which the head should be moved to. The
/// object can either be a commit or a tag, but tags must be dereferenceable
/// to a commit.
///
/// The `checkout` options will only be used for a hard reset.
pub fn reset(
&self,
target: &Object<'_>,
kind: ResetType,
checkout: Option<&mut CheckoutBuilder<'_>>,
) -> Result<(), Error> {
unsafe {
let mut opts: raw::git_checkout_options = mem::zeroed();
try_call!(raw::git_checkout_init_options(
&mut opts,
raw::GIT_CHECKOUT_OPTIONS_VERSION
));
let opts = checkout.map(|c| {
c.configure(&mut opts);
&mut opts
});
try_call!(raw::git_reset(self.raw, target.raw(), kind, opts));
}
Ok(())
}
/// Updates some entries in the index from the target commit tree.
///
/// The scope of the updated entries is determined by the paths being
/// in the iterator provided.
///
/// Passing a `None` target will result in removing entries in the index
/// matching the provided pathspecs.
pub fn reset_default<T, I>(&self, target: Option<&Object<'_>>, paths: I) -> Result<(), Error>
where
T: IntoCString,
I: IntoIterator<Item = T>,
{
let (_a, _b, mut arr) = crate::util::iter2cstrs_paths(paths)?;
let target = target.map(|t| t.raw());
unsafe {
try_call!(raw::git_reset_default(self.raw, target, &mut arr));
}
Ok(())
}
/// Retrieve and resolve the reference pointed at by HEAD.
pub fn head(&self) -> Result<Reference<'_>, Error> {
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_repository_head(&mut ret, self.raw));
Ok(Binding::from_raw(ret))
}
}
/// Make the repository HEAD point to the specified reference.
///
/// If the provided reference points to a tree or a blob, the HEAD is
/// unaltered and an error is returned.
///
/// If the provided reference points to a branch, the HEAD will point to
/// that branch, staying attached, or become attached if it isn't yet. If
/// the branch doesn't exist yet, no error will be returned. The HEAD will
/// then be attached to an unborn branch.
///
/// Otherwise, the HEAD will be detached and will directly point to the
/// commit.
pub fn set_head(&self, refname: &str) -> Result<(), Error> {
self.set_head_bytes(refname.as_bytes())
}
/// Make the repository HEAD point to the specified reference as a byte array.
///
/// If the provided reference points to a tree or a blob, the HEAD is
/// unaltered and an error is returned.
///
/// If the provided reference points to a branch, the HEAD will point to
/// that branch, staying attached, or become attached if it isn't yet. If
/// the branch doesn't exist yet, no error will be returned. The HEAD will
/// then be attached to an unborn branch.
///
/// Otherwise, the HEAD will be detached and will directly point to the
/// commit.
pub fn set_head_bytes(&self, refname: &[u8]) -> Result<(), Error> {
let refname = CString::new(refname)?;
unsafe {
try_call!(raw::git_repository_set_head(self.raw, refname));
}
Ok(())
}
/// Determines whether the repository HEAD is detached.
pub fn head_detached(&self) -> Result<bool, Error> {
unsafe {
let value = raw::git_repository_head_detached(self.raw);
match value {
0 => Ok(false),
1 => Ok(true),
_ => Err(Error::last_error(value).unwrap()),
}
}
}
/// Make the repository HEAD directly point to the commit.
///
/// If the provided commitish cannot be found in the repository, the HEAD
/// is unaltered and an error is returned.
///
/// If the provided commitish cannot be peeled into a commit, the HEAD is
/// unaltered and an error is returned.
///
/// Otherwise, the HEAD will eventually be detached and will directly point
/// to the peeled commit.
pub fn set_head_detached(&self, commitish: Oid) -> Result<(), Error> {
unsafe {
try_call!(raw::git_repository_set_head_detached(
self.raw,
commitish.raw()
));
}
Ok(())
}
/// Make the repository HEAD directly point to the commit.
///
/// If the provided commitish cannot be found in the repository, the HEAD
/// is unaltered and an error is returned.
/// If the provided commitish cannot be peeled into a commit, the HEAD is
/// unaltered and an error is returned.
/// Otherwise, the HEAD will eventually be detached and will directly point
/// to the peeled commit.
pub fn set_head_detached_from_annotated(
&self,
commitish: AnnotatedCommit<'_>,
) -> Result<(), Error> {
unsafe {
try_call!(raw::git_repository_set_head_detached_from_annotated(
self.raw,
commitish.raw()
));
}
Ok(())
}
/// Create an iterator for the repo's references
pub fn references(&self) -> Result<References<'_>, Error> {
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_reference_iterator_new(&mut ret, self.raw));
Ok(Binding::from_raw(ret))
}
}
/// Create an iterator for the repo's references that match the specified
/// glob
pub fn references_glob(&self, glob: &str) -> Result<References<'_>, Error> {
let mut ret = ptr::null_mut();
let glob = CString::new(glob)?;
unsafe {
try_call!(raw::git_reference_iterator_glob_new(
&mut ret, self.raw, glob
));
Ok(Binding::from_raw(ret))
}
}
/// Load all submodules for this repository and return them.
pub fn submodules(&self) -> Result<Vec<Submodule<'_>>, Error> {
struct Data<'a, 'b> {
repo: &'b Repository,
ret: &'a mut Vec<Submodule<'b>>,
}
let mut ret = Vec::new();
unsafe {
let mut data = Data {
repo: self,
ret: &mut ret,
};
let cb: raw::git_submodule_cb = Some(append);
try_call!(raw::git_submodule_foreach(
self.raw,
cb,
&mut data as *mut _ as *mut c_void
));
}
return Ok(ret);
extern "C" fn append(
_repo: *mut raw::git_submodule,
name: *const c_char,
data: *mut c_void,
) -> c_int {
unsafe {
let data = &mut *(data as *mut Data<'_, '_>);
let mut raw = ptr::null_mut();
let rc = raw::git_submodule_lookup(&mut raw, data.repo.raw(), name);
assert_eq!(rc, 0);
data.ret.push(Binding::from_raw(raw));
}
0
}
}
/// Gather file status information and populate the returned structure.
///
/// Note that if a pathspec is given in the options to filter the
/// status, then the results from rename detection (if you enable it) may
/// not be accurate. To do rename detection properly, this must be called
/// with no pathspec so that all files can be considered.
pub fn statuses(&self, options: Option<&mut StatusOptions>) -> Result<Statuses<'_>, Error> {
let mut ret = ptr::null_mut();
unsafe {
try_call!(raw::git_status_list_new(
&mut ret,
self.raw,
options.map(|s| s.raw()).unwrap_or(ptr::null())
));
Ok(Binding::from_raw(ret))
}
}
/// Test if the ignore rules apply to a given file.
///
/// This function checks the ignore rules to see if they would apply to the
/// given file. This indicates if the file would be ignored regardless of
/// whether the file is already in the index or committed to the repository.
///
/// One way to think of this is if you were to do "git add ." on the
/// directory containing the file, would it be added or not?
pub fn status_should_ignore(&self, path: &Path) -> Result<bool, Error> {
let mut ret = 0 as c_int;
let path = util::cstring_to_repo_path(path)?;
unsafe {
try_call!(raw::git_status_should_ignore(&mut ret, self.raw, path));
}
Ok(ret != 0)
}
/// Get file status for a single file.
///
/// This tries to get status for the filename that you give. If no files
/// match that name (in either the HEAD, index, or working directory), this
/// returns NotFound.
///