subcomponent 0.1.0

A components orchestrator
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
/*
 * Copyright (c) 2017 Jean Guyomarc'h
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

extern crate std;
use config;
use compiler::parser;
use compiler::parser::PropertyValue;
use fetcher;
use subprocess;

const METHOD_NAME: &'static str = "git";

pub enum Revision {
    Commit(String),
    Branch(String),
    Tag(String),
}

impl std::fmt::Display for Revision {
   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
      match *self {
         Revision::Commit(ref string) => write!(f, "{}", string),
         Revision::Branch(ref string) => write!(f, "{}", string),
         Revision::Tag(ref string) => write!(f, "{}", string),
      }
   }
}

struct GitVersion {
    major: usize,
    minor: usize,
}

impl std::fmt::Display for GitVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}.{}.x", self.major, self.minor)
    }
}

pub struct Method {
    urls: Vec<String>,
    clone_recursive: bool,
    shallow: bool,
    shallow_submodules: bool,
    revision: Revision,
    remote: String,
}

fn git_command_new() -> std::process::Command {
   subprocess::new("git")
}

impl Method {
   fn is_repository_clean(&self, component: &config::Component) -> Result<bool, fetcher::Error> {
      /*
       * Run a git status inside the component to see whether it is dirty or not.
       */
      let mut cmd = git_command_new();
      cmd.args(&["-C", component.path_get().as_str(),
               "status",
               "-z", "--porcelain", "-uall"]);
      let stdout = try!(subprocess::run_get_stdout(&mut cmd));

      /* Empty string: git status said nothing wrong */
      Ok(stdout.is_empty())
   }

   fn fetch_new_branch(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      for url in &self.urls {
         let revision = self.revision.to_string();
         let remote = self.remote.to_string();

         /*
          * Cloning a branch: git clone --branch=BRANCH <ARGS> URL PATH
          * It is a self-contained operation. Nothing needs to be done
          * after this command succeeds.
          */
         let mut cmd = git_command_new();
         cmd.stdout(std::process::Stdio::null());
         cmd.arg("clone");
         cmd.arg("--quiet");
         cmd.arg("--origin");
         cmd.arg(remote);
         cmd.arg("--branch");
         cmd.arg(revision.as_str());

         if self.clone_recursive {
            cmd.arg("--recursive");
         }
         if self.shallow {
            cmd.arg("--depth=1");
         }
         if self.shallow_submodules {
            cmd.arg("--shallow-submodules");
         }
         cmd.arg(url);
         cmd.arg(component.path_get());

         match subprocess::run(&mut cmd) {
            Ok(_) => { return Ok(()); },
            Err(_) => { error!("Fetcher failed"); }
         }
      }
      /*
       * At this point, everything failed to clone the branch.
       */
      error!("Unable to retrieve the component `{}`", component.name_get());
      Err(fetcher::Error::EverythingFailed)
   }

   fn fetch_new_revision(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      for url in &self.urls {
         let revision = self.revision.to_string();
         let remote = self.remote.to_string();

         /*
          * Cloning a tag or a commit: git clone + git checkout
          * We need to manually update submodules if requested
          */
         {
            let mut cmd = git_command_new();
            cmd.stdout(std::process::Stdio::null());
            cmd.arg("clone");
            cmd.arg("--quiet");
            cmd.arg("--origin");
            cmd.arg(remote);
            cmd.arg("--no-checkout");
            cmd.arg(url);
            cmd.arg(component.path_get());

            if subprocess::run(&mut cmd).is_err() {
               /* We failed, to clone. Try another URL (next loop iteration) */
               error!("Fetcher (clone) failed");
               continue;
            }
         }

         /*
          * Now that we have cloned the repository, we need to checkout
          * to the correct revision (tag/commit)
          */
         try!(self.git_checkout(component, &revision));

         /* Finally, update the submodules when necessary */
         if self.clone_recursive {
            try!(self.git_submodule_update(component));
         }

         /*
          * If we reached the end of an iteration, we suceeded. We can stop
          * here.
          */
         return Ok(());
      }
      /*
       * At this point, everything failed to clone the branch.
       */
      error!("Unable to retrieve the component `{}`", component.name_get());
      Err(fetcher::Error::EverythingFailed)
   }

   fn git_ls_remote(&self, component: &config::Component, param: &str) -> Result<String, fetcher::Error> {
      let remote = self.remote.to_string();
      let mut cmd = git_command_new();
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("ls-remote");
      cmd.arg("--quiet");
      cmd.arg("--refs");
      cmd.arg(param);
      cmd.arg(remote);

      let stdout = try!(subprocess::run_get_stdout(&mut cmd));
      Ok(stdout)
   }

   fn update_remote(&self, component: &config::Component, url: &str) -> Result<(), fetcher::Error> {
      let remote = self.remote.to_string();
      let mut cmd = git_command_new();
      cmd.stdout(std::process::Stdio::null());
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("remote");
      cmd.arg("set-url");
      cmd.arg(remote);
      cmd.arg(url);

      try!(subprocess::run(&mut cmd));
      Ok(())
   }

   fn create_remote(&self, component: &config::Component, url: &str) -> Result<(), fetcher::Error> {
      let remote = self.remote.to_string();
      let mut cmd = git_command_new();
      cmd.stdout(std::process::Stdio::null());
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("remote");
      cmd.arg("add");
      cmd.arg(remote);
      cmd.arg(url);

      try!(subprocess::run(&mut cmd));
      Ok(())
   }

   fn fixup_remote(&self, component: &config::Component, url: &str) -> Result<(), fetcher::Error> {
      /*
       * First, we need to check the existing remotes. If the remote specified in the
       * subcomponent file exists, we will update it to point to the first URL to be
       * checkouted. If it does not exist, we will create tit.
       */

      let mut cmd = git_command_new();
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("remote");

      for remote in  try!(subprocess::run_get_stdout(&mut cmd)).split('\n') {
         if remote == self.remote {
            return self.update_remote(component, url);
         }
      }

      self.create_remote(component, &self.urls[0])
   }

   fn is_shallow(&self, component: &config::Component) -> Result<bool, fetcher::Error> {
      /*
       * A git repository is shallow if it contains a 'shallow' file in its
       * git directory.
       */
      let mut cmd = git_command_new();
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("rev-parse");
      cmd.arg("--git-dir");

      /* Get where the .git/ directory resides */
      let mut git_dir = try!(subprocess::run_get_stdout(&mut cmd));
      git_dir.pop();

      let mut path = std::path::PathBuf::new();
      path.push(git_dir.as_str());
      path.push("shallow");

      let is_shallow = path.as_path().exists();
      Ok(is_shallow)
   }

   fn get_head_hash(&self, component: &config::Component) -> Result<String, fetcher::Error> {
      let mut cmd = git_command_new();
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("rev-parse");
      cmd.arg("HEAD");

      let mut hash = try!(subprocess::run_get_stdout(&mut cmd));
      hash.pop();
      Ok(hash)
   }
   fn needs_updating(&self, component: &config::Component) -> Result<bool, fetcher::Error> {
      /*
       * There are three cases:
       *  - if we want to update to a new COMMIT, we check that the current
       *    hash is not the same as the one we want to update to
       *  - if we want to update to a new TAG, we check that the current tag
       *    is different from the tag we want to update to
       *  - if we want to update to a new BRANCH, we check that the remote
       *    hash for the branch is not the same than the current
       */

      let hash = try!(self.get_head_hash(component));
      match self.revision {
         Revision::Commit(ref commit) => {
            trace!("Update (commit) from: {}, to: {}", hash, commit);
            Ok(&hash != commit)
         },
         Revision::Tag(ref tag) => {
            let tag_hash = try!(self.get_hash_for_ref(component, "tags", tag));
            trace!("Update (tag) from: {}, to: {}", hash, tag_hash);
            Ok(tag_hash != hash)
         },
         Revision::Branch(ref branch) => {
            let branch_hash = try!(self.get_hash_for_ref(component, "heads", branch));
            trace!("Update (branch) from: {}, to: {}", hash, branch_hash);
            Ok(branch_hash != hash)
         },
      }
   }

   fn get_hash_for_ref(&self, component: &config::Component, reftype: &str, gref: &str) -> Result<String, fetcher::Error> {
      let arg = format!("--{}", reftype);
      let git_ref = format!("refs/{}/{}", reftype, gref);

      let stdout = try!(self.git_ls_remote(component, arg.as_str()));
      let mut iterator = stdout.split_whitespace().rev();
      while let Some(it_ref) = iterator.next() {
         if git_ref == it_ref {
            if let Some(hash) = iterator.next() {
               return Ok(String::from(hash));
            }
         }
      }
      Err(fetcher::Error::InvalidReference)
   }

   fn unshallow(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      /*
       * Step one of unshallowing: remove the current remote configuration.
       * Shallow clones configure a remote not to fetch other refs.
       */
      {
         let remote = format!("remote.{}", self.remote).to_string();
         let mut cmd = git_command_new();
         cmd.stdout(std::process::Stdio::null());
         cmd.arg("-C");
         cmd.arg(component.path_get());
         cmd.arg("config");
         cmd.arg("--local");
         cmd.arg("--unset");
         cmd.arg(remote);
         try!(subprocess::run(&mut cmd));
      }
      /*
       * Step two of unshallowing: set the remote configuration so it can fetch
       * other refs.
       */
      {
         let remote = format!("remote.{}.fetch", self.remote).to_string();
         let remote_val = format!("+refs/heads/*:refs/remotes/{}/*", self.remote).to_string();
         let mut cmd = git_command_new();
         cmd.stdout(std::process::Stdio::null());
         cmd.arg("-C");
         cmd.arg(component.path_get());
         cmd.arg("config");
         cmd.arg("--unset");
         cmd.arg(remote);
         cmd.arg(remote_val);
         try!(subprocess::run(&mut cmd));
      }
      /*
       * Final step of unshallowing: run a git fetch --unshallow.
       */
      {
         let remote = self.remote.to_string();
         let mut cmd = git_command_new();
         cmd.stdout(std::process::Stdio::null());
         cmd.arg("-C");
         cmd.arg(component.path_get());
         cmd.arg("fetch");
         cmd.arg("--unshallow");
         cmd.arg(remote);
         try!(subprocess::run(&mut cmd));
      }
      Ok(())
   }

   fn git_submodule_update(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      let mut cmd = git_command_new();
      cmd.stdout(std::process::Stdio::null());
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("submodule");
      cmd.arg("update");
      cmd.arg("--quiet");
      cmd.arg("--init");
      cmd.arg("--recursive");
      if self.shallow_submodules {
         cmd.arg("--depth=1");
      }
      try!(subprocess::run(&mut cmd));
      Ok(())
   }

   fn git_checkout(&self, component: &config::Component, revision: &str) -> Result<(), fetcher::Error> {
      let mut cmd = git_command_new();
      cmd.stdout(std::process::Stdio::null());
      cmd.arg("-C");
      cmd.arg(component.path_get());
      cmd.arg("checkout");
      cmd.arg("--quiet");
      cmd.arg(revision);
      try!(subprocess::run(&mut cmd));
      Ok(())
   }

   fn update(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      /*
       * First, fetch the remote
       */
      {
         let remote = self.remote.to_string();
         let mut cmd = git_command_new();
         cmd.stdout(std::process::Stdio::null());
         cmd.arg("-C");
         cmd.arg(component.path_get());
         cmd.arg("fetch");
         cmd.arg("--tags");
         cmd.arg(remote);
         try!(subprocess::run(&mut cmd));
      }
      /*
       * Now, we can checkout
       */
      {
         let revision = self.revision.to_string();
         try!(self.git_checkout(component, &revision));
      }

      /* Finally, update the submodules when necessary */
      if self.clone_recursive {
         try!(self.git_submodule_update(component));
      }
      Ok(())
   }
}

