File: cmd_merging.cc

package info (click to toggle)
monotone 0.31-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 20,680 kB
  • ctags: 14,801
  • sloc: cpp: 87,711; ansic: 64,862; sh: 5,691; lisp: 954; perl: 783; makefile: 509; python: 265; sql: 98; sed: 16
file content (875 lines) | stat: -rw-r--r-- 30,650 bytes parent folder | download
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
// Copyright (C) 2002 Graydon Hoare <graydon@pobox.com>
//
// This program is made available under the GNU GPL version 2.0 or
// greater. See the accompanying file COPYING for details.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.

#include <iostream>
#include <cstring>

#include "cmd.hh"
#include "diff_patch.hh"
#include "merge.hh"
#include "packet.hh"
#include "restrictions.hh"
#include "revision.hh"
#include "roster_merge.hh"
#include "transforms.hh"
#include "update.hh"
#include "work.hh"
#include "safe_map.hh"

using std::cout;
using std::map;
using std::set;
using std::string;
using std::vector;
using std::strlen;

using boost::shared_ptr;

static void
three_way_merge(roster_t const & ancestor_roster,
                roster_t const & left_roster, roster_t const & right_roster,
                roster_merge_result & result)
{
  MM(ancestor_roster);
  MM(left_roster);
  MM(right_roster);

  // Make some fake rids
  revision_id ancestor_rid(fake_id()); MM(ancestor_rid);
  revision_id left_rid(fake_id()); MM(left_rid);
  revision_id right_rid(fake_id()); MM(right_rid);
  
  // Mark up the ANCESTOR
  marking_map ancestor_markings; MM(ancestor_markings);
  mark_roster_with_no_parents(ancestor_rid, ancestor_roster, ancestor_markings);

  // Mark up the LEFT roster
  marking_map left_markings; MM(left_markings);
  mark_roster_with_one_parent(ancestor_roster, ancestor_markings,
                              left_rid, left_roster, left_markings);
  
  // Mark up the RIGHT roster
  marking_map right_markings; MM(right_markings);
  mark_roster_with_one_parent(ancestor_roster, ancestor_markings,
                              right_rid, right_roster, right_markings);

  // Make the synthetic graph, by creating uncommon ancestor sets
  std::set<revision_id> left_uncommon_ancestors, right_uncommon_ancestors;
  safe_insert(left_uncommon_ancestors, left_rid);
  safe_insert(right_uncommon_ancestors, right_rid);

  // And do the merge
  roster_merge(left_roster, left_markings, left_uncommon_ancestors,
               right_roster, right_markings, right_uncommon_ancestors,
               result);
}
  
