chiark / gitweb /
git-debrebase: note that we have mostly done the gbp import
[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>] new-upstream-v0 \
25 #             <new-version> <orig-commitish> \
26 #            [<extra-orig-name> <extra-orig-commitish> ...] \
27 #            [<git-rebase options>...]
28 #
29 #    git-debrebase [<options> --] [<git-rebase options...>]
30 #    git-debrebase [<options>] analyse
31 #    git-debrebase [<options>] launder         # prints breakwater tip etc.
32 #    git-debrebase [<options>] downstream-rebase-launder-v0  # experimental
33 #
34 #    git-debrebase [<options>] gbp2debrebase-v0 \
35 #             <upstream>
36
37 # problems / outstanding questions:
38 #
39 #  *  dgit push with a `3.0 (quilt)' package means doing quilt
40 #     fixup.  Usually this involves recommitting the whole patch
41 #     series, one at a time, with dpkg-source --commit.  This is
42 #     terribly terribly slow.  (Maybe this should be fixed in dgit.)
43 #
44 #  * dgit push usually needs to (re)make a pseudomerge.  The "first"
45 #    git-debrebase stripped out the previous pseudomerge and could
46 #    have remembeed the HEAD.  But it's not quite clear what history
47 #    ought to be preserved and what should be discarded.  For now
48 #    the user will have to tell dgit --overwrite.
49 #
50 #    To fix this, do we need a new push hook for dgit ?
51 #
52 #  * Workflow is currently clumsy.  Lots of spurious runes to type.
53 #    There's not even a guide.
54 #
55 #  * There are no tests.
56 #
57 #  * new-upstream-v0 has a terrible UI.  You end up with giant
58 #    runic command lines.
59 #
60 #    One consequence of the lack of richness it can need --force in
61 #    fairly sensible situations and there is no way to tell it what
62 #    you are really trying to do, other than just --force.  There
63 #    should be an interface with some default branch names.
64 #
65 #  * There should be a standard convention for the version number,
66 #    and unfinalised or not changelog, after new-upstream.
67 #
68 #  * Handing of multi-orig dgit new-upstream .dsc imports is known to
69 #    be broken.  They may be not recognised, improperly converted, or
70 #    their conversion may be unrecognised.
71 #
72 #  * Docs need writing and updating.  Even README.git-debrebase
73 #    describes a design but may not reflect the implementation.
74 #
75 #  * We need to develop a plausible model that works for derivatives,
76 #    who probably want to maintain their stack on top of Debian's.
77 #    downstream-rebase-launder-v0 may be a starting point?
78
79 use strict;
80
81 use Debian::Dgit qw(:DEFAULT :playground);
82 setup_sigwarn();
83
84 use Memoize;
85 use Carp;
86 use POSIX;
87 use Data::Dumper;
88 use Getopt::Long qw(:config posix_default gnu_compat bundling);
89 use Dpkg::Version;
90
91 our ($opt_force);
92
93 sub badusage ($) {
94     my ($m) = @_;
95     die "bad usage: $m\n";
96 }
97
98 sub cfg ($) {
99     my ($k) = @_;
100     $/ = "\0";
101     my @cmd = qw(git config -z);
102     push @cmd, qw(--get-all) if wantarray;
103     push @cmd, $k;
104     my $out = cmdoutput @cmd;
105     return split /\0/, $out;
106 }
107
108 memoize('cfg');
109
110 sub dd ($) {
111     my ($v) = @_;
112     my $dd = new Data::Dumper [ $v ];
113     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
114     return Dump $dd;
115 }
116
117 sub get_commit ($) {
118     my ($objid) = @_;
119     my $data = (git_cat_file $objid, 'commit');
120     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
121     return ($`,$');
122 }
123
124 sub D_UPS ()      { 0x02; } # upstream files
125 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
126 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
127 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
128 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
129 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
130
131 our $playprefix = 'debrebase';
132 our $rd;
133 our $workarea;
134
135 our @git = qw(git);
136
137 sub in_workarea ($) {
138     my ($sub) = @_;
139     changedir $workarea;
140     my $r = eval { $sub->(); };
141     { local $@; changedir $maindir; }
142     die $@ if $@;
143 }
144
145 sub fresh_workarea () {
146     $workarea = fresh_playground "$playprefix/work";
147     in_workarea sub { playtree_setup };
148 }
149
150 sub get_differs ($$) {
151     my ($x,$y) = @_;
152     # This resembles quiltify_trees_differ, in dgit, a bit.
153     # But we don't care about modes, or dpkg-source-unrepresentable
154     # changes, and we don't need the plethora of different modes.
155     # Conversely we need to distinguish different kinds of changes to
156     # debian/ and debian/patches/.
157
158     my $differs = 0;
159
160     my $rundiff = sub {
161         my ($opts, $limits, $fn) = @_;
162         my @cmd = (@git, qw(diff-tree -z --no-renames));
163         push @cmd, @$opts;
164         push @cmd, "$_:" foreach $x, $y;
165         push @cmd, '--', @$limits;
166         my $diffs = cmdoutput @cmd;
167         foreach (split /\0/, $diffs) { $fn->(); }
168     };
169
170     $rundiff->([qw(--name-only)], [], sub {
171         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
172     });
173
174     if ($differs & DS_DEB) {
175         $differs &= ~DS_DEB;
176         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
177             $differs |=
178                 m{^debian/patches/}      ? D_PAT_OTH  :
179                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
180                                            D_DEB_OTH;
181         });
182         die "mysterious debian changes $x..$y"
183             unless $differs & (D_PAT_OTH|DS_DEB);
184     }
185
186     if ($differs & D_PAT_OTH) {
187         my $mode;
188         $differs &= ~D_PAT_OTH;
189         my $pat_oth = sub {
190             $differs |= D_PAT_OTH;
191             no warnings qw(exiting);  last;
192         };
193         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
194             no warnings qw(exiting);
195             if (!defined $mode) {
196                 $mode = $_;  next;
197             }
198             die unless s{^debian/patches/}{};
199             my $ok;
200             if ($mode eq 'A' && !m/\.series$/s) {
201                 $ok = 1;
202             } elsif ($mode eq 'M' && $_ eq 'series') {
203                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
204                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
205                 chomp $x_s;  $x_s .= "\n";
206                 $ok = $x_s eq substr($y_s, 0, length $x_s);
207             } else {
208                 # nope
209             }
210             $mode = undef;
211             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
212         });
213         die "mysterious debian/patches changes $x..$y"
214             unless $differs & (D_PAT_ADD|D_PAT_OTH);
215     }
216
217     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
218
219     return $differs;
220 }
221
222 sub commit_pr_info ($) {
223     my ($r) = @_;
224     return Data::Dumper->dump([$r], [qw(commit)]);
225 }
226
227 sub calculate_committer_authline () {
228     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
229         'DUMMY COMMIT (git-debrebase)', "HEAD:";
230     my ($h,$m) = get_commit $c;
231     $h =~ m/^committer .*$/m or confess "($h) ?";
232     return $&;
233 }
234
235 sub rm_subdir_cached ($) {
236     my ($subdir) = @_;
237     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
238 }
239
240 sub read_tree_subdir ($$) {
241     my ($subdir, $new_tree_object) = @_;
242     rm_subdir_cached $subdir;
243     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
244 }
245
246 sub make_commit ($$) {
247     my ($parents, $message_paras) = @_;
248     my $tree = cmdoutput @git, qw(write-tree);
249     my @cmd = (@git, qw(commit-tree), $tree);
250     push @cmd, qw(-p), $_ foreach @$parents;
251     push @cmd, qw(-m), $_ foreach @$message_paras;
252     return cmdoutput @cmd;
253 }
254
255 our $fproblems;
256 sub fproblem ($) {
257     my ($msg) = @_;
258     $fproblems++;
259     print STDERR "git-debrebase: safety catch tripped: $msg\n";
260 }
261 sub fproblems_maybe_bail () {
262     if ($fproblems) {
263         if ($opt_force) {
264             printf STDERR
265                 "safety catch trips (%d) overriden by --force\n",
266                 $fproblems;
267         } else {
268             fail sprintf
269                 "safety catch trips (%d) (you could --force)",
270                 $fproblems;
271         }
272     }
273 }
274
275 # classify returns an info hash like this
276 #   CommitId => $objid
277 #   Hdr => # commit headers, including 1 final newline
278 #   Msg => # commit message (so one newline is dropped)
279 #   Tree => $treeobjid
280 #   Type => (see below)
281 #   Parents = [ {
282 #       Ix => $index # ie 0, 1, 2, ...
283 #       CommitId
284 #       Differs => return value from get_differs
285 #       IsOrigin
286 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
287 #     } ...]
288 #   NewMsg => # commit message, but with any [dgit import ...] edited
289 #             # to say "[was: ...]"
290 #
291 # Types:
292 #   Packaging
293 #   Changelog
294 #   Upstream
295 #   AddPatches
296 #   Mixed
297 #   Unknown
298 #
299 #   Pseudomerge
300 #     has additional entres in classification result
301 #       Overwritten = [ subset of Parents ]
302 #       Contributor = $the_remaining_Parent
303 #
304 #   DgitImportUnpatched
305 #     has additional entry in classification result
306 #       OrigParents = [ subset of Parents ]
307 #
308 #   BreakwaterUpstreamMerge
309 #     has additional entry in classification result
310 #       OrigParents = [ subset of Parents ]  # singleton list
311
312 sub parsecommit ($;$) {
313     my ($objid, $p_ref) = @_;
314     # => hash with                   CommitId Hdr Msg Tree Parents
315     #    Parents entries have only   Ix CommitId
316     #    $p_ref, if provided, must be [] and is used as a base for Parents
317
318     $p_ref //= [];
319     die if @$p_ref;
320
321     my ($h,$m) = get_commit $objid;
322
323     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
324     my (@ph) = $h =~ m/^parent (\w+)$/mg;
325
326     my $r = {
327         CommitId => $objid,
328         Hdr => $h,
329         Msg => $m,
330         Tree => $t,
331         Parents => $p_ref,
332     };
333
334     foreach my $ph (@ph) {
335         push @$p_ref, {
336             Ix => scalar @$p_ref,
337             CommitId => $ph,
338         };
339     }
340
341     return $r;
342 }    
343
344 sub classify ($) {
345     my ($objid) = @_;
346
347     my @p;
348     my $r = parsecommit($objid, \@p);
349     my $t = $r->{Tree};
350
351     foreach my $p (@p) {
352         $p->{Differs} = (get_differs $p->{CommitId}, $t),
353     }
354
355     printdebug "classify $objid \$t=$t \@p",
356         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
357         "\n";
358
359     my $classify = sub {
360         my ($type, @rest) = @_;
361         $r = { %$r, Type => $type, @rest };
362         if ($debuglevel) {
363             printdebug " = $type ".(dd $r)."\n";
364         }
365         return $r;
366     };
367     my $unknown = sub {
368         my ($why) = @_;
369         $r = { %$r, Type => qw(Unknown) };
370         printdebug " ** Unknown\n";
371         return $r;
372     };
373
374     my $claims_to_be_breakwater =
375         $r->{Msg} =~ m{^\[git-debrebase breakwater.*\]$}m;
376
377     if (@p == 1) {
378         if ($claims_to_be_breakwater) {
379             return $unknown->("single-parent git-debrebase breakwater \`merge'");
380         }
381         my $d = $r->{Parents}[0]{Differs};
382         if ($d == D_PAT_ADD) {
383             return $classify->(qw(AddPatches));
384         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
385             return $unknown->("edits debian/patches");
386         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
387             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
388             if ($ty eq 'tree') {
389                 if ($d == D_DEB_CLOG) {
390                     return $classify->(qw(Changelog));
391                 } else {
392                     return $classify->(qw(Packaging));
393                 }
394             } elsif ($ty eq 'missing') {
395                 return $classify->(qw(BreakwaterStart));
396             } else {
397                 return $unknown->("parent's debian is not a directory");
398             }
399         } elsif ($d == D_UPS) {
400             return $classify->(qw(Upstream));
401         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
402             return $classify->(qw(Mixed));
403         } elsif ($d == 0) {
404             return $unknown->("no changes");
405         } else {
406             confess "internal error $objid ?";
407         }
408     }
409     if (!@p) {
410         return $unknown->("origin commit");
411     }
412
413     my @identical = grep { !$_->{Differs} } @p;
414     if (@p == 2 && @identical == 1 && !$claims_to_be_breakwater
415         # breakwater merges can look like pseudomerges, if they are
416         # "declare" commits (ie, there are no upstream changes)
417        ) {
418         my @overwritten = grep { $_->{Differs} } @p;
419         confess "internal error $objid ?" unless @overwritten==1;
420         return $classify->(qw(Pseudomerge),
421                            Overwritten => $overwritten[0],
422                            Contributor => $identical[0]);
423     }
424     if (@p == 2 && @identical == 2) {
425         my @bytime = nsort_by {
426             my ($ph,$pm) = get_commit $_->{CommitId};
427             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
428             $1;
429         } @p;
430         return $classify->(qw(Pseudomerge),
431                            SubType => qw(Ambiguous),
432                            Overwritten => $bytime[0],
433                            Contributor => $bytime[1]);
434     }
435     foreach my $p (@p) {
436         my ($p_h, $p_m) = get_commit $p->{CommitId};
437         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
438         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
439     }
440     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
441     my $m2 = $r->{Msg};
442     if (!(grep { !$_->{IsOrigin} } @p) and
443         (@orig_ps >= @p - 1) and
444         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
445         $r->{NewMsg} = $m2;
446         return $classify->(qw(DgitImportUnpatched),
447                            OrigParents => \@orig_ps);
448     }
449
450     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
451     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
452
453     # How to decide about l/r ordering of breakwater merges ?  git
454     # --topo-order prefers to expand 2nd parent first.  There's
455     # already an easy rune to look for debian/ history anyway (git log
456     # debian/) so debian breakwater branch should be 1st parent; that
457     # way also there's also an easy rune to look for the upstream
458     # patches (--topo-order).
459
460     # The above tells us which way *we* will generate them.  But we
461     # might encounter ad-hoc breakwater merges generated manually,
462     # which might be the other way around.  In principle, in some odd
463     # situations, a breakwater merge might have two identical parents.
464     # In that case we guess which way round it is (ie, which parent
465     # has the upstream history).  The order of the 2-iteration loop
466     # controls which guess we make.
467
468     foreach my $prevbrw (qw(0 1)) {
469         if (@p == 2 &&
470             !$haspatches &&
471             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
472             !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
473             !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
474             return $classify->(qw(BreakwaterUpstreamMerge),
475                                OrigParents => [ $p[!$prevbrw] ]);
476         }
477     }
478
479     # multi-orig upstreams are represented with a breakwater merge
480     # from a single upstream commit which combines the orig tarballs
481
482     return $unknown->("complex merge");
483 }
484
485 sub walk ($;$$);
486 sub walk ($;$$) {
487     my ($input,
488         $nogenerate,$report) = @_;
489     # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
490     # (or nothing, if $nogenerate)
491
492     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
493
494     # go through commits backwards
495     # we generate two lists of commits to apply:
496     # breakwater branch and upstream patches
497     my (@brw_cl, @upp_cl, @processed);
498     my %found;
499     my $upp_limit;
500     my @pseudomerges;
501
502     my $cl;
503     my $xmsg = sub {
504         my ($prose, $info) = @_;
505         my $ms = $cl->{Msg};
506         chomp $ms;
507         $info //= '';
508         $ms .= "\n\n[git-debrebase$info: $prose]\n";
509         return (Msg => $ms);
510     };
511     my $rewrite_from_here = sub {
512         my $sp_cl = { SpecialMethod => 'StartRewrite' };
513         push @brw_cl, $sp_cl;
514         push @processed, $sp_cl;
515     };
516     my $cur = $input;
517
518     my $prdelim = "";
519     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
520
521     my $prline = sub {
522         return unless $report;
523         print $report $prdelim, @_;
524         $prdelim = "\n";
525     };
526
527     my $bomb = sub { # usage: return $bomb->();
528         print $report " Unprocessable" if $report;
529         $prprdelim->();
530         if ($nogenerate) {
531             return (undef,undef);
532         }
533         die "commit $cur: Cannot cope with this commit (d.".
534             (join ' ', map { sprintf "%#x", $_->{Differs} }
535              @{ $cl->{Parents} }). ")";
536     };
537
538     my $build;
539     my $breakwater;
540
541     my $build_start = sub {
542         my ($msg, $parent) = @_;
543         $prline->(" $msg");
544         $build = $parent;
545         no warnings qw(exiting); last;
546     };
547
548     my $last_upstream_update;
549
550     for (;;) {
551         $cl = classify $cur;
552         my $ty = $cl->{Type};
553         my $st = $cl->{SubType};
554         $prline->("$cl->{CommitId} $cl->{Type}");
555         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
556         push @processed, $cl;
557         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
558         if ($ty eq 'AddPatches') {
559             $cur = $p0;
560             $rewrite_from_here->();
561             next;
562         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
563             push @brw_cl, $cl;
564             $cur = $p0;
565             next;
566         } elsif ($ty eq 'BreakwaterStart') {
567             $last_upstream_update = $cur;
568             $build_start->('FirstPackaging', $cur);
569         } elsif ($ty eq 'Upstream') {
570             push @upp_cl, $cl;
571             $cur = $p0;
572             next;
573         } elsif ($ty eq 'Mixed') {
574             my $queue = sub {
575                 my ($q, $wh) = @_;
576                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
577                 push @$q, $cls;
578             };
579             $queue->(\@brw_cl, "debian");
580             $queue->(\@upp_cl, "upstream");
581             $rewrite_from_here->();
582             $cur = $p0;
583             next;
584         } elsif ($ty eq 'Pseudomerge') {
585             my $contrib = $cl->{Contributor}{CommitId};
586             print $report " Contributor=$contrib" if $report;
587             push @pseudomerges, $cl;
588             $rewrite_from_here->();
589             $cur = $contrib;
590             next;
591         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
592             $last_upstream_update = $cur;
593             $build_start->("PreviousBreakwater", $cur);
594         } elsif ($ty eq 'DgitImportUnpatched') {
595             my $pm = $pseudomerges[-1];
596             if (defined $pm) {
597                 # To an extent, this is heuristic.  Imports don't have
598                 # a useful history of the debian/ branch.  We assume
599                 # that the first pseudomerge after an import has a
600                 # useful history of debian/, and ignore the histories
601                 # from later pseudomerges.  Often the first pseudomerge
602                 # will be the dgit import of the upload to the actual
603                 # suite intended by the non-dgit NMUer, and later
604                 # pseudomerges may represent in-archive copies.
605                 my $ovwrs = $pm->{Overwritten};
606                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
607                     if $report;
608                 if (@$ovwrs != 1) {
609                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
610                     return $bomb->();
611                 }
612                 my $ovwr = $ovwrs->[0]{CommitId};
613                 printf $report " Overwr=%s", $ovwr if $report;
614                 # This import has a tree which is just like a
615                 # breakwater tree, but it has the wrong history.  It
616                 # ought to have the previous breakwater (which the
617                 # pseudomerge overwrote) as an ancestor.  That will
618                 # make the history of the debian/ files correct.  As
619                 # for the upstream version: either it's the same as
620                 # was ovewritten (ie, same as the previous
621                 # breakwater), in which case that history is precisely
622                 # right; or, otherwise, it was a non-gitish upload of a
623                 # new upstream version.  We can tell these apart by
624                 # looking at the tree of the supposed upstream.
625                 push @brw_cl, {
626                     %$cl,
627                     SpecialMethod => 'DgitImportDebianUpdate',
628                     $xmsg->("convert dgit import: debian changes")
629                 };
630                 my $differs = (get_differs $ovwr, $cl->{Tree});
631                 printf $report " Differs=%#x", $differs if $report;
632                 if ($differs & D_UPS) {
633                     printf $report " D_UPS" if $report;
634                     # This will also trigger if a non-dgit git-based NMU
635                     # deleted .gitignore (which is a thing that some of
636                     # the existing git tools do if the user doesn't
637                     # somehow tell them not to).  Ah well.
638                     push @brw_cl, {
639                         %$cl,
640                         SpecialMethod => 'DgitImportUpstreamUpdate',
641                         $xmsg->("convert dgit import: upstream changes",
642                                 " breakwater")
643                     };
644                 }
645                 $prline->(" Import");
646                 $rewrite_from_here->();
647                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
648                 die 'BUG $upp_limit is not used anywhere?';
649                 $cur = $ovwr;
650                 next;
651             } else {
652                 # Everything is from this import.  This kind of import
653                 # is already in valid breakwater format, with the
654                 # patches as commits.
655                 printf $report " NoPM" if $report;
656                 # last thing we processed will have been the first patch,
657                 # if there is one; which is fine, so no need to rewrite
658                 # on account of this import
659                 $build_start->("ImportOrigin", $cur);
660             }
661             die "$ty ?";
662         } else {
663             printdebug "*** WALK BOMB unrecognised\n";
664             return $bomb->();
665         }
666     }
667     $prprdelim->();
668
669     printdebug "*** WALK prep done cur=$cur".
670         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
671
672     return if $nogenerate;
673
674     # Now we build it back up again
675
676     fresh_workarea();
677
678     my $rewriting = 0;
679
680     my $read_tree_debian = sub {
681         my ($treeish) = @_;
682         read_tree_subdir 'debian', "$treeish:debian";
683         rm_subdir_cached 'debian/patches';
684     };
685     my $read_tree_upstream = sub {
686         my ($treeish) = @_;
687         runcmd @git, qw(read-tree), $treeish;
688         $read_tree_debian->($build);
689     };
690  
691     my $committer_authline = calculate_committer_authline();
692
693     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
694
695     confess "internal error" unless $build eq (pop @processed)->{CommitId};
696
697     in_workarea sub {
698         mkdir $rd or $!==EEXIST or die $!;
699         my $current_method;
700         runcmd @git, qw(read-tree), $build;
701         foreach my $cl (qw(Debian), (reverse @brw_cl),
702                         { SpecialMethod => 'RecordBreakwaterTip' },
703                         qw(Upstream), (reverse @upp_cl)) {
704             if (!ref $cl) {
705                 $current_method = $cl;
706                 next;
707             }
708             my $method = $cl->{SpecialMethod} // $current_method;
709             my @parents = ($build);
710             my $cltree = $cl->{CommitId};
711             printdebug "WALK BUILD ".($cltree//'undef').
712                 " $method (rewriting=$rewriting)\n";
713             if ($method eq 'Debian') {
714                 $read_tree_debian->($cltree);
715             } elsif ($method eq 'Upstream') {
716                 $read_tree_upstream->($cltree);
717             } elsif ($method eq 'StartRewrite') {
718                 $rewriting = 1;
719                 next;
720             } elsif ($method eq 'RecordBreakwaterTip') {
721                 $breakwater = $build;
722                 next;
723             } elsif ($method eq 'DgitImportDebianUpdate') {
724                 $read_tree_debian->($cltree);
725                 rm_subdir_cached qw(debian/patches);
726             } elsif ($method eq 'DgitImportUpstreamUpdate') {
727                 $read_tree_upstream->($cltree);
728                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
729             } else {
730                 confess "$method ?";
731             }
732             if (!$rewriting) {
733                 my $procd = (pop @processed) // 'UNDEF';
734                 if ($cl ne $procd) {
735                     $rewriting = 1;
736                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
737                 }
738             }
739             my $newtree = cmdoutput @git, qw(write-tree);
740             my $ch = $cl->{Hdr};
741             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
742             $ch =~ s{^parent .*\n}{}m;
743             $ch =~ s{(?=^author)}{
744                 join '', map { "parent $_\n" } @parents
745             }me or confess "$ch ?";
746             if ($rewriting) {
747                 $ch =~ s{^committer .*$}{$committer_authline}m
748                     or confess "$ch ?";
749             }
750             my $cf = "$rd/m$rewriting";
751             open CD, ">", $cf or die $!;
752             print CD $ch, "\n", $cl->{Msg} or die $!;
753             close CD or die $!;
754             my @cmd = (@git, qw(hash-object));
755             push @cmd, qw(-w) if $rewriting;
756             push @cmd, qw(-t commit), $cf;
757             my $newcommit = cmdoutput @cmd;
758             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
759             $build = $newcommit;
760             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
761                 $last_upstream_update = $cur;
762             }
763         }
764     };
765
766     my $final_check = get_differs $build, $input;
767     die sprintf "internal error %#x %s %s", $final_check, $build, $input
768         if $final_check & ~D_PAT_ADD;
769
770     my @r = ($build, $breakwater, $last_upstream_update);
771     printdebug "*** WALK RETURN @r\n";
772     return @r
773 }
774
775 sub get_head () { return git_rev_parse qw(HEAD); }
776
777 sub update_head ($$$) {
778     my ($old, $new, $mrest) = @_;
779     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
780 }
781
782 sub update_head_checkout ($$$) {
783     my ($old, $new, $mrest) = @_;
784     update_head $old, $new, $mrest;
785     runcmd @git, qw(reset --hard);
786 }
787
788 sub update_head_postlaunder ($$$) {
789     my ($old, $tip, $reflogmsg) = @_;
790     return if $tip eq $old;
791     print "git-debrebase: laundered (head was $old)\n";
792     update_head $old, $tip, $reflogmsg;
793     # no tree changes except debian/patches
794     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
795 }
796
797 sub cmd_launder () {
798     badusage "no arguments to launder allowed" if @ARGV;
799     my $old = get_head();
800     my ($tip,$breakwater,$last_upstream_merge) = walk $old;
801     update_head_postlaunder $old, $tip, 'launder';
802     printf "# breakwater tip\n%s\n", $breakwater;
803     printf "# working tip\n%s\n", $tip;
804     printf "# last upstream merge\n%s\n", $last_upstream_merge;
805 }
806
807 sub defaultcmd_rebase () {
808     my $old = get_head();
809     my ($tip,$breakwater) = walk $old;
810     update_head_postlaunder $old, $tip, 'launder for rebase';
811     @ARGV = qw(-i) unless @ARGV; # make configurable
812     runcmd @git, qw(rebase), @ARGV, $breakwater;
813 }
814
815 sub cmd_analyse () {
816     die if ($ARGV[0]//'') =~ m/^-/;
817     badusage "too many arguments to analyse" if @ARGV>1;
818     my ($old) = @ARGV;
819     if (defined $old) {
820         $old = git_rev_parse $old;
821     } else {
822         $old = get_head();
823     }
824     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
825     STDOUT->error and die $!;
826 }
827
828 sub cmd_new_upstream_v0 () {
829     # tree should be clean and this is not checked
830     # automatically and unconditionally launders before rebasing
831     # if rebase --abort is used, laundering has still been done
832
833     my %pieces;
834
835     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
836
837     # parse args - low commitment
838     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
839     my $new_upstream_version = $new_version->version();
840
841     my $new_upstream = git_rev_parse shift @ARGV;
842
843     my $piece = sub {
844         my ($n, @x) = @_; # may be ''
845         my $pc = $pieces{$n} //= {
846             Name => $n,
847             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
848         };
849         while (my $k = shift @x) { $pc->{$k} = shift @x; }
850         $pc;
851     };
852
853     my @newpieces;
854     my $newpiece = sub {
855         my ($n, @x) = @_; # may be ''
856         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
857         push @newpieces, $pc;
858     };
859
860     $newpiece->('',
861         OldIx => 0,
862         New => $new_upstream,
863     );
864     while (@ARGV && $ARGV[0] !~ m{^-}) {
865         my $n = shift @ARGV;
866
867         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
868             unless @ARGV && $ARGV[0] !~ m{^-};
869
870         my $c = git_rev_parse shift @ARGV;
871         die unless $n =~ m/^$extra_orig_namepart_re$/;
872         $newpiece->($n, New => $c);
873     }
874
875     # now we need to investigate the branch this generates the
876     # laundered version but we don't switch to it yet
877     my $old_head = get_head();
878     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
879
880     my $old_bw_cl = classify $old_bw;
881     my $old_upstream_update_cl = classify $old_upstream_update;
882     confess unless $old_upstream_update_cl->{OrigParents};
883     my $old_upstream = parsecommit
884         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
885
886     $piece->('', Old => $old_upstream->{CommitId});
887
888     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
889         if ($old_upstream->{Msg} =~
890  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
891            ) {
892             my @oldpieces = ('', split / /, $1);
893             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
894             foreach my $i (0..$#oldpieces) {
895                 my $n = $oldpieces[$i];
896                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
897             }
898         } else {
899             fproblem "previous upstream $old_upstream->{CommitId} is from".
900                  " git-debrebase but not an \`upstream-combine' commit";
901         }
902     }
903
904     foreach my $pc (values %pieces) {
905         if (!$pc->{Old}) {
906             fproblem "introducing upstream piece \`$pc->{Name}'";
907         } elsif (!$pc->{New}) {
908             fproblem "dropping upstream piece \`$pc->{Name}'";
909         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
910             fproblem "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
911         }
912     }
913
914     printdebug "%pieces = ", (dd \%pieces), "\n";
915     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
916
917     fproblems_maybe_bail();
918
919     my $new_bw;
920
921     fresh_workarea();
922     in_workarea sub {
923         my @upstream_merge_parents;
924
925         if (!$fproblems) {
926             push @upstream_merge_parents, $old_upstream->{CommitId};
927         }
928
929         foreach my $pc (@newpieces) { # always has '' first
930             if ($pc->{Name}) {
931                 read_tree_subdir $pc->{Name}, $pc->{New};
932             } else {
933                 runcmd @git, qw(read-tree), $pc->{New};
934             }
935             push @upstream_merge_parents, $pc->{New};
936         }
937
938         # index now contains the new upstream
939
940         if (@newpieces > 1) {
941             # need to make the upstream subtree merge commit
942             $new_upstream = make_commit \@upstream_merge_parents,
943                 [ "Combine upstreams for $new_upstream_version",
944  ("[git-debrebase upstream-combine . ".
945  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
946  ": new upstream]"),
947                 ];
948         }
949
950         # $new_upstream is either the single upstream commit, or the
951         # combined commit we just made.  Either way it will be the
952         # "upstream" parent of the breakwater special merge.
953
954         read_tree_subdir 'debian', "$old_bw:debian";
955
956         # index now contains the breakwater merge contents
957         $new_bw = make_commit [ $old_bw, $new_upstream ],
958             [ "Update to upstream $new_upstream_version",
959  "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
960             ];
961
962         # Now we have to add a changelog stanza so the Debian version
963         # is right.
964         die if unlink "debian";
965         die $! unless $!==ENOENT or $!==ENOTEMPTY;
966         unlink "debian/changelog" or $!==ENOENT or die $!;
967         mkdir "debian" or die $!;
968         open CN, ">", "debian/changelog" or die $!;
969         my $oldclog = git_cat_file ":debian/changelog";
970         $oldclog =~ m/^($package_re) \(\S+\) / or
971             fail "cannot parse old changelog to get package name";
972         my $p = $1;
973         print CN <<END, $oldclog or die $!;
974 $p ($new_version) UNRELEASED; urgency=medium
975
976   * Update to new upstream version $new_upstream_version.
977
978  -- 
979
980 END
981         close CN or die $!;
982         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
983
984         # Now we have the final new breakwater branch in the index
985         $new_bw = make_commit [ $new_bw ],
986             [ "Update changelog for new upstream $new_upstream_version",
987               "[git-debrebase: new upstream $new_upstream_version, changelog]",
988             ];
989     };
990
991     # we have constructed the new breakwater. we now need to commit to
992     # the laundering output, because git-rebase can't easily be made
993     # to make a replay list which is based on some other branch
994
995     update_head_postlaunder $old_head, $old_laundered_tip,
996         'launder for new upstream';
997
998     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
999     runcmd @cmd;
1000     # now it's for the user to sort out
1001 }
1002
1003 sub cmd_gbp2debrebase () {
1004     badusage "needs 1 optional argument, the upstream" unless @ARGV<=1;
1005     my ($upstream_spec) = @ARGV;
1006     $upstream_spec //= 'refs/heads/upstream';
1007     my $upstream = git_rev_parse $upstream_spec;
1008     my $old_head = get_head();
1009
1010     my $upsdiff = get_differs $upstream, $old_head;
1011     if ($upsdiff & D_UPS) {
1012         runcmd @git, qw(--no-pager diff),
1013             $upstream, $old_head,
1014             qw( -- :!/debian :/);
1015  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1016     }
1017
1018     if (!is_fast_fwd $upstream, $old_head) {
1019         fproblem "upstream ($upstream) is not an ancestor of HEAD";
1020     } else {
1021         my $wrong = cmdoutput
1022             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1023              qw(-- :/ :!/debian));
1024         if (length $wrong) {
1025             fproblem "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1026             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1027         }
1028     }
1029
1030     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1031         fproblem "upstream ($upstream) contains debian/ directory";
1032     }
1033
1034     fproblems_maybe_bail();
1035
1036     my $work;
1037
1038     fresh_workarea();
1039     in_workarea sub {
1040         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1041         # make a branch out of the patch queue - we'll want this in a mo
1042         runcmd qw(gbp pq import);
1043         # strip the patches out
1044         runcmd @git, qw(checkout -q gdr-internal~0);
1045         rm_subdir_cached 'debian/patches';
1046         $work = make_commit ['HEAD'], [
1047  'git-debrebase import: drop patch queue',
1048  'Delete debian/patches, as part of converting to git-debrebase format.',
1049  '[git-debrebase: gbp2debrebase, drop patches]'
1050                               ];
1051         # make the breakwater pseudomerge
1052         # the tree is already exactly right
1053         $work = make_commit [$work, $upstream], [
1054  'git-debrebase import: declare upstream',
1055  'First breakwater merge.',
1056  '[git-debrebase breakwater: declare upstream]'
1057                               ];
1058
1059         # rebase the patch queue onto the new breakwater
1060         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1061         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1062         $work = get_head();
1063     };
1064
1065     update_head_checkout $old_head, $work, 'gbp2debrebase';
1066 }
1067
1068 sub cmd_downstream_rebase_launder_v0 () {
1069     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1070     my ($base) = @ARGV;
1071     $base = git_rev_parse $base;
1072     my $old_head = get_head();
1073     my $current = $old_head;
1074     my $topmost_keep;
1075     for (;;) {
1076         if ($current eq $base) {
1077             $topmost_keep //= $current;
1078             print " $current BASE stop\n";
1079             last;
1080         }
1081         my $cl = classify $current;
1082         print " $current $cl->{Type}";
1083         my $keep = 0;
1084         my $p0 = $cl->{Parents}[0]{CommitId};
1085         my $next;
1086         if ($cl->{Type} eq 'Pseudomerge') {
1087             print " ^".($cl->{Contributor}{Ix}+1);
1088             $next = $cl->{Contributor}{CommitId};
1089         } elsif ($cl->{Type} eq 'AddPatches' or
1090                  $cl->{Type} eq 'Changelog') {
1091             print " strip";
1092             $next = $p0;
1093         } else {
1094             print " keep";
1095             $next = $p0;
1096             $keep = 1;
1097         }
1098         print "\n";
1099         if ($keep) {
1100             $topmost_keep //= $current;
1101         } else {
1102             die "to-be stripped changes not on top of the branch\n"
1103                 if $topmost_keep;
1104         }
1105         $current = $next;
1106     }
1107     if ($topmost_keep eq $old_head) {
1108         print "unchanged\n";
1109     } else {
1110         print "updating to $topmost_keep\n";
1111         update_head_checkout
1112             $old_head, $topmost_keep,
1113             'downstream-rebase-launder-v0';
1114     }
1115 }
1116
1117 GetOptions("D+" => \$debuglevel,
1118            'force!') or die badusage "bad options\n";
1119 initdebug('git-debrebase ');
1120 enabledebug if $debuglevel;
1121
1122 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1123 chdir $toplevel or die "chdir $toplevel: $!";
1124
1125 $rd = fresh_playground "$playprefix/misc";
1126
1127 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1128     defaultcmd_rebase();
1129 } else {
1130     my $cmd = shift @ARGV;
1131     my $cmdfn = $cmd;
1132     $cmdfn =~ y/-/_/;
1133     $cmdfn = ${*::}{"cmd_$cmdfn"};
1134
1135     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1136     $cmdfn->();
1137 }