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
// 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 chrono;
use self::chrono::{DateTime, UTC};

extern crate git_workarea;
use self::git_workarea::{CommitId, Conflict, GitContext, Identity, MergeResult, MergeStatus};

use super::error::*;

use std::borrow::Borrow;
use std::fmt::{self, Debug, Display};
use std::io::Write;

#[derive(Debug, Clone)]
/// A branch for the stager.
///
/// A separate type is used so that topic branches cannot be mixed up with other commits.
pub struct Topic {
    /// The HEAD commit of the topic branch.
    pub commit: CommitId,
    /// The author of the stage request.
    pub author: Identity,
    /// The timestamp for the request to be staged.
    pub stamp: DateTime<UTC>,
    /// An ID for the topic.
    pub id: u64,
    /// The name of the topic.
    pub name: String,
    /// The name of the topic.
    pub url: String,
}

impl Topic {
    /// The HEAD commit of the topic branch.
    pub fn new<N, U>(commit: CommitId, author: Identity, stamp: DateTime<UTC>, id: u64, name: N,
                     url: U)
                     -> Self
        where N: ToString,
              U: ToString,
    {
        Topic {
            commit: commit,
            author: author,
            stamp: stamp,
            id: id,
            name: name.to_string(),
            url: url.to_string(),
        }
    }
}

impl Display for Topic {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "topic {} at {}, staged by {} at {}",
               self.name,
               self.commit,
               self.author,
               self.stamp)
    }
}

impl PartialEq for Topic {
    fn eq(&self, rhs: &Self) -> bool {
        // The author and stamp time are explicitly not considered since they are not important to
        // the actual topic comparison once on the stage.
        self.commit == rhs.commit && self.id == rhs.id
    }
}

#[derive(Debug, Clone, PartialEq)]
/// A topic branch which should be integrated into the stage.
pub struct CandidateTopic {
    /// The old revision for the topic (if available).
    pub old_id: Option<Topic>,
    /// The new revision for the topic.
    pub new_id: Topic,
}

impl Display for CandidateTopic {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref old_topic) = self.old_id {
            write!(f, "candidate {}, replacing {}", self.new_id, old_topic)
        } else {
            write!(f, "candidate {}, new", self.new_id)
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
/// A topic branch which has been staged.
pub struct StagedTopic {
    /// The commit where the topic branch has been merged into the staging branch.
    pub merge: CommitId,
    /// The topic branch which was merged.
    pub topic: Topic,
}

impl StagedTopic {
    /// The topic branch which was merged.
    pub fn topic(&self) -> &Topic {
        &self.topic
    }

    /// The HEAD commit of the topic branch.
    pub fn commit(&self) -> &CommitId {
        &self.topic().commit
    }
}

impl Display for StagedTopic {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "staged {}, via {}", self.topic, self.merge)
    }
}

/// Reasons a branch was unstaged.
pub enum UnstageReason {
    /// A merge conflict occurred while attempting to merge a topic.
    MergeConflict(Vec<Conflict>),
}

impl Debug for UnstageReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UnstageReason::MergeConflict(ref conflicts) => {
                write!(f, "MergeConflict ( {} conflicts )", conflicts.len())
            },
        }
    }
}

#[derive(Debug)]
/// Reasons an old branch was removed from the stage.
pub enum OldTopicRemoval {
    /// The topic branch has been obsoleted.
    Obsoleted {
        /// The old topic, as staged.
        old_merge: StagedTopic,
        /// The staged topic branch which has replaced the old topic branch.
        replacement: Option<StagedTopic>,
    },
    /// The topic branch has been removed, without replacement, from the stage.
    Removed(StagedTopic),
}

impl OldTopicRemoval {
    /// The topic branch which was removed.
    pub fn branch(&self) -> &Topic {
        match *self {
            OldTopicRemoval::Obsoleted { old_merge: ref ob, .. } => &ob.topic,
            OldTopicRemoval::Removed(ref rb) => &rb.topic,
        }
    }
}