impl fetcher::Method for Method {
   fn fetch_new(&self, component: &config::Component) -> Result<(), fetcher::Error> {
      /*
       * We make the distinction between cloning a branch an a revision (tag/commit).
       */
      match self.revision {
         Revision::Branch(_) => self.fetch_new_branch(component),
         _ => self.fetch_new_revision(component),
      }
   }

   fn fetch_update(&self, component: &config::Component, force: bool) -> Result<(), fetcher::Error> {
      /*
       * At this point we already know that we are in a git repository, as the
       * is_fetchable() interface has been called earlier.
       */

      /* Can we consider this repository as clean? */
      let is_clean = try!(self.is_repository_clean(component));

      /*
       * If the repository is dirty, we won't even bother to update. Unless we
       * are is force mode.
       */
      if is_clean || force {
         for url in &self.urls {
            /*
             * First step in updating is to make sure we have a remote that
             * subcomponent can play with.
             */
            self.fixup_remote(component, url)?;

            /*
             * Then, check if we have something to update, or if we can just
             * stop here.
             */
            if try!(self.needs_updating(component)) {
               /*
                * Unshallow the repository if need be.
                */
               if try!(self.is_shallow(component)) {
                  try!(self.unshallow(component));
               }

               /*
                * Update! On failure, we wil ltry another url.
                */
               if self.update(component).is_err() {
                  error!("Failed to update component \"{}\" with url \"{}\"",
                         component.id_get(), url);
                  continue;
               };
            } else {
               info!("Component \"{}\" is already up-to-date.", component.id_get());
            }

            /* We haven't failed until now? So we actually succeeded */
            return Ok(());
         }

         /* We have exhausted all URLs without success */
         Err(fetcher::Error::EverythingFailed)
      } else {
         /*
          * Dirty component... I won't update it.
          */
         Err(fetcher::Error::Dirty)
      }
   }