CMD(update, N_("workspace"), "",
    N_("update workspace.\n"
       "This command modifies your workspace to be based off of a\n"
       "different revision, preserving uncommitted changes as it does so.\n"
       "If a revision is given, update the workspace to that revision.\n"
       "If not, update the workspace to the head of the branch."),
    options::opts::branch | options::opts::revision)
{
  if (args.size() > 0)
    throw usage(name);

  if (app.opts.revision_selectors.size() > 1)
    throw usage(name);

  app.require_workspace();

  // Figure out where we are

  revision_id old_rid;
  app.work.get_revision_id(old_rid);

  N(!null_id(old_rid),
    F("this workspace is a new project; cannot update"));

  // Figure out where we're going

  revision_id chosen_rid;
  if (app.opts.revision_selectors.size() == 0)
    {
      P(F("updating along branch '%s'") % app.opts.branch_name);
      set<revision_id> candidates;
      pick_update_candidates(old_rid, app, candidates);
      N(!candidates.empty(),
        F("your request matches no descendents of the current revision\n"
          "in fact, it doesn't even match the current revision\n"
          "maybe you want something like --revision=h:%s")
        % app.opts.branch_name);
      if (candidates.size() != 1)
        {
          P(F("multiple update candidates:"));
          for (set<revision_id>::const_iterator i = candidates.begin();
               i != candidates.end(); ++i)
            P(i18n_format("  %s") % describe_revision(app, *i));
          P(F("choose one with '%s update -r<id>'") % ui.prog_name);
          E(false, F("multiple update candidates remain after selection"));
        }
      chosen_rid = *(candidates.begin());
    }
  else
    {
      complete(app, app.opts.revision_selectors[0](), chosen_rid);
      N(app.db.revision_exists(chosen_rid),
        F("no such revision '%s'") % chosen_rid);
    }
  I(!null_id(chosen_rid));

  // do this notification before checking to see if we can bail out early,
  // because when you are at one of several heads, and you hit update, you
  // want to know that merging would let you update further.
  notify_if_multiple_heads(app);

  if (old_rid == chosen_rid)
    {
      P(F("already up to date at %s") % old_rid);
      // do still switch the workspace branch, in case they have used
      // update to switch branches.
      if (!app.opts.branch_name().empty())
        app.make_branch_sticky();
      return;
    }

  P(F("selected update target %s") % chosen_rid);

  // Fiddle around with branches, in an attempt to guess what the user
  // wants.
  
  bool switched_branch = false;
  {
    // figure out which branches the target is in
    vector< revision<cert> > certs;
    app.db.get_revision_certs(chosen_rid, branch_cert_name, certs);
    erase_bogus_certs(certs, app);

    set< utf8 > branches;
    for (vector< revision<cert> >::const_iterator i = certs.begin();
         i != certs.end(); i++)
      {
        cert_value b;
        decode_base64(i->inner().value, b);
        branches.insert(utf8(b()));
      }

    if (branches.find(app.opts.branch_name) != branches.end())
      {
        L(FL("using existing branch %s") % app.opts.branch_name());
      }
    else
      {
        P(F("target revision is not in current branch"));
        if (branches.size() > 1)
          {
            // multiple non-matching branchnames
            string branch_list;
            for (set<utf8>::const_iterator i = branches.begin();
                 i != branches.end(); i++)
              branch_list += "\n  " + (*i)();
            N(false, F("target revision is in multiple branches:%s\n\n"
                       "try again with explicit --branch") % branch_list);
          }
        else if (branches.size() == 1)
          {
            // one non-matching, inform and update
            app.opts.branch_name = (*(branches.begin()))();
            switched_branch = true;
            P(F("switching to branch %s") % app.opts.branch_name());
          }
        else
          {
            I(branches.size() == 0);
            W(F("target revision not in any branch\n"
                "next commit will use branch %s")
              % app.opts.branch_name());
          }
      }
  }


  // Okay, we have a target, we have a branch, let's do this merge!

  // We have:
  //
  //    old  --> working
  //     |         |
  //     V         V
  //  chosen --> merged
  //
  // - old is the revision specified in _MTN/revision
  // - working is based on old and includes the workspace's changes
  // - chosen is the revision we're updating to and will end up in _MTN/revision
  // - merged is the merge of working and chosen, that will become the new
  //   workspace
  //
  // we apply the working to merged cset to the workspace
  // and write the cset from chosen to merged changeset in _MTN/work
  
  temp_node_id_source nis;

  // Get the OLD and WORKING rosters
  shared_ptr<roster_t> old_roster = shared_ptr<roster_t>(new roster_t());
  MM(*old_roster);
  roster_t working_roster; MM(working_roster);
  app.work.get_base_and_current_roster_shape(*old_roster, working_roster, nis);
  app.work.update_current_roster_from_filesystem(working_roster);

  // Get the CHOSEN roster
  roster_t chosen_roster; MM(chosen_roster);
  app.db.get_roster(chosen_rid, chosen_roster);
  
  // And finally do the merge
  roster_merge_result result;
  three_way_merge(*old_roster, working_roster, chosen_roster, result);

  roster_t & merged_roster = result.roster;

  content_merge_workspace_adaptor wca(app, old_roster);
  resolve_merge_conflicts(working_roster, chosen_roster,
                          result, wca, app);

  // Make sure it worked...
  I(result.is_clean());
  merged_roster.check_sane(true);

  // Now finally modify the workspace
  cset update;
  make_cset(working_roster, merged_roster, update);
  app.work.perform_content_update(update, wca);

  revision_t remaining;
  make_revision_for_workspace(chosen_rid, chosen_roster,
                              merged_roster, remaining);

  // small race condition here...
  app.work.put_work_rev(remaining);

  if (!app.opts.branch_name().empty())
    {
      app.make_branch_sticky();
    }
  if (switched_branch)
    P(F("switched branch; next commit will use branch %s") % app.opts.branch_name());
  P(F("updated to base revision %s") % chosen_rid);

  app.work.update_any_attrs();
  app.work.maybe_update_inodeprints();
}

