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
// Copyright 2016 Kitware, Inc.
//
// 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.

extern crate regex;
use self::regex::Regex;

extern crate tempdir;
use self::tempdir::TempDir;

use super::error::*;
use super::git::{CommitId, GitContext};

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

#[derive(Debug)]
/// Representation of merge conflict possibilities.
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 that conflicted.
    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()
    }
}

#[derive(Debug)]
/// The result of a merge.
pub enum MergeResult<'a> {
    /// Information about conflicts within the tree.
    Conflict(Vec<Conflict>),
    /// The merge is ready to be committed.
    Ready(Command),

    #[doc(hidden)]
    // Phantom entry which is used to tie a merge result's lifetime to the `PreparedGitWorkArea` to
    // which it applies.
    _Phantom(PhantomData<&'a str>),
}

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

// Intermediate type for setting up the work area. Does not include submodules.
pub struct PreparingGitWorkArea {
    context: GitContext,
    dir: TempDir,
}

#[derive(Debug)]
/// A representation of an empty work area where actions which require a work tree and an index may
/// be preformed.
pub struct PreparedGitWorkArea {
    context: GitContext,
    dir: TempDir,
    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();
}

impl PreparingGitWorkArea {
    // Create an area for performing actions which require a work tree.
    fn new(context: GitContext, rev: &CommitId) -> Result<Self> {
        let tempdir = try!(TempDir::new_in(context.gitdir(), "git-work-area")
            .chain_err(|| "failed to create temporary directory"));

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

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

        try!(fs::create_dir_all(workarea.work_tree())
            .chain_err(|| "failed to create the work area directory"));
        try!(workarea.prepare(rev));

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

        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) -> Result<()> {
        // Read the base into the temporary index
        let res = try!(self.git()
            .arg("read-tree")
            .arg("-i")  // ignore the working tree
            .arg("-m")  // perform a merge
            .arg(rev.as_str())
            .output()
            .chain_err(|| "failed to construct read-tree command"));
        if !res.status.success() {
            bail!(ErrorKind::Git(format!("reading the tree from {}: {}",
                                         rev,
                                         String::from_utf8_lossy(&res.stderr))));
        }

        // Make the index believe the working tree is fine.
        try!(self.git()
            .arg("update-index")
            .arg("--refresh")
            .arg("--ignore-missing")
            .arg("--skip-worktree")
            .stdout(Stdio::null())
            .status()
            .chain_err(|| "failed to construct update-index command"));
        // Explicitly do not check the return code; it is a failure.

        // Checkout .gitmodules so that submodules work.
        let ls_files = try!(self.git()
            .arg("ls-files")
            .arg("--")
            .arg(".gitmodules")
            .output()
            .chain_err(|| "failed to construct ls-files command for .gitmodules"));
        if !ls_files.status.success() {
            bail!(ErrorKind::Git(format!("listing .gitmodules files in the index: {}",
                                         String::from_utf8_lossy(&ls_files.stderr))));
        }
        let mut checkout_index = try!(self.git()
            .arg("checkout-index")
            .arg("-f")
            .arg("-q")
            .arg("--stdin")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .chain_err(|| "failed to construct checkout-index command"));
        try!(checkout_index.stdin
            .as_mut()
            .unwrap()
            .write_all(&ls_files.stdout)
            .chain_err(|| ErrorKind::Git("writing to checkout-index".to_string())));
        let res = checkout_index.wait().unwrap();
        if !res.success() {
            let mut stderr = String::new();
            try!(checkout_index.stderr
                .as_mut()
                .unwrap()
                .read_to_string(&mut stderr)
                .chain_err(|| "failed to read from checkout-index"));
            bail!(ErrorKind::Git(format!("running checkout-index for .gitmodules: {}", stderr)));
        }

        // Update the index for the files we put into the context
        let mut update_index = try!(self.git()
            .arg("update-index")
            .arg("--stdin")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .chain_err(|| "failed to construct update-index command"));
        try!(update_index.stdin
            .as_mut()
            .unwrap()
            .write_all(&ls_files.stdout)
            .chain_err(|| ErrorKind::Git("writing to update-index".to_string())));
        let res = update_index.wait().unwrap();
        if !res.success() {
            let mut stderr = String::new();
            try!(update_index.stderr
                .as_mut()
                .unwrap()
                .read_to_string(&mut stderr)
                .chain_err(|| "failed to read from update-index"));
            bail!(ErrorKind::Git(format!("running update-index for .gitmodules: {}", stderr)));
        }

        Ok(())
    }

