Debian Codegraph @

src/submodule.rs

raw
1 use std::marker;
2 use std::mem;
3 use std::os::raw::c_int;
4 use std::path::Path;
5 use std::ptr;
6 use std::str;
7
8 use crate::util::{self, Binding};
9 use crate::{build::CheckoutBuilder, SubmoduleIgnore, SubmoduleUpdate};
10 use crate::{raw, Error, FetchOptions, Oid, Repository};
11
12 /// A structure to represent a git [submodule][1]
13 ///
14 /// [1]: http://git-scm.com/book/en/Git-Tools-Submodules
15 pub struct Submodule<'repo> {
16 raw: *mut raw::git_submodule,
17 _marker: marker::PhantomData<&'repo Repository>,
18 }
19
20 impl<'repo> Submodule<'repo> {
21 /// Get the submodule's branch.
22 ///
23 /// Returns `Ok(None)` if the branch is not yet available.
24 pub fn branch(&self) -> Result<Option<&str>, Error> {
25 match self.branch_bytes() {
26 Some(bb) => str::from_utf8(bb).map(|s| Some(s)).map_err(|e| e.into()),
27 None => Ok(None),
28 }
29 }
30
31 /// Get the branch for the submodule.
32 ///
33 /// Returns `None` if the branch is not yet available.
34 pub fn branch_bytes(&self) -> Option<&[u8]> {
35 unsafe { crate::opt_bytes(self, raw::git_submodule_branch(self.raw)) }
36 }
37
38 /// Perform the clone step for a newly created submodule.
39 ///
40 /// This performs the necessary `git_clone` to setup a newly-created submodule.
41 pub fn clone(
42 &mut self,
43 opts: Option<&mut SubmoduleUpdateOptions<'_>>,
44 ) -> Result<Repository, Error> {
45 unsafe {
46 let raw_opts = opts.map(|o| o.raw());
47 let mut raw_repo = ptr::null_mut();
48 try_call!(raw::git_submodule_clone(
49 &mut raw_repo,
50 self.raw,
51 raw_opts.as_ref()
52 ));
53 Ok(Binding::from_raw(raw_repo))
54 }
55 }
56
57 /// Get the submodule's URL.
58 ///
59 /// Returns `Ok(None)` if the URL isn't present
60 pub fn url(&self) -> Result<Option<&str>, Error> {
61 match self.opt_url_bytes() {
62 Some(oub) => str::from_utf8(oub).map(|s| Some(s)).map_err(|e| e.into()),
63 None => Ok(None),
64 }
65 }
66
67 /// Get the URL for the submodule.
68 #[doc(hidden)]
69 #[deprecated(note = "renamed to `opt_url_bytes`")]
70 pub fn url_bytes(&self) -> &[u8] {
71 self.opt_url_bytes().unwrap()
72 }
73
74 /// Get the URL for the submodule.
75 ///
76 /// Returns `None` if the URL isn't present
77 // TODO: delete this method and fix the signature of `url_bytes` on next
78 // major version bump
79 pub fn opt_url_bytes(&self) -> Option<&[u8]> {
80 unsafe { crate::opt_bytes(self, raw::git_submodule_url(self.raw)) }
81 }
82
83 /// Get the submodule's name.
84 pub fn name(&self) -> Result<&str, Error> {
85 str::from_utf8(self.name_bytes()).map_err(|e| e.into())
86 }
87
88 /// Get the name for the submodule.
89 pub fn name_bytes(&self) -> &[u8] {
90 unsafe { crate::opt_bytes(self, raw::git_submodule_name(self.raw)).unwrap() }
91 }
92
93 /// Get the path for the submodule.
94 pub fn path(&self) -> &Path {
95 util::bytes2path(unsafe {
96 crate::opt_bytes(self, raw::git_submodule_path(self.raw)).unwrap()
97 })
98 }
99
100 /// Get the OID for the submodule in the current HEAD tree.
101 pub fn head_id(&self) -> Option<Oid> {
102 unsafe { Binding::from_raw_opt(raw::git_submodule_head_id(self.raw)) }
103 }
104
105 /// Get the OID for the submodule in the index.
106 pub fn index_id(&self) -> Option<Oid> {
107 unsafe { Binding::from_raw_opt(raw::git_submodule_index_id(self.raw)) }
108 }
109
110 /// Get the OID for the submodule in the current working directory.
111 ///
112 /// This returns the OID that corresponds to looking up 'HEAD' in the
113 /// checked out submodule. If there are pending changes in the index or
114 /// anything else, this won't notice that.
115 pub fn workdir_id(&self) -> Option<Oid> {
116 unsafe { Binding::from_raw_opt(raw::git_submodule_wd_id(self.raw)) }
117 }
118
119 /// Get the ignore rule that will be used for the submodule.
120 pub fn ignore_rule(&self) -> SubmoduleIgnore {
121 SubmoduleIgnore::from_raw(unsafe { raw::git_submodule_ignore(self.raw) })
122 }
123
124 /// Get the update rule that will be used for the submodule.
125 pub fn update_strategy(&self) -> SubmoduleUpdate {
126 SubmoduleUpdate::from_raw(unsafe { raw::git_submodule_update_strategy(self.raw) })
127 }
128
129 /// Copy submodule info into ".git/config" file.
130 ///
131 /// Just like "git submodule init", this copies information about the
132 /// submodule into ".git/config". You can use the accessor functions above
133 /// to alter the in-memory git_submodule object and control what is written
134 /// to the config, overriding what is in .gitmodules.
135 ///
136 /// By default, existing entries will not be overwritten, but passing `true`
137 /// for `overwrite` forces them to be updated.
138 pub fn init(&mut self, overwrite: bool) -> Result<(), Error> {
139 unsafe {
140 try_call!(raw::git_submodule_init(self.raw, overwrite));
141 }
142 Ok(())
143 }
144
145 /// Set up the subrepository for a submodule in preparation for clone.
146 ///
147 /// This function can be called to init and set up a submodule repository
148 /// from a submodule in preparation to clone it from its remote.
149
150 /// use_gitlink: Should the workdir contain a gitlink to the repo in
151 /// .git/modules vs. repo directly in workdir.
152 pub fn repo_init(&mut self, use_gitlink: bool) -> Result<Repository, Error> {
153 unsafe {
154 let mut raw_repo = ptr::null_mut();
155 try_call!(raw::git_submodule_repo_init(
156 &mut raw_repo,
157 self.raw,
158 use_gitlink
159 ));
160 Ok(Binding::from_raw(raw_repo))
161 }
162 }
163
164 /// Open the repository for a submodule.
165 ///
166 /// This will only work if the submodule is checked out into the working
167 /// directory.
168 pub fn open(&self) -> Result<Repository, Error> {
169 let mut raw = ptr::null_mut();
170 unsafe {
171 try_call!(raw::git_submodule_open(&mut raw, self.raw));
172 Ok(Binding::from_raw(raw))
173 }
174 }
175
176 /// Reread submodule info from config, index, and HEAD.
177 ///
178 /// Call this to reread cached submodule information for this submodule if
179 /// you have reason to believe that it has changed.
180 ///
181 /// If `force` is `true`, then data will be reloaded even if it doesn't seem
182 /// out of date
183 pub fn reload(&mut self, force: bool) -> Result<(), Error> {
184 unsafe {
185 try_call!(raw::git_submodule_reload(self.raw, force));
186 }
187 Ok(())
188 }
189
190 /// Copy submodule remote info into submodule repo.
191 ///
192 /// This copies the information about the submodules URL into the checked
193 /// out submodule config, acting like "git submodule sync". This is useful
194 /// if you have altered the URL for the submodule (or it has been altered
195 /// by a fetch of upstream changes) and you need to update your local repo.
196 pub fn sync(&mut self) -> Result<(), Error> {
197 unsafe {
198 try_call!(raw::git_submodule_sync(self.raw));
199 }
200 Ok(())
201 }
202
203 /// Add current submodule HEAD commit to index of superproject.
204 ///
205 /// If `write_index` is true, then the index file will be immediately
206 /// written. Otherwise you must explicitly call `write()` on an `Index`
207 /// later on.
208 pub fn add_to_index(&mut self, write_index: bool) -> Result<(), Error> {
209 unsafe {
210 try_call!(raw::git_submodule_add_to_index(self.raw, write_index));
211 }
212 Ok(())
213 }
214
215 /// Resolve the setup of a new git submodule.
216 ///
217 /// This should be called on a submodule once you have called add setup and
218 /// done the clone of the submodule. This adds the .gitmodules file and the
219 /// newly cloned submodule to the index to be ready to be committed (but
220 /// doesn't actually do the commit).
221 pub fn add_finalize(&mut self) -> Result<(), Error> {
222 unsafe {
223 try_call!(raw::git_submodule_add_finalize(self.raw));
224 }
225 Ok(())
226 }
227
228 /// Update submodule.
229 ///
230 /// This will clone a missing submodule and check out the subrepository to
231 /// the commit specified in the index of the containing repository. If
232 /// the submodule repository doesn't contain the target commit, then the
233 /// submodule is fetched using the fetch options supplied in `opts`.
234 ///
235 /// `init` indicates if the submodule should be initialized first if it has
236 /// not been initialized yet.
237 pub fn update(
238 &mut self,
239 init: bool,
240 opts: Option<&mut SubmoduleUpdateOptions<'_>>,
241 ) -> Result<(), Error> {
242 unsafe {
243 let mut raw_opts = opts.map(|o| o.raw());
244 try_call!(raw::git_submodule_update(
245 self.raw,
246 init as c_int,
247 raw_opts.as_mut().map_or(ptr::null_mut(), |o| o)
248 ));
249 }
250 Ok(())
251 }
252 }
253
254 impl<'repo> Binding for Submodule<'repo> {
255 type Raw = *mut raw::git_submodule;
256 unsafe fn from_raw(raw: *mut raw::git_submodule) -> Submodule<'repo> {
257 Submodule {
258 raw,
259 _marker: marker::PhantomData,
260 }
261 }
262 fn raw(&self) -> *mut raw::git_submodule {
263 self.raw
264 }
265 }
266
267 impl<'repo> Drop for Submodule<'repo> {
268 fn drop(&mut self) {
269 unsafe { raw::git_submodule_free(self.raw) }
270 }
271 }
272
273 /// Options to update a submodule.
274 pub struct SubmoduleUpdateOptions<'cb> {
275 checkout_builder: CheckoutBuilder<'cb>,
276 fetch_opts: FetchOptions<'cb>,
277 allow_fetch: bool,
278 }
279
280 impl<'cb> SubmoduleUpdateOptions<'cb> {
281 /// Return default options.
282 pub fn new() -> Self {
283 SubmoduleUpdateOptions {
284 checkout_builder: CheckoutBuilder::new(),
285 fetch_opts: FetchOptions::new(),
286 allow_fetch: true,
287 }
288 }
289
290 unsafe fn raw(&mut self) -> raw::git_submodule_update_options {
291 let mut checkout_opts: raw::git_checkout_options = mem::zeroed();
292 let init_res =
293 raw::git_checkout_init_options(&mut checkout_opts, raw::GIT_CHECKOUT_OPTIONS_VERSION);
294 assert_eq!(0, init_res);
295 self.checkout_builder.configure(&mut checkout_opts);
296 let opts = raw::git_submodule_update_options {
297 version: raw::GIT_SUBMODULE_UPDATE_OPTIONS_VERSION,
298 checkout_opts,
299 fetch_opts: self.fetch_opts.raw(),
300 allow_fetch: self.allow_fetch as c_int,
301 };
302 opts
303 }
304
305 /// Set checkout options.
306 pub fn checkout(&mut self, opts: CheckoutBuilder<'cb>) -> &mut Self {
307 self.checkout_builder = opts;
308 self
309 }
310
311 /// Set fetch options and allow fetching.
312 pub fn fetch(&mut self, opts: FetchOptions<'cb>) -> &mut Self {
313 self.fetch_opts = opts;
314 self.allow_fetch = true;
315 self
316 }
317
318 /// Allow or disallow fetching.
319 pub fn allow_fetch(&mut self, b: bool) -> &mut Self {
320 self.allow_fetch = b;
321 self
322 }
323 }
324
325 impl<'cb> Default for SubmoduleUpdateOptions<'cb> {
326 fn default() -> Self {
327 Self::new()
328 }
329 }
330
331 #[cfg(test)]
332 mod tests {
333 use std::fs;
334 use std::path::Path;
335 use tempfile::TempDir;
336 use url::Url;
337
338 use crate::Repository;
339 use crate::SubmoduleUpdateOptions;
340
341 #[test]
342 fn smoke() {
343 let td = TempDir::new().unwrap();
344 let repo = Repository::init(td.path()).unwrap();
345 let mut s1 = repo
346 .submodule("/path/to/nowhere", Path::new("foo"), true)
347 .unwrap();
348 s1.init(false).unwrap();
349 s1.sync().unwrap();
350
351 let s2 = repo
352 .submodule("/path/to/nowhere", Path::new("bar"), true)
353 .unwrap();
354 drop((s1, s2));
355
356 let mut submodules = repo.submodules().unwrap();
357 assert_eq!(submodules.len(), 2);
358 let mut s = submodules.remove(0);
359 assert_eq!(s.name(), Ok("bar"));
360 assert_eq!(s.url(), Ok(Some("/path/to/nowhere")));
361 assert_eq!(s.branch(), Ok(None));
362 assert!(s.head_id().is_none());
363 assert!(s.index_id().is_none());
364 assert!(s.workdir_id().is_none());
365
366 repo.find_submodule("bar").unwrap();
367 s.open().unwrap();
368 assert!(s.path() == Path::new("bar"));
369 s.reload(true).unwrap();
370 }
371
372 #[test]
373 fn add_a_submodule() {
374 let (_td, repo1) = crate::test::repo_init();
375 let (td, repo2) = crate::test::repo_init();
376
377 let url = Url::from_file_path(&repo1.workdir().unwrap()).unwrap();
378 let mut s = repo2
379 .submodule(&url.to_string(), Path::new("bar"), true)
380 .unwrap();
381 t!(fs::remove_dir_all(td.path().join("bar")));
382 t!(Repository::clone(&url.to_string(), td.path().join("bar")));
383 t!(s.add_to_index(false));
384 t!(s.add_finalize());
385 }
386
387 #[test]
388 fn update_submodule() {
389 // -----------------------------------
390 // Same as `add_a_submodule()`
391 let (_td, repo1) = crate::test::repo_init();
392 let (td, repo2) = crate::test::repo_init();
393
394 let url = Url::from_file_path(&repo1.workdir().unwrap()).unwrap();
395 let mut s = repo2
396 .submodule(&url.to_string(), Path::new("bar"), true)
397 .unwrap();
398 t!(fs::remove_dir_all(td.path().join("bar")));
399 t!(Repository::clone(&url.to_string(), td.path().join("bar")));
400 t!(s.add_to_index(false));
401 t!(s.add_finalize());
402 // -----------------------------------
403
404 // Attempt to update submodule
405 let submodules = t!(repo1.submodules());
406 for mut submodule in submodules {
407 let mut submodule_options = SubmoduleUpdateOptions::new();
408 let init = true;
409 let opts = Some(&mut submodule_options);
410
411 t!(submodule.update(init, opts));
412 }
413 }
414
415 #[test]
416 fn clone_submodule() {
417 // -----------------------------------
418 // Same as `add_a_submodule()`
419 let (_td, repo1) = crate::test::repo_init();
420 let (_td, repo2) = crate::test::repo_init();
421 let (_td, parent) = crate::test::repo_init();
422
423 let url1 = Url::from_file_path(&repo1.workdir().unwrap()).unwrap();
424 let url2 = Url::from_file_path(&repo2.workdir().unwrap()).unwrap();
425 let mut s1 = parent
426 .submodule(&url1.to_string(), Path::new("bar"), true)
427 .unwrap();
428 let mut s2 = parent
429 .submodule(&url2.to_string(), Path::new("bar2"), true)
430 .unwrap();
431 // -----------------------------------
432
433 t!(s1.clone(Some(&mut SubmoduleUpdateOptions::default())));
434 t!(s2.clone(None));
435 }
436
437 #[test]
438 fn repo_init_submodule() {
439 // -----------------------------------
440 // Same as `clone_submodule()`
441 let (_td, child) = crate::test::repo_init();
442 let (_td, parent) = crate::test::repo_init();
443
444 let url_child = Url::from_file_path(&child.workdir().unwrap()).unwrap();
445 let url_parent = Url::from_file_path(&parent.workdir().unwrap()).unwrap();
446 let mut sub = parent
447 .submodule(&url_child.to_string(), Path::new("bar"), true)
448 .unwrap();
449
450 // -----------------------------------
451 // Let's commit the submodule for later clone
452 t!(sub.clone(None));
453 t!(sub.add_to_index(true));
454 t!(sub.add_finalize());
455
456 crate::test::commit(&parent);
457
458 // Clone the parent to init its submodules
459 let td = TempDir::new().unwrap();
460 let new_parent = Repository::clone(&url_parent.to_string(), &td).unwrap();
461
462 let mut submodules = new_parent.submodules().unwrap();
463 let child = submodules.first_mut().unwrap();
464
465 // First init child
466 t!(child.init(false));
467 assert_eq!(
468 child.url().expect("Should be okay").unwrap(),
469 url_child.as_str()
470 );
471
472 // open() is not possible before initializing the repo
473 assert!(child.open().is_err());
474 t!(child.repo_init(true));
475 assert!(child.open().is_ok());
476 }
477 }