   fn is_fetchable(&self, component: &config::Component) -> bool {
      /*
       * We can see if a directory contains a repository by running a
       * git rev-parse --git-dir command.
       *
       * If the directory is NOT a git repository, git will try the parent
       * directory, and so on until it finds something or nothing. If there
       * is a git repository underneath, the git dir will be an ABSOLUTE path,
       * as it is containing us, and we are not running the git command in the
       * root directory. If there are no git directory underneath, the git
       * command will fail.
       */
      let mut cmd = git_command_new();
      cmd.args(&["-C", component.path_get().as_str(),
               "rev-parse",
               "--git-dir"]);
      cmd.stdout(std::process::Stdio::piped());
      cmd.stderr(std::process::Stdio::null()); /* Ignore errors */

      if subprocess::run(&mut cmd).is_ok() {
         if let Ok(output) = cmd.output() {
            let string = std::str::from_utf8(&output.stdout).unwrap();
            let git_dir_path = std::path::Path::new(string);
            if ! git_dir_path.has_root() {
               return true;
            }
         }
      }
      false
   }

   fn name_get(&self) -> &str {
      METHOD_NAME
   }
}

type RevisionResult = Result<Option<Revision>, parser::Error>;

fn rev_prop_get(component: &str, cfg: &config::Config, propname: &str) -> Result<Option<String>, parser::Error> {
    if let Some(prop) = cfg.get_fetch_property(component, METHOD_NAME, propname) {
        match prop {
            PropertyValue::StringValue(val) => { return Ok(Some(val.clone())); },
            _ => { return Err(parser::Error::InvalidPropertyType); }
        }
    }
    Ok(None)
}