    // Run a git command in the work area.
    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
    }

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

        let config = try!(self.git()
            .arg("config")
            .arg("-f")
            .arg(module_path)
            .arg("-l")
            .output()
            .chain_err(|| "failed to construct config command for submodules"));
        if !config.status.success() {
            bail!(ErrorKind::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").unwrap().as_str().to_string())
                .or_insert_with(HashMap::new)
                .insert(capture.name("key").unwrap().as_str().to_string(),
                        capture.name("value").unwrap().as_str().to_string());
        }

        let gitmoduledir = self.context.gitdir().join("modules");
        Ok(submodule_config.into_iter()
            .filter(|&(_, ref config)| {
                config.get("path")
                    .map(|path| gitmoduledir.join(path).exists())
                    .unwrap_or(false)
            })
            .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 PreparedGitWorkArea {
    /// Create an area for performing actions which require a work tree.
    pub fn new(context: GitContext, rev: &CommitId) -> Result<Self> {
        let intermediate = try!(PreparingGitWorkArea::new(context, rev));

        let workarea = PreparedGitWorkArea {
            submodule_config: try!(intermediate.query_submodules()),
            context: intermediate.context,
            dir: intermediate.dir,
        };

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

        try!(workarea.prepare_submodules());

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

        Ok(workarea)
    }

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

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

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

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

                continue;
            }

            let gitfiledir = self.work_tree().join(path);
            try!(fs::create_dir_all(&gitfiledir).chain_err(|| {
                format!("failed to create the {} submodule directory for the workarea",
                        name)
            }));

            let mut gitfile = try!(File::create(gitfiledir.join(".git"))
                .chain_err(|| format!("failed to create the .git file for the {} module", name)));
            try!(write!(gitfile, "gitdir: {}\n", gitdir.to_string_lossy())
                .chain_err(|| format!("failed to write the .git file for the {} module", name)));
        }

        Ok(())
    }

    /// Run a git command in the work area.
    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) -> Result<Conflict>
        where P: AsRef<Path>,
    {
        let path = path.as_ref().to_path_buf();

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

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

        let branch = if let Some(branch_name) = branch {
            if branch_name == "." {
                // TODO: 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));
            }

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

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

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

        // NOTE: The submodule is assumed to be kept up-to-date externally.
        let refs = try!(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()
            .chain_err(|| {
                "failed to construct rev-list command for submodule conflict resolution"
            }));
        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 = try!(submodule_ctx.git()
                .arg("merge-base")
                .arg("--is-ancestor")
                .arg(ours.as_str())
                .arg(hash)
                .status()
                .chain_err(|| {
                    "failed to construct merge-base command for submodule conflict resolution"
                }));
            let theirs_ancestor = try!(submodule_ctx.git()
                .arg("merge-base")
                .arg("--is-ancestor")
                .arg(theirs.as_str())
                .arg(hash)
                .status()
                .chain_err(|| {
                    "failed to construct merge-base command for submodule conflict resolution"
                }));

            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) -> Result<Vec<Conflict>> {
        let ls_files = try!(self.git()
            .arg("ls-files")
            .arg("-u")
            .output()
            .chain_err(|| "failed to construct ls-files command for conflict resolution"));
        if !ls_files.status.success() {
            bail!(ErrorKind::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![];

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

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

            assert!(info.len() == 4);

            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(try!(self.submodule_conflict(path,
                                                                    &ours,
                                                                    &CommitId::new(hash))));
                }
            } else {
                conflict_info.push(Conflict::Path(Path::new(path).to_path_buf()));
            }
        }

        Ok(conflict_info)
    }

    /// Prepare a command to create a merge commit. It does not actually perform the commit since
    /// authorship can be provided through the command's environment.
    pub fn setup_merge<'a>(&'a self, bases: &[CommitId], base: &CommitId, topic: &CommitId)
                           -> Result<MergeResult<'a>> {
        debug!(target: "git.workarea",
               "merging {} into {}",
               topic,
               base);

        let mut merge_recursive = self.git();
        merge_recursive.arg("merge-recursive");
        for base in bases {
            merge_recursive.arg(OsStr::new(base.as_str()));
        }
        let merge_recursive = try!(merge_recursive
            .arg("--")
            .arg(base.as_str())
            .arg(topic.as_str())
            .output()
            .chain_err(|| "failed to construct merge command"));
        if !merge_recursive.status.success() {
            return Ok(MergeResult::Conflict(try!(self.conflict_information())));
        }

        let write_tree = try!(self.git()
            .arg("write-tree")
            .output()
            .chain_err(|| "failed to construct write-tree command"));
        if !write_tree.status.success() {
            bail!(ErrorKind::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(commit_tree))
    }

    // 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")
    }

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

    /// The submodule configuration for the repository.
    pub fn submodule_config(&self) -> &SubmoduleConfig {
        &self.submodule_config
    }
}