#[derive(Debug)]
/// Results from integrating a branch.
pub enum IntegrationResult {
    /// The branch was successfully staged.
    Staged(StagedTopic),
    /// The branch was kicked out of the staging branch.
    Unstaged(Topic, UnstageReason),
    /// The branch was not mergeable.
    Unmerged(Topic, MergeStatus),
}

impl IntegrationResult {
    /// The topic branch.
    pub fn topic(&self) -> &Topic {
        match *self {
            IntegrationResult::Staged(ref sb) => &sb.topic,
            IntegrationResult::Unstaged(ref u, _) => u,
            IntegrationResult::Unmerged(ref t, _) => t,
        }
    }

    /// Whether the topic branch is currently staged or not.
    pub fn on_stage(&self) -> bool {
        match *self {
            IntegrationResult::Staged(_) => true,
            IntegrationResult::Unstaged(_, _) |
            IntegrationResult::Unmerged(_, _) => false,
        }
    }
}

// The result of rewinding the stage back to a point where new commits may be applied.
//
// The order is such that the first pair represents the old state of the staged topics while the
// last pair represents the topics which need to be re-integrated into the staging branch.
type RewoundStage = (Option<StagedTopic>, Vec<StagedTopic>, Option<Topic>);

#[derive(Debug)]
/// The results of a stage operation.
pub struct StageResult {
    /// The branch which the operation removed from the stage
    pub old_topic: Option<OldTopicRemoval>,
    /// Results from reintegrating the other staged branches.
    pub results: Vec<IntegrationResult>,
}

#[derive(Debug)]
/// The actual stager.
///
/// This stores the state of a staging branch
pub struct Stager {
    ctx: GitContext,
    topics: Vec<StagedTopic>,
    identity: Identity,
}

static STAGE_TOPIC_PREFIX: &'static str = "Stage topic '";
static STAGE_TOPIC_SUFFIX: &'static str = "'";
static TOPIC_ID_TRAILER: &'static str = "Topic-id: ";
static TOPIC_URL_TRAILER: &'static str = "Topic-url: ";

impl Stager {
    /// Create a new stage from the given commit.
    pub fn new(ctx: &GitContext, base: CommitId, identity: Identity) -> Self {
        Stager {
            ctx: ctx.clone(),
            topics: vec![Self::make_base_staged_topic(base)],
            identity: identity,
        }
    }

