Debian Codegraph @

src/remote.rs

raw
1 use raw::git_strarray;
2 use std::iter::FusedIterator;
3 use std::marker;
4 use std::mem;
5 use std::ops::Range;
6 use std::os::raw::c_uint;
7 use std::ptr;
8 use std::slice;
9 use std::str;
10 use std::{ffi::CString, os::raw::c_char};
11
12 use crate::string_array::StringArray;
13 use crate::util::Binding;
14 use crate::{
15 call, raw, Buf, Direction, Error, FetchPrune, ObjectFormat, Oid, ProxyOptions, Refspec,
16 };
17 use crate::{AutotagOption, Progress, RemoteCallbacks, RemoteUpdateFlags, Repository};
18
19 /// A structure representing a [remote][1] of a git repository.
20 ///
21 /// [1]: http://git-scm.com/book/en/Git-Basics-Working-with-Remotes
22 ///
23 /// The lifetime is the lifetime of the repository that it is attached to. The
24 /// remote is used to manage fetches and pushes as well as refspecs.
25 pub struct Remote<'repo> {
26 raw: *mut raw::git_remote,
27 _marker: marker::PhantomData<&'repo Repository>,
28 }
29
30 /// An iterator over the refspecs that a remote contains.
31 pub struct Refspecs<'remote> {
32 range: Range<usize>,
33 remote: &'remote Remote<'remote>,
34 }
35
36 /// Description of a reference advertised by a remote server, given out on calls
37 /// to `list`.
38 pub struct RemoteHead<'remote> {
39 raw: *const raw::git_remote_head,
40 _marker: marker::PhantomData<&'remote str>,
41 }
42
43 /// Options which can be specified to various fetch operations.
44 pub struct FetchOptions<'cb> {
45 callbacks: Option<RemoteCallbacks<'cb>>,
46 depth: i32,
47 proxy: Option<ProxyOptions<'cb>>,
48 prune: FetchPrune,
49 update_flags: RemoteUpdateFlags,
50 download_tags: AutotagOption,
51 follow_redirects: RemoteRedirect,
52 custom_headers: Vec<CString>,
53 custom_headers_ptrs: Vec<*const c_char>,
54 }
55
56 /// Options to control the behavior of a git push.
57 pub struct PushOptions<'cb> {
58 callbacks: Option<RemoteCallbacks<'cb>>,
59 proxy: Option<ProxyOptions<'cb>>,
60 pb_parallelism: u32,
61 follow_redirects: RemoteRedirect,
62 custom_headers: Vec<CString>,
63 custom_headers_ptrs: Vec<*const c_char>,
64 remote_push_options: Vec<CString>,
65 remote_push_options_ptrs: Vec<*const c_char>,
66 }
67
68 /// Holds callbacks for a connection to a `Remote`. Disconnects when dropped
69 pub struct RemoteConnection<'repo, 'connection, 'cb> {
70 _callbacks: Box<RemoteCallbacks<'cb>>,
71 _proxy: ProxyOptions<'cb>,
72 remote: &'connection mut Remote<'repo>,
73 }
74
75 /// Remote redirection settings; whether redirects to another host are
76 /// permitted.
77 ///
78 /// By default, git will follow a redirect on the initial request
79 /// (`/info/refs`), but not subsequent requests.
80 pub enum RemoteRedirect {
81 /// Do not follow any off-site redirects at any stage of the fetch or push.
82 None,
83 /// Allow off-site redirects only upon the initial request. This is the
84 /// default.
85 Initial,
86 /// Allow redirects at any stage in the fetch or push.
87 All,
88 }
89
90 pub fn remote_into_raw(remote: Remote<'_>) -> *mut raw::git_remote {
91 let ret = remote.raw;
92 mem::forget(remote);
93 ret
94 }
95
96 impl<'repo> Remote<'repo> {
97 /// Ensure the remote name is well-formed.
98 pub fn is_valid_name(remote_name: &str) -> bool {
99 crate::init();
100 let remote_name = CString::new(remote_name).unwrap();
101 let mut valid: libc::c_int = 0;
102 unsafe {
103 call::c_try(raw::git_remote_name_is_valid(
104 &mut valid,
105 remote_name.as_ptr(),
106 ))
107 .unwrap();
108 }
109 valid == 1
110 }
111
112 /// Create a detached remote
113 ///
114 /// Create a remote with the given URL in-memory. You can use this
115 /// when you have a URL instead of a remote's name.
116 /// Contrasted with an anonymous remote, a detached remote will not
117 /// consider any repo configuration values.
118 pub fn create_detached<S: Into<Vec<u8>>>(url: S) -> Result<Remote<'repo>, Error> {
119 crate::init();
120 let mut ret = ptr::null_mut();
121 let url = CString::new(url)?;
122 unsafe {
123 try_call!(raw::git_remote_create_detached(&mut ret, url));
124 Ok(Binding::from_raw(ret))
125 }
126 }
127
128 /// Get the remote's name.
129 ///
130 /// Returns `Ok(None)` if this remote has not yet been named.
131 pub fn name(&self) -> Result<Option<&str>, Error> {
132 match self.name_bytes() {
133 Some(nb) => str::from_utf8(nb).map(|s| Some(s)).map_err(|e| e.into()),
134 None => Ok(None),
135 }
136 }
137
138 /// Get the remote's name, in bytes.
139 ///
140 /// Returns `None` if this remote has not yet been named
141 pub fn name_bytes(&self) -> Option<&[u8]> {
142 unsafe { crate::opt_bytes(self, raw::git_remote_name(&*self.raw)) }
143 }
144
145 /// Get the remote's URL.
146 pub fn url(&self) -> Result<&str, Error> {
147 str::from_utf8(self.url_bytes()).map_err(|e| e.into())
148 }
149
150 /// Get the remote's URL as a byte array.
151 pub fn url_bytes(&self) -> &[u8] {
152 unsafe { crate::opt_bytes(self, raw::git_remote_url(&*self.raw)).unwrap_or(&[]) }
153 }
154
155 /// Get the remote's pushurl.
156 ///
157 /// Returns `Ok(None)` if no special url for pushing is set.
158 pub fn pushurl(&self) -> Result<Option<&str>, Error> {
159 match self.pushurl_bytes() {
160 Some(pb) => str::from_utf8(pb).map(|s| Some(s)).map_err(|e| e.into()),
161 None => Ok(None),
162 }
163 }
164
165 /// Get the remote's pushurl as a byte array.
166 ///
167 /// Returns `None` if no special url for pushing is set.
168 pub fn pushurl_bytes(&self) -> Option<&[u8]> {
169 unsafe { crate::opt_bytes(self, raw::git_remote_pushurl(&*self.raw)) }
170 }
171
172 /// Get the remote's default branch.
173 ///
174 /// The remote (or more exactly its transport) must have connected to the
175 /// remote repository. This default branch is available as soon as the
176 /// connection to the remote is initiated and it remains available after
177 /// disconnecting.
178 pub fn default_branch(&self) -> Result<Buf, Error> {
179 unsafe {
180 let buf = Buf::new();
181 try_call!(raw::git_remote_default_branch(buf.raw(), self.raw));
182 Ok(buf)
183 }
184 }
185
186 /// Get the remote's object format (hash algorithm).
187 ///
188 /// The remote (or more exactly its transport) must have connected to the
189 /// remote repository. The format is available as soon as the connection to
190 /// the remote is initiated and it remains available after disconnecting.
191 pub fn object_format(&self) -> Result<ObjectFormat, Error> {
192 let mut oid_type = raw::GIT_OID_SHA1;
193 unsafe {
194 try_call!(raw::git_remote_oid_type(&mut oid_type, self.raw));
195 Ok(Binding::from_raw(oid_type))
196 }
197 }
198
199 /// Open a connection to a remote.
200 pub fn connect(&mut self, dir: Direction) -> Result<(), Error> {
201 // TODO: can callbacks be exposed safely?
202 unsafe {
203 try_call!(raw::git_remote_connect(
204 self.raw,
205 dir,
206 ptr::null(),
207 ptr::null(),
208 ptr::null()
209 ));
210 }
211 Ok(())
212 }
213
214 /// Open a connection to a remote with callbacks and proxy settings
215 ///
216 /// Returns a `RemoteConnection` that will disconnect once dropped
217 pub fn connect_auth<'connection, 'cb>(
218 &'connection mut self,
219 dir: Direction,
220 cb: Option<RemoteCallbacks<'cb>>,
221 proxy_options: Option<ProxyOptions<'cb>>,
222 ) -> Result<RemoteConnection<'repo, 'connection, 'cb>, Error> {
223 let cb = Box::new(cb.unwrap_or_else(RemoteCallbacks::new));
224 let proxy_options = proxy_options.unwrap_or_else(ProxyOptions::new);
225 unsafe {
226 try_call!(raw::git_remote_connect(
227 self.raw,
228 dir,
229 &cb.raw(),
230 &proxy_options.raw(),
231 ptr::null()
232 ));
233 }
234
235 Ok(RemoteConnection {
236 _callbacks: cb,
237 _proxy: proxy_options,
238 remote: self,
239 })
240 }
241
242 /// Check whether the remote is connected
243 pub fn connected(&mut self) -> bool {
244 unsafe { raw::git_remote_connected(self.raw) == 1 }
245 }
246
247 /// Disconnect from the remote
248 pub fn disconnect(&mut self) -> Result<(), Error> {
249 unsafe {
250 try_call!(raw::git_remote_disconnect(self.raw));
251 }
252 Ok(())
253 }
254
255 /// Download and index the packfile
256 ///
257 /// Connect to the remote if it hasn't been done yet, negotiate with the
258 /// remote git which objects are missing, download and index the packfile.
259 ///
260 /// The .idx file will be created and both it and the packfile with be
261 /// renamed to their final name.
262 ///
263 /// The `specs` argument is a list of refspecs to use for this negotiation
264 /// and download. Use an empty array to use the base refspecs.
265 pub fn download<Str: AsRef<str> + crate::IntoCString + Clone>(
266 &mut self,
267 specs: &[Str],
268 opts: Option<&mut FetchOptions<'_>>,
269 ) -> Result<(), Error> {
270 let (_a, _b, arr) = crate::util::iter2cstrs(specs.iter())?;
271 let raw = opts.map(|o| o.raw());
272 unsafe {
273 try_call!(raw::git_remote_download(self.raw, &arr, raw.as_ref()));
274 }
275 Ok(())
276 }
277
278 /// Cancel the operation
279 ///
280 /// At certain points in its operation, the network code checks whether the
281 /// operation has been canceled and if so stops the operation.
282 pub fn stop(&mut self) -> Result<(), Error> {
283 unsafe {
284 try_call!(raw::git_remote_stop(self.raw));
285 }
286 Ok(())
287 }
288
289 /// Get the number of refspecs for a remote
290 pub fn refspecs(&self) -> Refspecs<'_> {
291 let cnt = unsafe { raw::git_remote_refspec_count(&*self.raw) as usize };
292 Refspecs {
293 range: 0..cnt,
294 remote: self,
295 }
296 }
297
298 /// Get the `nth` refspec from this remote.
299 ///
300 /// The `refspecs` iterator can be used to iterate over all refspecs.
301 pub fn get_refspec(&self, i: usize) -> Option<Refspec<'repo>> {
302 unsafe {
303 let ptr = raw::git_remote_get_refspec(&*self.raw, i as libc::size_t);
304 Binding::from_raw_opt(ptr)
305 }
306 }
307
308 /// Download new data and update tips
309 ///
310 /// Convenience function to connect to a remote, download the data,
311 /// disconnect and update the remote-tracking branches.
312 ///
313 /// # Examples
314 ///
315 /// Example of functionality similar to `git fetch origin main`:
316 ///
317 /// ```no_run
318 /// fn fetch_origin_main(repo: git2::Repository) -> Result<(), git2::Error> {
319 /// repo.find_remote("origin")?.fetch(&["main"], None, None)
320 /// }
321 ///
322 /// let repo = git2::Repository::discover("rust").unwrap();
323 /// fetch_origin_main(repo).unwrap();
324 /// ```
325 pub fn fetch<Str: AsRef<str> + crate::IntoCString + Clone>(
326 &mut self,
327 refspecs: &[Str],
328 opts: Option<&mut FetchOptions<'_>>,
329 reflog_msg: Option<&str>,
330 ) -> Result<(), Error> {
331 let (_a, _b, arr) = crate::util::iter2cstrs(refspecs.iter())?;
332 let msg = crate::opt_cstr(reflog_msg)?;
333 let raw = opts.map(|o| o.raw());
334 unsafe {
335 try_call!(raw::git_remote_fetch(self.raw, &arr, raw.as_ref(), msg));
336 }
337 Ok(())
338 }
339
340 /// Update the tips to the new state
341 pub fn update_tips(
342 &mut self,
343 callbacks: Option<&mut RemoteCallbacks<'_>>,
344 update_flags: RemoteUpdateFlags,
345 download_tags: AutotagOption,
346 msg: Option<&str>,
347 ) -> Result<(), Error> {
348 let msg = crate::opt_cstr(msg)?;
349 let cbs = callbacks.map(|cb| cb.raw());
350 unsafe {
351 try_call!(raw::git_remote_update_tips(
352 self.raw,
353 cbs.as_ref(),
354 update_flags.bits() as c_uint,
355 download_tags,
356 msg
357 ));
358 }
359 Ok(())
360 }
361
362 /// Perform a push
363 ///
364 /// Perform all the steps for a push. If no refspecs are passed then the
365 /// configured refspecs will be used.
366 ///
367 /// Note that you'll likely want to use `RemoteCallbacks` and set
368 /// `push_update_reference` to test whether all the references were pushed
369 /// successfully.
370 pub fn push<Str: AsRef<str> + crate::IntoCString + Clone>(
371 &mut self,
372 refspecs: &[Str],
373 opts: Option<&mut PushOptions<'_>>,
374 ) -> Result<(), Error> {
375 let (_a, _b, arr) = crate::util::iter2cstrs(refspecs.iter())?;
376 let raw = opts.map(|o| o.raw());
377 unsafe {
378 try_call!(raw::git_remote_push(self.raw, &arr, raw.as_ref()));
379 }
380 Ok(())
381 }
382
383 /// Get the statistics structure that is filled in by the fetch operation.
384 pub fn stats(&self) -> Progress<'_> {
385 unsafe { Binding::from_raw(raw::git_remote_stats(self.raw)) }
386 }
387
388 /// Get the remote repository's reference advertisement list.
389 ///
390 /// Get the list of references with which the server responds to a new
391 /// connection.
392 ///
393 /// The remote (or more exactly its transport) must have connected to the
394 /// remote repository. This list is available as soon as the connection to
395 /// the remote is initiated and it remains available after disconnecting.
396 pub fn list(&self) -> Result<&[RemoteHead<'_>], Error> {
397 let mut size = 0;
398 let mut base = ptr::null_mut();
399 unsafe {
400 try_call!(raw::git_remote_ls(&mut base, &mut size, self.raw));
401 assert_eq!(
402 mem::size_of::<RemoteHead<'_>>(),
403 mem::size_of::<*const raw::git_remote_head>()
404 );
405 if base.is_null() {
406 // We cannot use slice::from_raw_parts() since that requires
407 // that the pointer be non-null, but that is fine since the size
408 // should be zero
409 if size != 0 {
410 return Err(Error::from_str(&format!(
411 "git_remote_ls() set a null pointer for a list of size {}",
412 size
413 )));
414 }
415 return Ok(&[]);
416 }
417 let slice = slice::from_raw_parts(base as *const _, size as usize);
418 Ok(mem::transmute::<
419 &[*const raw::git_remote_head],
420 &[RemoteHead<'_>],
421 >(slice))
422 }
423 }
424
425 /// Prune tracking refs that are no longer present on remote
426 pub fn prune(&mut self, callbacks: Option<RemoteCallbacks<'_>>) -> Result<(), Error> {
427 let cbs = Box::new(callbacks.unwrap_or_else(RemoteCallbacks::new));
428 unsafe {
429 try_call!(raw::git_remote_prune(self.raw, &cbs.raw()));
430 }
431 Ok(())
432 }
433
434 /// Get the remote's list of fetch refspecs
435 pub fn fetch_refspecs(&self) -> Result<StringArray, Error> {
436 unsafe {
437 let mut raw: raw::git_strarray = mem::zeroed();
438 try_call!(raw::git_remote_get_fetch_refspecs(&mut raw, self.raw));
439 Ok(StringArray::from_raw(raw))
440 }
441 }
442
443 /// Get the remote's list of push refspecs
444 pub fn push_refspecs(&self) -> Result<StringArray, Error> {
445 unsafe {
446 let mut raw: raw::git_strarray = mem::zeroed();
447 try_call!(raw::git_remote_get_push_refspecs(&mut raw, self.raw));
448 Ok(StringArray::from_raw(raw))
449 }
450 }
451 }
452
453 impl<'repo> Clone for Remote<'repo> {
454 fn clone(&self) -> Remote<'repo> {
455 let mut ret = ptr::null_mut();
456 let rc = unsafe { call!(raw::git_remote_dup(&mut ret, self.raw)) };
457 assert_eq!(rc, 0);
458 Remote {
459 raw: ret,
460 _marker: marker::PhantomData,
461 }
462 }
463 }
464
465 impl<'repo> Binding for Remote<'repo> {
466 type Raw = *mut raw::git_remote;
467
468 unsafe fn from_raw(raw: *mut raw::git_remote) -> Remote<'repo> {
469 Remote {
470 raw,
471 _marker: marker::PhantomData,
472 }
473 }
474 fn raw(&self) -> *mut raw::git_remote {
475 self.raw
476 }
477 }
478
479 impl<'repo> Drop for Remote<'repo> {
480 fn drop(&mut self) {
481 unsafe { raw::git_remote_free(self.raw) }
482 }
483 }
484
485 impl<'repo> Iterator for Refspecs<'repo> {
486 type Item = Refspec<'repo>;
487 fn next(&mut self) -> Option<Refspec<'repo>> {
488 self.range.next().and_then(|i| self.remote.get_refspec(i))
489 }
490 fn size_hint(&self) -> (usize, Option<usize>) {
491 self.range.size_hint()
492 }
493 }
494 impl<'repo> DoubleEndedIterator for Refspecs<'repo> {
495 fn next_back(&mut self) -> Option<Refspec<'repo>> {
496 self.range
497 .next_back()
498 .and_then(|i| self.remote.get_refspec(i))
499 }
500 }
501 impl<'repo> FusedIterator for Refspecs<'repo> {}
502 impl<'repo> ExactSizeIterator for Refspecs<'repo> {}
503
504 #[allow(missing_docs)] // not documented in libgit2 :(
505 impl<'remote> RemoteHead<'remote> {
506 /// Flag if this is available locally.
507 pub fn is_local(&self) -> bool {
508 unsafe { (*self.raw).local != 0 }
509 }
510
511 pub fn oid(&self) -> Oid {
512 unsafe { Binding::from_raw(&(*self.raw).oid as *const _) }
513 }
514 pub fn loid(&self) -> Oid {
515 unsafe { Binding::from_raw(&(*self.raw).loid as *const _) }
516 }
517
518 pub fn name(&self) -> &str {
519 let b = unsafe { crate::opt_bytes(self, (*self.raw).name).unwrap() };
520 str::from_utf8(b).unwrap()
521 }
522
523 pub fn symref_target(&self) -> Option<&str> {
524 let b = unsafe { crate::opt_bytes(self, (*self.raw).symref_target) };
525 b.map(|b| str::from_utf8(b).unwrap())
526 }
527 }
528
529 impl<'cb> Default for FetchOptions<'cb> {
530 fn default() -> Self {
531 Self::new()
532 }
533 }
534
535 impl<'cb> FetchOptions<'cb> {
536 /// Creates a new blank set of fetch options
537 pub fn new() -> FetchOptions<'cb> {
538 FetchOptions {
539 callbacks: None,
540 proxy: None,
541 prune: FetchPrune::Unspecified,
542 update_flags: RemoteUpdateFlags::UPDATE_FETCHHEAD,
543 download_tags: AutotagOption::Unspecified,
544 follow_redirects: RemoteRedirect::Initial,
545 custom_headers: Vec::new(),
546 custom_headers_ptrs: Vec::new(),
547 depth: 0, // Not limited depth
548 }
549 }
550
551 /// Set the callbacks to use for the fetch operation.
552 pub fn remote_callbacks(&mut self, cbs: RemoteCallbacks<'cb>) -> &mut Self {
553 self.callbacks = Some(cbs);
554 self
555 }
556
557 /// Set the proxy options to use for the fetch operation.
558 pub fn proxy_options(&mut self, opts: ProxyOptions<'cb>) -> &mut Self {
559 self.proxy = Some(opts);
560 self
561 }
562
563 /// Set whether to perform a prune after the fetch.
564 pub fn prune(&mut self, prune: FetchPrune) -> &mut Self {
565 self.prune = prune;
566 self
567 }
568
569 /// Set whether to write the results to FETCH_HEAD.
570 ///
571 /// Defaults to `true`.
572 pub fn update_fetchhead(&mut self, update: bool) -> &mut Self {
573 self.update_flags
574 .set(RemoteUpdateFlags::UPDATE_FETCHHEAD, update);
575 self
576 }
577
578 /// Set whether to report unchanged tips in the update_tips callback.
579 ///
580 /// Defaults to `false`.
581 pub fn report_unchanged(&mut self, update: bool) -> &mut Self {
582 self.update_flags
583 .set(RemoteUpdateFlags::REPORT_UNCHANGED, update);
584 self
585 }
586
587 /// Set fetch depth, a value less or equal to 0 is interpreted as pull
588 /// everything (effectively the same as not declaring a limit depth).
589
590 // FIXME(blyxyas): We currently don't have a test for shallow functions
591 // because libgit2 doesn't support local shallow clones.
592 // https://github.com/rust-lang/git2-rs/pull/979#issuecomment-1716299900
593 pub fn depth(&mut self, depth: i32) -> &mut Self {
594 self.depth = depth.max(0);
595 self
596 }
597
598 /// Set how to behave regarding tags on the remote, such as auto-downloading
599 /// tags for objects we're downloading or downloading all of them.
600 ///
601 /// The default is to auto-follow tags.
602 pub fn download_tags(&mut self, opt: AutotagOption) -> &mut Self {
603 self.download_tags = opt;
604 self
605 }
606
607 /// Set remote redirection settings; whether redirects to another host are
608 /// permitted.
609 ///
610 /// By default, git will follow a redirect on the initial request
611 /// (`/info/refs`), but not subsequent requests.
612 pub fn follow_redirects(&mut self, redirect: RemoteRedirect) -> &mut Self {
613 self.follow_redirects = redirect;
614 self
615 }
616
617 /// Set extra headers for this fetch operation.
618 pub fn custom_headers(&mut self, custom_headers: &[&str]) -> &mut Self {
619 self.custom_headers = custom_headers
620 .iter()
621 .map(|&s| CString::new(s).unwrap())
622 .collect();
623 self.custom_headers_ptrs = self.custom_headers.iter().map(|s| s.as_ptr()).collect();
624 self
625 }
626 }
627
628 impl<'cb> Binding for FetchOptions<'cb> {
629 type Raw = raw::git_fetch_options;
630
631 unsafe fn from_raw(_raw: raw::git_fetch_options) -> FetchOptions<'cb> {
632 panic!("unimplemented");
633 }
634 fn raw(&self) -> raw::git_fetch_options {
635 raw::git_fetch_options {
636 version: 1,
637 callbacks: self
638 .callbacks
639 .as_ref()
640 .map(|m| m.raw())
641 .unwrap_or_else(|| RemoteCallbacks::new().raw()),
642 proxy_opts: self
643 .proxy
644 .as_ref()
645 .map(|m| m.raw())
646 .unwrap_or_else(|| ProxyOptions::new().raw()),
647 prune: crate::call::convert(&self.prune),
648 // `update_fetchhead` is an incorrectly named option which contains both
649 // the `UPDATE_FETCHHEAD` and `REPORT_UNCHANGED` flags.
650 // See https://github.com/libgit2/libgit2/pull/6806
651 update_fetchhead: self.update_flags.bits() as c_uint,
652 download_tags: crate::call::convert(&self.download_tags),
653 depth: self.depth,
654 follow_redirects: self.follow_redirects.raw(),
655 custom_headers: git_strarray {
656 count: self.custom_headers_ptrs.len(),
657 strings: self.custom_headers_ptrs.as_ptr() as *mut _,
658 },
659 }
660 }
661 }
662
663 impl<'cb> Default for PushOptions<'cb> {
664 fn default() -> Self {
665 Self::new()
666 }
667 }
668
669 impl<'cb> PushOptions<'cb> {
670 /// Creates a new blank set of push options
671 pub fn new() -> PushOptions<'cb> {
672 PushOptions {
673 callbacks: None,
674 proxy: None,
675 pb_parallelism: 1,
676 follow_redirects: RemoteRedirect::Initial,
677 custom_headers: Vec::new(),
678 custom_headers_ptrs: Vec::new(),
679 remote_push_options: Vec::new(),
680 remote_push_options_ptrs: Vec::new(),
681 }
682 }
683
684 /// Set the callbacks to use for the push operation.
685 pub fn remote_callbacks(&mut self, cbs: RemoteCallbacks<'cb>) -> &mut Self {
686 self.callbacks = Some(cbs);
687 self
688 }
689
690 /// Set the proxy options to use for the push operation.
691 pub fn proxy_options(&mut self, opts: ProxyOptions<'cb>) -> &mut Self {
692 self.proxy = Some(opts);
693 self
694 }
695
696 /// If the transport being used to push to the remote requires the creation
697 /// of a pack file, this controls the number of worker threads used by the
698 /// packbuilder when creating that pack file to be sent to the remote.
699 ///
700 /// if set to 0 the packbuilder will auto-detect the number of threads to
701 /// create, and the default value is 1.
702 pub fn packbuilder_parallelism(&mut self, parallel: u32) -> &mut Self {
703 self.pb_parallelism = parallel;
704 self
705 }
706
707 /// Set remote redirection settings; whether redirects to another host are
708 /// permitted.
709 ///
710 /// By default, git will follow a redirect on the initial request
711 /// (`/info/refs`), but not subsequent requests.
712 pub fn follow_redirects(&mut self, redirect: RemoteRedirect) -> &mut Self {
713 self.follow_redirects = redirect;
714 self
715 }
716
717 /// Set extra headers for this push operation.
718 pub fn custom_headers(&mut self, custom_headers: &[&str]) -> &mut Self {
719 self.custom_headers = custom_headers
720 .iter()
721 .map(|&s| CString::new(s).unwrap())
722 .collect();
723 self.custom_headers_ptrs = self.custom_headers.iter().map(|s| s.as_ptr()).collect();
724 self
725 }
726
727 /// Set "push options" to deliver to the remote.
728 pub fn remote_push_options(&mut self, remote_push_options: &[&str]) -> &mut Self {
729 self.remote_push_options = remote_push_options
730 .iter()
731 .map(|&s| CString::new(s).unwrap())
732 .collect();
733 self.remote_push_options_ptrs = self
734 .remote_push_options
735 .iter()
736 .map(|s| s.as_ptr())
737 .collect();
738 self
739 }
740 }
741
742 impl<'cb> Binding for PushOptions<'cb> {
743 type Raw = raw::git_push_options;
744
745 unsafe fn from_raw(_raw: raw::git_push_options) -> PushOptions<'cb> {
746 panic!("unimplemented");
747 }
748 fn raw(&self) -> raw::git_push_options {
749 raw::git_push_options {
750 version: 1,
751 callbacks: self
752 .callbacks
753 .as_ref()
754 .map(|m| m.raw())
755 .unwrap_or_else(|| RemoteCallbacks::new().raw()),
756 proxy_opts: self
757 .proxy
758 .as_ref()
759 .map(|m| m.raw())
760 .unwrap_or_else(|| ProxyOptions::new().raw()),
761 pb_parallelism: self.pb_parallelism as libc::c_uint,
762 follow_redirects: self.follow_redirects.raw(),
763 custom_headers: git_strarray {
764 count: self.custom_headers_ptrs.len(),
765 strings: self.custom_headers_ptrs.as_ptr() as *mut _,
766 },
767 remote_push_options: git_strarray {
768 count: self.remote_push_options.len(),
769 strings: self.remote_push_options_ptrs.as_ptr() as *mut _,
770 },
771 }
772 }
773 }
774
775 impl<'repo, 'connection, 'cb> RemoteConnection<'repo, 'connection, 'cb> {
776 /// Check whether the remote is (still) connected
777 pub fn connected(&mut self) -> bool {
778 self.remote.connected()
779 }
780
781 /// Get the remote repository's reference advertisement list.
782 ///
783 /// This list is available as soon as the connection to
784 /// the remote is initiated and it remains available after disconnecting.
785 pub fn list(&self) -> Result<&[RemoteHead<'_>], Error> {
786 self.remote.list()
787 }
788
789 /// Get the remote's default branch.
790 ///
791 /// This default branch is available as soon as the connection to the remote
792 /// is initiated and it remains available after disconnecting.
793 pub fn default_branch(&self) -> Result<Buf, Error> {
794 self.remote.default_branch()
795 }
796
797 /// access remote bound to this connection
798 pub fn remote(&mut self) -> &mut Remote<'repo> {
799 self.remote
800 }
801 }
802
803 impl<'repo, 'connection, 'cb> Drop for RemoteConnection<'repo, 'connection, 'cb> {
804 fn drop(&mut self) {
805 drop(self.remote.disconnect());
806 }
807 }
808
809 impl Default for RemoteRedirect {
810 fn default() -> Self {
811 RemoteRedirect::Initial
812 }
813 }
814
815 impl RemoteRedirect {
816 fn raw(&self) -> raw::git_remote_redirect_t {
817 match self {
818 RemoteRedirect::None => raw::GIT_REMOTE_REDIRECT_NONE,
819 RemoteRedirect::Initial => raw::GIT_REMOTE_REDIRECT_INITIAL,
820 RemoteRedirect::All => raw::GIT_REMOTE_REDIRECT_ALL,
821 }
822 }
823 }
824
825 #[cfg(test)]
826 mod tests {
827 use crate::{AutotagOption, PushOptions, RemoteUpdateFlags};
828 use crate::{Direction, FetchOptions, ObjectFormat, Remote, RemoteCallbacks, Repository};
829 use std::cell::Cell;
830 use tempfile::TempDir;
831
832 #[test]
833 fn smoke() {
834 let (td, repo) = crate::test::repo_init();
835 t!(repo.remote("origin", "/path/to/nowhere"));
836 drop(repo);
837
838 let repo = t!(Repository::init(td.path()));
839 let mut origin = t!(repo.find_remote("origin"));
840 assert_eq!(origin.name(), Ok(Some("origin")));
841 assert_eq!(origin.url(), Ok("/path/to/nowhere"));
842 assert_eq!(origin.pushurl(), Ok(None));
843
844 t!(repo.remote_set_url("origin", "/path/to/elsewhere"));
845 t!(repo.remote_set_pushurl("origin", Some("/path/to/elsewhere")));
846
847 let stats = origin.stats();
848 assert_eq!(stats.total_objects(), 0);
849
850 t!(origin.stop());
851 }
852
853 #[test]
854 fn create_remote() {
855 let td = TempDir::new().unwrap();
856 let remote = td.path().join("remote");
857 Repository::init_bare(&remote).unwrap();
858
859 let (_td, repo) = crate::test::repo_init();
860 let url = if cfg!(unix) {
861 format!("file://{}", remote.display())
862 } else {
863 format!(
864 "file:///{}",
865 remote.display().to_string().replace("\\", "/")
866 )
867 };
868
869 let mut origin = repo.remote("origin", &url).unwrap();
870 assert_eq!(origin.name(), Ok(Some("origin")));
871 assert_eq!(origin.url(), Ok(&url[..]));
872 assert_eq!(origin.pushurl(), Ok(None));
873
874 {
875 let mut specs = origin.refspecs();
876 let spec = specs.next().unwrap();
877 assert!(specs.next().is_none());
878 assert_eq!(spec.str(), Ok("+refs/heads/*:refs/remotes/origin/*"));
879 assert_eq!(spec.dst(), Ok("refs/remotes/origin/*"));
880 assert_eq!(spec.src(), Ok("refs/heads/*"));
881 assert!(spec.is_force());
882 }
883 assert!(origin.refspecs().next_back().is_some());
884 {
885 let remotes = repo.remotes().unwrap();
886 assert_eq!(remotes.len(), 1);
887 assert_eq!(remotes.get(0), Ok(Some("origin")));
888 assert_eq!(remotes.iter().count(), 1);
889 assert_eq!(remotes.iter().next().unwrap(), Ok(Some("origin")));
890 }
891
892 origin.connect(Direction::Push).unwrap();
893 assert!(origin.connected());
894 origin.disconnect().unwrap();
895
896 origin.connect(Direction::Fetch).unwrap();
897 assert!(origin.connected());
898 assert_eq!(origin.object_format().unwrap(), ObjectFormat::Sha1);
899 origin.download(&[] as &[&str], None).unwrap();
900 origin.disconnect().unwrap();
901
902 {
903 let mut connection = origin.connect_auth(Direction::Push, None, None).unwrap();
904 assert!(connection.connected());
905 }
906 assert!(!origin.connected());
907
908 {
909 let mut connection = origin.connect_auth(Direction::Fetch, None, None).unwrap();
910 assert!(connection.connected());
911 }
912 assert!(!origin.connected());
913
914 origin.fetch(&[] as &[&str], None, None).unwrap();
915 origin.fetch(&[] as &[&str], None, Some("foo")).unwrap();
916 origin
917 .update_tips(
918 None,
919 RemoteUpdateFlags::UPDATE_FETCHHEAD,
920 AutotagOption::Unspecified,
921 None,
922 )
923 .unwrap();
924 origin
925 .update_tips(
926 None,
927 RemoteUpdateFlags::UPDATE_FETCHHEAD,
928 AutotagOption::All,
929 Some("foo"),
930 )
931 .unwrap();
932
933 t!(repo.remote_add_fetch("origin", "foo"));
934 t!(repo.remote_add_fetch("origin", "bar"));
935 }
936
937 #[test]
938 fn rename_remote() {
939 let (_td, repo) = crate::test::repo_init();
940 repo.remote("origin", "foo").unwrap();
941 drop(repo.remote_rename("origin", "foo"));
942 drop(repo.remote_delete("foo"));
943 }
944
945 #[test]
946 fn create_remote_anonymous() {
947 let td = TempDir::new().unwrap();
948 let repo = Repository::init(td.path()).unwrap();
949
950 let origin = repo.remote_anonymous("/path/to/nowhere").unwrap();
951 assert_eq!(origin.name(), Ok(None));
952 drop(origin.clone());
953 }
954
955 #[test]
956 fn empty_remote_list() {
957 // Regression tests for issue #1217
958 let td = TempDir::new().unwrap();
959 let repo = Repository::init(td.path()).unwrap();
960
961 let remote_dir = TempDir::new().unwrap();
962 let _remote_repo = Repository::init_bare(remote_dir.path()).unwrap();
963 let remote_url = if cfg!(unix) {
964 format!("file://{}", remote_dir.path().display())
965 } else {
966 format!(
967 "file:///{}",
968 remote_dir.path().display().to_string().replace("\\", "/")
969 )
970 };
971 let mut remote = repo.remote("origin", &remote_url).unwrap();
972 remote.connect(Direction::Fetch).unwrap();
973 assert_eq!(0, remote.list().unwrap().len());
974 }
975
976 #[test]
977 fn is_valid_name() {
978 assert!(Remote::is_valid_name("foobar"));
979 assert!(!Remote::is_valid_name("\x01"));
980 }
981
982 #[test]
983 #[should_panic]
984 fn is_valid_name_for_invalid_remote() {
985 Remote::is_valid_name("ab\012");
986 }
987
988 #[test]
989 fn transfer_cb() {
990 let (td, _repo) = crate::test::repo_init();
991 let td2 = TempDir::new().unwrap();
992 let url = crate::test::path2url(&td.path());
993
994 let repo = Repository::init(td2.path()).unwrap();
995 let progress_hit = Cell::new(false);
996 {
997 let mut callbacks = RemoteCallbacks::new();
998 let mut origin = repo.remote("origin", &url).unwrap();
999
1000 callbacks.transfer_progress(|_progress| {
1001 progress_hit.set(true);
1002 true
1003 });
1004 origin
1005 .fetch(
1006 &[] as &[&str],
1007 Some(FetchOptions::new().remote_callbacks(callbacks)),
1008 None,
1009 )
1010 .unwrap();
1011
1012 let list = t!(origin.list());
1013 assert_eq!(list.len(), 2);
1014 assert_eq!(list[0].name(), "HEAD");
1015 assert!(!list[0].is_local());
1016 assert_eq!(list[1].name(), "refs/heads/main");
1017 assert!(!list[1].is_local());
1018 }
1019 assert!(progress_hit.get());
1020 }
1021
1022 /// This test is meant to assure that the callbacks provided to connect will not cause
1023 /// segfaults
1024 #[test]
1025 fn connect_list() {
1026 let (td, _repo) = crate::test::repo_init();
1027 let td2 = TempDir::new().unwrap();
1028 let url = crate::test::path2url(&td.path());
1029
1030 let repo = Repository::init(td2.path()).unwrap();
1031 let mut callbacks = RemoteCallbacks::new();
1032 callbacks.sideband_progress(|_progress| {
1033 // no-op
1034 true
1035 });
1036
1037 let mut origin = repo.remote("origin", &url).unwrap();
1038
1039 {
1040 let mut connection = origin
1041 .connect_auth(Direction::Fetch, Some(callbacks), None)
1042 .unwrap();
1043 assert!(connection.connected());
1044
1045 let list = t!(connection.list());
1046 assert_eq!(list.len(), 2);
1047 assert_eq!(list[0].name(), "HEAD");
1048 assert!(!list[0].is_local());
1049 assert_eq!(list[1].name(), "refs/heads/main");
1050 assert!(!list[1].is_local());
1051 }
1052 assert!(!origin.connected());
1053 }
1054
1055 #[test]
1056 fn push() {
1057 let (_td, repo) = crate::test::repo_init();
1058 let td2 = TempDir::new().unwrap();
1059 let td3 = TempDir::new().unwrap();
1060 let url = crate::test::path2url(&td2.path());
1061
1062 let mut opts = crate::RepositoryInitOptions::new();
1063 opts.bare(true);
1064 opts.initial_head("main");
1065 Repository::init_opts(td2.path(), &opts).unwrap();
1066 // git push
1067 let mut remote = repo.remote("origin", &url).unwrap();
1068 let mut updated = false;
1069 {
1070 let mut callbacks = RemoteCallbacks::new();
1071 callbacks.push_update_reference(|refname, status| {
1072 updated = true;
1073 assert_eq!(refname, "refs/heads/main");
1074 assert_eq!(status, None);
1075 Ok(())
1076 });
1077 let mut options = PushOptions::new();
1078 options.remote_callbacks(callbacks);
1079 remote
1080 .push(&["refs/heads/main"], Some(&mut options))
1081 .unwrap();
1082 }
1083 assert!(updated);
1084
1085 let repo = Repository::clone(&url, td3.path()).unwrap();
1086 let commit = repo.head().unwrap().target().unwrap();
1087 let commit = repo.find_commit(commit).unwrap();
1088 assert_eq!(commit.message(), Ok("initial\n\nbody"));
1089 }
1090
1091 #[test]
1092 fn prune() {
1093 let (td, remote_repo) = crate::test::repo_init();
1094 let oid = remote_repo.head().unwrap().target().unwrap();
1095 let commit = remote_repo.find_commit(oid).unwrap();
1096 remote_repo.branch("stale", &commit, true).unwrap();
1097
1098 let td2 = TempDir::new().unwrap();
1099 let url = crate::test::path2url(&td.path());
1100 let repo = Repository::clone(&url, &td2).unwrap();
1101
1102 fn assert_branch_count(repo: &Repository, count: usize) {
1103 assert_eq!(
1104 repo.branches(Some(crate::BranchType::Remote))
1105 .unwrap()
1106 .filter(|b| b.as_ref().unwrap().0.name().unwrap() == Some("origin/stale"))
1107 .count(),
1108 count,
1109 );
1110 }
1111
1112 assert_branch_count(&repo, 1);
1113
1114 // delete `stale` branch on remote repo
1115 let mut stale_branch = remote_repo
1116 .find_branch("stale", crate::BranchType::Local)
1117 .unwrap();
1118 stale_branch.delete().unwrap();
1119
1120 // prune
1121 let mut remote = repo.find_remote("origin").unwrap();
1122 remote.connect(Direction::Push).unwrap();
1123 let mut callbacks = RemoteCallbacks::new();
1124 callbacks.update_tips(|refname, _a, b| {
1125 assert_eq!(refname, "refs/remotes/origin/stale");
1126 assert!(b.is_zero());
1127 true
1128 });
1129 remote.prune(Some(callbacks)).unwrap();
1130 assert_branch_count(&repo, 0);
1131 }
1132
1133 #[test]
1134 fn push_negotiation() {
1135 let (_td, repo) = crate::test::repo_init();
1136 let oid = repo.head().unwrap().target().unwrap();
1137
1138 let td2 = TempDir::new().unwrap();
1139 let url = crate::test::path2url(td2.path());
1140 let mut opts = crate::RepositoryInitOptions::new();
1141 opts.bare(true);
1142 opts.initial_head("main");
1143 let remote_repo = Repository::init_opts(td2.path(), &opts).unwrap();
1144
1145 // reject pushing a branch
1146 let mut remote = repo.remote("origin", &url).unwrap();
1147 let mut updated = false;
1148 {
1149 let mut callbacks = RemoteCallbacks::new();
1150 callbacks.push_negotiation(|updates| {
1151 assert!(!updated);
1152 updated = true;
1153 assert_eq!(updates.len(), 1);
1154 let u = &updates[0];
1155 assert_eq!(u.src_refname().unwrap(), "refs/heads/main");
1156 assert!(u.src().is_zero());
1157 assert_eq!(u.dst_refname().unwrap(), "refs/heads/main");
1158 assert_eq!(u.dst(), oid);
1159 Err(crate::Error::from_str("rejected"))
1160 });
1161 let mut options = PushOptions::new();
1162 options.remote_callbacks(callbacks);
1163 assert!(remote
1164 .push(&["refs/heads/main"], Some(&mut options))
1165 .is_err());
1166 }
1167 assert!(updated);
1168 assert_eq!(remote_repo.branches(None).unwrap().count(), 0);
1169
1170 // push 3 branches
1171 let commit = repo.find_commit(oid).unwrap();
1172 repo.branch("new1", &commit, true).unwrap();
1173 repo.branch("new2", &commit, true).unwrap();
1174 let mut flag = 0;
1175 updated = false;
1176 {
1177 let mut callbacks = RemoteCallbacks::new();
1178 callbacks.push_negotiation(|updates| {
1179 assert!(!updated);
1180 updated = true;
1181 assert_eq!(updates.len(), 3);
1182 for u in updates {
1183 assert!(u.src().is_zero());
1184 assert_eq!(u.dst(), oid);
1185 let src_name = u.src_refname().unwrap();
1186 let dst_name = u.dst_refname().unwrap();
1187 match src_name {
1188 "refs/heads/main" => {
1189 assert_eq!(dst_name, src_name);
1190 flag |= 1;
1191 }
1192 "refs/heads/new1" => {
1193 assert_eq!(dst_name, "refs/heads/dev1");
1194 flag |= 2;
1195 }
1196 "refs/heads/new2" => {
1197 assert_eq!(dst_name, "refs/heads/dev2");
1198 flag |= 4;
1199 }
1200 _ => panic!("unexpected refname: {}", src_name),
1201 }
1202 }
1203 Ok(())
1204 });
1205 let mut options = PushOptions::new();
1206 options.remote_callbacks(callbacks);
1207 remote
1208 .push(
1209 &[
1210 "refs/heads/main",
1211 "refs/heads/new1:refs/heads/dev1",
1212 "refs/heads/new2:refs/heads/dev2",
1213 ],
1214 Some(&mut options),
1215 )
1216 .unwrap();
1217 }
1218 assert!(updated);
1219 assert_eq!(flag, 7);
1220 assert_eq!(remote_repo.branches(None).unwrap().count(), 3);
1221 }
1222 }