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