1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::borrow::Cow;
use std::collections::hash_map::HashMap;
use std::ffi::OsStr;
use std::fmt::{self, Debug};
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::iter;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use crates::chrono::{DateTime, Utc};
use crates::regex::Regex;
use crates::tempdir::TempDir;
use crates::thiserror::Error;

use git::{CommitId, GitContext, GitError, GitResult, Identity};

/// Steps which are involved in the submodule preparation process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// TODO: #[non_exhaustive]
pub enum SubmoduleIntent {
    /// Creating the directory for the submodule.
    CreateDirectory,
    /// Creating a `.git` file for the submodule.
    CreateGitFile,
    /// Writing a `.git` file for the submodule.
    WriteGitFile,
    /// This is here to force `_` matching right now.
    ///
    /// **DO NOT USE**
    #[doc(hidden)]
    _NonExhaustive,
}

impl fmt::Display for SubmoduleIntent {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let intent = match self {
            SubmoduleIntent::CreateDirectory => "create the directory structure",
            SubmoduleIntent::CreateGitFile => "create the .git file",
            SubmoduleIntent::WriteGitFile => "write the .git file",
            _ => unreachable!(),
        };

        write!(f, "{}", intent)
    }
}

/// Errors which may occur when using a workarea.
///
/// This enum is `non_exhaustive`, but cannot be marked as such until it is stable. In the
/// meantime, there is a hidden variant.
#[derive(Debug, Error)]
// TODO: #[non_exhaustive]
pub enum WorkAreaError {
    /// Failed to create a temporary directory for the workarea.
    #[error("failed to create workarea's temporary directory")]
    CreateTempDirectory {
        /// The cause of the failure.
        #[source]
        source: io::Error,
    },
    /// Failed to create a directory to hold the work tree.
    #[error("failed to create workarea's work tree directory")]
    CreateWorkTree {
        /// The cause of the failure.
        #[source]
        source: io::Error,
    },
    /// Failure to set up submodules in the workarea.
    #[error("failed to {} for the {} submodule", intent, submodule)]
    SubmoduleSetup {
        /// The action that failed.
        intent: SubmoduleIntent,
        /// The submodule that failed.
        submodule: String,
        /// The cause of the failure.
        #[source]
        source: io::Error,
    },
    /// A git operation failed.
    #[error("git error: {}", source)]
    Git {
        /// The cause of the failure.
        #[from]
        source: GitError,
    },
    /// This is here to force `_` matching right now.
    ///
    /// **DO NOT USE**
    #[doc(hidden)]
    #[error("unreachable...")]
    _NonExhaustive,
}

impl WorkAreaError {
    pub(crate) fn temp_directory(source: io::Error) -> Self {
        WorkAreaError::CreateTempDirectory {
            source,
        }
    }

    pub(crate) fn work_tree(source: io::Error) -> Self {
        WorkAreaError::CreateWorkTree {
            source,
        }
    }

    pub(crate) fn submodule<S>(intent: SubmoduleIntent, submodule: S, source: io::Error) -> Self
    where
        S: Into<String>,
    {
        WorkAreaError::SubmoduleSetup {
            intent,
            submodule: submodule.into(),
            source,
        }
    }
}

pub(crate) type WorkAreaResult<T> = Result<T, WorkAreaError>;

/// Representation of merge conflict possibilities.
#[derive(Debug)]
pub enum Conflict {
    /// A regular blob has conflicted.
    Path(PathBuf),
    /// A submodule points to a commit not merged into the target branch.
    SubmoduleNotMerged(PathBuf),
    /// The submodule points to a commit not present in the main repository.
    SubmoduleNotPresent(PathBuf),
    /// The submodule conflicts, but a resolution is available.
    ///
    /// This occurs when the submodule points to a commit not on the first-parent history of the
    /// target branch on both sides of the merge. The suggested commit is the oldest commit on the
    /// main branch which contains both branches.
    SubmoduleWithFix(PathBuf, CommitId),
}