    /// Create a new stage, discovering topic branches which have already been merged.
    ///
    /// This constructor takes a base branch and the name of the stage branch. It queries the given
    /// Git context for the history of the stage branch from the base and constructs its state from
    /// those commits.
    ///
    /// If the stage does not exist, it is created with the base commit as its start.
    ///
    /// Fails if the stage branch history does not appear to be a proper stage branch. A proper
    /// stage branch's first parent history from the base consists only of merge commits with
    /// exactly two parents.
    pub fn from_branch(ctx: &GitContext, base: CommitId, stage: CommitId, identity: Identity)
                       -> Result<Self> {
        let cat_file = try!(ctx.git()
            .arg("cat-file")
            .arg("-t")
            .arg(stage.as_str())
            .output()
            .chain_err(|| "failed to construct cat-file command"));
        if !cat_file.status.success() {
            let update_ref = try!(ctx.git()
                .arg("update-ref")
                .arg(stage.as_str())
                .arg(base.as_str())
                .output()
                .chain_err(|| "failed to construct update-ref command"));
            if !update_ref.status.success() {
                bail!(ErrorKind::Git(format!("failed to update the {} ref to {}: {}",
                                             stage,
                                             base,
                                             String::from_utf8_lossy(&update_ref.stderr))));
            }
        } else {
            let stage_type = String::from_utf8_lossy(&cat_file.stdout);
            if stage_type.trim() != "commit" {
                bail!(ErrorKind::InvalidIntegrationBranch(stage, InvalidCommitReason::NotACommit));
            }
        }

        let is_ancestor = try!(ctx.git()
            .arg("merge-base")
            .arg("--is-ancestor")
            .arg(base.as_str())
            .arg(stage.as_str())
            .status()
            .chain_err(|| "failed to construct merge-base command"));
        let needs_base_update = !is_ancestor.success();

        debug!(target: "git-topic-stage", "creating a stage branch from {} -> {}", base, stage);

        let rev_list = try!(ctx.git()
            .arg("rev-list")
            .arg("--first-parent")
            .arg("--reverse")
            .arg("--parents")
            .arg(stage.as_str())
            .arg(&format!("^{}", base))
            .output()
            .chain_err(|| "failed to construct rev-list command"));
        if !rev_list.status.success() {
            bail!(ErrorKind::Git(format!("failed to list the first parent history of the stage \
                                          branch: {}",
                                         String::from_utf8_lossy(&rev_list.stderr))));
        }
        let merges = String::from_utf8_lossy(&rev_list.stdout);

        let merge_base = try!(ctx.git()
            .arg("merge-base")
            .arg(base.as_str())
            .arg(stage.as_str())
            .output()
            .chain_err(|| "failed to construct merge-base command"));
        if !merge_base.status.success() {
            bail!(ErrorKind::InvalidIntegrationBranch(stage, InvalidCommitReason::NotRelated));
        }
        let merge_base = String::from_utf8_lossy(&merge_base.stdout);

        let mut topics = vec![Self::make_base_staged_topic(CommitId::new(merge_base.trim()))];

        let new_topics = try!(merges.lines()
            .map(|merge| {
                let revs = merge.split_whitespace().collect::<Vec<_>>();
                let (ref rev, ref parents) =
                    revs[..].split_first().expect("invalid rev-list format");
                let rev_commit = CommitId::new(rev);

                if parents.len() == 1 {
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit,
                                                              InvalidCommitReason::NonMergeCommit));
                }

                if parents.len() > 2 {
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit,
                                                              InvalidCommitReason::OctopusMerge));
                }

                let commit_info = try!(ctx.git()
                    .arg("log")
                    .arg("--max-count=1")
                    .arg("--pretty=%an%n%ae%n%aI%n%B")
                    .arg(rev)
                    .output()
                    .chain_err(|| "failed to construct log command"));
                if !commit_info.status.success() {
                    bail!(ErrorKind::Git(format!("failed to get information about a merge on \
                                                  the topic stage: {}",
                                                 String::from_utf8_lossy(&commit_info.stderr))));
                }
                let info = String::from_utf8_lossy(&commit_info.stdout);
                let info = info.lines().collect::<Vec<_>>();

