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
use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::ffi::{CStr, CString};
use std::mem;
use std::path::Path;
use std::ptr;
use crate::util::{self, Binding};
use crate::{panic, raw, Error, FetchOptions, IntoCString, Repository};
use crate::{CheckoutNotificationType, DiffFile, Remote};
pub struct RepoBuilder<'cb> {
bare: bool,
branch: Option<CString>,
local: bool,
hardlinks: bool,
checkout: Option<CheckoutBuilder<'cb>>,
fetch_opts: Option<FetchOptions<'cb>>,
clone_local: Option<CloneLocal>,
remote_create: Option<Box<RemoteCreate<'cb>>>,
}
pub type RemoteCreate<'cb> =
dyn for<'a> FnMut(&'a Repository, &str, &str) -> Result<Remote<'a>, Error> + 'cb;
pub struct CheckoutBuilder<'cb> {
their_label: Option<CString>,
our_label: Option<CString>,
ancestor_label: Option<CString>,
target_dir: Option<CString>,
paths: Vec<CString>,
path_ptrs: Vec<*const c_char>,
file_perm: Option<i32>,
dir_perm: Option<i32>,
disable_filters: bool,
checkout_opts: u32,
progress: Option<Box<Progress<'cb>>>,
notify: Option<Box<Notify<'cb>>>,
notify_flags: CheckoutNotificationType,
}
pub type Progress<'a> = dyn FnMut(Option<&Path>, usize, usize) + 'a;
pub type Notify<'a> = dyn FnMut(
CheckoutNotificationType,
Option<&Path>,
Option<DiffFile<'_>>,
Option<DiffFile<'_>>,
Option<DiffFile<'_>>,
) -> bool
+ 'a;
impl<'cb> Default for RepoBuilder<'cb> {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Copy)]
pub enum CloneLocal {
Auto = raw::GIT_CLONE_LOCAL_AUTO as isize,
Local = raw::GIT_CLONE_LOCAL as isize,
None = raw::GIT_CLONE_NO_LOCAL as isize,
NoLinks = raw::GIT_CLONE_LOCAL_NO_LINKS as isize,
#[doc(hidden)]
__Nonexhaustive = 0xff,
}
impl<'cb> RepoBuilder<'cb> {
pub fn new() -> RepoBuilder<'cb> {
crate::init();
RepoBuilder {
bare: false,
branch: None,
local: true,
clone_local: None,
hardlinks: true,
checkout: None,
fetch_opts: None,
remote_create: None,
}
}
pub fn bare(&mut self, bare: bool) -> &mut RepoBuilder<'cb> {
self.bare = bare;
self
}
pub fn branch(&mut self, branch: &str) -> &mut RepoBuilder<'cb> {
self.branch = Some(CString::new(branch).unwrap());
self
}
pub fn clone_local(&mut self, clone_local: CloneLocal) -> &mut RepoBuilder<'cb> {
self.clone_local = Some(clone_local);
self
}
#[deprecated(note = "use `clone_local` instead")]
#[doc(hidden)]
pub fn local(&mut self, local: bool) -> &mut RepoBuilder<'cb> {
self.local = local;
self
}
#[deprecated(note = "use `clone_local` instead")]
#[doc(hidden)]
pub fn hardlinks(&mut self, links: bool) -> &mut RepoBuilder<'cb> {
self.hardlinks = links;
self
}
pub fn with_checkout(&mut self, checkout: CheckoutBuilder<'cb>) -> &mut RepoBuilder<'cb> {
self.checkout = Some(checkout);
self
}
pub fn fetch_options(&mut self, fetch_opts: FetchOptions<'cb>) -> &mut RepoBuilder<'cb> {
self.fetch_opts = Some(fetch_opts);
self
}
pub fn remote_create<F>(&mut self, f: F) -> &mut RepoBuilder<'cb>
where
F: for<'a> FnMut(&'a Repository, &str, &str) -> Result<Remote<'a>, Error> + 'cb,
{
self.remote_create = Some(Box::new(f));
self
}
pub fn clone(&mut self, url: &str, into: &Path) -> Result<Repository, Error> {
let mut opts: raw::git_clone_options = unsafe { mem::zeroed() };
unsafe {
try_call!(raw::git_clone_init_options(
&mut opts,
raw::GIT_CLONE_OPTIONS_VERSION
));
}
opts.bare = self.bare as c_int;
opts.checkout_branch = self
.branch
.as_ref()
.map(|s| s.as_ptr())
.unwrap_or(ptr::null());
if let Some(ref local) = self.clone_local {
opts.local = *local as raw::git_clone_local_t;
} else {
opts.local = match (self.local, self.hardlinks) {
(true, false) => raw::GIT_CLONE_LOCAL_NO_LINKS,
(false, _) => raw::GIT_CLONE_NO_LOCAL,
(true, _) => raw::GIT_CLONE_LOCAL_AUTO,
};
}
if let Some(ref mut cbs) = self.fetch_opts {
opts.fetch_opts = cbs.raw();
}
if let Some(ref mut c) = self.checkout {
unsafe {
c.configure(&mut opts.checkout_opts);
}
}
if let Some(ref mut callback) = self.remote_create {
opts.remote_cb = Some(remote_create_cb);
opts.remote_cb_payload = callback as *mut _ as *mut _;
}
let url = CString::new(url)?;
let into = into.into_c_string()?;
let mut raw = ptr::null_mut();
unsafe {
try_call!(raw::git_clone(&mut raw, url, into, &opts));
Ok(Binding::from_raw(raw))
}
}
}
extern "C" fn remote_create_cb(
out: *mut *mut raw::git_remote,
repo: *mut raw::git_repository,
name: *const c_char,
url: *const c_char,
payload: *mut c_void,
) -> c_int {
unsafe {
let repo = Repository::from_raw(repo);
let code = panic::wrap(|| {
let name = CStr::from_ptr(name).to_str().unwrap();
let url = CStr::from_ptr(url).to_str().unwrap();
let f = payload as *mut Box<RemoteCreate<'_>>;
match (*f)(&repo, name, url) {
Ok(remote) => {
*out = crate::remote::remote_into_raw(remote);
0
}
Err(e) => e.raw_code(),
}
});
mem::forget(repo);
code.unwrap_or(-1)
}
}
impl<'cb> Default for CheckoutBuilder<'cb> {
fn default() -> Self {
Self::new()
}
}
impl<'cb> CheckoutBuilder<'cb> {
pub fn new() -> CheckoutBuilder<'cb> {
crate::init();
CheckoutBuilder {
disable_filters: false,
dir_perm: None,
file_perm: None,
path_ptrs: Vec::new(),
paths: Vec::new(),
target_dir: None,
ancestor_label: None,
our_label: None,
their_label: None,
checkout_opts: raw::GIT_CHECKOUT_SAFE as u32,
progress: None,
notify: None,
notify_flags: CheckoutNotificationType::empty(),
}
}
pub fn dry_run(&mut self) -> &mut CheckoutBuilder<'cb> {
self.checkout_opts &= !((1 << 4) - 1);
self.checkout_opts |= raw::GIT_CHECKOUT_NONE as u32;
self
}
pub fn force(&mut self) -> &mut CheckoutBuilder<'cb> {
self.checkout_opts &= !((1 << 4) - 1);
self.checkout_opts |= raw::GIT_CHECKOUT_FORCE as u32;
self
}
pub fn safe(&mut self) -> &mut CheckoutBuilder<'cb> {
self.checkout_opts &= !((1 << 4) - 1);
self.checkout_opts |= raw::GIT_CHECKOUT_SAFE as u32;
self
}
fn flag(&mut self, bit: raw::git_checkout_strategy_t, on: bool) -> &mut CheckoutBuilder<'cb> {
if on {
self.checkout_opts |= bit as u32;
} else {
self.checkout_opts &= !(bit as u32);
}
self
}
pub fn recreate_missing(&mut self, allow: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_RECREATE_MISSING, allow)
}
pub fn allow_conflicts(&mut self, allow: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_ALLOW_CONFLICTS, allow)
}
pub fn remove_untracked(&mut self, remove: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_REMOVE_UNTRACKED, remove)
}
pub fn remove_ignored(&mut self, remove: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_REMOVE_IGNORED, remove)
}
pub fn update_only(&mut self, update: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_UPDATE_ONLY, update)
}
pub fn update_index(&mut self, update: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_DONT_UPDATE_INDEX, !update)
}
pub fn refresh(&mut self, refresh: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_NO_REFRESH, !refresh)
}
pub fn skip_unmerged(&mut self, skip: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_SKIP_UNMERGED, skip)
}
pub fn use_ours(&mut self, ours: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_USE_OURS, ours)
}
pub fn use_theirs(&mut self, theirs: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_USE_THEIRS, theirs)
}
pub fn overwrite_ignored(&mut self, overwrite: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_DONT_OVERWRITE_IGNORED, !overwrite)
}
pub fn conflict_style_merge(&mut self, on: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_CONFLICT_STYLE_MERGE, on)
}
pub fn notify_on(
&mut self,
notification_types: CheckoutNotificationType,
) -> &mut CheckoutBuilder<'cb> {
self.notify_flags = notification_types;
self
}
pub fn conflict_style_diff3(&mut self, on: bool) -> &mut CheckoutBuilder<'cb> {
self.flag(raw::GIT_CHECKOUT_CONFLICT_STYLE_DIFF3, on)
}
pub fn disable_filters(&mut self, disable: bool) -> &mut CheckoutBuilder<'cb> {
self.disable_filters = disable;
self
}
pub fn dir_perm(&mut self, perm: i32) -> &mut CheckoutBuilder<'cb> {
self.dir_perm = Some(perm);
self
}
pub fn file_perm(&mut self, perm: i32) -> &mut CheckoutBuilder<'cb> {
self.file_perm = Some(perm);
self
}
pub fn path<T: IntoCString>(&mut self, path: T) -> &mut CheckoutBuilder<'cb> {
let path = path.into_c_string().unwrap();
self.path_ptrs.push(path.as_ptr());
self.paths.push(path);
self
}
pub fn target_dir(&mut self, dst: &Path) -> &mut CheckoutBuilder<'cb> {
self.target_dir = Some(dst.into_c_string().unwrap());
self
}
pub fn ancestor_label(&mut self, label: &str) -> &mut CheckoutBuilder<'cb> {
self.ancestor_label = Some(CString::new(label).unwrap());
self
}
pub fn our_label(&mut self, label: &str) -> &mut CheckoutBuilder<'cb> {
self.our_label = Some(CString::new(label).unwrap());
self
}
pub fn their_label(&mut self, label: &str) -> &mut CheckoutBuilder<'cb> {
self.their_label = Some(CString::new(label).unwrap());
self
}
pub fn progress<F>(&mut self, cb: F) -> &mut CheckoutBuilder<'cb>
where
F: FnMut(Option<&Path>, usize, usize) + 'cb,
{
self.progress = Some(Box::new(cb) as Box<Progress<'cb>>);
self
}
pub fn notify<F>(&mut self, cb: F) -> &mut CheckoutBuilder<'cb>
where
F: FnMut(
CheckoutNotificationType,
Option<&Path>,
Option<DiffFile<'_>>,
Option<DiffFile<'_>>,
Option<DiffFile<'_>>,
) -> bool
+ 'cb,
{
self.notify = Some(Box::new(cb) as Box<Notify<'cb>>);
self
}
pub unsafe fn configure(&mut self, opts: &mut raw::git_checkout_options) {
opts.version = raw::GIT_CHECKOUT_OPTIONS_VERSION;
opts.disable_filters = self.disable_filters as c_int;
opts.dir_mode = self.dir_perm.unwrap_or(0) as c_uint;
opts.file_mode = self.file_perm.unwrap_or(0) as c_uint;
if !self.path_ptrs.is_empty() {
opts.paths.strings = self.path_ptrs.as_ptr() as *mut _;
opts.paths.count = self.path_ptrs.len() as size_t;
}
if let Some(ref c) = self.target_dir {
opts.target_directory = c.as_ptr();
}
if let Some(ref c) = self.ancestor_label {
opts.ancestor_label = c.as_ptr();
}
if let Some(ref c) = self.our_label {
opts.our_label = c.as_ptr();
}
if let Some(ref c) = self.their_label {
opts.their_label = c.as_ptr();
}
if self.progress.is_some() {
let f: raw::git_checkout_progress_cb = progress_cb;
opts.progress_cb = Some(f);
opts.progress_payload = self as *mut _ as *mut _;
}
if self.notify.is_some() {
let f: raw::git_checkout_notify_cb = notify_cb;
opts.notify_cb = Some(f);
opts.notify_payload = self as *mut _ as *mut _;
opts.notify_flags = self.notify_flags.bits() as c_uint;
}
opts.checkout_strategy = self.checkout_opts as c_uint;
}
}
extern "C" fn progress_cb(
path: *const c_char,
completed: size_t,
total: size_t,
data: *mut c_void,
) {
panic::wrap(|| unsafe {
let payload = &mut *(data as *mut CheckoutBuilder<'_>);
let callback = match payload.progress {
Some(ref mut c) => c,
None => return,
};
let path = if path.is_null() {
None
} else {
Some(util::bytes2path(CStr::from_ptr(path).to_bytes()))
};
callback(path, completed as usize, total as usize)
});
}
extern "C" fn notify_cb(
why: raw::git_checkout_notify_t,
path: *const c_char,
baseline: *const raw::git_diff_file,
target: *const raw::git_diff_file,
workdir: *const raw::git_diff_file,
data: *mut c_void,
) -> c_int {
panic::wrap(|| unsafe {
let payload = &mut *(data as *mut CheckoutBuilder<'_>);
let callback = match payload.notify {
Some(ref mut c) => c,
None => return 0,
};
let path = if path.is_null() {
None
} else {
Some(util::bytes2path(CStr::from_ptr(path).to_bytes()))
};
let baseline = if baseline.is_null() {
None
} else {
Some(DiffFile::from_raw(baseline))
};
let target = if target.is_null() {
None
} else {
Some(DiffFile::from_raw(target))
};
let workdir = if workdir.is_null() {
None
} else {
Some(DiffFile::from_raw(workdir))
};
let why = CheckoutNotificationType::from_bits_truncate(why as u32);
let keep_going = callback(why, path, baseline, target, workdir);
if keep_going {
0
} else {
1
}
})
.unwrap_or(2)
}
#[cfg(test)]
mod tests {
use super::{CheckoutBuilder, RepoBuilder};
use crate::{CheckoutNotificationType, Repository};
use std::fs;
use std::path::Path;
use tempfile::TempDir;
#[test]
fn smoke() {
let r = RepoBuilder::new().clone("/path/to/nowhere", Path::new("foo"));
assert!(r.is_err());
}
#[test]
fn smoke2() {
let td = TempDir::new().unwrap();
Repository::init_bare(&td.path().join("bare")).unwrap();
let url = if cfg!(unix) {
format!("file://{}/bare", td.path().display())
} else {
format!(
"file:///{}/bare",
td.path().display().to_string().replace("\\", "/")
)
};
let dst = td.path().join("foo");
RepoBuilder::new().clone(&url, &dst).unwrap();
fs::remove_dir_all(&dst).unwrap();
assert!(RepoBuilder::new().branch("foo").clone(&url, &dst).is_err());
}
#[test]
fn notify_callback() {
let td = TempDir::new().unwrap();
let cd = TempDir::new().unwrap();
{
let repo = Repository::init(&td.path()).unwrap();
let mut config = repo.config().unwrap();
config.set_str("user.name", "name").unwrap();
config.set_str("user.email", "email").unwrap();
let mut index = repo.index().unwrap();
let p = Path::new(td.path()).join("file");
println!("using path {:?}", p);
fs::File::create(&p).unwrap();
index.add_path(&Path::new("file")).unwrap();
let id = index.write_tree().unwrap();
let tree = repo.find_tree(id).unwrap();
let sig = repo.signature().unwrap();
repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
.unwrap();
}
let repo = Repository::open_bare(&td.path().join(".git")).unwrap();
let tree = repo
.revparse_single(&"master")
.unwrap()
.peel_to_tree()
.unwrap();
let mut index = repo.index().unwrap();
index.read_tree(&tree).unwrap();
let mut checkout_opts = CheckoutBuilder::new();
checkout_opts.target_dir(&cd.path());
checkout_opts.notify_on(CheckoutNotificationType::all());
checkout_opts.notify(|_notif, _path, baseline, target, workdir| {
assert!(baseline.is_none());
assert_eq!(target.unwrap().path(), Some(Path::new("file")));
assert!(workdir.is_none());
true
});
repo.checkout_index(Some(&mut index), Some(&mut checkout_opts))
.unwrap();
}
}