impl Conflict {
    /// The path to the blob that for the conflict.
    pub fn path(&self) -> &Path {
        match *self {
            Conflict::Path(ref p)
            | Conflict::SubmoduleNotMerged(ref p)
            | Conflict::SubmoduleNotPresent(ref p)
            | Conflict::SubmoduleWithFix(ref p, _) => p,
        }
    }
}

impl PartialEq for Conflict {
    fn eq(&self, rhs: &Self) -> bool {
        self.path() == rhs.path()
    }
}

/// A command which has been prepared to create a merge commit.
pub struct MergeCommand<'a> {
    /// The merge command.
    command: Command,

    /// Phantom entry which is used to tie a merge command's lifetime to the `GitWorkArea` to which
    /// it applies.
    _phantom: PhantomData<&'a str>,
}

impl<'a> MergeCommand<'a> {
    /// Set the committer of the merge.
    pub fn committer(&mut self, committer: &Identity) -> &mut Self {
        self.command
            .env("GIT_COMMITTER_NAME", &committer.name)
            .env("GIT_COMMITTER_EMAIL", &committer.email);
        self
    }

    /// Set the authorship of the merge.
    pub fn author(&mut self, author: &Identity) -> &mut Self {
        self.command
            .env("GIT_AUTHOR_NAME", &author.name)
            .env("GIT_AUTHOR_EMAIL", &author.email);
        self
    }

    /// Set the authorship date of the merge.
    pub fn author_date(&mut self, when: DateTime<Utc>) -> &mut Self {
        self.command.env("GIT_AUTHOR_DATE", when.to_rfc2822());
        self
    }

    /// Commit the merge with the given commit message.
    ///
    /// Returns the ID of the merge commit itself.
    pub fn commit<M>(self, message: M) -> GitResult<CommitId>
    where
        M: AsRef<str>,
    {
        self.commit_impl(message.as_ref())
    }

    /// The implementation of the commit.
    ///
    /// This spawns the commit command, feeds the message in over its standard input, runs it and
    /// returns the new commit object's ID.
    fn commit_impl(mut self, message: &str) -> GitResult<CommitId> {
        let mut commit_tree = self
            .command
            .spawn()
            .map_err(|err| GitError::subcommand("commit-tree", err))?;

        {
            let commit_tree_stdin = commit_tree
                .stdin
                .as_mut()
                .expect("expected commit-tree to have a stdin");
            commit_tree_stdin
                .write_all(message.as_bytes())
                .map_err(|err| {
                    GitError::git_with_source(
                        "failed to write the commit message to commit-tree",
                        err,
                    )
                })?;
        }

        let commit_tree = commit_tree
            .wait_with_output()
            .map_err(|err| GitError::subcommand("commit-tree", err))?;
        if !commit_tree.status.success() {
            return Err(GitError::git(format!(
                "failed to commit the merged tree: {}",
                String::from_utf8_lossy(&commit_tree.stderr)
            )));
        }

        let merge_commit = String::from_utf8_lossy(&commit_tree.stdout);
        Ok(CommitId::new(merge_commit.trim()))
    }
}

impl<'a> Debug for MergeCommand<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("MergeCommand").finish()
    }
}

/// The result of an attempted merge.
#[derive(Debug)]
pub enum MergeResult<'a> {
    /// A merge conflict occurred.
    Conflict(Vec<Conflict>),
    /// The merge is ready to be committed.
    ///
    /// The command may be executed in order to create the commit from the merged tree.
    Ready(MergeCommand<'a>),
}

/// The configuration for submodules within the tree.
pub type SubmoduleConfig = HashMap<String, HashMap<String, String>>;

/// Intermediate type for setting up the workarea. Does not include submodules.
struct PreparingGitWorkArea {
    /// The context to work with.
    context: GitContext,
    /// The directory the workarea lives under.
    dir: TempDir,
}