// Subroutine of CMD(merge) and CMD(explicit_merge).  Merge LEFT with RIGHT,
// placing results onto BRANCH.  Note that interactive_merge_and_store may
// bomb out, and therefore so may this.
static void
merge_two(revision_id const & left, revision_id const & right,
          string const & branch, string const & caller, app_state & app)
{
  // The following mess constructs a neatly formatted log message that looks
  // like this:
  //    CALLER of 'LEFT'
  //          and 'RIGHT'
  //    to branch 'BRANCH'
  // where the last line is left out if we're merging onto the current branch.
  // We use a stringstream because boost::format does not support %-*s.
  using std::ostringstream;
  using std::setw;
  using std::max;

  ostringstream log;
  size_t fieldwidth = max(caller.size() + strlen(" of '"), strlen("and '"));

  if (branch != app.opts.branch_name())
    fieldwidth = max(fieldwidth, strlen("to branch '"));

  log << setw(fieldwidth - strlen(" of '")) << caller << " of '" << left
      << "'\n" << setw(fieldwidth) << "and '" << right
      << "'\n";

  if (branch != app.opts.branch_name())
    log << setw(fieldwidth) << "to branch '" << branch << "'\n";

  // Now it's time for the real work.
  P(F("[left]  %s") % left);
  P(F("[right] %s") % right);
  
  revision_id merged;
  transaction_guard guard(app.db);
  interactive_merge_and_store(left, right, merged, app);

  packet_db_writer dbw(app);
  cert_revision_in_branch(merged, branch, app, dbw);
  cert_revision_changelog(merged, log.str(), app, dbw);

  guard.commit();
  P(F("[merged] %s") % merged);
}

// should merge support --message, --message-file?  It seems somewhat weird,
// since a single 'merge' command may perform arbitrarily many actual merges.
// (Possibility: append the --message/--message-file text to the synthetic
// log message constructed in merge_two().)
CMD(merge, N_("tree"), "", N_("merge unmerged heads of branch"),
    options::opts::branch | options::opts::date | options::opts::author)
{
  typedef std::pair<revision_id, revision_id> revpair;
  typedef set<revision_id>::const_iterator rid_set_iter;

  if (args.size() != 0)
    throw usage(name);

  N(app.opts.branch_name() != "",
    F("please specify a branch, with --branch=BRANCH"));

  set<revision_id> heads;
  get_branch_heads(app.opts.branch_name(), app, heads);

  N(heads.size() != 0, F("branch '%s' is empty") % app.opts.branch_name);
  if (heads.size() == 1)
    {
      P(F("branch '%s' is already merged") % app.opts.branch_name);
      return;
    }

  P(FP("%d head on branch '%s'", "%d heads on branch '%s'", heads.size())
    % heads.size() % app.opts.branch_name);

  map<revision_id, revpair> heads_for_ancestor;
  set<revision_id> ancestors;
  size_t pass = 1, todo = heads.size() - 1;

  // If there are more than two heads to be merged, on each iteration we
  // merge a pair whose least common ancestor is not an ancestor of any
  // other pair's least common ancestor.  For example, if the history graph
  // looks like this:
  //
  //            X
  //           / \.                      (periods to prevent multi-line
  //          Y   C                       comment warnings)
  //         / \.
  //        A   B
  //
  // A and B will be merged first, and then the result will be merged with C.
  while (heads.size() > 2)
    {
      P(F("merge %d / %d:") % pass % todo);
      P(F("calculating best pair of heads to merge next"));

      // For every pair of heads, determine their merge ancestor, and
      // remember the ancestor->head mapping. 
      for (rid_set_iter i = heads.begin(); i != heads.end(); ++i)
        for (rid_set_iter j = i; j != heads.end(); ++j)
          {
            // It is not possible to initialize j to i+1 (set iterators
            // expose neither operator+ nor a nondestructive next() method)
            if (j == i)
              continue;

            revision_id ancestor;
            find_common_ancestor_for_merge(*i, *j, ancestor, app);
            
            // More than one pair might have the same ancestor (e.g. if we
            // have three heads all with the same parent); as this table
            // will be recalculated on every pass, we just take the first
            // one we find.
            if (ancestors.insert(ancestor).second)
              safe_insert(heads_for_ancestor, std::make_pair(ancestor, revpair(*i, *j)));
          }
    
      // Erasing ancestors from ANCESTORS will now produce a set of merge
      // ancestors each of which is not itself an ancestor of any other
      // merge ancestor.
      erase_ancestors(ancestors, app);
      I(ancestors.size() > 0);

      // Take the first ancestor from the above set and merge its
      // corresponding pair of heads.
      revpair p = heads_for_ancestor[*ancestors.begin()];
      
      merge_two(p.first, p.second, app.opts.branch_name(), string("merge"), app);

      ancestors.clear();
      heads_for_ancestor.clear();
      get_branch_heads(app.opts.branch_name(), app, heads);
      pass++;
    }

  // Last one.
  I(pass == todo);
  if (todo > 1)
    P(F("merge %d / %d:") % pass % todo);

  rid_set_iter i = heads.begin();
  revision_id left = *i++;
  revision_id right = *i++;
  I(i == heads.end());
  
  merge_two(left, right, app.opts.branch_name(), string("merge"), app);
  P(F("note: your workspaces have not been updated"));
}