                let subject = info[3];
                if !subject.starts_with(STAGE_TOPIC_PREFIX) ||
                   !subject.ends_with(STAGE_TOPIC_SUFFIX) {
                    let reason = InvalidCommitReason::InvalidSubject(subject.to_string());
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit, reason));
                }
                let name = &subject[STAGE_TOPIC_PREFIX.len()..subject.len() -
                                                              STAGE_TOPIC_SUFFIX.len()];

                let mut id = None;
                let mut url = None;

                for line in info[5..info.len() - 1].iter().rev() {
                    if line.is_empty() {
                        break;
                    } else if line.starts_with(TOPIC_ID_TRAILER) {
                        id = Some(try!(line[TOPIC_ID_TRAILER.len()..]
                            .parse()
                            .chain_err(|| ErrorKind::IdParse)));
                    } else if line.starts_with(TOPIC_URL_TRAILER) {
                        url = Some(line[TOPIC_URL_TRAILER.len()..].to_string());
                    } else {
                        warn!(target: "git-topic-stage",
                          "unrecognized trailier in {}: {}",
                          parents[1],
                          line);
                    }
                }

                if id.is_none() {
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit,
                                                              InvalidCommitReason::MissingId));
                }
                if url.is_none() {
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit,
                                                              InvalidCommitReason::MissingUrl));
                }

                if id.unwrap() == 0 {
                    bail!(ErrorKind::InvalidIntegrationBranch(rev_commit,
                                                              InvalidCommitReason::ZeroId));
                }

                info!(target: "git-topic-stage",
                  "found staged topic '{}' from {:?}",
                  name, url);

                Ok(StagedTopic {
                    merge: rev_commit,
                    topic: Topic::new(CommitId::new(parents[1]),
                                      Identity::new(info[0], info[1]),
                                      try!(info[2].parse().chain_err(|| ErrorKind::DateParse)),
                                      id.unwrap(),
                                      name,
                                      url.unwrap()),
                })
            })
            .collect::<Result<Vec<_>>>());

        topics.extend(new_topics.into_iter());

        let mut stager = Stager {
            ctx: ctx.clone(),
            topics: topics,
            identity: identity,
        };

        if needs_base_update {
            let base_update = CandidateTopic {
                old_id: Some(Self::make_base_topic(CommitId::new(merge_base.trim()))),
                new_id: Self::make_base_topic(base),
            };

            try!(stager.stage(base_update));
        }

        Ok(stager)
    }

    /// Returns the git context the stager uses for operations.
    pub fn git_context(&self) -> &GitContext {
        &self.ctx
    }

    /// Returns the identity the stager uses for its merges.
    pub fn identity(&self) -> &Identity {
        &self.identity
    }

    /// Returns the base branch for the integration branch.
    pub fn base(&self) -> &CommitId {
        self.topics[0].commit()
    }

    /// The topics which have been merged into the stage.
    pub fn topics(&self) -> &[StagedTopic] {
        &self.topics[1..]
    }

    /// The a topic on the stage by id.
    pub fn find_topic_by_id(&self, id: u64) -> Option<&StagedTopic> {
        let mut topics = self.topics[1..]
            .iter()
            .filter(|staged_topic| id == staged_topic.topic.id);

        topics.next()
    }

    /// Find a where a topic has been merged into the stage.
    pub fn find_topic(&self, topic: &Topic) -> Option<&StagedTopic> {
        let mut topics = self.topics[1..]
            .iter()
            .filter(|staged_topic| topic == &staged_topic.topic);

        topics.next()
    }

    /// Returns the newest commit in the integration branch.
    pub fn head(&self) -> &CommitId {
        &self.topics.iter().last().unwrap().merge
    }

    fn make_base_staged_topic(base: CommitId) -> StagedTopic {
        StagedTopic {
            merge: base.clone(),
            topic: Self::make_base_topic(base),
        }
    }

    fn make_base_topic(base: CommitId) -> Topic {
        Topic {
            commit: base,
            author: Identity::new("stager", "stager@example.com"),
            stamp: UTC::now(),
            id: 0,
            name: "base".to_string(),
            url: "url".to_string(),
        }
    }

    fn rewind_stage(&mut self, topic: CandidateTopic) -> RewoundStage {
        // Find the topic branch's old commit in the current stage.
        let root = topic.old_id
            .and_then(|old| self.topics.iter().position(|staged_topic| old == staged_topic.topic))
            .unwrap_or(self.topics.len());

        // Grab the branches which must be restaged.
        let mut old_stage = self.topics.drain(root..).collect::<Vec<_>>();

        if self.topics.is_empty() {
            debug!(target: "git-topic-stage", "rewinding the stage to its base");
        } else {
            debug!(target: "git-topic-stage", "rewinding the stage to {}", self.head());
        }

        let (old_topic, new_topic) = if self.topics.is_empty() {
            // TODO: Check that the new base is newer than the old base?

            // The base is being replaced.
            self.topics.push(Self::make_base_staged_topic(topic.new_id.commit));

            // The old topic branch is the first one in the list of branches that need to be
            // restaged, so remove it from the vector.
            (Some(old_stage.remove(0)), None)
        } else if !old_stage.is_empty() {
            // The old topic branch is the first one in the list of branches that need to be
            // restaged, so remove it from the vector.
            (Some(old_stage.remove(0)), Some(topic.new_id))
        } else {
            // This topic is brand new.
            (None, Some(topic.new_id))
        };

        (old_topic, old_stage, new_topic)
    }

    fn replay_stage(&mut self, old_stage: Vec<StagedTopic>) -> Result<Vec<IntegrationResult>> {
        debug!(target: "git-topic-stage", "replaying {} branches into the stage", old_stage.len());

        // Restage old branches.
        old_stage.into_iter()
            .map(|old_staged_topic| {
                let (staged, res) = try!(self.merge_to_stage(old_staged_topic.topic));
                staged.map(|t| self.topics.push(t));
                Ok(res)
            })
            .collect()
    }

    /// Remove a topic branch from the stage.
    pub fn unstage(&mut self, topic: StagedTopic) -> Result<StageResult> {
        info!(target: "git-topic-stage", "unstaging a topic: {}", topic);

        if topic.commit() == self.base() {
            debug!(target: "git-topic-stage", "ignoring a request to unstage the base");

            bail!(ErrorKind::CannotUnstageBase);
        }

        let (old_topic, old_stage, new_topic) = self.rewind_stage(CandidateTopic {
            old_id: Some(topic.topic.clone()),
            new_id: topic.topic,
        });

        let results = try!(self.replay_stage(old_stage));

        if new_topic.is_none() {
            // Requested the unstaging of the base branch.
            warn!(target: "git-topic-stage", "unstage called on the base branch");
        }

        if let Some(ref old_topic) = old_topic {
            debug!(target: "git-topic-stage", "unstaged {}", old_topic);
        }

        // Give some information about the old topic branch (if it existed).
        let old_branch_result = old_topic.map(OldTopicRemoval::Removed);

        Ok(StageResult {
            old_topic: old_branch_result,
            results: results,
        })
    }

    /// Add a topic branch to the stage.
    ///
    /// If the topic branch already existed on the staging branch, it is first removed from the
    /// stage and then any topic branches which were merged after it are merged again, in order.
    /// The updated topic branch is then merged as the last operation.
    pub fn stage(&mut self, topic: CandidateTopic) -> Result<StageResult> {
        info!(target: "git-topic-stage", "staging a topic: {}", topic);

        // Rewind the stage.
        let (old_topic, old_stage, new_topic) = self.rewind_stage(topic);

        let mut results = try!(self.replay_stage(old_stage));

        let old_branch_result = if let Some(topic) = new_topic {
            // Apply the new topic branch.
            let (staged, res) = try!(self.merge_to_stage(topic));

            staged.clone().map(|sb| self.topics.push(sb));
            results.push(res);

            // Give some information about the old topic branch (if it existed).
            old_topic.map(|topic| {
                OldTopicRemoval::Obsoleted {
                    old_merge: topic,
                    replacement: staged,
                }
            })
        } else {
            // The base of the branch was replaced; return the old stage base.
            old_topic.map(|topic| {
                OldTopicRemoval::Obsoleted {
                    old_merge: topic,
                    replacement: Some(self.topics[0].clone()),
                }
            })
        };

        Ok(StageResult {
            old_topic: old_branch_result,
            results: results,
        })
    }

    /// Remove all staged topics from the staging branch.
    ///
    /// Previously staged topics are returned.
    pub fn clear(&mut self) -> Vec<StagedTopic> {
        let new_id = Self::make_base_staged_topic(self.base().clone()).topic;
        let old_id = Some(new_id.clone());

        info!(target: "git-topic-stage", "clearing the stage");

        self.rewind_stage(CandidateTopic {
                old_id: old_id,
                new_id: new_id,
            })
            .1
    }

    fn merge_to_stage(&self, topic: Topic) -> Result<(Option<StagedTopic>, IntegrationResult)> {
        let base_commit = self.base();
        let head_commit = self.head();
        let topic_commit = topic.commit.clone();

        debug!(target: "git-topic-stage", "merging {} into the stage", topic);

        // Check that the topic is mergeable against the *base* commit. New root commits may have
        // appeared in topic branches that have since been merged. Checking against the base commit
        // ensures that it at least has a chance if it becomes the first branch on the stage again.
        let merge_status = try!(self.ctx.mergeable(&base_commit, &topic_commit));
        let bases = match merge_status {
            MergeStatus::Mergeable(bases) => bases,
            // Reject branches which are not mergeable.
            _ => {
                debug!(target: "git-topic-stage", "rejecting: unmergeable: {:?}", merge_status);
                return Ok((None, IntegrationResult::Unmerged(topic.clone(), merge_status)));
            },
        };

        // Prepare a workarea in which to perform the merge.
        let workarea = try!(self.ctx.prepare(head_commit));

        // Prepare the merged tree.
        let merge_result = try!(workarea.setup_merge(&bases, &head_commit, &topic_commit));

        let mut merge_command = match merge_result {
            MergeResult::Conflict(conflicts) => {
                debug!(target: "git-topic-stage", "rejecting: conflicts: {}", conflicts.len());

                return Ok((None,
                           IntegrationResult::Unstaged(topic,
                                                       UnstageReason::MergeConflict(conflicts))));
            },
            MergeResult::Ready(command) => command,
            MergeResult::_Phantom(..) => unreachable!(),
        };

        merge_command
            .env("GIT_COMMITTER_NAME", &self.identity.name)
            .env("GIT_COMMITTER_EMAIL", &self.identity.email)
            .env("GIT_AUTHOR_NAME", &topic.author.name)
            .env("GIT_AUTHOR_EMAIL", &topic.author.email)
            .env("GIT_AUTHOR_DATE", topic.stamp.to_rfc3339());

        // Create the merge commit.
        let mut commit_tree = try!(merge_command.spawn()
            .chain_err(|| "failed to construct commit-tree command"));

        // Write the commit message.
        {
            let mut commit_tree_stdin = commit_tree.stdin.as_mut().unwrap();
            try!(commit_tree_stdin.write_all(self.create_message(self.base(), &topic).as_bytes())
                .chain_err(|| {
                    ErrorKind::Git("failed to write the commit message to commit-tree".to_string())
                }));
        }

        let commit_tree = try!(commit_tree.wait_with_output()
            .chain_err(|| "failed to execute commit-tree command"));
        if !commit_tree.status.success() {
            bail!(ErrorKind::Git(format!("failed to commit the merge of the {} topic: {}",
                                         topic.name,
                                         String::from_utf8_lossy(&commit_tree.stderr))));
        }
        let merge_commit = String::from_utf8_lossy(&commit_tree.stdout);

        let merge_ref: &str = merge_commit.borrow();
        let staged_topic = StagedTopic {
            merge: CommitId::new(merge_ref.trim()),
            topic: topic,
        };

        debug!(target: "git-topic-stage", "successfully staged as {}", staged_topic);

        Ok((Some(staged_topic.clone()), IntegrationResult::Staged(staged_topic)))
    }

    fn create_message(&self, _: &CommitId, topic: &Topic) -> String {
        format!("{}{}{}\n\n{}{}\n{}{}\n",
                STAGE_TOPIC_PREFIX,
                topic.name,
                STAGE_TOPIC_SUFFIX,
                TOPIC_ID_TRAILER,
                topic.id,
                TOPIC_URL_TRAILER,
                topic.url)
    }
}