/// A representation of an empty workarea where actions which require a work tree and an index may
/// be preformed.
#[derive(Debug)]
pub struct GitWorkArea {
    /// The context to work with.
    context: GitContext,
    /// The directory the workarea lives under.
    dir: TempDir,
    /// The submodule configuration for the workarea.
    submodule_config: SubmoduleConfig,
}

lazy_static! {
    // When reading `.gitmodules`, we need to extract configuration values. This regex matches it
    // and extracts the relevant parts.
    static ref SUBMODULE_CONFIG_RE: Regex =
        Regex::new(r"^submodule\.(?P<name>.*)\.(?P<key>[^=]*)=(?P<value>.*)$").unwrap();
}

/// A trait to abstract over both `GitWorkArea` and `PreparingGitWorkArea`.
trait WorkAreaGitContext {
    /// The `git` command for the workarea.
    fn cmd(&self) -> Command;
}

/// Checkout a set of paths into a workarea.
fn checkout<I, P>(ctx: &dyn WorkAreaGitContext, paths: I) -> GitResult<()>
where
    I: IntoIterator<Item = P>,
    P: AsRef<OsStr>,
{
    let ls_files = ctx
        .cmd()
        .arg("ls-files")
        .arg("--")
        .args(paths.into_iter())
        .output()
        .map_err(|err| GitError::subcommand("ls-files", err))?;
    if !ls_files.status.success() {
        return Err(GitError::git(format!(
            "listing paths in the index: {}",
            String::from_utf8_lossy(&ls_files.stderr)
        )));
    }

    checkout_files(ctx, &ls_files.stdout)
}