CMD(propagate, N_("tree"), N_("SOURCE-BRANCH DEST-BRANCH"),
    N_("merge from one branch to another asymmetrically"),
    options::opts::date | options::opts::author | options::opts::message | options::opts::msgfile)
{
  if (args.size() != 2)
    throw usage(name);
  vector<utf8> a = args;
  a.push_back(utf8());
  process(app, "merge_into_dir", a);
}

CMD(merge_into_dir, N_("tree"), N_("SOURCE-BRANCH DEST-BRANCH DIR"),
    N_("merge one branch into a subdirectory in another branch"),
    options::opts::date | options::opts::author | options::opts::message | options::opts::msgfile)
{
  //   This is a special merge operator, but very useful for people
  //   maintaining "slightly disparate but related" trees. It does a one-way
  //   merge; less powerful than putting things in the same branch and also
  //   more flexible.
  //
  //   1. Check to see if src and dst branches are merged, if not abort, if so
  //   call heads N1 and N2 respectively.
  //
  //   2. (FIXME: not yet present) Run the hook propagate ("src-branch",
  //   "dst-branch", N1, N2) which gives the user a chance to massage N1 into
  //   a state which is likely to "merge nicely" with N2, eg. edit pathnames,
  //   omit optional files of no interest.
  //
  //   3. Do a normal 2 or 3-way merge on N1 and N2, depending on the
  //   existence of common ancestors.
  //
  //   4. Save the results as the delta (N2,M), the ancestry edges (N1,M)
  //   and (N2,M), and the cert (N2,dst).
  //
  //   There are also special cases we have to check for where no merge is
  //   actually necessary, because there hasn't been any divergence since the
  //   last time propagate was run.
  //
  //   If dir is not the empty string, rename the root of N1 to have the name
  //   'dir' in the merged tree. (ie, it has name "basename(dir)", and its
  //   parent node is "N2.get_node(dirname(dir))")

  set<revision_id> src_heads, dst_heads;

  if (args.size() != 3)
    throw usage(name);

  get_branch_heads(idx(args, 0)(), app, src_heads);
  get_branch_heads(idx(args, 1)(), app, dst_heads);

  N(src_heads.size() != 0, F("branch '%s' is empty") % idx(args, 0)());
  N(src_heads.size() == 1, F("branch '%s' is not merged") % idx(args, 0)());

  N(dst_heads.size() != 0, F("branch '%s' is empty") % idx(args, 1)());
  N(dst_heads.size() == 1, F("branch '%s' is not merged") % idx(args, 1)());

  set<revision_id>::const_iterator src_i = src_heads.begin();
  set<revision_id>::const_iterator dst_i = dst_heads.begin();

  P(F("propagating %s -> %s") % idx(args,0) % idx(args,1));
  P(F("[source] %s") % *src_i);
  P(F("[target] %s") % *dst_i);

  // check for special cases
  if (*src_i == *dst_i || is_ancestor(*src_i, *dst_i, app))
    {
      P(F("branch '%s' is up-to-date with respect to branch '%s'")
          % idx(args, 1)() % idx(args, 0)());
      P(F("no action taken"));
    }
  else if (is_ancestor(*dst_i, *src_i, app))
    {
      P(F("no merge necessary; putting %s in branch '%s'")
        % (*src_i) % idx(args, 1)());
      transaction_guard guard(app.db);
      packet_db_writer dbw(app);
      cert_revision_in_branch(*src_i, idx(args, 1)(), app, dbw);
      guard.commit();
    }
  else
    {
      revision_id merged;
      transaction_guard guard(app.db);

      {
        revision_id const & left_rid(*src_i), & right_rid(*dst_i);
        roster_t left_roster, right_roster;
        MM(left_roster);
        MM(right_roster);
        marking_map left_marking_map, right_marking_map;
        set<revision_id> 
          left_uncommon_ancestors, 
          right_uncommon_ancestors;

        app.db.get_roster(left_rid, left_roster, left_marking_map);
        app.db.get_roster(right_rid, right_roster, right_marking_map);
        app.db.get_uncommon_ancestors(left_rid, right_rid,
                                      left_uncommon_ancestors,
                                      right_uncommon_ancestors);

        {
          dir_t moved_root = left_roster.root();
          split_path sp, dirname;
          path_component basename;
          MM(dirname);
          if (!idx(args,2)().empty())
            {
              file_path_external(idx(args,2)).split(sp);
              dirname_basename(sp, dirname, basename);
              N(right_roster.has_node(dirname),
                F("Path %s not found in destination tree.") % sp);
              node_t parent = right_roster.get_node(dirname);
              moved_root->parent = parent->self;
              moved_root->name = basename;
              marking_map::iterator 
                i = left_marking_map.find(moved_root->self);
              I(i != left_marking_map.end());
              i->second.parent_name.clear();
              i->second.parent_name.insert(left_rid);
            }
        }

        roster_merge_result result;
        roster_merge(left_roster, 
                     left_marking_map, 
                     left_uncommon_ancestors,
                     right_roster, 
                     right_marking_map, 
                     right_uncommon_ancestors,
                     result);

        content_merge_database_adaptor 
          dba(app, left_rid, right_rid, left_marking_map);

        resolve_merge_conflicts(left_roster, right_roster,
                                result, dba, app);

        {
          dir_t moved_root = left_roster.root();
          moved_root->parent = the_null_node;
          moved_root->name = the_null_component;
        }

        // Write new files into the db.
        store_roster_merge_result(left_roster, right_roster, result,
                                  left_rid, right_rid, merged,
                                  app);
      }

      packet_db_writer dbw(app);

      cert_revision_in_branch(merged, idx(args, 1)(), app, dbw);

      bool log_message_given;
      utf8 log_message;
      process_commit_message_args(log_message_given, log_message, app);
      if (!log_message_given)
        log_message = (FL("propagate from branch '%s' (head %s)\n"
                          "            to branch '%s' (head %s)\n")
                       % idx(args, 0) % (*src_i)
                       % idx(args, 1) % (*dst_i)).str();

      cert_revision_changelog(merged, log_message, app, dbw);

      guard.commit();
      P(F("[merged] %s") % merged);
    }
}