fn commit_prop_get(component: &str, cfg: &config::Config) -> RevisionResult {
    if let Some(commit) = try!(rev_prop_get(component, cfg, "commit")) {
        Ok(Some(Revision::Commit(commit)))
    } else {
        Ok(None)
    }
}

fn branch_prop_get(component: &str, cfg: &config::Config) -> RevisionResult {
    if let Some(commit) = try!(rev_prop_get(component, cfg, "branch")) {
        Ok(Some(Revision::Branch(commit)))
    } else {
        Ok(None)
    }
}

fn tag_prop_get(component: &str, cfg: &config::Config) -> RevisionResult {
    if let Some(commit) = try!(rev_prop_get(component, cfg, "tag")) {
        Ok(Some(Revision::Tag(commit)))
    } else {
        Ok(None)
    }
}

fn parse_revision(component: &str, cfg: &config::Config) -> Result<Revision, parser::Error> {
    let mut count = 0;
    let mut revision: Option<Revision> = None;

    /* Search for the commit property */
    if let Some(rev) = try!(commit_prop_get(component, cfg)) {
        revision = Some(rev);
        count += 1;
    }

    /* Search for the branch property */
    if let Some(rev) = try!(branch_prop_get(component, cfg)) {
        revision = Some(rev);
        count += 1;
    }

    /* Search for the tag property */
    if let Some(rev) = try!(tag_prop_get(component, cfg)) {
        revision = Some(rev);
        count += 1;
    }

    /*
     * We must have exactly one of the properties above.
     * If we have none, that's an error.
     * If we have several, that's also an error!
     */
    if count > 1 {
        error!("Conflicting properties: \"branch\", \"tag\", \"commit\" are mutually exclusive");
        Err(parser::Error::ConflictingProperties)
    } else {
        revision.ok_or(parser::Error::MissingRequiredProperty)
    }
}

