chiark / gitweb /
git-debrebase(1): wip
[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
22 # usages:
23 #
24 #    git-debrebase [<options>] analyse
25 #    git-debrebase [<options>] launder-v0      # prints breakwater tip etc.
26 #    git-debrebase [<options>] downstream-rebase-launder-v0  # experimental
27 #
28 #    git-debrebase [<options>] convert-from-gbp [<upstream-git-rev>]
29 #    git-debrebase [<options>] convert-to-gbp
30
31 # problems / outstanding questions:
32 #
33 #  *  dgit push with a `3.0 (quilt)' package means doing quilt
34 #     fixup.  Usually this involves recommitting the whole patch
35 #     series, one at a time, with dpkg-source --commit.  This is
36 #     terribly terribly slow.  (Maybe this should be fixed in dgit.)
37 #
38 #  * dgit push usually needs to (re)make a pseudomerge.  The "first"
39 #    git-debrebase stripped out the previous pseudomerge and could
40 #    have remembeed the HEAD.  But it's not quite clear what history
41 #    ought to be preserved and what should be discarded.  For now
42 #    the user will have to tell dgit --overwrite.
43 #
44 #    To fix this, do we need a new push hook for dgit ?
45 #
46 #  * Workflow is currently clumsy.  Lots of spurious runes to type.
47 #    There's not even a guide.
48 #
49 #  * There are no tests.
50 #
51 #  * new-upstream-v0 has a terrible UI.  You end up with giant
52 #    runic command lines.
53 #
54 #    One consequence of the lack of richness it can need --force in
55 #    fairly sensible situations and there is no way to tell it what
56 #    you are really trying to do, other than just --force.  There
57 #    should be an interface with some default branch names.
58 #
59 #  * There should be a standard convention for the version number,
60 #    and unfinalised or not changelog, after new-upstream.
61 #
62 #  * Handing of multi-orig dgit new-upstream .dsc imports is known to
63 #    be broken.  They may be not recognised, improperly converted, or
64 #    their conversion may be unrecognised.
65 #
66 #  * Docs need writing and updating.  Even README.git-debrebase
67 #    describes a design but may not reflect the implementation.
68 #
69 #  * We need to develop a plausible model that works for derivatives,
70 #    who probably want to maintain their stack on top of Debian's.
71 #    downstream-rebase-launder-v0 may be a starting point?
72
73 use strict;
74
75 use Debian::Dgit qw(:DEFAULT :playground);
76 setup_sigwarn();
77
78 use Memoize;
79 use Carp;
80 use POSIX;
81 use Data::Dumper;
82 use Getopt::Long qw(:config posix_default gnu_compat bundling);
83 use Dpkg::Version;
84 use File::FnMatch qw(:fnmatch);
85
86 our ($opt_force, $opt_noop_ok, @opt_anchors);
87
88 our $us = qw(git-debrebase);
89
90 sub badusage ($) {
91     my ($m) = @_;
92     die "bad usage: $m\n";
93 }
94
95 sub cfg ($;$) {
96     my ($k, $optional) = @_;
97     local $/ = "\0";
98     my @cmd = qw(git config -z);
99     push @cmd, qw(--get-all) if wantarray;
100     push @cmd, $k;
101     my $out = cmdoutput_errok @cmd;
102     if (!defined $out) {
103         fail "missing required git config $k" unless $optional;
104         return ();
105     }
106     my @l = split /\0/, $out;
107     return wantarray ? @l : $l[0];
108 }
109
110 memoize('cfg');
111
112 sub dd ($) {
113     my ($v) = @_;
114     my $dd = new Data::Dumper [ $v ];
115     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
116     return Dump $dd;
117 }
118
119 sub get_commit ($) {
120     my ($objid) = @_;
121     my $data = (git_cat_file $objid, 'commit');
122     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
123     return ($`,$');
124 }
125
126 sub D_UPS ()      { 0x02; } # upstream files
127 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
128 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
129 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
130 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
131 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
132
133 our $playprefix = 'debrebase';
134 our $rd;
135 our $workarea;
136
137 our @git = qw(git);
138
139 sub in_workarea ($) {
140     my ($sub) = @_;
141     changedir $workarea;
142     my $r = eval { $sub->(); };
143     { local $@; changedir $maindir; }
144     die $@ if $@;
145 }
146
147 sub fresh_workarea () {
148     $workarea = fresh_playground "$playprefix/work";
149     in_workarea sub { playtree_setup };
150 }
151
152 our @deferred_updates;
153 our @deferred_update_messages;
154
155 sub run_deferred_updates ($) {
156     my ($mrest) = @_;
157
158     my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
159     debugcmd '>|', @upd_cmd;
160     open U, "|-", @upd_cmd or die $!;
161     foreach (@deferred_updates) {
162         printdebug ">= ", $_, "\n";
163         print U $_, "\n" or die $!;
164     }
165     printdebug ">\$\n";
166     close U or failedcmd @upd_cmd;
167
168     print $_, "\n" foreach @deferred_update_messages;
169
170     @deferred_updates = ();
171     @deferred_update_messages = ();
172 }
173
174 sub get_differs ($$) {
175     my ($x,$y) = @_;
176     # This resembles quiltify_trees_differ, in dgit, a bit.
177     # But we don't care about modes, or dpkg-source-unrepresentable
178     # changes, and we don't need the plethora of different modes.
179     # Conversely we need to distinguish different kinds of changes to
180     # debian/ and debian/patches/.
181
182     my $differs = 0;
183
184     my $rundiff = sub {
185         my ($opts, $limits, $fn) = @_;
186         my @cmd = (@git, qw(diff-tree -z --no-renames));
187         push @cmd, @$opts;
188         push @cmd, "$_:" foreach $x, $y;
189         push @cmd, '--', @$limits;
190         my $diffs = cmdoutput @cmd;
191         foreach (split /\0/, $diffs) { $fn->(); }
192     };
193
194     $rundiff->([qw(--name-only)], [], sub {
195         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
196     });
197
198     if ($differs & DS_DEB) {
199         $differs &= ~DS_DEB;
200         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
201             $differs |=
202                 m{^debian/patches/}      ? D_PAT_OTH  :
203                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
204                                            D_DEB_OTH;
205         });
206         die "mysterious debian changes $x..$y"
207             unless $differs & (D_PAT_OTH|DS_DEB);
208     }
209
210     if ($differs & D_PAT_OTH) {
211         my $mode;
212         $differs &= ~D_PAT_OTH;
213         my $pat_oth = sub {
214             $differs |= D_PAT_OTH;
215             no warnings qw(exiting);  last;
216         };
217         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
218             no warnings qw(exiting);
219             if (!defined $mode) {
220                 $mode = $_;  next;
221             }
222             die unless s{^debian/patches/}{};
223             my $ok;
224             if ($mode eq 'A' && !m/\.series$/s) {
225                 $ok = 1;
226             } elsif ($mode eq 'M' && $_ eq 'series') {
227                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
228                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
229                 chomp $x_s;  $x_s .= "\n";
230                 $ok = $x_s eq substr($y_s, 0, length $x_s);
231             } else {
232                 # nope
233             }
234             $mode = undef;
235             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
236         });
237         die "mysterious debian/patches changes $x..$y"
238             unless $differs & (D_PAT_ADD|D_PAT_OTH);
239     }
240
241     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
242
243     return $differs;
244 }
245
246 sub commit_pr_info ($) {
247     my ($r) = @_;
248     return Data::Dumper->dump([$r], [qw(commit)]);
249 }
250
251 sub calculate_committer_authline () {
252     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
253         'DUMMY COMMIT (git-debrebase)', "HEAD:";
254     my ($h,$m) = get_commit $c;
255     $h =~ m/^committer .*$/m or confess "($h) ?";
256     return $&;
257 }
258
259 sub rm_subdir_cached ($) {
260     my ($subdir) = @_;
261     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
262 }
263
264 sub read_tree_subdir ($$) {
265     my ($subdir, $new_tree_object) = @_;
266     rm_subdir_cached $subdir;
267     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
268 }
269
270 sub make_commit ($$) {
271     my ($parents, $message_paras) = @_;
272     my $tree = cmdoutput @git, qw(write-tree);
273     my @cmd = (@git, qw(commit-tree), $tree);
274     push @cmd, qw(-p), $_ foreach @$parents;
275     push @cmd, qw(-m), $_ foreach @$message_paras;
276     return cmdoutput @cmd;
277 }
278
279 our @fproblem_force_opts;
280 our $fproblems_forced;
281 our $fproblems_tripped;
282 sub fproblem ($$) {
283     my ($tag,$msg) = @_;
284     if (grep { $_ eq $tag } @fproblem_force_opts) {
285         $fproblems_forced++;
286         print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
287     } else {
288         $fproblems_tripped++;
289         print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
290     }
291 }
292
293 sub fproblems_maybe_bail () {
294     if ($fproblems_forced) {
295         printf STDERR
296             "%s: safety catch trips: %d overriden by individual -f options\n",
297             $us, $fproblems_forced;
298     }
299     if ($fproblems_tripped) {
300         if ($opt_force) {
301             printf STDERR
302                 "%s: safety catch trips: %d overriden by global --force\n",
303                 $us, $fproblems_tripped;
304         } else {
305             fail sprintf
306   "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
307                 $us, $fproblems_tripped;
308         }
309     }
310 }
311 sub any_fproblems () {
312     return $fproblems_forced || $fproblems_tripped;
313 }
314
315 # classify returns an info hash like this
316 #   CommitId => $objid
317 #   Hdr => # commit headers, including 1 final newline
318 #   Msg => # commit message (so one newline is dropped)
319 #   Tree => $treeobjid
320 #   Type => (see below)
321 #   Parents = [ {
322 #       Ix => $index # ie 0, 1, 2, ...
323 #       CommitId
324 #       Differs => return value from get_differs
325 #       IsOrigin
326 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
327 #     } ...]
328 #   NewMsg => # commit message, but with any [dgit import ...] edited
329 #             # to say "[was: ...]"
330 #
331 # Types:
332 #   Packaging
333 #   Changelog
334 #   Upstream
335 #   AddPatches
336 #   Mixed
337 #
338 #   Pseudomerge
339 #     has additional entres in classification result
340 #       Overwritten = [ subset of Parents ]
341 #       Contributor = $the_remaining_Parent
342 #
343 #   DgitImportUnpatched
344 #     has additional entry in classification result
345 #       OrigParents = [ subset of Parents ]
346 #
347 #   Anchor
348 #     has additional entry in classification result
349 #       OrigParents = [ subset of Parents ]  # singleton list
350 #
351 #   TreatAsAnchor
352 #
353 #   BreakwaterStart
354 #
355 #   Unknown
356 #     has additional entry in classification result
357 #       Why => "prose"
358
359 sub parsecommit ($;$) {
360     my ($objid, $p_ref) = @_;
361     # => hash with                   CommitId Hdr Msg Tree Parents
362     #    Parents entries have only   Ix CommitId
363     #    $p_ref, if provided, must be [] and is used as a base for Parents
364
365     $p_ref //= [];
366     die if @$p_ref;
367
368     my ($h,$m) = get_commit $objid;
369
370     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
371     my (@ph) = $h =~ m/^parent (\w+)$/mg;
372
373     my $r = {
374         CommitId => $objid,
375         Hdr => $h,
376         Msg => $m,
377         Tree => $t,
378         Parents => $p_ref,
379     };
380
381     foreach my $ph (@ph) {
382         push @$p_ref, {
383             Ix => scalar @$p_ref,
384             CommitId => $ph,
385         };
386     }
387
388     return $r;
389 }    
390
391 sub classify ($) {
392     my ($objid) = @_;
393
394     my @p;
395     my $r = parsecommit($objid, \@p);
396     my $t = $r->{Tree};
397
398     foreach my $p (@p) {
399         $p->{Differs} = (get_differs $p->{CommitId}, $t),
400     }
401
402     printdebug "classify $objid \$t=$t \@p",
403         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
404         "\n";
405
406     my $classify = sub {
407         my ($type, @rest) = @_;
408         $r = { %$r, Type => $type, @rest };
409         if ($debuglevel) {
410             printdebug " = $type ".(dd $r)."\n";
411         }
412         return $r;
413     };
414     my $unknown = sub {
415         my ($why) = @_;
416         $r = { %$r, Type => qw(Unknown), Why => $why };
417         printdebug " ** Unknown\n";
418         return $r;
419     };
420
421     if (grep { $_ eq $objid } @opt_anchors) {
422         return $classify->('TreatAsAnchor');
423     }
424
425     my @identical = grep { !$_->{Differs} } @p;
426     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
427     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
428
429     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
430         # multi-orig upstreams are represented with an anchor merge
431         # from a single upstream commit which combines the orig tarballs
432
433         # Every anchor tagged this way must be a merge.
434         # We are relying on the
435         #     [git-debrebase anchor: ...]
436         # commit message annotation in "declare" anchor merges (which
437         # do not have any upstream changes), to distinguish those
438         # anchor merges from ordinary pseudomerges (which we might
439         # just try to strip).
440         #
441         # However, the user is going to be doing git-rebase a lot.  We
442         # really don't want them to rewrite an anchor commit.
443         # git-rebase trips up on merges, so that is a useful safety
444         # catch.
445         #
446         # BreakwaterStart commits are also anchors in the terminology
447         # of git-debrebase(5), but they are untagged (and always
448         # manually generated).
449
450         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
451         @p == 2 or return $badanchor->("has other than two parents");
452         $haspatches and return $badanchor->("contains debian/patches");
453
454         # How to decide about l/r ordering of anchors ?  git
455         # --topo-order prefers to expand 2nd parent first.  There's
456         # already an easy rune to look for debian/ history anyway (git log
457         # debian/) so debian breakwater branch should be 1st parent; that
458         # way also there's also an easy rune to look for the upstream
459         # patches (--topo-order).
460
461         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
462         $p[1]{Differs} & ~DS_DEB and
463             $badanchor->("upstream files differ from left parent");
464         $p[0]{Differs} & ~D_UPS and
465             $badanchor->("debian/ differs from right parent");
466
467         return $classify->(qw(Anchor),
468                            OrigParents => [ $p[1] ]);
469     }
470
471     if (@p == 1) {
472         my $d = $r->{Parents}[0]{Differs};
473         if ($d == D_PAT_ADD) {
474             return $classify->(qw(AddPatches));
475         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
476             return $unknown->("edits debian/patches");
477         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
478             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
479             if ($ty eq 'tree') {
480                 if ($d == D_DEB_CLOG) {
481                     return $classify->(qw(Changelog));
482                 } else {
483                     return $classify->(qw(Packaging));
484                 }
485             } elsif ($ty eq 'missing') {
486                 return $classify->(qw(BreakwaterStart));
487             } else {
488                 return $unknown->("parent's debian is not a directory");
489             }
490         } elsif ($d == D_UPS) {
491             return $classify->(qw(Upstream));
492         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
493             return $classify->(qw(Mixed));
494         } elsif ($d == 0) {
495             return $unknown->("no changes");
496         } else {
497             confess "internal error $objid ?";
498         }
499     }
500     if (!@p) {
501         return $unknown->("origin commit");
502     }
503
504     if (@p == 2 && @identical == 1) {
505         my @overwritten = grep { $_->{Differs} } @p;
506         confess "internal error $objid ?" unless @overwritten==1;
507         return $classify->(qw(Pseudomerge),
508                            Overwritten => [ $overwritten[0] ],
509                            Contributor => $identical[0]);
510     }
511     if (@p == 2 && @identical == 2) {
512         my $get_t = sub {
513             my ($ph,$pm) = get_commit $_[0]{CommitId};
514             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
515             $1;
516         };
517         my @bytime = @p;
518         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
519         if ($order > 0) { # newer first
520         } elsif ($order < 0) {
521             @bytime = reverse @bytime;
522         } else {
523             # same age, default to order made by -s ours
524             # that is, commit was made by someone who preferred L
525         }
526         return $classify->(qw(Pseudomerge),
527                            SubType => qw(Ambiguous),
528                            Contributor => $bytime[0],
529                            Overwritten => [ $bytime[1] ]);
530     }
531     foreach my $p (@p) {
532         my ($p_h, $p_m) = get_commit $p->{CommitId};
533         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
534         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
535     }
536     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
537     my $m2 = $r->{Msg};
538     if (!(grep { !$_->{IsOrigin} } @p) and
539         (@orig_ps >= @p - 1) and
540         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
541         $r->{NewMsg} = $m2;
542         return $classify->(qw(DgitImportUnpatched),
543                            OrigParents => \@orig_ps);
544     }
545
546     return $unknown->("complex merge");
547 }
548
549 sub breakwater_of ($) {
550     my ($head) = @_; # must be laundered
551     my $breakwater;
552     my $unclean = sub {
553         my ($why) = @_;
554         fail "branch needs laundering (run git-debrebase): $why";
555     };
556     for (;;) {
557         my $cl = classify $head;
558         my $ty = $cl->{Type};
559         if ($ty eq 'Packaging' or
560             $ty eq 'Changelog') {
561             $breakwater //= $head;
562         } elsif ($ty eq 'Anchor' or
563                  $ty eq 'TreatAsAnchor' or
564                  $ty eq 'BreakwaterStart') {
565             $breakwater //= $head;
566             last;
567         } elsif ($ty eq 'Upstream') {
568             $unclean->("packaging change ($breakwater)".
569                        " follows upstream change (eg $head)")
570                 if defined $breakwater;
571         } elsif ($ty eq 'Mixed') {
572             $unclean->('found mixed upstream/packaging commit ($head)');
573         } elsif ($ty eq 'Pseudomerge' or
574                  $ty eq 'AddPatches') {
575             $unclean->("found interchange conversion commit ($ty, $head)");
576         } elsif ($ty eq 'DgitImportUnpatched') {
577             $unclean->("found dgit dsc import ($head)");
578         } else {
579             fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
580         }
581         $head = $cl->{Parents}[0]{CommitId};
582     }
583     return $breakwater;
584 }
585
586 sub walk ($;$$);
587 sub walk ($;$$) {
588     my ($input,
589         $nogenerate,$report) = @_;
590     # => ($tip, $breakwater_tip, $last_anchor)
591     # (or nothing, if $nogenerate)
592
593     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
594
595     # go through commits backwards
596     # we generate two lists of commits to apply:
597     # breakwater branch and upstream patches
598     my (@brw_cl, @upp_cl, @processed);
599     my %found;
600     my $upp_limit;
601     my @pseudomerges;
602
603     my $cl;
604     my $xmsg = sub {
605         my ($prose, $info) = @_;
606         my $ms = $cl->{Msg};
607         chomp $ms;
608         $info //= '';
609         $ms .= "\n\n[git-debrebase$info: $prose]\n";
610         return (Msg => $ms);
611     };
612     my $rewrite_from_here = sub {
613         my ($cl) = @_;
614         my $sp_cl = { SpecialMethod => 'StartRewrite' };
615         push @$cl, $sp_cl;
616         push @processed, $sp_cl;
617     };
618     my $cur = $input;
619
620     my $prdelim = "";
621     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
622
623     my $prline = sub {
624         return unless $report;
625         print $report $prdelim, @_;
626         $prdelim = "\n";
627     };
628
629     my $bomb = sub { # usage: return $bomb->();
630         print $report " Unprocessable" if $report;
631         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
632         $prprdelim->();
633         if ($nogenerate) {
634             return (undef,undef);
635         }
636         die "commit $cur: Cannot cope with this commit (d.".
637             (join ' ', map { sprintf "%#x", $_->{Differs} }
638              @{ $cl->{Parents} }).
639             (defined $cl->{Why} ? "; $cl->{Why}": '').
640                  ")";
641     };
642
643     my $build;
644     my $breakwater;
645
646     my $build_start = sub {
647         my ($msg, $parent) = @_;
648         $prline->(" $msg");
649         $build = $parent;
650         no warnings qw(exiting); last;
651     };
652
653     my $last_anchor;
654
655     for (;;) {
656         $cl = classify $cur;
657         my $ty = $cl->{Type};
658         my $st = $cl->{SubType};
659         $prline->("$cl->{CommitId} $cl->{Type}");
660         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
661         push @processed, $cl;
662         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
663         if ($ty eq 'AddPatches') {
664             $cur = $p0;
665             $rewrite_from_here->(\@upp_cl);
666             next;
667         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
668             push @brw_cl, $cl;
669             $cur = $p0;
670             next;
671         } elsif ($ty eq 'BreakwaterStart') {
672             $last_anchor = $cur;
673             $build_start->('FirstPackaging', $cur);
674         } elsif ($ty eq 'Upstream') {
675             push @upp_cl, $cl;
676             $cur = $p0;
677             next;
678         } elsif ($ty eq 'Mixed') {
679             my $queue = sub {
680                 my ($q, $wh) = @_;
681                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
682                 push @$q, $cls;
683             };
684             $queue->(\@brw_cl, "debian");
685             $queue->(\@upp_cl, "upstream");
686             $rewrite_from_here->(\@brw_cl);
687             $cur = $p0;
688             next;
689         } elsif ($ty eq 'Pseudomerge') {
690             my $contrib = $cl->{Contributor}{CommitId};
691             print $report " Contributor=$contrib" if $report;
692             push @pseudomerges, $cl;
693             $rewrite_from_here->(\@upp_cl);
694             $cur = $contrib;
695             next;
696         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
697             $last_anchor = $cur;
698             $build_start->("Anchor", $cur);
699         } elsif ($ty eq 'DgitImportUnpatched') {
700             my $pm = $pseudomerges[-1];
701             if (defined $pm) {
702                 # To an extent, this is heuristic.  Imports don't have
703                 # a useful history of the debian/ branch.  We assume
704                 # that the first pseudomerge after an import has a
705                 # useful history of debian/, and ignore the histories
706                 # from later pseudomerges.  Often the first pseudomerge
707                 # will be the dgit import of the upload to the actual
708                 # suite intended by the non-dgit NMUer, and later
709                 # pseudomerges may represent in-archive copies.
710                 my $ovwrs = $pm->{Overwritten};
711                 printf $report " PM=%s \@Overwr:%d",
712                     $pm->{CommitId}, (scalar @$ovwrs)
713                     if $report;
714                 if (@$ovwrs != 1) {
715                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
716                     return $bomb->();
717                 }
718                 my $ovwr = $ovwrs->[0]{CommitId};
719                 printf $report " Overwr=%s", $ovwr if $report;
720                 # This import has a tree which is just like a
721                 # breakwater tree, but it has the wrong history.  It
722                 # ought to have the previous breakwater (which the
723                 # pseudomerge overwrote) as an ancestor.  That will
724                 # make the history of the debian/ files correct.  As
725                 # for the upstream version: either it's the same as
726                 # was ovewritten (ie, same as the previous
727                 # breakwater), in which case that history is precisely
728                 # right; or, otherwise, it was a non-gitish upload of a
729                 # new upstream version.  We can tell these apart by
730                 # looking at the tree of the supposed upstream.
731                 push @brw_cl, {
732                     %$cl,
733                     SpecialMethod => 'DgitImportDebianUpdate',
734                     $xmsg->("convert dgit import: debian changes")
735                 }, {
736                     %$cl,
737                     SpecialMethod => 'DgitImportUpstreamUpdate',
738                     $xmsg->("convert dgit import: upstream update",
739                             " anchor")
740                 };
741                 $prline->(" Import");
742                 $rewrite_from_here->(\@brw_cl);
743                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
744                 $cur = $ovwr;
745                 next;
746             } else {
747                 # Everything is from this import.  This kind of import
748                 # is already in valid breakwater format, with the
749                 # patches as commits.
750                 printf $report " NoPM" if $report;
751                 # last thing we processed will have been the first patch,
752                 # if there is one; which is fine, so no need to rewrite
753                 # on account of this import
754                 $build_start->("ImportOrigin", $cur);
755             }
756             die "$ty ?";
757         } else {
758             printdebug "*** WALK BOMB unrecognised\n";
759             return $bomb->();
760         }
761     }
762     $prprdelim->();
763
764     printdebug "*** WALK prep done cur=$cur".
765         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
766
767     return if $nogenerate;
768
769     # Now we build it back up again
770
771     fresh_workarea();
772
773     my $rewriting = 0;
774
775     my $read_tree_debian = sub {
776         my ($treeish) = @_;
777         read_tree_subdir 'debian', "$treeish:debian";
778         rm_subdir_cached 'debian/patches';
779     };
780     my $read_tree_upstream = sub {
781         my ($treeish) = @_;
782         runcmd @git, qw(read-tree), $treeish;
783         $read_tree_debian->($build);
784     };
785
786     $#upp_cl = $upp_limit if defined $upp_limit;
787  
788     my $committer_authline = calculate_committer_authline();
789
790     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
791
792     confess "internal error" unless $build eq (pop @processed)->{CommitId};
793
794     in_workarea sub {
795         mkdir $rd or $!==EEXIST or die $!;
796         my $current_method;
797         runcmd @git, qw(read-tree), $build;
798         foreach my $cl (qw(Debian), (reverse @brw_cl),
799                         { SpecialMethod => 'RecordBreakwaterTip' },
800                         qw(Upstream), (reverse @upp_cl)) {
801             if (!ref $cl) {
802                 $current_method = $cl;
803                 next;
804             }
805             my $method = $cl->{SpecialMethod} // $current_method;
806             my @parents = ($build);
807             my $cltree = $cl->{CommitId};
808             printdebug "WALK BUILD ".($cltree//'undef').
809                 " $method (rewriting=$rewriting)\n";
810             if ($method eq 'Debian') {
811                 $read_tree_debian->($cltree);
812             } elsif ($method eq 'Upstream') {
813                 $read_tree_upstream->($cltree);
814             } elsif ($method eq 'StartRewrite') {
815                 $rewriting = 1;
816                 next;
817             } elsif ($method eq 'RecordBreakwaterTip') {
818                 $breakwater = $build;
819                 next;
820             } elsif ($method eq 'DgitImportDebianUpdate') {
821                 $read_tree_debian->($cltree);
822             } elsif ($method eq 'DgitImportUpstreamUpdate') {
823                 confess unless $rewriting;
824                 my $differs = (get_differs $build, $cltree);
825                 next unless $differs & D_UPS;
826                 $read_tree_upstream->($cltree);
827                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
828             } else {
829                 confess "$method ?";
830             }
831             if (!$rewriting) {
832                 my $procd = (pop @processed) // 'UNDEF';
833                 if ($cl ne $procd) {
834                     $rewriting = 1;
835                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
836                 }
837             }
838             my $newtree = cmdoutput @git, qw(write-tree);
839             my $ch = $cl->{Hdr};
840             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
841             $ch =~ s{^parent .*\n}{}mg;
842             $ch =~ s{(?=^author)}{
843                 join '', map { "parent $_\n" } @parents
844             }me or confess "$ch ?";
845             if ($rewriting) {
846                 $ch =~ s{^committer .*$}{$committer_authline}m
847                     or confess "$ch ?";
848             }
849             my $cf = "$rd/m$rewriting";
850             open CD, ">", $cf or die $!;
851             print CD $ch, "\n", $cl->{Msg} or die $!;
852             close CD or die $!;
853             my @cmd = (@git, qw(hash-object));
854             push @cmd, qw(-w) if $rewriting;
855             push @cmd, qw(-t commit), $cf;
856             my $newcommit = cmdoutput @cmd;
857             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
858             $build = $newcommit;
859             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
860                 $last_anchor = $cur;
861             }
862         }
863     };
864
865     my $final_check = get_differs $build, $input;
866     die sprintf "internal error %#x %s %s", $final_check, $build, $input
867         if $final_check & ~D_PAT_ADD;
868
869     my @r = ($build, $breakwater, $last_anchor);
870     printdebug "*** WALK RETURN @r\n";
871     return @r
872 }
873
874 sub get_head () {
875     git_check_unmodified();
876     return git_rev_parse qw(HEAD);
877 }
878
879 sub update_head ($$$) {
880     my ($old, $new, $mrest) = @_;
881     push @deferred_updates, "update HEAD $new $old";
882     run_deferred_updates $mrest;
883 }
884
885 sub update_head_checkout ($$$) {
886     my ($old, $new, $mrest) = @_;
887     update_head $old, $new, $mrest;
888     runcmd @git, qw(reset --hard);
889 }
890
891 sub update_head_postlaunder ($$$) {
892     my ($old, $tip, $reflogmsg) = @_;
893     return if $tip eq $old;
894     print "git-debrebase: laundered (head was $old)\n";
895     update_head $old, $tip, $reflogmsg;
896     # no tree changes except debian/patches
897     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
898 }
899
900 sub cmd_launder_v0 () {
901     badusage "no arguments to launder-v0 allowed" if @ARGV;
902     my $old = get_head();
903     my ($tip,$breakwater,$last_anchor) = walk $old;
904     update_head_postlaunder $old, $tip, 'launder';
905     printf "# breakwater tip\n%s\n", $breakwater;
906     printf "# working tip\n%s\n", $tip;
907     printf "# last anchor\n%s\n", $last_anchor;
908 }
909
910 sub defaultcmd_rebase () {
911     my $old = get_head();
912     record_ffq_auto();
913     my ($tip,$breakwater) = walk $old;
914     update_head_postlaunder $old, $tip, 'launder for rebase';
915     runcmd @git, qw(rebase), @ARGV, $breakwater;
916 }
917
918 sub cmd_analyse () {
919     die if ($ARGV[0]//'') =~ m/^-/;
920     badusage "too many arguments to analyse" if @ARGV>1;
921     my ($old) = @ARGV;
922     if (defined $old) {
923         $old = git_rev_parse $old;
924     } else {
925         $old = git_rev_parse 'HEAD';
926     }
927     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
928     STDOUT->error and die $!;
929 }
930
931 sub ffq_prev_branchinfo () {
932     # => ('status', "message", [$current, $ffq_prev])
933     # 'status' may be
934     #    branch         message is undef
935     #    weird-symref   } no $current,
936     #    notbranch      }  no $ffq_prev
937     my $current = git_get_symref();
938     return ('detached', 'detached HEAD') unless defined $current;
939     return ('weird-symref', 'HEAD symref is not to refs/')
940         unless $current =~ m{^refs/};
941     my $ffq_prev = "refs/$ffq_refprefix/$'";
942     printdebug "ffq_prev_branchinfo branch current $current\n";
943     return ('branch', undef, $current, $ffq_prev);
944 }
945
946 sub record_ffq_prev_deferred () {
947     # => ('status', "message")
948     # 'status' may be
949     #    deferred          message is undef
950     #    exists
951     #    detached
952     #    weird-symref
953     #    notbranch
954     # if not ff from some branch we should be ff from, is an fproblem
955     # if "deferred", will have added something about that to
956     #   @deferred_update_messages, and also maybe printed (already)
957     #   some messages about ff checks
958     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
959     return ($status, $message) unless $status eq 'branch';
960
961     my $currentval = get_head();
962
963     my $exists = git_get_ref $ffq_prev;
964     return ('exists',"$ffq_prev already exists") if $exists;
965
966     return ('not-branch', 'HEAD symref is not to refs/heads/')
967         unless $current =~ m{^refs/heads/};
968     my $branch = $';
969
970     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
971     my %checked;
972
973     printdebug "ffq check_specs @check_specs\n";
974
975     my $check = sub {
976         my ($lrref, $desc) = @_;
977         printdebug "ffq might check $lrref ($desc)\n";
978         my $invert;
979         for my $chk (@check_specs) {
980             my $glob = $chk;
981             $invert = $glob =~ s{^[!^]}{};
982             last if fnmatch $glob, $lrref;
983         }
984         return if $invert;
985         my $lrval = git_get_ref $lrref;
986         return unless defined $lrval;
987
988         if (is_fast_fwd $lrval, $currentval) {
989             print "OK, you are ahead of $lrref\n" or die $!;
990             $checked{$lrref} = 1;
991         } elsif (is_fast_fwd $currentval, $lrval) {
992             $checked{$lrref} = -1;
993             fproblem 'behind', "you are behind $lrref, divergence risk";
994         } else {
995             $checked{$lrref} = -1;
996             fproblem 'diverged', "you have diverged from $lrref";
997         }
998     };
999
1000     my $merge = cfg "branch.$branch.merge",1;
1001     if (defined $merge and $merge =~ m{^refs/heads/}) {
1002         my $rhs = $';
1003         printdebug "ffq merge $rhs\n";
1004         my $check_remote = sub {
1005             my ($remote, $desc) = @_;
1006             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1007             return unless defined $remote;
1008             $check->("refs/remotes/$remote/$rhs", $desc);
1009         };
1010         $check_remote->((scalar cfg "branch.$branch.remote",1),
1011                         'remote fetch/merge branch');
1012         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1013                         (scalar cfg "branch.$branch.pushDefault",1),
1014                         'remote push branch');
1015     }
1016     if ($branch =~ m{^dgit/}) {
1017         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1018     } elsif ($branch =~ m{^master$}) {
1019         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1020     }
1021
1022     fproblems_maybe_bail();
1023
1024     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1025     push @deferred_update_messages, "Recorded current head for preservation";
1026     return ('deferred', undef);
1027 }
1028
1029 sub record_ffq_auto () {
1030     my ($status, $message) = record_ffq_prev_deferred();
1031     if ($status eq 'deferred' || $status eq 'exists') {
1032     } else {
1033         fproblem $status, "could not record ffq-prev: $message";
1034         fproblems_maybe_bail();
1035     }
1036 }
1037
1038 sub cmd_new_upstream_v0 () {
1039     # automatically and unconditionally launders before rebasing
1040     # if rebase --abort is used, laundering has still been done
1041
1042     my %pieces;
1043
1044     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1045
1046     # parse args - low commitment
1047     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1048     my $new_upstream_version = $new_version->version();
1049
1050     my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1051
1052     record_ffq_auto();
1053
1054     my $piece = sub {
1055         my ($n, @x) = @_; # may be ''
1056         my $pc = $pieces{$n} //= {
1057             Name => $n,
1058             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1059         };
1060         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1061         $pc;
1062     };
1063
1064     my @newpieces;
1065     my $newpiece = sub {
1066         my ($n, @x) = @_; # may be ''
1067         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1068         push @newpieces, $pc;
1069     };
1070
1071     $newpiece->('',
1072         OldIx => 0,
1073         New => $new_upstream,
1074     );
1075     while (@ARGV && $ARGV[0] !~ m{^-}) {
1076         my $n = shift @ARGV;
1077
1078         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1079             unless @ARGV && $ARGV[0] !~ m{^-};
1080
1081         my $c = git_rev_parse shift @ARGV;
1082         die unless $n =~ m/^$extra_orig_namepart_re$/;
1083         $newpiece->($n, New => $c);
1084     }
1085
1086     # now we need to investigate the branch this generates the
1087     # laundered version but we don't switch to it yet
1088     my $old_head = get_head();
1089     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1090
1091     my $old_bw_cl = classify $old_bw;
1092     my $old_anchor_cl = classify $old_anchor;
1093     my $old_upstream;
1094     if (!$old_anchor_cl->{OrigParents}) {
1095         fproblem 'anchor-treated',
1096             'old anchor is recognised due to --anchor, cannot check upstream';
1097     } else {
1098         $old_upstream = parsecommit
1099             $old_anchor_cl->{OrigParents}[0]{CommitId};
1100         $piece->('', Old => $old_upstream->{CommitId});
1101     }
1102
1103     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1104         if ($old_upstream->{Msg} =~
1105  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1106            ) {
1107             my @oldpieces = ('', split / /, $1);
1108             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1109             foreach my $i (0..$#oldpieces) {
1110                 my $n = $oldpieces[$i];
1111                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1112             }
1113         } else {
1114             fproblem 'upstream-confusing',
1115                 "previous upstream $old_upstream->{CommitId} is from".
1116                " git-debrebase but not an \`upstream-combine' commit";
1117         }
1118     }
1119
1120     foreach my $pc (values %pieces) {
1121         if (!$old_upstream) {
1122             # we have complained already
1123         } elsif (!$pc->{Old}) {
1124             fproblem 'upstream-new-piece',
1125                 "introducing upstream piece \`$pc->{Name}'";
1126         } elsif (!$pc->{New}) {
1127             fproblem 'upstream-rm-piece',
1128                 "dropping upstream piece \`$pc->{Name}'";
1129         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1130             fproblem 'upstream-not-ff',
1131                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1132         }
1133     }
1134
1135     printdebug "%pieces = ", (dd \%pieces), "\n";
1136     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1137
1138     fproblems_maybe_bail();
1139
1140     my $new_bw;
1141
1142     fresh_workarea();
1143     in_workarea sub {
1144         my @upstream_merge_parents;
1145
1146         if (!any_fproblems()) {
1147             push @upstream_merge_parents, $old_upstream->{CommitId};
1148         }
1149
1150         foreach my $pc (@newpieces) { # always has '' first
1151             if ($pc->{Name}) {
1152                 read_tree_subdir $pc->{Name}, $pc->{New};
1153             } else {
1154                 runcmd @git, qw(read-tree), $pc->{New};
1155             }
1156             push @upstream_merge_parents, $pc->{New};
1157         }
1158
1159         # index now contains the new upstream
1160
1161         if (@newpieces > 1) {
1162             # need to make the upstream subtree merge commit
1163             $new_upstream = make_commit \@upstream_merge_parents,
1164                 [ "Combine upstreams for $new_upstream_version",
1165  ("[git-debrebase upstream-combine . ".
1166  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1167  ": new upstream]"),
1168                 ];
1169         }
1170
1171         # $new_upstream is either the single upstream commit, or the
1172         # combined commit we just made.  Either way it will be the
1173         # "upstream" parent of the anchor merge.
1174
1175         read_tree_subdir 'debian', "$old_bw:debian";
1176
1177         # index now contains the anchor merge contents
1178         $new_bw = make_commit [ $old_bw, $new_upstream ],
1179             [ "Update to upstream $new_upstream_version",
1180  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1181             ];
1182
1183         # Now we have to add a changelog stanza so the Debian version
1184         # is right.
1185         die if unlink "debian";
1186         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1187         unlink "debian/changelog" or $!==ENOENT or die $!;
1188         mkdir "debian" or die $!;
1189         open CN, ">", "debian/changelog" or die $!;
1190         my $oldclog = git_cat_file ":debian/changelog";
1191         $oldclog =~ m/^($package_re) \(\S+\) / or
1192             fail "cannot parse old changelog to get package name";
1193         my $p = $1;
1194         print CN <<END, $oldclog or die $!;
1195 $p ($new_version) UNRELEASED; urgency=medium
1196
1197   * Update to new upstream version $new_upstream_version.
1198
1199  -- 
1200
1201 END
1202         close CN or die $!;
1203         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1204
1205         # Now we have the final new breakwater branch in the index
1206         $new_bw = make_commit [ $new_bw ],
1207             [ "Update changelog for new upstream $new_upstream_version",
1208               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1209             ];
1210     };
1211
1212     # we have constructed the new breakwater. we now need to commit to
1213     # the laundering output, because git-rebase can't easily be made
1214     # to make a replay list which is based on some other branch
1215
1216     update_head_postlaunder $old_head, $old_laundered_tip,
1217         'launder for new upstream';
1218
1219     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1220     runcmd @cmd;
1221     # now it's for the user to sort out
1222 }
1223
1224 sub cmd_record_ffq_prev () {
1225     badusage "no arguments allowed" if @ARGV;
1226     my ($status, $msg) = record_ffq_prev_deferred();
1227     if ($status eq 'exists' && $opt_noop_ok) {
1228         print "Previous head already recorded\n" or die $!;
1229     } elsif ($status eq 'deferred') {
1230         run_deferred_updates 'record-ffq-prev';
1231     } else {
1232         fail "Could not preserve: $msg";
1233     }
1234 }
1235
1236 sub cmd_breakwater () {
1237     badusage "no arguments allowed" if @ARGV;
1238     my $bw = breakwater_of git_rev_parse 'HEAD';
1239     print "$bw\n" or die $!;
1240 }
1241
1242 sub cmd_stitch () {
1243     my $prose = '';
1244     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1245     badusage "no arguments allowed" if @ARGV;
1246     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1247     if ($status ne 'branch') {
1248         fproblem $status, "could not check ffq-prev: $message";
1249         fproblems_maybe_bail();
1250     }
1251     my $prev = $ffq_prev && git_get_ref $ffq_prev;
1252     if (!$prev) {
1253         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1254     }
1255     push @deferred_updates, "delete $ffq_prev $prev";
1256
1257     my $old_head = get_head();
1258     if (is_fast_fwd $old_head, $prev) {
1259         my $differs = get_differs $old_head, $prev;
1260         unless ($differs & ~D_PAT_ADD) {
1261             # ffq-prev is ahead of us, and the only tree changes it has
1262             # are possibly addition of things in debian/patches/.
1263             # Just wind forwards rather than making a pointless pseudomerge.
1264             update_head_checkout $old_head, $prev, "stitch (fast forward)";
1265             return;
1266         }
1267     }
1268     fresh_workarea();
1269     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1270         'Declare fast forward / record previous work',
1271         "[git-debrebase pseudomerge: stitch$prose]",
1272     ];
1273     update_head $old_head, $new_head, "stitch";
1274 }
1275
1276 sub cmd_convert_from_gbp () {
1277     badusage "needs 1 optional argument, the upstream git rev"
1278         unless @ARGV<=1;
1279     my ($upstream_spec) = @ARGV;
1280     $upstream_spec //= 'refs/heads/upstream';
1281     my $upstream = git_rev_parse $upstream_spec;
1282     my $old_head = get_head();
1283
1284     my $upsdiff = get_differs $upstream, $old_head;
1285     if ($upsdiff & D_UPS) {
1286         runcmd @git, qw(--no-pager diff),
1287             $upstream, $old_head,
1288             qw( -- :!/debian :/);
1289  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1290     }
1291
1292     if (!is_fast_fwd $upstream, $old_head) {
1293         fproblem 'upstream-not-ancestor',
1294             "upstream ($upstream) is not an ancestor of HEAD";
1295     } else {
1296         my $wrong = cmdoutput
1297             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1298              qw(-- :/ :!/debian));
1299         if (length $wrong) {
1300             fproblem 'unexpected-upstream-changes',
1301                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1302             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1303         }
1304     }
1305
1306     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1307         fproblem 'upstream-has-debian',
1308             "upstream ($upstream) contains debian/ directory";
1309     }
1310
1311     fproblems_maybe_bail();
1312
1313     my $work;
1314
1315     fresh_workarea();
1316     in_workarea sub {
1317         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1318         # make a branch out of the patch queue - we'll want this in a mo
1319         runcmd qw(gbp pq import);
1320         # strip the patches out
1321         runcmd @git, qw(checkout -q gdr-internal~0);
1322         rm_subdir_cached 'debian/patches';
1323         $work = make_commit ['HEAD'], [
1324  'git-debrebase convert-from-gbp: drop patches from tree',
1325  'Delete debian/patches, as part of converting to git-debrebase format.',
1326  '[git-debrebase convert-from-gbp: drop patches from tree]'
1327                               ];
1328         # make the anchor merge
1329         # the tree is already exactly right
1330         $work = make_commit [$work, $upstream], [
1331  'git-debrebase import: declare upstream',
1332  'First breakwater merge.',
1333  '[git-debrebase anchor: declare upstream]'
1334                               ];
1335
1336         # rebase the patch queue onto the new breakwater
1337         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1338         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1339         $work = git_rev_parse 'HEAD';
1340     };
1341
1342     update_head_checkout $old_head, $work, 'convert-from-gbp';
1343 }
1344
1345 sub cmd_convert_to_gbp () {
1346     badusage "no arguments allowed" if @ARGV;
1347     my $head = get_head();
1348     my $ffq = (ffq_prev_branchinfo())[3];
1349     my $bw = breakwater_of $head;
1350     fresh_workarea();
1351     my $out;
1352     in_workarea sub {
1353         runcmd @git, qw(checkout -q -b bw), $bw;
1354         runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1355         runcmd qw(gbp pq export);
1356         runcmd @git, qw(add debian/patches);
1357         $out = make_commit ['HEAD'], [
1358             'Commit patch queue (converted from git-debrebase format)',
1359             '[git-debrebase convert-to-gbp: commit patches]',
1360         ];
1361     };
1362     if (defined $ffq) {
1363         push @deferred_updates, "delete $ffq";
1364     }
1365     update_head_checkout $head, $out, "convert to gbp (v0)";
1366     print <<END or die $!;
1367 git-debrebase: converted to git-buildpackage branch format
1368 git-debrebase: WARNING: do not now run "git-debrebase" any more
1369 git-debrebase: WARNING: doing so would drop all upstream patches!
1370 END
1371 }
1372
1373 sub cmd_downstream_rebase_launder_v0 () {
1374     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1375     my ($base) = @ARGV;
1376     $base = git_rev_parse $base;
1377     my $old_head = get_head();
1378     my $current = $old_head;
1379     my $topmost_keep;
1380     for (;;) {
1381         if ($current eq $base) {
1382             $topmost_keep //= $current;
1383             print " $current BASE stop\n";
1384             last;
1385         }
1386         my $cl = classify $current;
1387         print " $current $cl->{Type}";
1388         my $keep = 0;
1389         my $p0 = $cl->{Parents}[0]{CommitId};
1390         my $next;
1391         if ($cl->{Type} eq 'Pseudomerge') {
1392             print " ^".($cl->{Contributor}{Ix}+1);
1393             $next = $cl->{Contributor}{CommitId};
1394         } elsif ($cl->{Type} eq 'AddPatches' or
1395                  $cl->{Type} eq 'Changelog') {
1396             print " strip";
1397             $next = $p0;
1398         } else {
1399             print " keep";
1400             $next = $p0;
1401             $keep = 1;
1402         }
1403         print "\n";
1404         if ($keep) {
1405             $topmost_keep //= $current;
1406         } else {
1407             die "to-be stripped changes not on top of the branch\n"
1408                 if $topmost_keep;
1409         }
1410         $current = $next;
1411     }
1412     if ($topmost_keep eq $old_head) {
1413         print "unchanged\n";
1414     } else {
1415         print "updating to $topmost_keep\n";
1416         update_head_checkout
1417             $old_head, $topmost_keep,
1418             'downstream-rebase-launder-v0';
1419     }
1420 }
1421
1422 GetOptions("D+" => \$debuglevel,
1423            'noop-ok', => \$opt_noop_ok,
1424            'f=s' => \@fproblem_force_opts,
1425            'anchor=s' => \@opt_anchors,
1426            'force!') or die badusage "bad options\n";
1427 initdebug('git-debrebase ');
1428 enabledebug if $debuglevel;
1429
1430 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1431 chdir $toplevel or die "chdir $toplevel: $!";
1432
1433 $rd = fresh_playground "$playprefix/misc";
1434
1435 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1436
1437 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1438     defaultcmd_rebase();
1439 } else {
1440     my $cmd = shift @ARGV;
1441     my $cmdfn = $cmd;
1442     $cmdfn =~ y/-/_/;
1443     $cmdfn = ${*::}{"cmd_$cmdfn"};
1444
1445     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1446     $cmdfn->();
1447 }