CMD(explicit_merge, N_("tree"),
    N_("LEFT-REVISION RIGHT-REVISION DEST-BRANCH"),
    N_("merge two explicitly given revisions, "
       "placing result in given branch"),
    options::opts::date | options::opts::author)
{
  revision_id left, right;
  string branch;

  if (args.size() != 3)
    throw usage(name);

  complete(app, idx(args, 0)(), left);
  complete(app, idx(args, 1)(), right);
  branch = idx(args, 2)();

  N(!(left == right),
    F("%s and %s are the same revision, aborting") % left % right);
  N(!is_ancestor(left, right, app),
    F("%s is already an ancestor of %s") % left % right);
  N(!is_ancestor(right, left, app),
    F("%s is already an ancestor of %s") % right % left);

  merge_two(left, right, branch, string("explicit merge"), app);
}

CMD(show_conflicts, N_("informative"), N_("REV REV"), 
    N_("Show what conflicts would need to be resolved "
       "to merge the given revisions."),
    options::opts::branch | options::opts::date | options::opts::author)
{
  if (args.size() != 2)
    throw usage(name);
  revision_id l_id, r_id;
  complete(app, idx(args,0)(), l_id);
  complete(app, idx(args,1)(), r_id);                                                                    
  N(!is_ancestor(l_id, r_id, app),
    F("%s is an ancestor of %s; no merge is needed.") % l_id % r_id);
  N(!is_ancestor(r_id, l_id, app),
    F("%s is an ancestor of %s; no merge is needed.") % r_id % l_id);
  roster_t l_roster, r_roster;
  marking_map l_marking, r_marking;
  app.db.get_roster(l_id, l_roster, l_marking);
  app.db.get_roster(r_id, r_roster, r_marking);
  set<revision_id> l_uncommon_ancestors, r_uncommon_ancestors;
  app.db.get_uncommon_ancestors(l_id, r_id,
                                l_uncommon_ancestors,
                                r_uncommon_ancestors);
  roster_merge_result result;
  roster_merge(l_roster, l_marking, l_uncommon_ancestors,
               r_roster, r_marking, r_uncommon_ancestors,
               result);

  P(F("There are %s node_name_conflicts.") 
    % result.node_name_conflicts.size());
  P(F("There are %s file_content_conflicts.") 
    % result.file_content_conflicts.size());
  P(F("There are %s node_attr_conflicts.") 
    % result.node_attr_conflicts.size());
  P(F("There are %s orphaned_node_conflicts.") 
    % result.orphaned_node_conflicts.size());
  P(F("There are %s rename_target_conflicts.") 
    % result.rename_target_conflicts.size());
  P(F("There are %s directory_loop_conflicts.") 
    % result.directory_loop_conflicts.size());
}                                                                