fn parse_clone_recursive(component: &str, cfg: &config::Config) -> Result<bool, parser::Error> {
    /*
     * Get the clone-recursive property. It has a default value of 'true'.
     */
    if let Some(prop) = cfg.get_fetch_property(component, METHOD_NAME, "clone-recursive") {
        match prop {
            PropertyValue::BooleanValue(val) => { return Ok(val); },
            _ => { return Err(parser::Error::InvalidPropertyType); }
        }
    }
    Ok(true)
}

fn parse_shallow(component: &str, cfg: &config::Config) -> Result<bool, parser::Error> {
   if let Some(prop) = cfg.get_fetch_property(component, METHOD_NAME, "shallow") {
      match prop {
         PropertyValue::BooleanValue(val) => { return Ok(val); },
         _ => { return Err(parser::Error::InvalidPropertyType); }
      }
   }
   Ok(false)
}

fn parse_shallow_submodules(component: &str, cfg: &config::Config) -> Result<bool, parser::Error> {
   if let Some(prop) = cfg.get_fetch_property(component, METHOD_NAME, "shallow-submodules") {
      match prop {
         PropertyValue::BooleanValue(val) => { return Ok(val); },
         _ => { return Err(parser::Error::InvalidPropertyType); }
      }
   }
   Ok(false)
}

fn parse_remote(component: &str, cfg: &config::Config) -> Result<String, parser::Error> {
   if let Some(prop) = cfg.get_fetch_property(component, METHOD_NAME, "remote") {
      match prop {
         PropertyValue::StringValue(val) => { return Ok(val.clone()); },
         _ => { return Err(parser::Error::InvalidPropertyType); }
      }
   }
   Ok(String::from("subcomponent"))
}

fn git_version_extract(string: &str) -> Option<GitVersion> {
   if let Some(index) = string.rfind(' ') {
      let version = &string[index+1..string.len() - 1];

      let parts: Vec<&str> = version.split('.').collect();

      /*
       * We will just parse the first two components (major + minor).
       * We expect these two to be both valid. We won't check for
       * patch, because we currently don't know how to do... doing
       * a regex search is tedious...
       */
      if parts.len() >= 2 {
         if let Ok(major) = parts[0].parse() {
            if let Ok(minor) = parts[1].parse() {
               return Some(GitVersion {
                  major: major,
                  minor: minor,
               })
            }
         }
      }
   }
   None
}