/// Checkout a set of files (in `git ls-files` format) into a workarea.
fn checkout_files(ctx: &dyn WorkAreaGitContext, files: &[u8]) -> GitResult<()> {
    let mut checkout_index = ctx
        .cmd()
        .arg("checkout-index")
        .arg("-f")
        .arg("-q")
        .arg("--stdin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|err| GitError::subcommand("checkout-index", err))?;
    checkout_index
        .stdin
        .as_mut()
        .expect("expected checkout-index to have a stdin")
        .write_all(files)
        .map_err(|err| GitError::git_with_source("writing to checkout-index", err))?;
    let res = checkout_index
        .wait()
        .expect("expected checkout-index to execute successfully");
    if !res.success() {
        let mut stderr = Vec::new();
        checkout_index
            .stderr
            .as_mut()
            .expect("expected checkout-index to have a stderr")
            .read_to_end(&mut stderr)
            .map_err(|err| GitError::git_with_source("failed to read from checkout-index", err))?;
        return Err(GitError::git(format!(
            "running checkout-index: {}",
            String::from_utf8_lossy(&stderr),
        )));
    }

    // Update the index for the files we put into the context
    let mut update_index = ctx
        .cmd()
        .arg("update-index")
        .arg("--stdin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|err| GitError::subcommand("update-index", err))?;
    update_index
        .stdin
        .as_mut()
        .expect("expected update-index to have a stdin")
        .write_all(files)
        .map_err(|err| GitError::git_with_source("writing to update-index", err))?;
    let res = update_index
        .wait()
        .expect("expected update-index to execute successfully");
    if !res.success() {
        let mut stderr = Vec::new();
        update_index
            .stderr
            .as_mut()
            .expect("expected update-index to have a stderr")
            .read_to_end(&mut stderr)
            .map_err(|err| GitError::git_with_source("failed to read from update-index", err))?;
        return Err(GitError::git(format!(
            "running update-index: {}",
            String::from_utf8_lossy(&stderr),
        )));
    }

    Ok(())
}

/// Get the file name of a path.
///
/// Used to simplify printing a filename.
fn file_name(path: &Path) -> Cow<str> {
    path.file_name()
        .map_or_else(|| Cow::Borrowed("<unknown>"), OsStr::to_string_lossy)
}

impl PreparingGitWorkArea {
    /// Create an area for performing actions which require a work tree.
    fn new(context: GitContext, rev: &CommitId) -> Result<Self, WorkAreaError> {
        let tempdir = TempDir::new_in(context.gitdir(), "git-work-area")
            .map_err(WorkAreaError::temp_directory)?;

        let workarea = Self {
            context,
            dir: tempdir,
        };

        debug!(target: "git.workarea",
               "creating prepared workarea under {}",
               workarea.dir.path().display());

        fs::create_dir_all(workarea.work_tree()).map_err(WorkAreaError::work_tree)?;
        workarea.prepare(rev)?;

        debug!(target: "git.workarea",
               "created prepared workarea under {}",
               file_name(workarea.dir.path()));

        Ok(workarea)
    }

    /// Set up the index file such that it things everything is OK, but no files are actually on
    /// the filesystem. Also sets up `.gitmodules` since it needs to be on disk for further
    /// preparations.
    fn prepare(&self, rev: &CommitId) -> GitResult<()> {
        // Read the base into the temporary index
        let res = self
            .git()
            .arg("read-tree")
            .arg("-i") // ignore the working tree
            .arg("-m") // perform a merge
            .arg(rev.as_str())
            .output()
            .map_err(|err| GitError::subcommand("read-tree", err))?;
        if !res.status.success() {
            return Err(GitError::git(format!(
                "reading the tree from {}: {}",
                rev,
                String::from_utf8_lossy(&res.stderr)
            )));
        }

        // Make the index believe the working tree is fine.
        self.git()
            .arg("update-index")
            .arg("--refresh")
            .arg("--ignore-missing")
            .arg("--skip-worktree")
            .stdout(Stdio::null())
            .status()
            .map_err(|err| GitError::subcommand("update-index", err))?;
        // Explicitly do not check the return code; it is a failure.

        // Checkout .gitmodules so that submodules work.
        checkout(self, iter::once(".gitmodules"))
    }

    /// Run a git command in the workarea.
    fn git(&self) -> Command {
        let mut git = self.context.git();

        git.env("GIT_WORK_TREE", self.work_tree())
            .env("GIT_INDEX_FILE", self.index());

        git
    }

    /// Create a `SubmoduleConfig` for the repository.
    fn query_submodules(&self) -> GitResult<SubmoduleConfig> {
        let module_path = self.work_tree().join(".gitmodules");
        if !module_path.exists() {
            return Ok(SubmoduleConfig::new());
        }

        let config = self
            .git()
            .arg("config")
            .arg("-f")
            .arg(module_path)
            .arg("-l")
            .output()
            .map_err(|err| GitError::subcommand("config -f .gitmodules", err))?;
        if !config.status.success() {
            return Err(GitError::git(format!(
                "reading the submodule configuration: {}",
                String::from_utf8_lossy(&config.stderr)
            )));
        }
        let config = String::from_utf8_lossy(&config.stdout);

        let mut submodule_config = SubmoduleConfig::new();

        let captures = config
            .lines()
            .filter_map(|l| SUBMODULE_CONFIG_RE.captures(l));
        for capture in captures {
            submodule_config
                .entry(
                    capture
                        .name("name")
                        .expect("the submodule regex should have a 'name' group")
                        .as_str()
                        .to_string(),
                )
                .or_insert_with(HashMap::new)
                .insert(
                    capture
                        .name("key")
                        .expect("the submodule regex should have a 'key' group")
                        .as_str()
                        .to_string(),
                    capture
                        .name("value")
                        .expect("the submodule regex should have a 'value' group")
                        .as_str()
                        .to_string(),
                );
        }

        let gitmoduledir = self.context.gitdir().join("modules");
        Ok(submodule_config
            .into_iter()
            .filter(|&(ref name, _)| gitmoduledir.join(name).exists())
            .collect())
    }

    /// The path to the index file for the work tree.
    fn index(&self) -> PathBuf {
        self.dir.path().join("index")
    }

    /// The path to the directory for the work tree.
    fn work_tree(&self) -> PathBuf {
        self.dir.path().join("work")
    }
}

impl WorkAreaGitContext for PreparingGitWorkArea {
    fn cmd(&self) -> Command {
        self.git()
    }
}

impl GitWorkArea {
    /// Create an area for performing actions which require a work tree.
    pub fn new(context: GitContext, rev: &CommitId) -> WorkAreaResult<Self> {
        let intermediate = PreparingGitWorkArea::new(context, rev)?;

        let workarea = Self {
            submodule_config: intermediate.query_submodules()?,
            context: intermediate.context,
            dir: intermediate.dir,
        };

        debug!(target: "git.workarea",
               "creating prepared workarea with submodules under {}",
               workarea.dir.path().display());

        workarea.prepare_submodules()?;

        debug!(target: "git.workarea",
               "created prepared workarea with submodules under {}",
               file_name(workarea.dir.path()));

        Ok(workarea)
    }

    /// Prepare requested submodules for use.
    fn prepare_submodules(&self) -> WorkAreaResult<()> {
        if self.submodule_config.is_empty() {
            return Ok(());
        }

        debug!(target: "git.workarea",
               "preparing submodules for {}",
               file_name(self.dir.path()));

        for (name, config) in &self.submodule_config {
            let gitdir = self.context.gitdir().join("modules").join(name);

            if !gitdir.exists() {
                error!(target: "git.workarea",
                       "{}: submodule configuration for {} does not exist: {}",
                       file_name(self.dir.path()),
                       name,
                       gitdir.display());

                continue;
            }

            let path = match config.get("path") {
                Some(path) => path,
                None => {
                    error!(target: "git.workarea",
                           "{}: submodule configuration for {}.path does not exist (skipping): {}",
                           file_name(self.dir.path()),
                           name,
                           gitdir.display());
                    continue;
                },
            };
            let gitfiledir = self.work_tree().join(path);
            fs::create_dir_all(&gitfiledir).map_err(|err| {
                WorkAreaError::submodule(SubmoduleIntent::CreateDirectory, name as &str, err)
            })?;

            let mut gitfile = File::create(gitfiledir.join(".git")).map_err(|err| {
                WorkAreaError::submodule(SubmoduleIntent::CreateGitFile, name as &str, err)
            })?;
            writeln!(gitfile, "gitdir: {}", gitdir.display()).map_err(|err| {
                WorkAreaError::submodule(SubmoduleIntent::WriteGitFile, name as &str, err)
            })?;
        }

        Ok(())
    }

    /// Run a git command in the workarea.
    pub fn git(&self) -> Command {
        let mut git = self.context.git();

        git.env("GIT_WORK_TREE", self.work_tree())
            .env("GIT_INDEX_FILE", self.index());

        git
    }

    /// Figure out if there's a possible resolution for the submodule.
    fn submodule_conflict<P>(
        &self,
        path: P,
        ours: &CommitId,
        theirs: &CommitId,
    ) -> GitResult<Conflict>
    where
        P: AsRef<Path>,
    {
        let path = path.as_ref().to_path_buf();

        debug!(target: "git.workarea",
               "{} checking for a submodule conflict for {}",
               file_name(self.dir.path()),
               path.display());

        let branch_info = self
            .submodule_config
            .iter()
            .find(|&(_, config)| {
                config.get("path").map_or(false, |submod_path| {
                    submod_path.as_str() == path.to_string_lossy()
                })
            })
            .map(|(name, config)| (name, config.get("branch").map_or("master", String::as_str)));

        let (name, branch) = if let Some((name, branch_name)) = branch_info {
            if branch_name == "." {
                // TODO(#6): Pass the branch name we are working on down to here.
                debug!(target: "git.workarea",
                       "the `.` branch specifier for submodules is not supported for conflict \
                        resolution");

                return Ok(Conflict::Path(path));
            }

            (name, branch_name)
        } else {
            debug!(target: "git.workarea",
                   "no submodule configured for {}; cannot attempt smarter resolution",
                   path.display());

            return Ok(Conflict::Path(path));
        };

        let submodule_ctx = GitContext::new(self.gitdir().join("modules").join(name));

        // NOTE: The submodule is assumed to be kept up-to-date externally.
        let refs = submodule_ctx
            .git()
            .arg("rev-list")
            .arg("--first-parent") // only look at first-parent history
            .arg("--reverse") // start with oldest commits
            .arg(branch)
            .arg(format!("^{}", ours))
            .arg(format!("^{}", theirs))
            .output()
            .map_err(|err| GitError::subcommand("rev-list new-submodule ^old-submodule", err))?;
        if !refs.status.success() {
            return Ok(Conflict::SubmoduleNotPresent(path));
        }
        let refs = String::from_utf8_lossy(&refs.stdout);

        for hash in refs.lines() {
            let ours_ancestor = submodule_ctx
                .git()
                .arg("merge-base")
                .arg("--is-ancestor")
                .arg(ours.as_str())
                .arg(hash)
                .status()
                .map_err(|err| GitError::subcommand("merge-base --is-ancestor ours", err))?;
            let theirs_ancestor = submodule_ctx
                .git()
                .arg("merge-base")
                .arg("--is-ancestor")
                .arg(theirs.as_str())
                .arg(hash)
                .status()
                .map_err(|err| GitError::subcommand("merge-base --is-ancestor theirs", err))?;

            if ours_ancestor.success() && theirs_ancestor.success() {
                return Ok(Conflict::SubmoduleWithFix(path, CommitId::new(hash)));
            }
        }

        Ok(Conflict::SubmoduleNotMerged(path))
    }

    /// Extract conflict information from the repository.
    fn conflict_information(&self) -> GitResult<Vec<Conflict>> {
        let ls_files = self
            .git()
            .arg("ls-files")
            .arg("-u")
            .output()
            .map_err(|err| GitError::subcommand("ls-files -u", err))?;
        if !ls_files.status.success() {
            return Err(GitError::git(format!(
                "listing unmerged files: {}",
                String::from_utf8_lossy(&ls_files.stderr)
            )));
        }
        let conflicts = String::from_utf8_lossy(&ls_files.stdout);

        let mut conflict_info = Vec::new();

        // Submodule conflict info scratch space
        let mut ours = CommitId::new(String::new());

        for conflict in conflicts.lines() {
            let info = conflict.split_whitespace().collect::<Vec<_>>();

            assert!(
                info.len() == 4,
                "expected 4 entries for a conflict, received {}",
                info.len(),
            );

            let permissions = info[0];
            let hash = info[1];
            let stage = info[2];
            let path = info[3];

            if permissions.starts_with("160000") {
                if stage == "1" {
                    // Nothing to do; we don't need to know the hash of the submodule at the
                    // mergebase of the two branches.
                    // old = hash.to_owned();
                } else if stage == "2" {
                    ours = CommitId::new(hash);
                } else if stage == "3" {
                    conflict_info.push(self.submodule_conflict(
                        path,
                        &ours,
                        &CommitId::new(hash),
                    )?);
                }
            } else {
                conflict_info.push(Conflict::Path(Path::new(path).to_path_buf()));
            }
        }

        Ok(conflict_info)
    }

    /// Checkout paths from the index to the filesystem.
    ///
    /// Normally, files are not placed into the worktree, so checks which use other tools to
    /// inspect file contents do not work. This method checks out files to the working directory
    /// and fixes up Git's knowledge that they are there.
    ///
    /// All paths supported by Git's globbing and searching mechanisms are supported.
    pub fn checkout<I, P>(&mut self, paths: I) -> GitResult<()>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<OsStr>,
    {
        checkout(self, paths)
    }

    /// Prepare a command to create a merge commit.
    ///
    /// The merge is performed, but only as a tree object. In order to create the actual commit
    /// object, a successful merge returns a command which should be executed to create the commit
    /// object. That commit object should then be stored in a reference using `git update-ref`.
    pub fn setup_merge<'a>(
        &'a self,
        bases: &[CommitId],
        base: &CommitId,
        topic: &CommitId,
    ) -> GitResult<MergeResult<'a>> {
        let merge_recursive = self
            .git()
            .arg("merge-recursive")
            .args(bases.iter().map(CommitId::as_str))
            .arg("--")
            .arg(base.as_str())
            .arg(topic.as_str())
            .output()
            .map_err(|err| GitError::subcommand("merge-recursive", err))?;
        if !merge_recursive.status.success() {
            return Ok(MergeResult::Conflict(self.conflict_information()?));
        }

        self.setup_merge_impl(base, topic)
    }

    /// Prepare a command to create a merge commit.
    ///
    /// The merge is performed, but only as a tree object. In order to create the actual commit
    /// object, a successful merge returns a command which should be executed to create the commit
    /// object. That commit object should then be stored in a reference using `git update-ref`.
    pub fn setup_update_merge<'a>(
        &'a self,
        base: &CommitId,
        topic: &CommitId,
    ) -> GitResult<MergeResult<'a>> {
        self.setup_merge_impl(base, topic)
    }

    /// Prepare a command to create a merge commit.
    ///
    /// This supports choosing the merge strategy.
    fn setup_merge_impl<'a>(
        &'a self,
        base: &CommitId,
        topic: &CommitId,
    ) -> GitResult<MergeResult<'a>> {
        debug!(target: "git.workarea",
               "merging {} into {}",
               topic,
               base);

        let write_tree = self
            .git()
            .arg("write-tree")
            .output()
            .map_err(|err| GitError::subcommand("write-tree", err))?;
        if !write_tree.status.success() {
            return Err(GitError::git(format!(
                "writing the tree object: {}",
                String::from_utf8_lossy(&write_tree.stderr)
            )));
        }
        let merged_tree = String::from_utf8_lossy(&write_tree.stdout);
        let merged_tree = merged_tree.trim();

        let mut commit_tree = self.git();

        commit_tree
            .arg("commit-tree")
            .arg(merged_tree)
            .arg("-p")
            .arg(base.as_str())
            .arg("-p")
            .arg(topic.as_str())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped());

        Ok(MergeResult::Ready(MergeCommand {
            command: commit_tree,
            _phantom: PhantomData,
        }))
    }

    /// The path to the index file for the workarea.
    fn index(&self) -> PathBuf {
        self.dir.path().join("index")
    }

    /// The path to the working directory for the workarea.
    fn work_tree(&self) -> PathBuf {
        self.dir.path().join("work")
    }

    /// Run a command from the work tree root.
    pub fn cd_to_work_tree<'a>(&self, cmd: &'a mut Command) -> &'a mut Command {
        cmd.current_dir(self.work_tree())
    }

    /// The path to the git repository.
    pub fn gitdir(&self) -> &Path {
        self.context.gitdir()
    }

    /// The submodule configuration for the repository.
    ///
    /// This is read from the `.gitmodules` file in the commit (if it exists).
    pub fn submodule_config(&self) -> &SubmoduleConfig {
        &self.submodule_config
    }

    /// The path to the working directory for the workarea.
    ///
    /// Only exported for testing purposes.
    #[cfg(test)]
    pub fn __work_tree(&self) -> PathBuf {
        self.work_tree()
    }
}

impl WorkAreaGitContext for GitWorkArea {
    fn cmd(&self) -> Command {
        self.git()
    }
}