CMD(pluck, N_("workspace"), N_("[-r FROM] -r TO [PATH...]"),
    N_("Apply changes made at arbitrary places in history to current workspace.\n"
       "This command takes changes made at any point in history, and\n"
       "edits your current workspace to include those changes.  The end result\n"
       "is identical to 'mtn diff -r FROM -r TO | patch -p0', except that\n"
       "this command uses monotone's merger, and thus intelligently handles\n"
       "renames, conflicts, and so on.\n"
       "\n"
       "If one revision is given, applies the changes made in that revision\n"
       "compared to its parent.\n"                                                                                  
       "\n"
       "If two revisions are given, applies the changes made to get from the\n"  
       "first revision to the second."),
    options::opts::revision | options::opts::depth | options::opts::exclude)
{
  // Work out our arguments
  revision_id from_rid, to_rid;

  if (app.opts.revision_selectors.size() == 1)
    {
      complete(app, idx(app.opts.revision_selectors, 0)(), to_rid);
      N(app.db.revision_exists(to_rid),
        F("no such revision '%s'") % to_rid);
      std::set<revision_id> parents;
      app.db.get_revision_parents(to_rid, parents);
      N(parents.size() == 1,
        F("revision %s is a merge\n"
          "to apply the changes relative to one of its parents, use:\n"
          "  %s pluck -r PARENT -r %s")
        % to_rid
        % ui.prog_name % to_rid);
      from_rid = *parents.begin();
    }
  else if (app.opts.revision_selectors.size() == 2)
    {
      complete(app, idx(app.opts.revision_selectors, 0)(), from_rid);
      N(app.db.revision_exists(from_rid),
        F("no such revision '%s'") % from_rid);
      complete(app, idx(app.opts.revision_selectors, 1)(), to_rid);
      N(app.db.revision_exists(to_rid),
        F("no such revision '%s'") % to_rid);
    }
  else
    throw usage(name);
  
  app.require_workspace();

  N(!(from_rid == to_rid), F("no changes to apply"));

  // notionally, we have the situation
  //
  // from --> working
  //   |         | 
  //   V         V
  //   to --> merged
  //
  // - from is the revision we start plucking from
  // - to is the revision we stop plucking at
  // - working is the current contents of the workspace
  // - merged is the result of the plucking, and achieved by running a
  //   merge in the fictional graph seen above
  //
  // To perform the merge, we use the real from roster, and the real working
  // roster, but synthesize a temporary 'to' roster.  This ensures that the
  // 'from', 'working' and 'base' rosters all use the same nid namespace,
  // while any additions that happened between 'from' and 'to' should be
  // considered as new nodes, even if the file that was added is in fact in
  // 'working' already -- so 'to' needs its own namespace.  (Among other
  // things, it is impossible with our merge formalism to have the above
  // graph with a node that exists in 'to' and 'working', but not 'from'.)
  //
  // finally, we take the cset from working -> merged, and apply that to the
  //   workspace
  // and take the cset from the workspace's base, and write that to _MTN/work

  // The node id source we'll use for the 'working' and 'to' rosters.
  temp_node_id_source nis;

  // Get the FROM roster
  shared_ptr<roster_t> from_roster = shared_ptr<roster_t>(new roster_t());
  MM(*from_roster);
  app.db.get_roster(from_rid, *from_roster);

  // Get the WORKING roster, and also the base roster while we're at it
  roster_t working_roster; MM(working_roster);
  roster_t base_roster; MM(base_roster);
  app.work.get_base_and_current_roster_shape(base_roster, working_roster, nis);
  app.work.update_current_roster_from_filesystem(working_roster);

  // Get the FROM->TO cset...
  cset from_to_to; MM(from_to_to);
  cset from_to_to_excluded; MM(from_to_to_excluded);
  {
    roster_t to_true_roster;
    app.db.get_roster(to_rid, to_true_roster);
    node_restriction mask(args_to_paths(args),
                          args_to_paths(app.opts.exclude_patterns),
                          app.opts.depth,
                          *from_roster, to_true_roster, app);
    make_restricted_csets(*from_roster, to_true_roster,
                          from_to_to, from_to_to_excluded,
                          mask);
    check_restricted_cset(*from_roster, from_to_to);
  }
  N(!from_to_to.empty(), F("no changes to be applied"));
  // ...and use it to create the TO roster
  roster_t to_roster; MM(to_roster);
  {
    to_roster = *from_roster;
    editable_roster_base editable_to_roster(to_roster, nis);
    from_to_to.apply_to(editable_to_roster);
  }

  // Now do the merge
  roster_merge_result result;
  three_way_merge(*from_roster, working_roster, to_roster, result);

  roster_t & merged_roster = result.roster;

  content_merge_workspace_adaptor wca(app, from_roster);
  resolve_merge_conflicts(working_roster, to_roster,
                          result, wca, app);

  I(result.is_clean());
  // temporary node ids may appear
  merged_roster.check_sane(true);

  // we apply the working to merged cset to the workspace 
  cset update;
  MM(update);
  make_cset(working_roster, merged_roster, update);
  E(!update.empty(), F("no changes were applied"));
  app.work.perform_content_update(update, wca);

  P(F("applied changes to workspace"));

  // and record any remaining changes in _MTN/revision
  revision_id base_id;
  revision_t remaining;
  MM(remaining);
  app.work.get_revision_id(base_id);
  make_revision_for_workspace(base_id, base_roster, merged_roster, remaining);

  // small race condition here...
  app.work.put_work_rev(remaining);
  app.work.update_any_attrs();
  
  // add a note to the user log file about what we did
  {
    utf8 log;
    app.work.read_user_log(log);
    std::string log_str = log();
    if (!log_str.empty())
      log_str += "\n";
    if (from_to_to_excluded.empty())
      log_str += (FL("applied changes from %s\n"
                     "             through %s\n")
                  % from_rid % to_rid).str();
    else
      log_str += (FL("applied partial changes from %s\n"
                     "                     through %s\n")
                  % from_rid % to_rid).str();
    app.work.write_user_log(utf8(log_str));
  }
}