fn git_fallback_version_new() -> GitVersion {
   /*
    * We provide zero to major and minor values. This will make all
    * check for features fail, as 0 will be always less than a required
    * version.
    */
   GitVersion {
      major: 0,
      minor: 0,
   }
}

fn git_version_get() -> GitVersion {
   let mut cmd = git_command_new();
   cmd.arg("--version");

   if let Ok(stdout) = subprocess::run_get_stdout(&mut cmd) {
      if let Some(version) = git_version_extract(&stdout) {
         return version;
      }
   }

   warn!("Failed to determine the version of git. Using a safe fallback.");
   git_fallback_version_new()
}

pub fn parse(component: &str, cfg: &config::Config) -> Result<Box<fetcher::Method>, parser::Error> {
    /*
     * Parse the properties. Checks are done when possible.
     */
    let clone_recursive = try!(parse_clone_recursive(component, cfg));
    let revision = try!(parse_revision(component, cfg));
    let shallow = try!(parse_shallow(component, cfg));
    let mut shallow_submodules = try!(parse_shallow_submodules(component, cfg));
    let remote = try!(parse_remote(component, cfg));
    let urls = try!(fetcher::parse_url(component, METHOD_NAME, cfg));

    /*
     * Last-minute checks
     */
    if let Revision::Branch(_) = revision {
    } else {
       /* shallow cannot be used with a revision that is not a branch! */
       if shallow {
          error!("Only a branch can be cloned as shallow");
          return Err(parser::Error::ConflictingProperties)
       }
    }

    /*
     * Get the version of the git program used to handle the component.
     * This function does not fail. If we could not determine what the
     * git version was, we use a "0.0" as a fallback. Which means we
     * won't make any hypothesis on the git version and always assume
     * zero feature.
     */
    let git_version = git_version_get();

    /*
     * Versions check. Not all features are available for all git versions!!
     */
    if git_version.major <= 2 && git_version.minor < 9 {
       if shallow_submodules {
          warn!("Shallow submodules are enabled for component {}, but the \
                git version you are using ({}) has no support for them.",
                component, git_version);
          shallow_submodules = false;
       }
    }

    Ok(Box::new(Method {
        urls: urls,
        clone_recursive: clone_recursive,
        shallow: shallow,
        shallow_submodules: shallow_submodules,
        revision: revision,
        remote: remote,
    }))
}



#[cfg(test)]
mod tests {
   extern crate std;
   use fetcher;

   fn check_version(string: &str, expected_major: usize, expected_minor: usize) -> bool {
      let text = String::from(string);
      match fetcher::git::git_version_extract(&text) {
         Some(version) => {
            assert!(version.major == expected_major &&
                    version.minor == expected_minor);
            true
         },
         None => false,
      }
   }
   fn check_error_version(string: &str) -> bool {
      check_version(string, 0, 0)
   }

   #[test]
   fn extract_correct_git_versions() {
      assert!(check_version("git version 2.10.2", 2, 10));
      assert!(check_version("git version 1.18.4", 1, 18));
      assert!(check_version("git version 1.0.", 1, 0));
      assert!(check_version("git version 1.8.5.6", 1, 8)); /* That's a Travis case! */
      assert!(check_version("git version 2.10.0-rc3", 2, 10));
   }

   #[test]
   fn extract_invalid_git_versions() {
      assert!(! check_error_version("git version 2 10 2"));
      assert!(! check_error_version("git version 1 18.4"));
      assert!(! check_error_version("1.18.4"));
      assert!(! check_error_version("scrambled"));
      assert!(! check_error_version("git version 1.18-rc0"));
   }
}