chiark / gitweb /
git-debrebase: merge: conflict: Some xxx's now done
[dgit.git] / git-debrebase
1 #!/usr/bin/perl -w
2 # git-debrebase
3 # Script helping make fast-forwarding histories while still rebasing
4 # upstream deltas when working on Debian packaging
5 #
6 # Copyright (C)2017,2018 Ian Jackson
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
24
25 use strict;
26
27 use Debian::Dgit qw(:DEFAULT :playground);
28 setup_sigwarn();
29
30 use Memoize;
31 use Carp;
32 use POSIX;
33 use Data::Dumper;
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
35 use Dpkg::Version;
36 use File::FnMatch qw(:fnmatch);
37 use File::Copy;
38
39 $debugcmd_when_debuglevel = 2;
40
41 our ($usage_message) = <<'END';
42 usages:
43   git-debrebase [<options>] [--|-i <git rebase options...>]
44   git-debrebase [<options>] status
45   git-debrebase [<options>] prepush [--prose=...]
46   git-debrebase [<options>] quick|conclude
47   git-debrebase [<options>] new-upstream <new-version> [<details ...>]
48   git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
49   ...
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 END
52
53 our ($opt_force, $opt_noop_ok, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
55
56 our $us = qw(git-debrebase);
57
58 our $wrecknoteprefix = 'refs/debrebase/wreckage';
59 our $merge_cache_ref = 'refs/debrebase/merge-resolutions';
60
61 $|=1;
62
63 sub badusage ($) {
64     my ($m) = @_;
65     print STDERR "$us: bad usage: $m\n";
66     finish 8;
67 }
68
69 sub getoptions_main {
70     my $m = shift;
71     local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
72     GetOptions @_ or badusage $m;
73 }
74 sub getoptions {
75     my $sc = shift;
76     getoptions_main "bad options follow \`git-debrebase $sc'", @_;
77 }
78
79 sub cfg ($;$) {
80     my ($k, $optional) = @_;
81     local $/ = "\0";
82     my @cmd = qw(git config -z);
83     push @cmd, qw(--get-all) if wantarray;
84     push @cmd, $k;
85     my $out = cmdoutput_errok @cmd;
86     if (!defined $out) {
87         fail "missing required git config $k" unless $optional;
88         return ();
89     }
90     my @l = split /\0/, $out;
91     return wantarray ? @l : $l[0];
92 }
93
94 memoize('cfg');
95
96 sub dd ($) {
97     my ($v) = @_;
98     my $dd = new Data::Dumper [ $v ];
99     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
100     return Dump $dd;
101 }
102
103 sub get_commit ($) {
104     my ($objid) = @_;
105     my $data = (git_cat_file $objid, 'commit');
106     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
107     return ($`,$');
108 }
109
110 sub D_UPS ()      { 0x02; } # upstream files
111 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
112 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
113 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
114 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
115 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
116
117 our $playprefix = 'debrebase';
118 our $rd;
119 our $workarea;
120
121 our @git = qw(git);
122 our @dgit = qw(dgit);
123
124 sub in_workarea ($) {
125     my ($sub) = @_;
126     changedir $workarea;
127     my $r = eval { $sub->(); };
128     { local $@; changedir $maindir; }
129     die $@ if $@;
130 }
131
132 sub fresh_workarea (;$) {
133     my ($subdir) = @_;
134     $subdir //= 'work';
135     $workarea = fresh_playground "$playprefix/$subdir";
136     in_workarea sub { playtree_setup };
137 }
138
139 sub run_ref_updates_now ($$) {
140     my ($mrest, $updates) = @_;
141     # @$updates is a list of lines for git-update-ref, without \ns
142
143     my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
144     debugcmd '>|', @upd_cmd;
145     open U, "|-", @upd_cmd or die $!;
146     foreach (@$updates) {
147         printdebug ">= ", $_, "\n";
148         print U $_, "\n" or die $!;
149     }
150     printdebug ">\$\n";
151     close U or failedcmd @upd_cmd;
152 }
153
154 our $snags_forced = 0;
155 our $snags_tripped = 0;
156 our $snags_summarised = 0;
157 our @deferred_updates;
158 our @deferred_update_messages;
159
160 sub merge_wreckage_cleaning ($) {
161     my ($updates) = @_;
162     git_for_each_ref("$wrecknoteprefix/*", sub {
163         my ($objid,$objtype,$fullrefname,$reftail) = @_;
164         push @$updates, "delete $fullrefname";
165     });
166 }
167
168 sub all_snags_summarised () {
169     $snags_forced + $snags_tripped == $snags_summarised;
170 }
171 sub run_deferred_updates ($) {
172     my ($mrest) = @_;
173
174     confess 'dangerous internal error' unless all_snags_summarised();
175
176     merge_wreckage_cleaning \@deferred_updates;
177     run_ref_updates_now $mrest, \@deferred_updates;
178     print $_, "\n" foreach @deferred_update_messages;
179
180     @deferred_updates = ();
181     @deferred_update_messages = ();
182 }
183
184 sub get_differs ($$) {
185     my ($x,$y) = @_;
186     # This resembles quiltify_trees_differ, in dgit, a bit.
187     # But we don't care about modes, or dpkg-source-unrepresentable
188     # changes, and we don't need the plethora of different modes.
189     # Conversely we need to distinguish different kinds of changes to
190     # debian/ and debian/patches/.
191
192     my $differs = 0;
193
194     my $rundiff = sub {
195         my ($opts, $limits, $fn) = @_;
196         my @cmd = (@git, qw(diff-tree -z --no-renames));
197         push @cmd, @$opts;
198         push @cmd, "$_:" foreach $x, $y;
199         push @cmd, '--', @$limits;
200         my $diffs = cmdoutput @cmd;
201         foreach (split /\0/, $diffs) { $fn->(); }
202     };
203
204     $rundiff->([qw(--name-only)], [], sub {
205         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
206     });
207
208     if ($differs & DS_DEB) {
209         $differs &= ~DS_DEB;
210         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
211             $differs |=
212                 m{^debian/patches/}      ? D_PAT_OTH  :
213                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
214                                            D_DEB_OTH;
215         });
216         die "mysterious debian changes $x..$y"
217             unless $differs & (D_PAT_OTH|DS_DEB);
218     }
219
220     if ($differs & D_PAT_OTH) {
221         my $mode;
222         $differs &= ~D_PAT_OTH;
223         my $pat_oth = sub {
224             $differs |= D_PAT_OTH;
225             no warnings qw(exiting);  last;
226         };
227         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
228             no warnings qw(exiting);
229             if (!defined $mode) {
230                 $mode = $_;  next;
231             }
232             die unless s{^debian/patches/}{};
233             my $ok;
234             if ($mode eq 'A' && !m/\.series$/s) {
235                 $ok = 1;
236             } elsif ($mode eq 'M' && $_ eq 'series') {
237                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
238                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
239                 chomp $x_s;  $x_s .= "\n";
240                 $ok = $x_s eq substr($y_s, 0, length $x_s);
241             } else {
242                 # nope
243             }
244             $mode = undef;
245             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
246         });
247         die "mysterious debian/patches changes $x..$y"
248             unless $differs & (D_PAT_ADD|D_PAT_OTH);
249     }
250
251     printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
252
253     return $differs;
254 }
255
256 sub commit_pr_info ($) {
257     my ($r) = @_;
258     return Data::Dumper->dump([$r], [qw(commit)]);
259 }
260
261 sub calculate_committer_authline () {
262     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
263         'DUMMY COMMIT (git-debrebase)', "HEAD:";
264     my ($h,$m) = get_commit $c;
265     $h =~ m/^committer .*$/m or confess "($h) ?";
266     return $&;
267 }
268
269 sub rm_subdir_cached ($) {
270     my ($subdir) = @_;
271     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
272 }
273
274 sub read_tree_subdir ($$) {
275     my ($subdir, $new_tree_object) = @_;
276     rm_subdir_cached $subdir;
277     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
278 }
279
280 sub read_tree_debian ($) {
281     my ($treeish) = @_;
282     read_tree_subdir 'debian', "$treeish:debian";
283     rm_subdir_cached 'debian/patches';
284 }
285
286 sub read_tree_upstream ($;$$) {
287     my ($treeish, $keep_patches, $tree_with_debian) = @_;
288     # if $tree_with_debian is supplied, will use that for debian/
289     # otherwise will save and restore it.
290     my $debian =
291         $tree_with_debian ? "$tree_with_debian:debian"
292         : cmdoutput @git, qw(write-tree --prefix=debian/);
293     runcmd @git, qw(read-tree), $treeish;
294     read_tree_subdir 'debian', $debian;
295     rm_subdir_cached 'debian/patches' unless $keep_patches;
296 };
297
298 sub make_commit ($$) {
299     my ($parents, $message_paras) = @_;
300     my $tree = cmdoutput @git, qw(write-tree);
301     my @cmd = (@git, qw(commit-tree), $tree);
302     push @cmd, qw(-p), $_ foreach @$parents;
303     push @cmd, qw(-m), $_ foreach @$message_paras;
304     return cmdoutput @cmd;
305 }
306
307 our @snag_force_opts;
308 sub snag ($$;@) {
309     my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
310     if (grep { $_ eq $tag } @snag_force_opts) {
311         $snags_forced++;
312         print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
313     } else {
314         $snags_tripped++;
315         print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
316     }
317 }
318
319 # Important: all mainline code must call snags_maybe_bail after
320 # any point where snag might be called, but before making changes
321 # (eg before any call to run_deferred_updates).  snags_maybe_bail
322 # may be called more than once if necessary (but this is not ideal
323 # because then the messages about number of snags may be confusing).
324 sub snags_maybe_bail () {
325     return if all_snags_summarised();
326     if ($snags_forced) {
327         printf STDERR
328             "%s: snags: %d overriden by individual -f options\n",
329             $us, $snags_forced;
330     }
331     if ($snags_tripped) {
332         if ($opt_force) {
333             printf STDERR
334                 "%s: snags: %d overriden by global --force\n",
335                 $us, $snags_tripped;
336         } else {
337             fail sprintf
338   "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
339                 $us, $snags_tripped;
340         }
341     }
342     $snags_summarised = $snags_forced + $snags_tripped;
343 }
344 sub snags_maybe_bail_early () {
345     # useful to bail out early without doing a lot of work;
346     # not a substitute for snags_maybe_bail.
347     snags_maybe_bail() if $snags_tripped && !$opt_force;
348 }
349 sub any_snags () {
350     return $snags_forced || $snags_tripped;
351 }
352
353 sub gbp_pq_export ($$$) {
354     my ($bname, $base, $tip) = @_;
355     # must be run in a workarea.  $bname and patch-queue/$bname
356     # ought not to exist.  Leaves you on patch-queue/$bname with
357     # the patches staged but not committed.
358     printdebug "gbp_pq_export $bname $base $tip\n";
359     runcmd @git, qw(checkout -q -b), $bname, $base;
360     runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
361     my @gbp_cmd = (qw(gbp pq export));
362     my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
363     if ($r) {
364         { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
365         failedcmd @gbp_cmd;
366     }
367     runcmd @git, qw(add -f debian/patches) if stat_exists 'debian/patches';
368 }
369
370
371 # xxx allow merge resolution separately from laundering, before git merge
372 #
373 # xxx general gdr docs highlight forbidden things
374 # xxx general gdr docs list allowable things ?
375 # xxx general gdr docs explicitly forbid some rebase
376
377 # later/rework?
378 #  use git-format-patch?
379 #  our own patch identification algorithm?
380 #  this is an alternative strategy
381
382 sub merge_failed ($$;@) {
383     my ($wrecknotes, $emsg, @xmsgs) = @_;
384     my @m;
385     push @m, "Merge resolution failed: $emsg";
386     push @m, @xmsgs;
387
388     changedir $maindir;
389
390     my @updates;
391     merge_wreckage_cleaning \@updates;
392     run_ref_updates_now "merge failed", \@updates;
393
394     @updates = ();
395     keys %$wrecknotes;
396     while (my ($k,$v) = each %$wrecknotes) {
397         push @updates, "create $wrecknoteprefix/$k $v";
398     }
399     run_ref_updates_now "merge failed", \@updates;
400     push @m, "Wreckage left in $wrecknoteprefix/*.";
401
402     push @m, "See git-debrebase(1) section FAILED MERGES for suggestions.";
403
404     # use finish rather than fail, in case we are within an eval
405     # (that can happen inside walk!)
406     print STDERR "\n";
407     print STDERR "$us: $_\n" foreach @m;
408     finish 15;
409 }
410
411 sub mwrecknote ($$$) {
412     my ($wrecknotes, $reftail, $commitish) = @_;
413     confess unless defined $commitish;
414     printdebug "mwrecknote $reftail $commitish\n";
415     $wrecknotes->{$reftail} = $commitish;
416 }
417
418 sub merge_attempt_cmd {
419     my $wrecknotes = shift @_;
420     debugcmd '+', @_;
421     $!=0; $?=-1;
422     if (system @_) {
423         merge_failed $wrecknotes,
424             failedcmd_waitstatus(),
425             "failed command: @_";
426     }
427 }
428
429 sub merge_series_patchqueue_convert ($$$);
430
431 sub merge_series ($$$;@) {
432     my ($newbase, $wrecknotes, $base_q, @input_qs) = @_;
433     # $base_q{SeriesBase}  $input_qs[]{SeriesBase}
434     # $base_q{SeriesTip}   $input_qs[]{SeriesTip}
435     # ^ specifies several patch series (currently we only support exactly 2)
436     # return value is a commit which is the result of
437     # merging the two versions of the same topic branch
438     #   $input_q[0] and $input_q[1]
439     # with respect to the old version
440     #   $base_q
441     # all onto $newbase.
442
443     # Creates, in *_q, a key MR for its private use
444
445     printdebug "merge_series newbase=$newbase\n";
446
447     $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
448     $base_q->{MR}{S} = 'base';
449
450     my %prereq;
451     # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
452     # $prereq{<patch filename>}{<possible prereq}  exists or not (later)
453     # $prereq{<patch filename>}               exists or not (even later)
454
455     my $merged_pq;
456
457     my $mwrecknote = sub { &mwrecknote($wrecknotes, @_); };
458
459     my $attempt_cmd = sub { &merge_attempt_cmd($wrecknotes, @_); };
460
461     local $workarea;
462     fresh_workarea "merge";
463     my $seriesfile = "debian/patches/series";
464     in_workarea sub {
465         playtree_setup();
466         foreach my $q ($base_q, reverse @input_qs) {
467             my $s = $q->{MR}{S};
468             gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
469             my @earlier;
470             if (open S, $seriesfile) {
471                 while (my $patch = <S>) {
472                     chomp $patch or die $!;
473                     $prereq{$patch} //= {};
474                     foreach my $earlier (@earlier) {
475                         $prereq{$patch}{$earlier}{$s}++ and die;
476                     }
477                     push @earlier, $patch;
478                     stat "debian/patches/$patch" or die "$patch ?";
479                 }
480                 S->error and die "$seriesfile $!";
481                 close S;
482             } else {
483                 die "$seriesfile $!" unless $!==ENOENT;
484             }
485             read_tree_upstream $newbase, 1;
486             my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
487                 "Convert $s to patch queue for merging",
488                 "[git-debrebase merge-innards patch-queue import:".
489                 " $q->{SeriesTip}]"
490             ];
491             printdebug "merge_series  pec $pec ";
492             runcmd @git, qw(rm -q --ignore-unmatch --cached), $seriesfile;
493             $pec = make_commit [ $pec ], [
494                 "Drop series file from $s to avoid merge trouble",
495                 "[git-debrebase merge-innards patch-queue prep:".
496                 " $q->{SeriesTip}]"
497             ];
498
499             read_tree_debian $newbase;
500             if (@earlier) {
501                 read_tree_subdir 'debian/patches', "$pec:debian/patches";
502             } else {
503                 rm_subdir_cached 'debian/patches';
504             }
505             $pec = make_commit [ $pec ], [
506  "Update debian/ (excluding patches) to final to avoid re-merging",
507  "debian/ was already merged and we need to just take that.",
508                 "[git-debrebase merge-innards patch-queue packaging:".
509                 " $q->{SeriesTip}]"
510             ];
511
512             printdebug "pec' $pec\n";
513             runcmd @git, qw(reset -q --hard), $pec;
514             $q->{MR}{PEC} = $pec;
515             $mwrecknote->("$q->{LeftRight}-patchqueue", $pec);
516         }
517         # now, because of reverse, we are on $input_q->{MR}{OQC}
518         runcmd @git, qw(checkout -q -b merge);
519         printdebug "merge_series merging...\n";
520         my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
521
522         $attempt_cmd->(@mergecmd);
523
524         printdebug "merge_series merge ok, series...\n";
525         # We need to construct a new series file
526         # Firstly, resolve prereq
527         foreach my $f (sort keys %prereq) {
528             printdebug "merge_series  patch\t$f\t";
529             if (!stat_exists "debian/patches/$f") {
530                 print DEBUG " drop\n" if $debuglevel;
531                 # git merge deleted it; that's how we tell it's not wanted
532                 delete $prereq{$f};
533                 next;
534             }
535             print DEBUG " keep\n" if $debuglevel;
536             foreach my $g (sort keys %{ $prereq{$f} }) {
537                 my $gfp = $prereq{$f}{$g};
538                 printdebug "merge_series  prereq\t$f\t-> $g\t";
539                 if (!!$gfp->{0} == !!$gfp->{1}
540                     ? $gfp->{0}
541                     : !$gfp->{base}) {
542                     print DEBUG "\tkeep\n" if $debuglevel;
543                 } else {
544                     print DEBUG "\tdrop\n" if $debuglevel;
545                     delete $prereq{$f}{$g};
546                 }
547             }
548         }
549
550         my $unsat = sub {
551             my ($f) = @_;
552             return scalar keys %{ $prereq{$f} };
553         };
554
555         my $nodate = time + 1;
556         my %authordate;
557         # $authordate{<patch filename>};
558         my $authordate = sub {
559             my ($f) = @_;
560             $authordate{$f} //= do {
561                 open PF, "<", "debian/patches/$f" or die "$f $!";
562                 while (<PF>) {
563                     return $nodate if m/^$/;
564                     last if s{^Date: }{};
565                 }
566                 chomp;
567                 return cmdoutput qw(date +%s -d), $_;
568             };
569         };
570
571         open NS, '>', $seriesfile or die $!;
572
573         while (keys %prereq) {
574             my $best;
575             foreach my $try (sort keys %prereq) {
576                 if ($best) {
577                     next if (
578                              $unsat->($try) <=> $unsat->($best) or
579                              $authordate->($try) <=> $authordate->($best) or
580                              $try cmp $best
581                             ) >= 0;
582                 }
583                 $best = $try;
584             }
585             printdebug "merge_series series next $best\n";
586             print NS "$best\n" or die $!;
587             delete $prereq{$best};
588             foreach my $gp (values %prereq) {
589                 delete $gp->{$best};
590             }
591         }
592
593         runcmd @git, qw(add), $seriesfile;
594         runcmd @git, qw(commit --quiet -m), 'Merged patch queue form';
595         $merged_pq = git_rev_parse 'HEAD';
596         $mwrecknote->('merged-patchqueue', $merged_pq);
597     };
598     return merge_series_patchqueue_convert
599             $wrecknotes, $newbase, $merged_pq;
600 }
601
602 sub merge_series_patchqueue_convert ($$$) {
603     my ($wrecknotes, $newbase, $merged_pq) = @_;
604
605     my $result;
606     in_workarea sub {
607         playtree_setup();
608         printdebug "merge_series series gbp pq import\n";
609         runcmd @git, qw(checkout -q -b mergec), $merged_pq;
610
611         merge_attempt_cmd($wrecknotes, qw(gbp pq import));
612
613         # OK now we are on patch-queue/merge, and we need to rebase
614         # onto the intended parent and drop the patches from each one
615
616         printdebug "merge_series series ok, building...\n";
617         my $build = $newbase;
618         my @lcmd = (@git, qw(rev-list --reverse mergec..patch-queue/mergec));
619         foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
620             my $commit = git_cat_file $c, 'commit';
621             printdebug "merge_series series ok, building $c\n";
622             read_tree_upstream $c, 0, $newbase;
623             my $tree = cmdoutput @git, qw(write-tree);
624             $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
625             $commit =~ s{^tree (\S+)$}{tree $tree}m      or confess;
626             open C, ">", "../mcommit" or die $!;
627             print C $commit or die $!;
628             close C or die $!;
629             $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
630         }
631         $result = $build;
632         mwrecknote($wrecknotes, 'merged-result', $result);
633
634         runcmd @git, qw(update-ref refs/heads/result), $result;
635
636         runcmd @git, qw(checkout -q -b debug);
637         runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
638         runcmd @git, qw(add .);
639         runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
640         my $mdebug = git_rev_parse 'HEAD';
641         printdebug sprintf "merge_series done debug=%s\n", $mdebug;
642         mwrecknote($wrecknotes, 'merged-debug', $mdebug);
643     };
644     printdebug "merge_series returns $result\n";
645     return $result;
646 }
647
648 # classify returns an info hash like this
649 #   CommitId => $objid
650 #   Hdr => # commit headers, including 1 final newline
651 #   Msg => # commit message (so one newline is dropped)
652 #   Tree => $treeobjid
653 #   Type => (see below)
654 #   Parents = [ {
655 #       Ix => $index # ie 0, 1, 2, ...
656 #       CommitId
657 #       Differs => return value from get_differs
658 #       IsOrigin
659 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
660 #     } ...]
661 #   NewMsg => # commit message, but with any [dgit import ...] edited
662 #             # to say "[was: ...]"
663 #
664 # Types:
665 #   Packaging
666 #   Changelog
667 #   Upstream
668 #   AddPatches
669 #   Mixed
670 #
671 #   Pseudomerge
672 #     has additional entres in classification result
673 #       Overwritten = [ subset of Parents ]
674 #       Contributor = $the_remaining_Parent
675 #
676 #   DgitImportUnpatched
677 #     has additional entry in classification result
678 #       OrigParents = [ subset of Parents ]
679 #
680 #   Anchor
681 #     has additional entry in classification result
682 #       OrigParents = [ subset of Parents ]  # singleton list
683 #
684 #   TreatAsAnchor
685 #
686 #   BreakwaterStart
687 #
688 #   Unknown
689 #     has additional entry in classification result
690 #       Why => "prose"
691
692 sub parsecommit ($;$) {
693     my ($objid, $p_ref) = @_;
694     # => hash with                   CommitId Hdr Msg Tree Parents
695     #    Parents entries have only   Ix CommitId
696     #    $p_ref, if provided, must be [] and is used as a base for Parents
697
698     $p_ref //= [];
699     die if @$p_ref;
700
701     my ($h,$m) = get_commit $objid;
702
703     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
704     my (@ph) = $h =~ m/^parent (\w+)$/mg;
705
706     my $r = {
707         CommitId => $objid,
708         Hdr => $h,
709         Msg => $m,
710         Tree => $t,
711         Parents => $p_ref,
712     };
713
714     foreach my $ph (@ph) {
715         push @$p_ref, {
716             Ix => scalar @$p_ref,
717             CommitId => $ph,
718         };
719     }
720
721     return $r;
722 }    
723
724 sub classify ($) {
725     my ($objid) = @_;
726
727     my @p;
728     my $r = parsecommit($objid, \@p);
729     my $t = $r->{Tree};
730
731     foreach my $p (@p) {
732         $p->{Differs} = (get_differs $p->{CommitId}, $t),
733     }
734
735     printdebug "classify $objid \$t=$t \@p",
736         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
737         "\n";
738
739     my $classify = sub {
740         my ($type, @rest) = @_;
741         $r = { %$r, Type => $type, @rest };
742         if ($debuglevel) {
743             printdebug " = $type ".(dd $r)."\n";
744         }
745         return $r;
746     };
747     my $unknown = sub {
748         my ($why) = @_;
749         $r = { %$r, Type => qw(Unknown), Why => $why };
750         printdebug " ** Unknown\n";
751         return $r;
752     };
753
754     if (grep { $_ eq $objid } @opt_anchors) {
755         return $classify->('TreatAsAnchor');
756     }
757
758     my @identical = grep { !$_->{Differs} } @p;
759     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
760     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
761
762     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
763         # multi-orig upstreams are represented with an anchor merge
764         # from a single upstream commit which combines the orig tarballs
765
766         # Every anchor tagged this way must be a merge.
767         # We are relying on the
768         #     [git-debrebase anchor: ...]
769         # commit message annotation in "declare" anchor merges (which
770         # do not have any upstream changes), to distinguish those
771         # anchor merges from ordinary pseudomerges (which we might
772         # just try to strip).
773         #
774         # However, the user is going to be doing git-rebase a lot.  We
775         # really don't want them to rewrite an anchor commit.
776         # git-rebase trips up on merges, so that is a useful safety
777         # catch.
778         #
779         # BreakwaterStart commits are also anchors in the terminology
780         # of git-debrebase(5), but they are untagged (and always
781         # manually generated).
782         #
783         # We cannot not tolerate any tagged linear commit (ie,
784         # BreakwaterStart commits tagged `[anchor:') because such a
785         # thing could result from an erroneous linearising raw git
786         # rebase of a merge anchor.  That would represent a corruption
787         # of the branch. and we want to detect and reject the results
788         # of such corruption before it makes it out anywhere.  If we
789         # reject it here then we avoid making the pseudomerge which
790         # would be needed to push it.
791
792         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
793         @p == 2 or return $badanchor->("has other than two parents");
794         $haspatches and return $badanchor->("contains debian/patches");
795
796         # How to decide about l/r ordering of anchors ?  git
797         # --topo-order prefers to expand 2nd parent first.  There's
798         # already an easy rune to look for debian/ history anyway (git log
799         # debian/) so debian breakwater branch should be 1st parent; that
800         # way also there's also an easy rune to look for the upstream
801         # patches (--topo-order).
802
803         # Also this makes --first-parent be slightly more likely to
804         # be useful - it makes it provide a linearised breakwater history.
805
806         # Of course one can say somthing like
807         #  gitk -- ':/' ':!/debian'
808         # to get _just_ the commits touching upstream files, and by
809         # the TREESAME logic in git-rev-list this will leave the
810         # breakwater into upstream at the first anchor.  But that
811         # doesn't report debian/ changes at all.
812
813         # Other observations about gitk: by default, gitk seems to
814         # produce output in a different order to git-rev-list.  I
815         # can't seem to find this documented anywhere.  gitk
816         # --date-order DTRT.  But, gitk always seems to put the
817         # parents from left to right, in order, so it's easy to see
818         # which way round a pseudomerge is.
819
820         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
821         $p[1]{Differs} & ~DS_DEB and
822             $badanchor->("upstream files differ from left parent");
823         $p[0]{Differs} & ~D_UPS and
824             $badanchor->("debian/ differs from right parent");
825
826         return $classify->(qw(Anchor),
827                            OrigParents => [ $p[1] ]);
828     }
829
830     if (@p == 1) {
831         my $d = $r->{Parents}[0]{Differs};
832         if ($d == D_PAT_ADD) {
833             return $classify->(qw(AddPatches));
834         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
835             return $unknown->("edits debian/patches");
836         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
837             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
838             if ($ty eq 'tree') {
839                 if ($d == D_DEB_CLOG) {
840                     return $classify->(qw(Changelog));
841                 } else {
842                     return $classify->(qw(Packaging));
843                 }
844             } elsif ($ty eq 'missing') {
845                 return $classify->(qw(BreakwaterStart));
846             } else {
847                 return $unknown->("parent's debian is not a directory");
848             }
849         } elsif ($d == D_UPS) {
850             return $classify->(qw(Upstream));
851         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
852             return $classify->(qw(Mixed));
853         } elsif ($d == 0) {
854             return $unknown->("no changes");
855         } else {
856             confess "internal error $objid ?";
857         }
858     }
859     if (!@p) {
860         return $unknown->("origin commit");
861     }
862
863     if (@p == 2 && @identical == 1) {
864         my @overwritten = grep { $_->{Differs} } @p;
865         confess "internal error $objid ?" unless @overwritten==1;
866         return $classify->(qw(Pseudomerge),
867                            Overwritten => [ $overwritten[0] ],
868                            Contributor => $identical[0]);
869     }
870     if (@p == 2 && @identical == 2) {
871         my $get_t = sub {
872             my ($ph,$pm) = get_commit $_[0]{CommitId};
873             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
874             $1;
875         };
876         my @bytime = @p;
877         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
878         if ($order > 0) { # newer first
879         } elsif ($order < 0) {
880             @bytime = reverse @bytime;
881         } else {
882             # same age, default to order made by -s ours
883             # that is, commit was made by someone who preferred L
884         }
885         return $classify->(qw(Pseudomerge),
886                            SubType => qw(Ambiguous),
887                            Contributor => $bytime[0],
888                            Overwritten => [ $bytime[1] ]);
889     }
890     foreach my $p (@p) {
891         my ($p_h, $p_m) = get_commit $p->{CommitId};
892         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
893         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
894     }
895     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
896     my $m2 = $r->{Msg};
897     if (!(grep { !$_->{IsOrigin} } @p) and
898         (@orig_ps >= @p - 1) and
899         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
900         $r->{NewMsg} = $m2;
901         return $classify->(qw(DgitImportUnpatched),
902                            OrigParents => \@orig_ps);
903     }
904
905     if (@p == 2 and
906         $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
907         # xxx ^ metadata tag needs adding to (5)
908         return $classify->("MergedBreakwaters");
909     }
910     if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
911         return $unknown->("unknown kind of merge from $1");
912     }
913     if (@p > 2) {
914         return $unknown->("octopus merge");
915     }
916
917     if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
918         return $unknown->("general two-parent merge");
919     }
920
921     return $classify->("VanillaMerge");
922 }
923
924 sub keycommits ($;$$$$$);
925
926 sub mergedbreakwaters_anchor ($) {
927     my ($cl) = @_;
928     my $best_anchor;
929     foreach my $p (@{ $cl->{Parents} }) {
930         my ($panchor, $pbw) = keycommits $p->{CommitId},
931             undef,undef,undef,undef, 1;
932         $best_anchor = $panchor
933             if !defined $best_anchor
934             or is_fast_fwd $best_anchor, $panchor;
935         fail "inconsistent anchors in merged-breakwaters $p->{CommitId}"
936             unless is_fast_fwd $panchor, $best_anchor;
937     }
938     return $best_anchor;
939 }
940
941 sub keycommits ($;$$$$$) {
942     my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
943     # => ($anchor, $breakwater)
944
945     # $unclean->("unclean-$tagsfx", $msg, $cl)
946     # $furniture->("unclean-$tagsfx", $msg, $cl)
947     # $dgitimport->("unclean-$tagsfx", $msg, $cl))
948     #   is callled for each situation or commit that
949     #   wouldn't be found in a laundered branch
950     # $furniture is for furniture commits such as might be found on an
951     #   interchange branch (pseudomerge, d/patches, changelog)
952     # $trouble is for things whnich prevent the return of
953     #   anchor and breakwater information; if that is ignored,
954     #   then keycommits returns (undef, undef) instead.
955     # $fatal is for unprocessable commits, and should normally cause
956     #    a failure.  If ignored, agaion, (undef, undef) is returned.
957     #
958     # If $claimed_bw, this is supposed to be a breakwater commit.
959     #
960     # If a callback is undef, fail is called instead.
961     # If a callback is defined but false, the situation is ignored.
962     # Callbacks may say:
963     #   no warnings qw(exiting); last;
964     # if the answer is no longer wanted.
965
966     my ($anchor, $breakwater);
967     $breakwater = $head if $claimed_bw;
968     my $clogonly;
969     my $cl;
970     my $found_pm;
971     $fatal //= sub { fail $_[1]; };
972     my $x = sub {
973         my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
974         my $why = $mainwhy.$xwhy;
975         my $m = "branch needs laundering (run git-debrebase): $why";
976         fail $m unless defined $cb;
977         return unless $cb;
978         $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
979     };
980     my $found_anchor = sub {
981         ($anchor) = @_;
982         $breakwater //= $clogonly;
983         $breakwater //= $head;
984         no warnings qw(exiting);
985         last;
986     };
987     for (;;) {
988         $cl = classify $head;
989         my $ty = $cl->{Type};
990         if ($ty eq 'Packaging') {
991             $breakwater //= $clogonly;
992             $breakwater //= $head;
993         } elsif ($ty eq 'Changelog') {
994             # this is going to count as the tip of the breakwater
995             # only if it has no upstream stuff before it
996             $clogonly //= $head;
997         } elsif ($ty eq 'Anchor' or
998                  $ty eq 'TreatAsAnchor' or
999                  $ty eq 'BreakwaterStart') {
1000             $found_anchor->($head);
1001         } elsif ($ty eq 'Upstream') {
1002             $x->($unclean, 'ordering',
1003  "packaging change ($breakwater) follows upstream change"," (eg $head)")
1004                 if defined $breakwater;
1005             $clogonly = undef;
1006             $breakwater = undef;
1007         } elsif ($ty eq 'Mixed') {
1008             $x->($unclean, 'mixed',
1009                  "found mixed upstream/packaging commit"," ($head)");
1010             $clogonly = undef;
1011             $breakwater = undef;
1012         } elsif ($ty eq 'Pseudomerge' or
1013                  $ty eq 'AddPatches') {
1014             my $found_pm = 1;
1015             $x->($furniture, (lc $ty),
1016                  "found interchange bureaucracy commit ($ty)"," ($head)");
1017         } elsif ($ty eq 'DgitImportUnpatched') {
1018             if ($found_pm) {
1019                 $x->($trouble, 'dgitimport',
1020                      "found dgit dsc import"," ($head)");
1021                 return (undef,undef);
1022             } else {
1023                 $x->($fatal, 'unprocessable',
1024                      "found bare dgit dsc import with no prior history",
1025                      " ($head)");
1026                 return (undef,undef);
1027             }
1028         } elsif ($ty eq 'VanillaMerge') {
1029             $x->($trouble, 'vanillamerge',
1030                  "found vanilla merge"," ($head)");
1031             return (undef,undef);
1032         } elsif ($ty eq 'MergedBreakwaters') {
1033             $found_anchor->(mergedbreakwaters_anchor $cl);
1034         } else {
1035             $x->($fatal, 'unprocessable',
1036                  "found unprocessable commit, cannot cope: $cl->{Why}",
1037                  " ($head)");
1038             return (undef,undef);
1039         }
1040         $head = $cl->{Parents}[0]{CommitId};
1041     }
1042     return ($anchor, $breakwater);
1043 }
1044
1045 sub walk ($;$$$);
1046 sub walk ($;$$$) {
1047     my ($input,
1048         $nogenerate,$report, $report_lprefix) = @_;
1049     # => ($tip, $breakwater_tip, $last_anchor)
1050     # (or nothing, if $nogenerate)
1051
1052     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
1053     $report_lprefix //= '';
1054
1055     # go through commits backwards
1056     # we generate two lists of commits to apply:
1057     # breakwater branch and upstream patches
1058     my (@brw_cl, @upp_cl, @processed);
1059     my %found;
1060     my $upp_limit;
1061     my @pseudomerges;
1062
1063     my $cl;
1064     my $xmsg = sub {
1065         my ($prose, $info) = @_;
1066         my $ms = $cl->{Msg};
1067         chomp $ms;
1068         $info //= '';
1069         $ms .= "\n\n[git-debrebase$info: $prose]\n";
1070         return (Msg => $ms);
1071     };
1072     my $rewrite_from_here = sub {
1073         my ($cl) = @_;
1074         my $sp_cl = { SpecialMethod => 'StartRewrite' };
1075         push @$cl, $sp_cl;
1076         push @processed, $sp_cl;
1077     };
1078     my $cur = $input;
1079
1080     my $prdelim = "";
1081     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
1082
1083     my $prline = sub {
1084         return unless $report;
1085         print $report $prdelim, $report_lprefix, @_;
1086         $prdelim = "\n";
1087     };
1088
1089     my $bomb = sub { # usage: return $bomb->();
1090         print $report " Unprocessable" if $report;
1091         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
1092         $prprdelim->();
1093         if ($nogenerate) {
1094             return (undef,undef);
1095         }
1096         fail "found unprocessable commit, cannot cope".
1097             (defined $cl->{Why} ? "; $cl->{Why}:": ':').
1098             " (commit $cur) (d.".
1099             (join ' ', map { sprintf "%#x", $_->{Differs} }
1100              @{ $cl->{Parents} }).
1101                  ")";
1102     };
1103
1104     my $build;
1105     my $breakwater;
1106
1107     my $build_start = sub {
1108         my ($msg, $parent) = @_;
1109         $prline->(" $msg");
1110         $build = $parent;
1111         no warnings qw(exiting); last;
1112     };
1113
1114     my $nomerge = sub {
1115         my ($emsg) = @_;
1116         merge_failed $cl->{MergeWreckNotes}, $emsg;
1117     };
1118
1119     my $mwrecknote = sub { &mwrecknote($cl->{MergeWreckNotes}, @_); };
1120
1121     my $last_anchor;
1122
1123     for (;;) {
1124         $cl = classify $cur;
1125         $cl->{MergeWreckNotes} //= {};
1126         my $ty = $cl->{Type};
1127         my $st = $cl->{SubType};
1128         $prline->("$cl->{CommitId} $cl->{Type}");
1129         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1130         push @processed, $cl;
1131         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1132         if ($ty eq 'AddPatches') {
1133             $cur = $p0;
1134             $rewrite_from_here->(\@upp_cl);
1135             next;
1136         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1137             push @brw_cl, $cl;
1138             $cur = $p0;
1139             next;
1140         } elsif ($ty eq 'BreakwaterStart') {
1141             $last_anchor = $cur;
1142             $build_start->('FirstPackaging', $cur);
1143         } elsif ($ty eq 'Upstream') {
1144             push @upp_cl, $cl;
1145             $cur = $p0;
1146             next;
1147         } elsif ($ty eq 'Mixed') {
1148             my $queue = sub {
1149                 my ($q, $wh) = @_;
1150                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1151                 push @$q, $cls;
1152             };
1153             $queue->(\@brw_cl, "debian");
1154             $queue->(\@upp_cl, "upstream");
1155             $rewrite_from_here->(\@brw_cl);
1156             $cur = $p0;
1157             next;
1158         } elsif ($ty eq 'Pseudomerge') {
1159             my $contrib = $cl->{Contributor}{CommitId};
1160             print $report " Contributor=$contrib" if $report;
1161             push @pseudomerges, $cl;
1162             $rewrite_from_here->(\@upp_cl);
1163             $cur = $contrib;
1164             next;
1165         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1166             $last_anchor = $cur;
1167             $build_start->("Anchor", $cur);
1168         } elsif ($ty eq 'DgitImportUnpatched') {
1169             my $pm = $pseudomerges[-1];
1170             if (defined $pm) {
1171                 # To an extent, this is heuristic.  Imports don't have
1172                 # a useful history of the debian/ branch.  We assume
1173                 # that the first pseudomerge after an import has a
1174                 # useful history of debian/, and ignore the histories
1175                 # from later pseudomerges.  Often the first pseudomerge
1176                 # will be the dgit import of the upload to the actual
1177                 # suite intended by the non-dgit NMUer, and later
1178                 # pseudomerges may represent in-archive copies.
1179                 my $ovwrs = $pm->{Overwritten};
1180                 printf $report " PM=%s \@Overwr:%d",
1181                     $pm->{CommitId}, (scalar @$ovwrs)
1182                     if $report;
1183                 if (@$ovwrs != 1) {
1184                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
1185                     return $bomb->();
1186                 }
1187                 my $ovwr = $ovwrs->[0]{CommitId};
1188                 printf $report " Overwr=%s", $ovwr if $report;
1189                 # This import has a tree which is just like a
1190                 # breakwater tree, but it has the wrong history.  It
1191                 # ought to have the previous breakwater (which the
1192                 # pseudomerge overwrote) as an ancestor.  That will
1193                 # make the history of the debian/ files correct.  As
1194                 # for the upstream version: either it's the same as
1195                 # was ovewritten (ie, same as the previous
1196                 # breakwater), in which case that history is precisely
1197                 # right; or, otherwise, it was a non-gitish upload of a
1198                 # new upstream version.  We can tell these apart by
1199                 # looking at the tree of the supposed upstream.
1200                 push @brw_cl, {
1201                     %$cl,
1202                     SpecialMethod => 'DgitImportDebianUpdate',
1203                     $xmsg->("convert dgit import: debian changes")
1204                 }, {
1205                     %$cl,
1206                     SpecialMethod => 'DgitImportUpstreamUpdate',
1207                     $xmsg->("convert dgit import: upstream update",
1208                             " anchor")
1209                 };
1210                 $prline->(" Import");
1211                 $rewrite_from_here->(\@brw_cl);
1212                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1213                 $cur = $ovwr;
1214                 next;
1215             } else {
1216                 # Everything is from this import.  This kind of import
1217                 # is already nearly in valid breakwater format, with the
1218                 # patches as commits.  Unfortunately it contains
1219                 # debian/patches/.
1220                 printdebug "*** WALK BOMB bare dgit import\n";
1221                 $cl->{Why} = "bare dgit dsc import";
1222                 return $bomb->();
1223             }
1224             die "$ty ?";
1225         } elsif ($ty eq 'MergedBreakwaters') {
1226             $last_anchor = mergedbreakwaters_anchor $cl;
1227             $build_start->(' MergedBreakwaters', $cur);
1228             last;
1229         } elsif ($ty eq 'VanillaMerge') {
1230             # User may have merged unstitched branch(es).  We will
1231             # have now lost what ffq-prev was then (since the later
1232             # pseudomerge may introduce further changes).  The effect
1233             # of resolving such a merge is that we may have to go back
1234             # further in history to find a merge base, since the one
1235             # which was reachable via ffq-prev is no longer findable.
1236             # This is suboptimal, but if it all works we'll have done
1237             # the right thing.
1238             # xxx we should warn the user in the docs about this
1239
1240             my $ok=1;
1241             my $best_anchor;
1242             # We expect to find a dominating anchor amongst the
1243             # inputs' anchors.  That will be the new anchor.
1244             #
1245             # More complicated is finding a merge base for the
1246             # breakwaters.  We need a merge base that is a breakwater
1247             # commit.  The ancestors of breakwater commits are more
1248             # breakwater commits and possibly upstream commits and the
1249             # ancestors of those upstream.  Upstreams might have
1250             # arbitrary ancestors.  But any upstream commit U is
1251             # either included in both anchors, in which case the
1252             # earlier anchor is a better merge base than any of U's
1253             # ancestors; or U is not included in the older anchor, in
1254             # which case U is not an ancestor of the vanilla merge at
1255             # all.  So no upstream commit, nor any ancestor thereof,
1256             # is a best merge base.  As for non-breakwater Debian
1257             # commits: these are never ancestors of any breakwater.
1258             #
1259             # So any best merge base as found by git-merge-base
1260             # is a suitable breakwater anchor.  Usually there will
1261             # be only one.
1262
1263             printdebug "*** MERGE\n";
1264
1265             my @bwbcmd = (@git, qw(merge-base));
1266             my @ibcmd = (@git, qw(merge-base --all));
1267             my $might_be_in_bw = 1;
1268
1269             my $ps = $cl->{Parents};
1270
1271             $mwrecknote->('vanilla-merge', $cl->{CommitId});
1272
1273             foreach my $p (@$ps) {
1274                 $prline->(" VanillaMerge ".$p->{Ix});
1275                 $prprdelim->();
1276                 my ($ptip, $pbw, $panchor) =
1277                     walk $p->{CommitId}, 0, $report,
1278                          $report_lprefix.'  ';
1279                 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1280                 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1281                 $p->{Anchor} = $panchor;
1282
1283                 my $lr = $p->{LeftRight} = (qw(left right))[$p->{Ix}];
1284                 $mwrecknote->("$lr-input", $p->{CommitId});
1285
1286                 my $mwrecknote_parent = sub {
1287                     my ($which) = @_;
1288                     $mwrecknote->("$lr-".(lc $which), $p->{$which});
1289                 };
1290                 $mwrecknote_parent->('Laundered');
1291                 $mwrecknote_parent->('Breakwater');
1292                 $mwrecknote_parent->('Anchor');
1293
1294                 $best_anchor = $panchor if
1295                     !defined $best_anchor or
1296                     is_fast_fwd $best_anchor, $panchor;
1297
1298                 printdebug " MERGE BA best=".($best_anchor//'-').
1299                     " p=$panchor\n";
1300             }
1301
1302             $mwrecknote->('result-anchor', $best_anchor);
1303
1304             foreach my $p (@$ps) {
1305                 $prline->(" VanillaMerge ".$p->{Ix});
1306                 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1307                     $nomerge->('divergent anchors');
1308                 } elsif ($p->{Anchor} eq $best_anchor) {
1309                     print $report " SameAnchor" if $report;
1310                 } else {
1311                     print $report " SupersededAnchor" if $report;
1312                 }
1313                 if ($p->{Breakwater} eq $p->{CommitId}) {
1314                     # this parent commit was its own breakwater,
1315                     # ie it is part of the breakwater
1316                     print $report " Breakwater" if $report;
1317                 } else {
1318                     $might_be_in_bw = 0;
1319                 }
1320                 push @bwbcmd, $p->{Breakwater};
1321                 push @ibcmd, $p->{CommitId};
1322             }
1323
1324             if ($ok && $might_be_in_bw) {
1325                 # We could rewrite this to contaion the metadata
1326                 # declaring it to be MergedBreakwaters, but
1327                 # unnecessarily rewriting a merge seems unhelpful.
1328                 $prline->(" VanillaMerge MergedBreakwaters");
1329                 $last_anchor = $best_anchor;
1330                 $build_start->('MergedBreakwaters', $cur);
1331             }
1332
1333             my $bwb = cmdoutput @bwbcmd;
1334
1335             # OK, now we have a breakwater base, but we need the merge
1336             # base for the interchange branch because we need the delta
1337             # queue.
1338             #
1339             # This a the best merge base of our inputs which has the
1340             # breakwater merge base as an ancestor.
1341
1342             my @ibs =
1343                 grep /./,
1344                 split /\n/,
1345                 cmdoutput @ibcmd;
1346
1347             @ibs or confess 'internal error, expected anchor at least ?';
1348
1349             my $ib;
1350             my $ibleaf;
1351             foreach my $tibix (0..$#ibs) {
1352                 my $tib = $ibs[$tibix];
1353                 my $ff = is_fast_fwd $bwb, $tib;
1354                 my $ok = !$ff ? 'rej' : $ib ? 'extra' : 'ok';
1355                 my $tibleaf = "interchange-mbcand-$ok-$tibix";
1356                 $mwrecknote->($tibleaf, $tib);
1357                 next unless $ff;
1358                 next if $ib;
1359                 $ib = $tib;
1360                 $ibleaf = $tibleaf;
1361             }
1362
1363             $ib or $nomerge->("no suitable interchange merge base");
1364
1365             $prline->("  VanillaMerge Base");
1366             $prprdelim->();
1367             my ($btip, $bbw, $banchor) = eval {
1368                 walk $ib, 0, $report, $report_lprefix.'  ';
1369             };
1370             $nomerge->("walking interchange branch merge base ($ibleaf):\n".
1371                        $@)
1372                 if length $@;
1373
1374             $mwrecknote->("mergebase-laundered", $btip);
1375             $mwrecknote->("mergebase-breakwater", $bbw);
1376             $mwrecknote->("mergebase-anchor", $banchor);
1377
1378             my $ibinfo = { SeriesTip => $btip,
1379                            SeriesBase => $bbw,
1380                            Anchor => $banchor,
1381                            LeftRight => 'mergebase' };
1382
1383             $bbw eq $bwb
1384                 or $nomerge->("interchange merge-base ($ib)'s".
1385                               " breakwater ($bbw)".
1386                               " != breakwaters' merge-base ($bwb)");
1387
1388             grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1389                  or $nomerge->("interchange merge-base ($ib)'s".
1390                                " anchor ($ibinfo->{SeriesBase})".
1391                                " != any merge input's anchor (".
1392                                (join ' ', map { $_->{Anchor} } @$ps).
1393                                ")");
1394
1395             $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1396             $cl->{MergeBestAnchor} = $best_anchor;
1397             push @brw_cl, {
1398                 %$cl,
1399                 SpecialMethod => 'MergeCreateMergedBreakwaters',
1400                 $xmsg->('constructed from vanilla merge',
1401                         ' merged-breakwater'),
1402             };
1403             push @upp_cl, {
1404                 %$cl,
1405                 SpecialMethod => 'MergeMergeSeries',
1406             };
1407             $build_start->('MergeBreakwaters', $cur);
1408         } else {
1409             printdebug "*** WALK BOMB unrecognised\n";
1410             return $bomb->();
1411         }
1412     }
1413     $prprdelim->();
1414
1415     printdebug "*** WALK prep done cur=$cur".
1416         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1417
1418     return if $nogenerate;
1419
1420     # Now we build it back up again
1421
1422     fresh_workarea();
1423
1424     my $rewriting = 0;
1425
1426     my $read_tree_upstream = sub {
1427         my ($treeish) = @_;
1428         read_tree_upstream $treeish, 0, $build;
1429     };
1430
1431     $#upp_cl = $upp_limit if defined $upp_limit;
1432  
1433     my $committer_authline = calculate_committer_authline();
1434
1435     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1436
1437     confess "internal error" unless $build eq (pop @processed)->{CommitId};
1438
1439     in_workarea sub {
1440         mkdir $rd or $!==EEXIST or die $!;
1441         my $current_method;
1442         runcmd @git, qw(read-tree), $build;
1443         foreach my $cl (qw(Debian), (reverse @brw_cl),
1444                         { SpecialMethod => 'RecordBreakwaterTip' },
1445                         qw(Upstream), (reverse @upp_cl)) {
1446             if (!ref $cl) {
1447                 $current_method = $cl;
1448                 next;
1449             }
1450             my $method = $cl->{SpecialMethod} // $current_method;
1451             my @parents = ($build);
1452             my $cltree = $cl->{CommitId};
1453             printdebug "WALK BUILD ".($cltree//'undef').
1454                 " $method (rewriting=$rewriting)\n";
1455             if ($method eq 'Debian') {
1456                 read_tree_debian($cltree);
1457             } elsif ($method eq 'Upstream') {
1458                 $read_tree_upstream->($cltree);
1459             } elsif ($method eq 'StartRewrite') {
1460                 $rewriting = 1;
1461                 next;
1462             } elsif ($method eq 'RecordBreakwaterTip') {
1463                 $breakwater = $build;
1464                 next;
1465             } elsif ($method eq 'DgitImportDebianUpdate') {
1466                 read_tree_debian($cltree);
1467             } elsif ($method eq 'DgitImportUpstreamUpdate') {
1468                 confess unless $rewriting;
1469                 my $differs = (get_differs $build, $cltree);
1470                 next unless $differs & D_UPS;
1471                 $read_tree_upstream->($cltree);
1472                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1473             } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1474                 print "Found a general merge, will try to tidy it up.\n";
1475                 $rewriting = 1;
1476                 $read_tree_upstream->($cl->{MergeBestAnchor});
1477                 $read_tree_upstream->($cl->{MergeBestAnchor});
1478                 read_tree_debian($cltree);
1479                 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1480             } elsif ($method eq 'MergeMergeSeries') {
1481                 my $cachehit = reflog_cache_lookup
1482                     $merge_cache_ref, "vanilla-merge $cl->{CommitId}";
1483                 if ($cachehit) {
1484                     print "Using supplied resolution for $cl->{CommitId}...\n";
1485                     $build = $cachehit;
1486                     $mwrecknote->('cached-resolution', $build);
1487                 } else {
1488                     print "Running merge resolution for $cl->{CommitId}...\n";
1489                     $mwrecknote->('new-base', $build);
1490                     $build = merge_series
1491                         $build, $cl->{MergeWreckNotes},
1492                         $cl->{MergeInterchangeBaseInfo},
1493                         @{ $cl->{Parents} };
1494                 }
1495                 $last_anchor = $cl->{MergeBestAnchor};
1496
1497                 # Check for mismerges:
1498                 my $check = sub {
1499                     my ($against, $allow, $what) = @_;
1500                     my $differs = get_differs $build, $against;
1501                     $nomerge->(sprintf
1502        "merge misresolved: %s are not the same (%s %s d.%#x)",
1503                                $what, $against, $build, $differs)
1504                         if $differs & ~($allow | D_PAT_ADD);
1505                 };
1506
1507                 # Breakwater changes which were in each side of the
1508                 # merge will have been incorporated into the
1509                 # MergeCreateMergedBreakwaters output.  Because the
1510                 # upstream series was rebased onto the new breakwater,
1511                 # so should all of the packaging changes which were in
1512                 # the input.
1513                 $check->($input, D_UPS, 'debian files');
1514
1515                 # Upstream files are merge_series, which ought to
1516                 # have been identical to the original merge.
1517                 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1518
1519                 print "Merge resolution successful.\n";
1520                 next;
1521             } else {
1522                 confess "$method ?";
1523             }
1524             if (!$rewriting) {
1525                 my $procd = (pop @processed) // 'UNDEF';
1526                 if ($cl ne $procd) {
1527                     $rewriting = 1;
1528                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1529                 }
1530             }
1531             my $newtree = cmdoutput @git, qw(write-tree);
1532             my $ch = $cl->{Hdr};
1533             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1534             $ch =~ s{^parent .*\n}{}mg;
1535             $ch =~ s{(?=^author)}{
1536                 join '', map { "parent $_\n" } @parents
1537             }me or confess "$ch ?";
1538             if ($rewriting) {
1539                 $ch =~ s{^committer .*$}{$committer_authline}m
1540                     or confess "$ch ?";
1541             }
1542             my $cf = "$rd/m$rewriting";
1543             open CD, ">", $cf or die $!;
1544             print CD $ch, "\n", $cl->{Msg} or die $!;
1545             close CD or die $!;
1546             my @cmd = (@git, qw(hash-object));
1547             push @cmd, qw(-w) if $rewriting;
1548             push @cmd, qw(-t commit), $cf;
1549             my $newcommit = cmdoutput @cmd;
1550             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1551             $build = $newcommit;
1552             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1553                 $last_anchor = $cur;
1554             }
1555         }
1556     };
1557
1558     my $final_check = get_differs $build, $input;
1559     die sprintf "internal error %#x %s %s", $final_check, $input, $build
1560         if $final_check & ~D_PAT_ADD;
1561
1562     my @r = ($build, $breakwater, $last_anchor);
1563     printdebug "*** WALK RETURN @r\n";
1564     return @r
1565 }
1566
1567 sub get_head () {
1568     git_check_unmodified();
1569     return git_rev_parse qw(HEAD);
1570 }
1571
1572 sub update_head ($$$) {
1573     my ($old, $new, $mrest) = @_;
1574     push @deferred_updates, "update HEAD $new $old";
1575     run_deferred_updates $mrest;
1576 }
1577
1578 sub update_head_checkout ($$$) {
1579     my ($old, $new, $mrest) = @_;
1580     update_head $old, $new, $mrest;
1581     runcmd @git, qw(reset --hard);
1582 }
1583
1584 sub update_head_postlaunder ($$$) {
1585     my ($old, $tip, $reflogmsg) = @_;
1586     return if $tip eq $old;
1587     print "git-debrebase: laundered (head was $old)\n";
1588     update_head $old, $tip, $reflogmsg;
1589     # no tree changes except debian/patches
1590     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1591 }
1592
1593 sub currently_rebasing() {
1594     foreach (qw(rebase-merge rebase-apply)) {
1595         return 1 if stat_exists "$maindir_gitdir/$_";
1596     }
1597     return 0;
1598 }
1599
1600 sub bail_if_rebasing() {
1601     fail "you are in the middle of a git-rebase already"
1602         if currently_rebasing();
1603 }
1604
1605 sub do_launder_head ($) {
1606     my ($reflogmsg) = @_;
1607     my $old = get_head();
1608     record_ffq_auto();
1609     my ($tip,$breakwater) = walk $old;
1610     snags_maybe_bail();
1611     update_head_postlaunder $old, $tip, $reflogmsg;
1612     return ($tip,$breakwater);
1613 }
1614
1615 sub cmd_launder_v0 () {
1616     badusage "no arguments to launder-v0 allowed" if @ARGV;
1617     my $old = get_head();
1618     my ($tip,$breakwater,$last_anchor) = walk $old;
1619     update_head_postlaunder $old, $tip, 'launder';
1620     printf "# breakwater tip\n%s\n", $breakwater;
1621     printf "# working tip\n%s\n", $tip;
1622     printf "# last anchor\n%s\n", $last_anchor;
1623 }
1624
1625 sub defaultcmd_rebase () {
1626     push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1627     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1628     runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1629 }
1630
1631 sub cmd_analyse () {
1632     badusage "analyse does not support any options"
1633         if @ARGV and $ARGV[0] =~ m/^-/;
1634     badusage "too many arguments to analyse" if @ARGV>1;
1635     my ($old) = @ARGV;
1636     if (defined $old) {
1637         $old = git_rev_parse $old;
1638     } else {
1639         $old = git_rev_parse 'HEAD';
1640     }
1641     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1642     STDOUT->error and die $!;
1643 }
1644
1645 sub ffq_prev_branchinfo () {
1646     my $current = git_get_symref();
1647     return gdr_ffq_prev_branchinfo($current);
1648 }
1649
1650 sub ffq_check ($;$$) {
1651     # calls $ff and/or $notff zero or more times
1652     # then returns either (status,message) where status is
1653     #    exists
1654     #    detached
1655     #    weird-symref
1656     #    notbranch
1657     # or (undef,undef, $ffq_prev,$gdrlast)
1658     # $ff and $notff are called like this:
1659     #   $ff->("message for stdout\n");
1660     #   $notff->('snag-name', $message);
1661     # normally $currentval should be HEAD
1662     my ($currentval, $ff, $notff) =@_;
1663
1664     $ff //= sub { print $_[0] or die $!; };
1665     $notff //= \&snag;
1666
1667     my ($status, $message, $current, $ffq_prev, $gdrlast)
1668         = ffq_prev_branchinfo();
1669     return ($status, $message) unless $status eq 'branch';
1670
1671     my $exists = git_get_ref $ffq_prev;
1672     return ('exists',"$ffq_prev already exists") if $exists;
1673
1674     return ('not-branch', 'HEAD symref is not to refs/heads/')
1675         unless $current =~ m{^refs/heads/};
1676     my $branch = $';
1677
1678     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1679     my %checked;
1680
1681     printdebug "ffq check_specs @check_specs\n";
1682
1683     my $check = sub {
1684         my ($lrref, $desc) = @_;
1685         printdebug "ffq might check $lrref ($desc)\n";
1686         my $invert;
1687         for my $chk (@check_specs) {
1688             my $glob = $chk;
1689             $invert = $glob =~ s{^[!^]}{};
1690             last if fnmatch $glob, $lrref;
1691         }
1692         return if $invert;
1693         my $lrval = git_get_ref $lrref;
1694         return unless length $lrval;
1695
1696         if (is_fast_fwd $lrval, $currentval) {
1697             $ff->("OK, you are ahead of $lrref\n");
1698             $checked{$lrref} = 1;
1699         } elsif (is_fast_fwd $currentval, $lrval) {
1700             $checked{$lrref} = -1;
1701             $notff->('behind', "you are behind $lrref, divergence risk");
1702         } else {
1703             $checked{$lrref} = -1;
1704             $notff->('diverged', "you have diverged from $lrref");
1705         }
1706     };
1707
1708     my $merge = cfg "branch.$branch.merge",1;
1709     if (defined $merge and $merge =~ m{^refs/heads/}) {
1710         my $rhs = $';
1711         printdebug "ffq merge $rhs\n";
1712         my $check_remote = sub {
1713             my ($remote, $desc) = @_;
1714             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1715             return unless defined $remote;
1716             $check->("refs/remotes/$remote/$rhs", $desc);
1717         };
1718         $check_remote->((scalar cfg "branch.$branch.remote",1),
1719                         'remote fetch/merge branch');
1720         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1721                         (scalar cfg "branch.$branch.pushDefault",1),
1722                         'remote push branch');
1723     }
1724     if ($branch =~ m{^dgit/}) {
1725         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1726     } elsif ($branch =~ m{^master$}) {
1727         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1728     }
1729     return (undef, undef, $ffq_prev, $gdrlast);
1730 }
1731
1732 sub record_ffq_prev_deferred () {
1733     # => ('status', "message")
1734     # 'status' may be
1735     #    deferred          message is undef
1736     #    exists
1737     #    detached
1738     #    weird-symref
1739     #    notbranch
1740     # if not ff from some branch we should be ff from, is an snag
1741     # if "deferred", will have added something about that to
1742     #   @deferred_update_messages, and also maybe printed (already)
1743     #   some messages about ff checks
1744     bail_if_rebasing();
1745     my $currentval = get_head();
1746
1747     my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1748     return ($status,$message) if defined $status;
1749
1750     snags_maybe_bail();
1751
1752     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1753     push @deferred_updates, "delete $gdrlast";
1754     push @deferred_update_messages, "Recorded previous head for preservation";
1755     return ('deferred', undef);
1756 }
1757
1758 sub record_ffq_auto () {
1759     my ($status, $message) = record_ffq_prev_deferred();
1760     if ($status eq 'deferred' || $status eq 'exists') {
1761     } else {
1762         snag $status, "could not record ffq-prev: $message";
1763         snags_maybe_bail();
1764     }
1765 }
1766
1767 sub ffq_prev_info () {
1768     bail_if_rebasing();
1769     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1770     my ($status, $message, $current, $ffq_prev, $gdrlast)
1771         = ffq_prev_branchinfo();
1772     if ($status ne 'branch') {
1773         snag $status, "could not check ffq-prev: $message";
1774         snags_maybe_bail();
1775     }
1776     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1777     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1778 }
1779
1780 sub stitch ($$$$$) {
1781     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1782
1783     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1784
1785     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1786         my $differs = get_differs $old_head, $ffq_prev_commitish;
1787         unless ($differs & ~D_PAT_ADD) {
1788             # ffq-prev is ahead of us, and the only tree changes it has
1789             # are possibly addition of things in debian/patches/.
1790             # Just wind forwards rather than making a pointless pseudomerge.
1791             push @deferred_updates,
1792                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1793             update_head_checkout $old_head, $ffq_prev_commitish,
1794                 "stitch (fast forward)";
1795             return;
1796         }
1797     }
1798     fresh_workarea();
1799     # We make pseudomerges with L as the contributing parent.
1800     # This makes git rev-list --first-parent work properly.
1801     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1802         'Declare fast forward / record previous work',
1803         "[git-debrebase pseudomerge: $prose]",
1804     ];
1805     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1806     update_head $old_head, $new_head, "stitch: $prose";
1807 }
1808
1809 sub do_stitch ($;$) {
1810     my ($prose, $unclean) = @_;
1811
1812     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1813     if (!$ffq_prev_commitish) {
1814         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1815         return;
1816     }
1817     my $dangling_head = get_head();
1818
1819     keycommits $dangling_head, $unclean,$unclean,$unclean;
1820     snags_maybe_bail();
1821
1822     stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1823 }
1824
1825 sub upstream_commitish_search ($$) {
1826     my ($upstream_version, $tried) = @_;
1827     # todo: at some point maybe use git-deborig to do this
1828     foreach my $tagpfx ('', 'v', 'upstream/') {
1829         my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1830         my $new_upstream = git_get_ref "refs/tags/$tag";
1831         push @$tried, $tag;
1832         return $new_upstream if length $new_upstream;
1833     }
1834 }
1835
1836 sub resolve_upstream_version ($$) {
1837     my ($new_upstream, $upstream_version) = @_;
1838
1839     if (!defined $new_upstream) {
1840         my @tried;
1841         $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1842         if (!length $new_upstream) {
1843             fail "Could not determine appropriate upstream commitish.\n".
1844                 " (Tried these tags: @tried)\n".
1845                 " Check version, and specify upstream commitish explicitly.";
1846         }
1847     }
1848     $new_upstream = git_rev_parse $new_upstream;
1849
1850     return $new_upstream;
1851 }
1852
1853 sub cmd_new_upstream () {
1854     # automatically and unconditionally launders before rebasing
1855     # if rebase --abort is used, laundering has still been done
1856
1857     my %pieces;
1858
1859     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1860
1861     # parse args - low commitment
1862     my $spec_version = shift @ARGV;
1863     my $new_version = (new Dpkg::Version $spec_version, check => 1);
1864     fail "bad version number \`$spec_version'" unless defined $new_version;
1865     if ($new_version->is_native()) {
1866         $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1867     }
1868
1869     my $new_upstream = shift @ARGV;
1870     my $new_upstream_version = upstreamversion  $new_version;
1871     $new_upstream =
1872         resolve_upstream_version $new_upstream, $new_upstream_version;
1873
1874     record_ffq_auto();
1875
1876     my $piece = sub {
1877         my ($n, @x) = @_; # may be ''
1878         my $pc = $pieces{$n} //= {
1879             Name => $n,
1880             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1881         };
1882         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1883         $pc;
1884     };
1885
1886     my @newpieces;
1887     my $newpiece = sub {
1888         my ($n, @x) = @_; # may be ''
1889         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1890         push @newpieces, $pc;
1891     };
1892
1893     $newpiece->('',
1894         OldIx => 0,
1895         New => $new_upstream,
1896     );
1897     while (@ARGV && $ARGV[0] !~ m{^-}) {
1898         my $n = shift @ARGV;
1899
1900         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1901             unless @ARGV && $ARGV[0] !~ m{^-};
1902
1903         my $c = git_rev_parse shift @ARGV;
1904         die unless $n =~ m/^$extra_orig_namepart_re$/;
1905         $newpiece->($n, New => $c);
1906     }
1907
1908     # now we need to investigate the branch this generates the
1909     # laundered version but we don't switch to it yet
1910     my $old_head = get_head();
1911     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1912
1913     my $old_bw_cl = classify $old_bw;
1914     my $old_anchor_cl = classify $old_anchor;
1915     my $old_upstream;
1916     if (!$old_anchor_cl->{OrigParents}) {
1917         snag 'anchor-treated',
1918             'old anchor is recognised due to --anchor, cannot check upstream';
1919     } else {
1920         $old_upstream = parsecommit
1921             $old_anchor_cl->{OrigParents}[0]{CommitId};
1922         $piece->('', Old => $old_upstream->{CommitId});
1923     }
1924
1925     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1926         if ($old_upstream->{Msg} =~
1927  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1928            ) {
1929             my @oldpieces = (split / /, $1);
1930             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1931             if ($old_n_parents != @oldpieces &&
1932                 $old_n_parents != @oldpieces + 1) {
1933                 snag 'upstream-confusing', sprintf
1934                     "previous upstream combine %s".
1935                     " mentions %d pieces (each implying one parent)".
1936                     " but has %d parents".
1937                     " (one per piece plus maybe a previous combine)",
1938                     $old_upstream->{CommitId},
1939                     (scalar @oldpieces),
1940                     $old_n_parents;
1941             } elsif ($oldpieces[0] ne '.') {
1942                 snag 'upstream-confusing', sprintf
1943                     "previous upstream combine %s".
1944                     " first piece is not \`.'",
1945                     $oldpieces[0];
1946             } else {
1947                 $oldpieces[0] = '';
1948                 foreach my $i (0..$#oldpieces) {
1949                     my $n = $oldpieces[$i];
1950                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1951                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1952                 }
1953             }
1954         } else {
1955             snag 'upstream-confusing',
1956                 "previous upstream $old_upstream->{CommitId} is from".
1957                " git-debrebase but not an \`upstream-combine' commit";
1958         }
1959     }
1960
1961     foreach my $pc (values %pieces) {
1962         if (!$old_upstream) {
1963             # we have complained already
1964         } elsif (!$pc->{Old}) {
1965             snag 'upstream-new-piece',
1966                 "introducing upstream piece \`$pc->{Name}'";
1967         } elsif (!$pc->{New}) {
1968             snag 'upstream-rm-piece',
1969                 "dropping upstream piece \`$pc->{Name}'";
1970         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1971             snag 'upstream-not-ff',
1972                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1973         }
1974     }
1975
1976     printdebug "%pieces = ", (dd \%pieces), "\n";
1977     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1978
1979     snags_maybe_bail();
1980
1981     my $new_bw;
1982
1983     fresh_workarea();
1984     in_workarea sub {
1985         my @upstream_merge_parents;
1986
1987         if (!any_snags()) {
1988             push @upstream_merge_parents, $old_upstream->{CommitId};
1989         }
1990
1991         foreach my $pc (@newpieces) { # always has '' first
1992             if ($pc->{Name}) {
1993                 read_tree_subdir $pc->{Name}, $pc->{New};
1994             } else {
1995                 runcmd @git, qw(read-tree), $pc->{New};
1996             }
1997             push @upstream_merge_parents, $pc->{New};
1998         }
1999
2000         # index now contains the new upstream
2001
2002         if (@newpieces > 1) {
2003             # need to make the upstream subtree merge commit
2004             $new_upstream = make_commit \@upstream_merge_parents,
2005                 [ "Combine upstreams for $new_upstream_version",
2006  ("[git-debrebase upstream-combine . ".
2007  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
2008  ": new upstream]"),
2009                 ];
2010         }
2011
2012         # $new_upstream is either the single upstream commit, or the
2013         # combined commit we just made.  Either way it will be the
2014         # "upstream" parent of the anchor merge.
2015
2016         read_tree_subdir 'debian', "$old_bw:debian";
2017
2018         # index now contains the anchor merge contents
2019         $new_bw = make_commit [ $old_bw, $new_upstream ],
2020             [ "Update to upstream $new_upstream_version",
2021  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
2022             ];
2023
2024         my $clogsignoff = cmdoutput qw(git show),
2025             '--pretty=format:%an <%ae>  %aD',
2026             $new_bw;
2027
2028         # Now we have to add a changelog stanza so the Debian version
2029         # is right.
2030         die if unlink "debian";
2031         die $! unless $!==ENOENT or $!==ENOTEMPTY;
2032         unlink "debian/changelog" or $!==ENOENT or die $!;
2033         mkdir "debian" or die $!;
2034         open CN, ">", "debian/changelog" or die $!;
2035         my $oldclog = git_cat_file ":debian/changelog";
2036         $oldclog =~ m/^($package_re) \(\S+\) / or
2037             fail "cannot parse old changelog to get package name";
2038         my $p = $1;
2039         print CN <<END, $oldclog or die $!;
2040 $p ($new_version) UNRELEASED; urgency=medium
2041
2042   * Update to new upstream version $new_upstream_version.
2043
2044  -- $clogsignoff
2045
2046 END
2047         close CN or die $!;
2048         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
2049
2050         # Now we have the final new breakwater branch in the index
2051         $new_bw = make_commit [ $new_bw ],
2052             [ "Update changelog for new upstream $new_upstream_version",
2053               "[git-debrebase: new upstream $new_upstream_version, changelog]",
2054             ];
2055     };
2056
2057     # we have constructed the new breakwater. we now need to commit to
2058     # the laundering output, because git-rebase can't easily be made
2059     # to make a replay list which is based on some other branch
2060
2061     update_head_postlaunder $old_head, $old_laundered_tip,
2062         'launder for new upstream';
2063
2064     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
2065     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
2066         "debrebase new-upstream $new_version: rebase";
2067     runcmd @cmd;
2068     # now it's for the user to sort out
2069 }
2070
2071 sub cmd_record_ffq_prev () {
2072     badusage "no arguments allowed" if @ARGV;
2073     my ($status, $msg) = record_ffq_prev_deferred();
2074     if ($status eq 'exists' && $opt_noop_ok) {
2075         print "Previous head already recorded\n" or die $!;
2076     } elsif ($status eq 'deferred') {
2077         run_deferred_updates 'record-ffq-prev';
2078     } else {
2079         fail "Could not preserve: $msg";
2080     }
2081 }
2082
2083 sub cmd_anchor () {
2084     badusage "no arguments allowed" if @ARGV;
2085     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2086     print "$bw\n" or die $!;
2087 }
2088
2089 sub cmd_breakwater () {
2090     badusage "no arguments allowed" if @ARGV;
2091     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
2092     print "$bw\n" or die $!;
2093 }
2094
2095 sub cmd_status () {
2096     badusage "no arguments allowed" if @ARGV;
2097
2098     # todo: gdr status should print divergence info
2099     # todo: gdr status should print upstream component(s) info
2100     # todo: gdr should leave/maintain some refs with this kind of info ?
2101
2102     my $oldest = { Badness => 0 };
2103     my $newest;
2104     my $note = sub {
2105         my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
2106         if ($oldest->{Badness} < $badness) {
2107             $oldest = $newest = undef;
2108         }
2109         $oldest = {
2110                    Badness => $badness,
2111                    CommitId => $cl->{CommitId},
2112                    OurMsg => $ourmsg,
2113                    KcMsg => $kcmsg,
2114                   };
2115         $newest //= $oldest;
2116     };
2117     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
2118         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
2119         sub { $note->(2, 'branch is unlaundered', @_); },
2120         sub { $note->(3, 'branch needs laundering', @_); },
2121         sub { $note->(4, 'branch not in git-debrebase form', @_); };
2122
2123     my $prcommitinfo = sub {
2124         my ($cid) = @_;
2125         flush STDOUT or die $!;
2126         runcmd @git, qw(--no-pager log -n1),
2127             '--pretty=format:    %h %s%n',
2128             $cid;
2129     };
2130
2131     print "current branch contents, in git-debrebase terms:\n";
2132     if (!$oldest->{Badness}) {
2133         print "  branch is laundered\n";
2134     } else {
2135         print "  $oldest->{OurMsg}\n";
2136         my $printed = '';
2137         foreach my $info ($oldest, $newest) {
2138             my $cid = $info->{CommitId};
2139             next if $cid eq $printed;
2140             $printed = $cid;
2141             print "  $info->{KcMsg}\n";
2142             $prcommitinfo->($cid);
2143         }
2144     }
2145
2146     my $prab = sub {
2147         my ($cid, $what) = @_;
2148         if (!defined $cid) {
2149             print "  $what is not well-defined\n";
2150         } else {
2151             print "  $what\n";
2152             $prcommitinfo->($cid);
2153         }
2154     };
2155     print "key git-debrebase commits:\n";
2156     $prab->($anchor, 'anchor');
2157     $prab->($bw, 'breakwater');
2158
2159     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
2160         ffq_prev_branchinfo();
2161
2162     print "branch and ref status, in git-debrebase terms:\n";
2163     if ($ffq_msg) {
2164         print "  $ffq_msg\n";
2165     } else {
2166         $ffq_prev = git_get_ref $ffq_prev;
2167         $gdrlast = git_get_ref $gdrlast;
2168         if ($ffq_prev) {
2169             print "  unstitched; previous tip was:\n";
2170             $prcommitinfo->($ffq_prev);
2171         } elsif (!$gdrlast) {
2172             print "  stitched? (no record of git-debrebase work)\n";
2173         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2174             print "  stitched\n";
2175         } else {
2176             print "  not git-debrebase (diverged since last stitch)\n"
2177         }
2178     }
2179     print "you are currently rebasing\n" if currently_rebasing();
2180 }
2181
2182 sub cmd_stitch () {
2183     my $prose = 'stitch';
2184     getoptions("stitch",
2185                'prose=s', \$prose);
2186     badusage "no arguments allowed" if @ARGV;
2187     do_stitch $prose, 0;
2188 }
2189 sub cmd_prepush () { cmd_stitch(); }
2190
2191 sub cmd_quick () {
2192     badusage "no arguments allowed" if @ARGV;
2193     do_launder_head 'launder for git-debrebase quick';
2194     do_stitch 'quick';
2195 }
2196
2197 sub cmd_conclude () {
2198     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2199     if (!$ffq_prev_commitish) {
2200         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2201         return;
2202     }
2203     my $dangling_head = get_head();
2204     
2205     badusage "no arguments allowed" if @ARGV;
2206     do_launder_head 'launder for git-debrebase quick';
2207     do_stitch 'quick';
2208 }
2209
2210 sub cmd_scrap () {
2211     if (currently_rebasing()) {
2212         runcmd @git, qw(rebase --abort);
2213         push @deferred_updates, 'verify HEAD HEAD';
2214         # noop, but stops us complaining that scrap was a noop
2215     }
2216     badusage "no arguments allowed" if @ARGV;
2217     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2218     my $scrapping_head;
2219     if ($ffq_prev_commitish) {
2220         $scrapping_head = get_head();
2221         push @deferred_updates,
2222             "update $gdrlast $ffq_prev_commitish $git_null_obj",
2223             "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2224     }
2225     if (git_get_ref $merge_cache_ref) {
2226         push @deferred_updates,
2227             "delete $merge_cache_ref";
2228     }
2229     if (!@deferred_updates) {
2230         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2231         finish 0;
2232     }
2233     snags_maybe_bail();
2234     if ($scrapping_head) {
2235         update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2236     } else {
2237         run_deferred_updates "scrap";
2238     }
2239 }
2240
2241 sub make_patches_staged ($) {
2242     my ($head) = @_;
2243     # Produces the patches that would result from $head if it were
2244     # laundered.
2245     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2246     fresh_workarea();
2247     in_workarea sub {
2248         gbp_pq_export 'bw', $secret_bw, $secret_head;
2249     };
2250 }
2251
2252 sub make_patches ($) {
2253     my ($head) = @_;
2254     keycommits $head, 0, \&snag;
2255     make_patches_staged $head;
2256     my $out;
2257     in_workarea sub {
2258         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2259         runcmd @git, qw(read-tree), $head;
2260         read_tree_subdir 'debian/patches', $ptree;
2261         $out = make_commit [$head], [
2262             'Commit patch queue (exported by git-debrebase)',
2263             '[git-debrebase: export and commit patches]',
2264         ];
2265     };
2266     return $out;
2267 }
2268
2269 sub cmd_make_patches () {
2270     my $opt_quiet_would_amend;
2271     getoptions("make-patches",
2272                'quiet-would-amend!', \$opt_quiet_would_amend);
2273     badusage "no arguments allowed" if @ARGV;
2274     bail_if_rebasing();
2275     my $old_head = get_head();
2276     my $new = make_patches $old_head;
2277     my $d = get_differs $old_head, $new;
2278     if ($d == 0) {
2279         fail "No (more) patches to export." unless $opt_noop_ok;
2280         return;
2281     } elsif ($d == D_PAT_ADD) {
2282         snags_maybe_bail();
2283         update_head_checkout $old_head, $new, 'make-patches';
2284     } else {
2285         print STDERR failmsg
2286             "Patch export produced patch amendments".
2287             " (abandoned output commit $new).".
2288             "  Try laundering first."
2289             unless $opt_quiet_would_amend;
2290         finish 7;
2291     }
2292 }
2293
2294 sub cmd_convert_from_gbp () {
2295     badusage "want only 1 optional argument, the upstream git commitish"
2296         unless @ARGV<=1;
2297
2298     my $clogp = parsechangelog();
2299     my $version = $clogp->{'Version'}
2300         // die "missing Version from changelog";
2301
2302     my ($upstream_spec) = @ARGV;
2303
2304     my $upstream_version = upstreamversion $version;
2305     my $upstream =
2306         resolve_upstream_version($upstream_spec, $upstream_version);
2307
2308     my $old_head = get_head();
2309
2310     my $upsdiff = get_differs $upstream, $old_head;
2311     if ($upsdiff & D_UPS) {
2312         runcmd @git, qw(--no-pager diff --stat),
2313             $upstream, $old_head,
2314             qw( -- :!/debian :/);
2315         fail <<END;
2316 upstream ($upstream_spec) and HEAD are not
2317 identical in upstream files.  See diffstat above, or run
2318   git diff $upstream_spec HEAD -- :!/debian :/
2319 END
2320     }
2321
2322     if (!is_fast_fwd $upstream, $old_head) {
2323         snag 'upstream-not-ancestor',
2324             "upstream ($upstream) is not an ancestor of HEAD";
2325     } else {
2326         my $wrong = cmdoutput
2327             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2328              qw(-- :/ :!/debian));
2329         if (length $wrong) {
2330             snag 'unexpected-upstream-changes',
2331                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2332             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2333         }
2334     }
2335
2336     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2337         snag 'upstream-has-debian',
2338             "upstream ($upstream) contains debian/ directory";
2339     }
2340
2341     my $previous_dgit_view = eval {
2342         my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2343         my ($lvsn, $suite);
2344         parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2345             my ($stz, $desc) = @_;
2346             no warnings qw(exiting);
2347             printdebug 'CHANGELOG ', Dumper($desc, $stz);
2348             next unless $stz->{Date};
2349             next unless $stz->{Distribution} ne 'UNRELEASED';
2350             $lvsn = $stz->{Version};
2351             $suite = $stz->{Distribution};
2352             last;
2353         };
2354         die "neither of the first two changelog entries are released\n"
2355             unless defined $lvsn;
2356         print "last finished-looking changelog entry: ($lvsn) $suite\n";
2357         my $mtag_pat = debiantag_maintview $lvsn, '*';
2358         my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2359             $mtag_pat;
2360         die "could not find suitable maintainer view tag $mtag_pat\n"
2361             unless $mtag_pat =~ m{/};
2362         is_fast_fwd $mtag, 'HEAD' or
2363             die "HEAD is not FF from maintainer tag $mtag!";
2364         my $dtag = "archive/$mtag";
2365         is_fast_fwd $mtag, $dtag or
2366             die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2367         print "will stitch in dgit view, $dtag\n";
2368         git_rev_parse $dtag;
2369     };
2370     if (!$previous_dgit_view) {
2371         $@ =~ s/^\n+//;
2372         chomp $@;
2373         print STDERR "cannot stitch in dgit view: $@\n";
2374     }
2375
2376     snags_maybe_bail_early();
2377
2378     my $work;
2379
2380     fresh_workarea();
2381     in_workarea sub {
2382         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2383         # make a branch out of the patch queue - we'll want this in a mo
2384         runcmd qw(gbp pq import);
2385         # strip the patches out
2386         runcmd @git, qw(checkout -q gdr-internal~0);
2387         rm_subdir_cached 'debian/patches';
2388         $work = make_commit ['HEAD'], [
2389  'git-debrebase convert-from-gbp: drop patches from tree',
2390  'Delete debian/patches, as part of converting to git-debrebase format.',
2391  '[git-debrebase convert-from-gbp: drop patches from tree]'
2392                               ];
2393         # make the anchor merge
2394         # the tree is already exactly right
2395         $work = make_commit [$work, $upstream], [
2396  'git-debrebase import: declare upstream',
2397  'First breakwater merge.',
2398  '[git-debrebase anchor: declare upstream]'
2399                               ];
2400
2401         # rebase the patch queue onto the new breakwater
2402         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2403         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2404         $work = git_rev_parse 'HEAD';
2405
2406         if ($previous_dgit_view) {
2407             $work = make_commit [$work, $previous_dgit_view], [
2408  'git-debrebase import: declare ff from dgit archive view',
2409  '[git-debrebase pseudomerge: import-from-gbp]',
2410             ];
2411         }
2412     };
2413
2414     ffq_check $work;
2415     snags_maybe_bail();
2416     update_head_checkout $old_head, $work, 'convert-from-gbp';
2417 }
2418
2419 sub cmd_convert_to_gbp () {
2420     badusage "no arguments allowed" if @ARGV;
2421     my $head = get_head();
2422     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2423     keycommits $head, 0;
2424     my $out;
2425     make_patches_staged $head;
2426     in_workarea sub {
2427         $out = make_commit ['HEAD'], [
2428             'Commit patch queue (converted from git-debrebase format)',
2429             '[git-debrebase convert-to-gbp: commit patches]',
2430         ];
2431     };
2432     if (defined $ffq) {
2433         push @deferred_updates, "delete $ffq";
2434         push @deferred_updates, "delete $gdrlast";
2435     }
2436     snags_maybe_bail();
2437     update_head_checkout $head, $out, "convert to gbp (v0)";
2438     print <<END or die $!;
2439 git-debrebase: converted to git-buildpackage branch format
2440 git-debrebase: WARNING: do not now run "git-debrebase" any more
2441 git-debrebase: WARNING: doing so would drop all upstream patches!
2442 END
2443 }
2444
2445 sub cmd_convert_from_dgit_view () { 
2446     my $clogp = parsechangelog();
2447
2448     my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2449     my $do_origs = 1;
2450     my $do_tags = 1;
2451     my $always = 0;
2452     my $diagnose = 0;
2453
2454     getoptions("convert-from-dgit-view",
2455                'diagnose!', \$diagnose,
2456                'build-products-dir:s', \$bpd,
2457                'origs!', \$do_origs,
2458                'tags!', \$do_tags,
2459                'always-convert-anyway!', \$always);
2460     fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2461
2462     my @upstreams;
2463
2464     if (@ARGV) {
2465         my $spec = shift @ARGV;
2466         my $commit = git_rev_parse "$spec^{commit}";
2467         push @upstreams, { Commit => $commit,
2468                            Source => "$ARGV[0], from command line",
2469                            Only => 1,
2470                          };
2471     }
2472
2473     my $head = get_head();
2474
2475     if (!$always) {
2476         my $troubles = 0;
2477         my $trouble = sub { $troubles++; };
2478         keycommits $head, sub{}, sub{}, $trouble, $trouble;
2479         printdebug "troubles=$troubles\n";
2480         if (!$troubles) {
2481             print STDERR <<END;
2482 $us: Branch already seems to be in git-debrebase format!
2483 $us: --always-convert-anyway would do the conversion operation anyway
2484 $us: but is probably a bad idea.  Probably, you wanted to do nothing.
2485 END
2486             fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2487             finish 0;
2488         }
2489     }
2490
2491     snags_maybe_bail_early();
2492
2493     my $version = upstreamversion $clogp->{Version};
2494     print STDERR "Considering possible commits corresponding to upstream:\n";
2495
2496     if (!@upstreams) {
2497         if ($do_tags) {
2498             my @tried;
2499             my $ups_tag = upstream_commitish_search $version, \@tried;
2500             if ($ups_tag) {
2501                 my $this = "git tag $tried[-1]";
2502                 push @upstreams, { Commit => $ups_tag,
2503                                    Source => $this,
2504                                  };
2505             } else {
2506                 printf STDERR
2507                     " git tag: no suitable tag found (tried %s)\n",
2508                     "@tried";
2509             }
2510         }
2511         if ($do_origs) {
2512             my $p = $clogp->{'Source'};
2513             # we do a quick check to see if there are plausible origs
2514             my $something=0;
2515             if (!opendir BPD, $bpd) {
2516                 die "$bpd: opendir: $!" unless $!==ENOENT;
2517             } else {
2518                 while ($!=0, my $f = readdir BPD) {
2519                     next unless is_orig_file_of_p_v $f, $p, $version;
2520                     printf STDERR
2521                         " orig: found what looks like a .orig, %s\n",
2522                         "$bpd/$f";
2523                     $something=1;
2524                     last;
2525                 }
2526                 die "read $bpd: $!" if $!;
2527                 closedir BPD;
2528             }
2529             if ($something) {
2530                 my $tree = cmdoutput
2531                     @dgit, qw(--build-products-dir), $bpd,
2532                     qw(print-unapplied-treeish);
2533                 fresh_workarea();
2534                 in_workarea sub {
2535                     runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2536                     rm_subdir_cached 'debian';
2537                     $tree = cmdoutput @git, qw(write-tree);
2538                     my $ups_synth = make_commit [], [ <<END, <<END,
2539 Import effective orig tree for upstream version $version
2540 END
2541 This includes the contents of the .orig(s), minus any debian/ directory.
2542
2543 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2544 END
2545                                                     ];
2546                     push @upstreams, { Commit => $ups_synth,
2547                                        Source => "orig(s) imported via dgit",
2548                                      };
2549                 }
2550             } else {
2551                 printf STDERR
2552                     " orig: no suitable origs found (looked for %s in %s)\n",
2553                     "${p}_".(stripeoch $version)."...", $bpd;
2554             }
2555         }
2556     }
2557
2558     my $some_patches = stat_exists 'debian/patches/series';
2559
2560     print STDERR "Evaluating possible commits corresponding to upstream:\n";
2561
2562     my $result;
2563     foreach my $u (@upstreams) {
2564         my $work = $head;
2565         fresh_workarea();
2566         in_workarea sub {
2567             runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2568             runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2569             runcmd @git, qw(clean -xdff);
2570             runcmd @git, qw(checkout), $head, qw(-- debian);
2571             if ($some_patches) {
2572                 rm_subdir_cached 'debian/patches';
2573                 $work = make_commit [ $work ], [
2574  'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2575  "Drop upstream changes, and delete debian/patches, as part of converting\n".
2576  "to git-debrebase format.  Upstream changes will appear as commits.",
2577  '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2578                                            ];
2579             }
2580             $work = make_commit [ $work, $u->{Commit} ], [
2581  'git-debrebase convert-from-dgit-view: declare upstream',
2582  '(Re)constructed breakwater merge.',
2583  '[git-debrebase anchor: declare upstream]'
2584                                                          ];
2585             runcmd @git, qw(checkout --quiet -b mk), $work;
2586             if ($some_patches) {
2587                 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2588                 runcmd @git, qw(reset --quiet);
2589                 my @gbp_cmd = (qw(gbp pq import));
2590                 if (!$diagnose) {
2591                     my $gbp_err = "../gbp-pq-err";
2592                     @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2593                 }
2594                 my $r = system @gbp_cmd;
2595                 if ($r) {
2596                     printf STDERR
2597                         " %s: couldn't apply patches: gbp pq %s",
2598                         $u->{Source}, waitstatusmsg();
2599                     return;
2600                 }
2601             }
2602             my $work = git_rev_parse qw(HEAD);
2603             my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2604             if (length $diffout) {
2605                 print STDERR
2606                     " $u->{Source}: applying patches gives different tree\n";
2607                 print STDERR $diffout if $diagnose;
2608                 return;
2609             }
2610             # OMG!
2611             $u->{Result} = $work;
2612             $result = $u;
2613         };
2614         last if $result;
2615     }
2616
2617     if (!$result) {
2618         fail <<END;
2619 Could not find or construct a suitable upstream commit.
2620 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2621 upstream commmit explicitly or provide suitable origs.
2622 END
2623     }
2624
2625     printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2626
2627     ffq_check $result->{Result};
2628     snags_maybe_bail();
2629     update_head_checkout $head, $result->{Result},
2630         'convert-from-dgit-view';
2631 }
2632
2633 sub cmd_record_resolved_merge () {
2634     badusage "record-resolved-merge takes no further arguments" if @ARGV;
2635     # xxx needs documentation
2636     my $new = get_head();
2637     my $method;
2638
2639     print "Checking how you have resolved the merge problem\n";
2640     my $nope = sub { print "Not $method: @_"; 0; };
2641
2642     my $maybe = sub { print "Seems to be $method.\n"; };
2643     my $yes = sub {
2644         my ($key, $ref) = @_;
2645         reflog_cache_insert $merge_cache_ref, $key, $ref;
2646         print "OK.  You can switch branches and try git-debrebase again.\n";
2647         1;
2648     };
2649
2650     fresh_workarea 'merge';
2651     sub {
2652         $method = 'vanilla-merge patchqueue';
2653         my $vanilla = git_get_ref "$wrecknoteprefix/vanilla-merge";
2654         $vanilla or return $nope->("wreckage was not of vanilla-merge");
2655         foreach my $lr (qw(left right)) {
2656             my $n = "$wrecknoteprefix/$lr-patchqueue";
2657             my $lrpq = git_get_ref $n;
2658             $lrpq or return $nope->("wreckage did not contain patchqueues");
2659             is_fast_fwd $lrpq, $new or return $nope->("HEAD not ff of $n");
2660         }
2661         $maybe->();
2662         my $newbase = git_get_ref "$wrecknoteprefix/new-base"
2663             or die "wreckage element $wrecknoteprefix/new-base missing";
2664         my $result = merge_series_patchqueue_convert
2665             {}, $newbase, $new;
2666         $yes->("vanilla-merge $vanilla", $result);
2667         1;
2668     }->() or sub {
2669         fail "No resolved merge method seems applicable.\n";
2670     }->();
2671 }
2672
2673 sub cmd_downstream_rebase_launder_v0 () {
2674     badusage "needs 1 argument, the baseline" unless @ARGV==1;
2675     my ($base) = @ARGV;
2676     $base = git_rev_parse $base;
2677     my $old_head = get_head();
2678     my $current = $old_head;
2679     my $topmost_keep;
2680     for (;;) {
2681         if ($current eq $base) {
2682             $topmost_keep //= $current;
2683             print " $current BASE stop\n";
2684             last;
2685         }
2686         my $cl = classify $current;
2687         print " $current $cl->{Type}";
2688         my $keep = 0;
2689         my $p0 = $cl->{Parents}[0]{CommitId};
2690         my $next;
2691         if ($cl->{Type} eq 'Pseudomerge') {
2692             print " ^".($cl->{Contributor}{Ix}+1);
2693             $next = $cl->{Contributor}{CommitId};
2694         } elsif ($cl->{Type} eq 'AddPatches' or
2695                  $cl->{Type} eq 'Changelog') {
2696             print " strip";
2697             $next = $p0;
2698         } else {
2699             print " keep";
2700             $next = $p0;
2701             $keep = 1;
2702         }
2703         print "\n";
2704         if ($keep) {
2705             $topmost_keep //= $current;
2706         } else {
2707             die "to-be stripped changes not on top of the branch\n"
2708                 if $topmost_keep;
2709         }
2710         $current = $next;
2711     }
2712     if ($topmost_keep eq $old_head) {
2713         print "unchanged\n";
2714     } else {
2715         print "updating to $topmost_keep\n";
2716         update_head_checkout
2717             $old_head, $topmost_keep,
2718             'downstream-rebase-launder-v0';
2719     }
2720 }
2721
2722 getoptions_main
2723           ("bad options\n",
2724            "D+" => \$debuglevel,
2725            'noop-ok', => \$opt_noop_ok,
2726            'f=s' => \@snag_force_opts,
2727            'anchor=s' => \@opt_anchors,
2728            '--dgit=s' => \($dgit[0]),
2729            'force!',
2730            '-i:s' => sub {
2731                my ($opt,$val) = @_;
2732                badusage "git-debrebase: no cuddling to -i for git-rebase"
2733                    if length $val;
2734                die if $opt_defaultcmd_interactive; # should not happen
2735                $opt_defaultcmd_interactive = [ qw(-i) ];
2736                # This access to @ARGV is excessive familiarity with
2737                # Getopt::Long, but there isn't another sensible
2738                # approach.  '-i=s{0,}' does not work with bundling.
2739                push @$opt_defaultcmd_interactive, @ARGV;
2740                @ARGV=();
2741            },
2742            'help' => sub { print $usage_message or die $!; finish 0; },
2743            );
2744
2745 initdebug('git-debrebase ');
2746 enabledebug if $debuglevel;
2747
2748 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2749 chdir $toplevel or die "chdir $toplevel: $!";
2750
2751 $rd = fresh_playground "$playprefix/misc";
2752
2753 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2754
2755 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2756     defaultcmd_rebase();
2757 } else {
2758     my $cmd = shift @ARGV;
2759     my $cmdfn = $cmd;
2760     $cmdfn =~ y/-/_/;
2761     $cmdfn = ${*::}{"cmd_$cmdfn"};
2762
2763     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
2764     $cmdfn->();
2765 }
2766
2767 finish 0;