CMD(heads, N_("tree"), "", N_("show unmerged head revisions of branch"),
    options::opts::branch)
{
  set<revision_id> heads;
  if (args.size() != 0)
    throw usage(name);

  N(app.opts.branch_name() != "",
    F("please specify a branch, with --branch=BRANCH"));

  get_branch_heads(app.opts.branch_name(), app, heads);

  if (heads.size() == 0)
    P(F("branch '%s' is empty") % app.opts.branch_name);
  else if (heads.size() == 1)
    P(F("branch '%s' is currently merged:") % app.opts.branch_name);
  else
    P(F("branch '%s' is currently unmerged:") % app.opts.branch_name);

  for (set<revision_id>::const_iterator i = heads.begin();
       i != heads.end(); ++i)
    cout << describe_revision(app, *i) << "\n";
}

CMD(get_roster, N_("debug"), N_("REVID"),
    N_("dump the roster associated with the given REVID"),
    options::opts::none)
{
  revision_id rid;
  if (args.size() == 0)
    app.work.get_revision_id(rid);
  else if (args.size() == 1)
    complete(app, idx(args, 0)(), rid);
  else
    throw usage(name);

  I(!null_id(rid));

  roster_t roster;
  marking_map mm;
  app.db.get_roster(rid, roster, mm);

  roster_data dat;
  write_roster_and_marking(roster, mm, dat);
  cout << dat;
}


// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s: