chiark / gitweb /
b57e42833cee4a5562d2cf8510d62620ad6c44e0
[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 # classify returns an info hash like this
256 #   CommitId => $objid
257 #   Hdr => # commit headers, including 1 final newline
258 #   Msg => # commit message (so one newline is dropped)
259 #   Tree => $treeobjid
260 #   Type => (see below)
261 #   Parents = [ {
262 #       Ix => $index # ie 0, 1, 2, ...
263 #       CommitId
264 #       Differs => return value from get_differs
265 #       IsOrigin
266 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
267 #     } ...]
268 #   NewMsg => # commit message, but with any [dgit import ...] edited
269 #             # to say "[was: ...]"
270 #
271 # Types:
272 #   Packaging
273 #   Changelog
274 #   Upstream
275 #   AddPatches
276 #   Mixed
277 #   Unknown
278 #
279 #   Pseudomerge
280 #     has additional entres in classification result
281 #       Overwritten = [ subset of Parents ]
282 #       Contributor = $the_remaining_Parent
283 #
284 #   DgitImportUnpatched
285 #     has additional entry in classification result
286 #       OrigParents = [ subset of Parents ]
287 #
288 #   BreakwaterUpstreamMerge
289 #     has additional entry in classification result
290 #       OrigParents = [ subset of Parents ]  # singleton list
291
292 sub parsecommit ($;$) {
293     my ($objid, $p_ref) = @_;
294     # => hash with                   CommitId Hdr Msg Tree Parents
295     #    Parents entries have only   Ix CommitId
296     #    $p_ref, if provided, must be [] and is used as a base for Parents
297
298     $p_ref //= [];
299     die if @$p_ref;
300
301     my ($h,$m) = get_commit $objid;
302
303     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
304     my (@ph) = $h =~ m/^parent (\w+)$/mg;
305
306     my $r = {
307         CommitId => $objid,
308         Hdr => $h,
309         Msg => $m,
310         Tree => $t,
311         Parents => $p_ref,
312     };
313
314     foreach my $ph (@ph) {
315         push @$p_ref, {
316             Ix => scalar @$p_ref,
317             CommitId => $ph,
318         };
319     }
320
321     return $r;
322 }    
323
324 sub classify ($) {
325     my ($objid) = @_;
326
327     my @p;
328     my $r = parsecommit($objid, \@p);
329     my $t = $r->{Tree};
330
331     foreach my $p (@p) {
332         $p->{Differs} = (get_differs $p->{CommitId}, $t),
333     }
334
335     printdebug "classify $objid \$t=$t \@p",
336         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
337         "\n";
338
339     my $classify = sub {
340         my ($type, @rest) = @_;
341         $r = { %$r, Type => $type, @rest };
342         if ($debuglevel) {
343             printdebug " = $type ".(dd $r)."\n";
344         }
345         return $r;
346     };
347     my $unknown = sub {
348         my ($why) = @_;
349         $r = { %$r, Type => qw(Unknown) };
350         printdebug " ** Unknown\n";
351         return $r;
352     };
353
354     if (@p == 1) {
355         my $d = $r->{Parents}[0]{Differs};
356         if ($d == D_PAT_ADD) {
357             return $classify->(qw(AddPatches));
358         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
359             return $unknown->("edits debian/patches");
360         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
361             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
362             if ($ty eq 'tree') {
363                 if ($d == D_DEB_CLOG) {
364                     return $classify->(qw(Changelog));
365                 } else {
366                     return $classify->(qw(Packaging));
367                 }
368             } elsif ($ty eq 'missing') {
369                 return $classify->(qw(BreakwaterStart));
370             } else {
371                 return $unknown->("parent's debian is not a directory");
372             }
373         } elsif ($d == D_UPS) {
374             return $classify->(qw(Upstream));
375         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
376             return $classify->(qw(Mixed));
377         } elsif ($d == 0) {
378             return $unknown->("no changes");
379         } else {
380             confess "internal error $objid ?";
381         }
382     }
383     if (!@p) {
384         return $unknown->("origin commit");
385     }
386
387     my @identical = grep { !$_->{Differs} } @p;
388     if (@p == 2 && @identical == 1) {
389         my @overwritten = grep { $_->{Differs} } @p;
390         confess "internal error $objid ?" unless @overwritten==1;
391         return $classify->(qw(Pseudomerge),
392                            Overwritten => $overwritten[0],
393                            Contributor => $identical[0]);
394     }
395     if (@p == 2 && @identical == 2) {
396         my @bytime = nsort_by {
397             my ($ph,$pm) = get_commit $_->{CommitId};
398             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
399             $1;
400         } @p;
401         return $classify->(qw(Pseudomerge),
402                            SubType => qw(Ambiguous),
403                            Overwritten => $bytime[0],
404                            Contributor => $bytime[1]);
405     }
406     foreach my $p (@p) {
407         my ($p_h, $p_m) = get_commit $p->{CommitId};
408         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
409         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
410     }
411     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
412     my $m2 = $r->{Msg};
413     if (!(grep { !$_->{IsOrigin} } @p) and
414         (@orig_ps >= @p - 1) and
415         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
416         $r->{NewMsg} = $m2;
417         return $classify->(qw(DgitImportUnpatched),
418                            OrigParents => \@orig_ps);
419     }
420
421     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
422     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
423
424     # How to decide about l/r ordering of breakwater merges ?  git
425     # --topo-order prefers to expand 2nd parent first.  There's
426     # already an easy rune to look for debian/ history anyway (git log
427     # debian/) so debian breakwater branch should be 1st parent; that
428     # way also there's also an easy rune to look for the upstream
429     # patches (--topo-order).
430
431     # The above tells us which way *we* will generate them.  But we
432     # might encounter ad-hoc breakwater merges generated manually,
433     # which might be the other way around.  In principle, in some odd
434     # situations, a breakwater merge might have two identical parents.
435     # In that case we guess which way round it is (ie, which parent
436     # has the upstream history).  The order of the 2-iteration loop
437     # controls which guess we make.
438
439     foreach my $prevbrw (qw(0 1)) {
440         if (@p == 2 &&
441             !$haspatches &&
442             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
443             !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
444             !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
445             return $classify->(qw(BreakwaterUpstreamMerge),
446                                OrigParents => [ $p[!$prevbrw] ]);
447         }
448     }
449
450     # multi-orig upstreams are represented with a breakwater merge
451     # from a single upstream commit which combines the orig tarballs
452
453     return $unknown->("complex merge");
454 }
455
456 sub walk ($;$$);
457 sub walk ($;$$) {
458     my ($input,
459         $nogenerate,$report) = @_;
460     # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
461     # (or nothing, if $nogenerate)
462
463     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
464
465     # go through commits backwards
466     # we generate two lists of commits to apply:
467     # breakwater branch and upstream patches
468     my (@brw_cl, @upp_cl, @processed);
469     my %found;
470     my $upp_limit;
471     my @pseudomerges;
472
473     my $cl;
474     my $xmsg = sub {
475         my ($appendinfo) = @_;
476         my $ms = $cl->{Msg};
477         chomp $ms;
478         $ms .= "\n\n[git-debrebase $appendinfo]\n";
479         return (Msg => $ms);
480     };
481     my $rewrite_from_here = sub {
482         my $sp_cl = { SpecialMethod => 'StartRewrite' };
483         push @brw_cl, $sp_cl;
484         push @processed, $sp_cl;
485     };
486     my $cur = $input;
487
488     my $prdelim = "";
489     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
490
491     my $prline = sub {
492         return unless $report;
493         print $report $prdelim, @_;
494         $prdelim = "\n";
495     };
496
497     my $bomb = sub { # usage: return $bomb->();
498         print $report " Unprocessable" if $report;
499         $prprdelim->();
500         if ($nogenerate) {
501             return (undef,undef);
502         }
503         die "commit $cur: Cannot cope with this commit (d.".
504             (join ' ', map { sprintf "%#x", $_->{Differs} }
505              @{ $cl->{Parents} }). ")";
506     };
507
508     my $build;
509     my $breakwater;
510
511     my $build_start = sub {
512         my ($msg, $parent) = @_;
513         $prline->(" $msg");
514         $build = $parent;
515         no warnings qw(exiting); last;
516     };
517
518     my $last_upstream_update;
519
520     for (;;) {
521         $cl = classify $cur;
522         my $ty = $cl->{Type};
523         my $st = $cl->{SubType};
524         $prline->("$cl->{CommitId} $cl->{Type}");
525         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
526         push @processed, $cl;
527         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
528         if ($ty eq 'AddPatches') {
529             $cur = $p0;
530             $rewrite_from_here->();
531             next;
532         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
533             push @brw_cl, $cl;
534             $cur = $p0;
535             next;
536         } elsif ($ty eq 'BreakwaterStart') {
537             $last_upstream_update = $cur;
538             $build_start->('FirstPackaging', $cur);
539         } elsif ($ty eq 'Upstream') {
540             push @upp_cl, $cl;
541             $cur = $p0;
542             next;
543         } elsif ($ty eq 'Mixed') {
544             my $queue = sub {
545                 my ($q, $wh) = @_;
546                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
547                 push @$q, $cls;
548             };
549             $queue->(\@brw_cl, "debian");
550             $queue->(\@upp_cl, "upstream");
551             $rewrite_from_here->();
552             $cur = $p0;
553             next;
554         } elsif ($ty eq 'Pseudomerge') {
555             my $contrib = $cl->{Contributor}{CommitId};
556             print $report " Contributor=$contrib" if $report;
557             push @pseudomerges, $cl;
558             $rewrite_from_here->();
559             $cur = $contrib;
560             next;
561         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
562             $last_upstream_update = $cur;
563             $build_start->("PreviousBreakwater", $cur);
564         } elsif ($ty eq 'DgitImportUnpatched') {
565             my $pm = $pseudomerges[-1];
566             if (defined $pm) {
567                 # To an extent, this is heuristic.  Imports don't have
568                 # a useful history of the debian/ branch.  We assume
569                 # that the first pseudomerge after an import has a
570                 # useful history of debian/, and ignore the histories
571                 # from later pseudomerges.  Often the first pseudomerge
572                 # will be the dgit import of the upload to the actual
573                 # suite intended by the non-dgit NMUer, and later
574                 # pseudomerges may represent in-archive copies.
575                 my $ovwrs = $pm->{Overwritten};
576                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
577                     if $report;
578                 if (@$ovwrs != 1) {
579                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
580                     return $bomb->();
581                 }
582                 my $ovwr = $ovwrs->[0]{CommitId};
583                 printf $report " Overwr=%s", $ovwr if $report;
584                 # This import has a tree which is just like a
585                 # breakwater tree, but it has the wrong history.  It
586                 # ought to have the previous breakwater (which the
587                 # pseudomerge overwrote) as an ancestor.  That will
588                 # make the history of the debian/ files correct.  As
589                 # for the upstream version: either it's the same as
590                 # was ovewritten (ie, same as the previous
591                 # breakwater), in which case that history is precisely
592                 # right; or, otherwise, it was a non-gitish upload of a
593                 # new upstream version.  We can tell these apart by
594                 # looking at the tree of the supposed upstream.
595                 push @brw_cl, {
596                     %$cl,
597                     SpecialMethod => 'DgitImportDebianUpdate',
598                     $xmsg->("convert dgit import: debian changes")
599                 };
600                 my $differs = (get_differs $ovwr, $cl->{Tree});
601                 printf $report " Differs=%#x", $differs if $report;
602                 if ($differs & D_UPS) {
603                     printf $report " D_UPS" if $report;
604                     # This will also trigger if a non-dgit git-based NMU
605                     # deleted .gitignore (which is a thing that some of
606                     # the existing git tools do if the user doesn't
607                     # somehow tell them not to).  Ah well.
608                     push @brw_cl, {
609                         %$cl,
610                         SpecialMethod => 'DgitImportUpstreamUpdate',
611                         $xmsg->("convert dgit import: upstream changes")
612                     };
613                 }
614                 $prline->(" Import");
615                 $rewrite_from_here->();
616                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
617                 die 'BUG $upp_limit is not used anywhere?';
618                 $cur = $ovwr;
619                 next;
620             } else {
621                 # Everything is from this import.  This kind of import
622                 # is already in valid breakwater format, with the
623                 # patches as commits.
624                 printf $report " NoPM" if $report;
625                 # last thing we processed will have been the first patch,
626                 # if there is one; which is fine, so no need to rewrite
627                 # on account of this import
628                 $build_start->("ImportOrigin", $cur);
629             }
630             die "$ty ?";
631         } else {
632             printdebug "*** WALK BOMB unrecognised\n";
633             return $bomb->();
634         }
635     }
636     $prprdelim->();
637
638     printdebug "*** WALK prep done cur=$cur".
639         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
640
641     return if $nogenerate;
642
643     # Now we build it back up again
644
645     fresh_workarea();
646
647     my $rewriting = 0;
648
649     my $read_tree_debian = sub {
650         my ($treeish) = @_;
651         read_tree_subdir 'debian', "$treeish:debian";
652         rm_subdir_cached 'debian/patches';
653     };
654     my $read_tree_upstream = sub {
655         my ($treeish) = @_;
656         runcmd @git, qw(read-tree), $treeish;
657         $read_tree_debian->($build);
658     };
659  
660     my $committer_authline = calculate_committer_authline();
661
662     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
663
664     confess "internal error" unless $build eq (pop @processed)->{CommitId};
665
666     in_workarea sub {
667         mkdir $rd or $!==EEXIST or die $!;
668         my $current_method;
669         runcmd @git, qw(read-tree), $build;
670         foreach my $cl (qw(Debian), (reverse @brw_cl),
671                         { SpecialMethod => 'RecordBreakwaterTip' },
672                         qw(Upstream), (reverse @upp_cl)) {
673             if (!ref $cl) {
674                 $current_method = $cl;
675                 next;
676             }
677             my $method = $cl->{SpecialMethod} // $current_method;
678             my @parents = ($build);
679             my $cltree = $cl->{CommitId};
680             printdebug "WALK BUILD ".($cltree//'undef').
681                 " $method (rewriting=$rewriting)\n";
682             if ($method eq 'Debian') {
683                 $read_tree_debian->($cltree);
684             } elsif ($method eq 'Upstream') {
685                 $read_tree_upstream->($cltree);
686             } elsif ($method eq 'StartRewrite') {
687                 $rewriting = 1;
688                 next;
689             } elsif ($method eq 'RecordBreakwaterTip') {
690                 $breakwater = $build;
691                 next;
692             } elsif ($method eq 'DgitImportDebianUpdate') {
693                 $read_tree_debian->($cltree);
694                 rm_subdir_cached qw(debian/patches);
695             } elsif ($method eq 'DgitImportUpstreamUpdate') {
696                 $read_tree_upstream->($cltree);
697                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
698             } else {
699                 confess "$method ?";
700             }
701             if (!$rewriting) {
702                 my $procd = (pop @processed) // 'UNDEF';
703                 if ($cl ne $procd) {
704                     $rewriting = 1;
705                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
706                 }
707             }
708             my $newtree = cmdoutput @git, qw(write-tree);
709             my $ch = $cl->{Hdr};
710             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
711             $ch =~ s{^parent .*\n}{}m;
712             $ch =~ s{(?=^author)}{
713                 join '', map { "parent $_\n" } @parents
714             }me or confess "$ch ?";
715             if ($rewriting) {
716                 $ch =~ s{^committer .*$}{$committer_authline}m
717                     or confess "$ch ?";
718             }
719             my $cf = "$rd/m$rewriting";
720             open CD, ">", $cf or die $!;
721             print CD $ch, "\n", $cl->{Msg} or die $!;
722             close CD or die $!;
723             my @cmd = (@git, qw(hash-object));
724             push @cmd, qw(-w) if $rewriting;
725             push @cmd, qw(-t commit), $cf;
726             my $newcommit = cmdoutput @cmd;
727             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
728             $build = $newcommit;
729             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
730                 $last_upstream_update = $cur;
731             }
732         }
733     };
734
735     my $final_check = get_differs $build, $input;
736     die sprintf "internal error %#x %s %s", $final_check, $build, $input
737         if $final_check & ~D_PAT_ADD;
738
739     my @r = ($build, $breakwater, $last_upstream_update);
740     printdebug "*** WALK RETURN @r\n";
741     return @r
742 }
743
744 sub get_head () { return git_rev_parse qw(HEAD); }
745
746 sub update_head ($$$) {
747     my ($old, $new, $mrest) = @_;
748     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
749 }
750
751 sub update_head_checkout ($$$) {
752     my ($old, $new, $mrest) = @_;
753     my $symref = git_get_symref();
754     runcmd @git, qw(checkout), $new, qw(.);
755     update_head $old, $new, $mrest;
756 }
757
758 sub update_head_postlaunder ($$$) {
759     my ($old, $tip, $reflogmsg) = @_;
760     return if $tip eq $old;
761     print "git-debrebase: laundered (head was $old)\n";
762     update_head $old, $tip, $reflogmsg;
763     # no tree changes except debian/patches
764     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
765 }
766
767 sub cmd_launder () {
768     badusage "no arguments to launder allowed" if @ARGV;
769     my $old = get_head();
770     my ($tip,$breakwater,$last_upstream_merge) = walk $old;
771     update_head_postlaunder $old, $tip, 'launder';
772     printf "# breakwater tip\n%s\n", $breakwater;
773     printf "# working tip\n%s\n", $tip;
774     printf "# last upstream merge\n%s\n", $last_upstream_merge;
775 }
776
777 sub defaultcmd_rebase () {
778     my $old = get_head();
779     my ($tip,$breakwater) = walk $old;
780     update_head_postlaunder $old, $tip, 'launder for rebase';
781     @ARGV = qw(-i) unless @ARGV; # make configurable
782     runcmd @git, qw(rebase), @ARGV, $breakwater;
783 }
784
785 sub cmd_analyse () {
786     die if ($ARGV[0]//'') =~ m/^-/;
787     badusage "too many arguments to analyse" if @ARGV>1;
788     my ($old) = @ARGV;
789     if (defined $old) {
790         $old = git_rev_parse $old;
791     } else {
792         $old = get_head();
793     }
794     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
795     STDOUT->error and die $!;
796 }
797
798 sub cmd_new_upstream_v0 () {
799     # tree should be clean and this is not checked
800     # automatically and unconditionally launders before rebasing
801     # if rebase --abort is used, laundering has still been done
802
803     my %pieces;
804
805     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
806
807     # parse args - low commitment
808     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
809     my $new_upstream_version = $new_version->version();
810
811     my $new_upstream = git_rev_parse shift @ARGV;
812
813     my $piece = sub {
814         my ($n, @x) = @_; # may be ''
815         my $pc = $pieces{$n} //= {
816             Name => $n,
817             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
818         };
819         while (my $k = shift @x) { $pc->{$k} = shift @x; }
820         $pc;
821     };
822
823     my @newpieces;
824     my $newpiece = sub {
825         my ($n, @x) = @_; # may be ''
826         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
827         push @newpieces, $pc;
828     };
829
830     $newpiece->('',
831         OldIx => 0,
832         New => $new_upstream,
833     );
834     while (@ARGV && $ARGV[0] !~ m{^-}) {
835         my $n = shift @ARGV;
836
837         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
838             unless @ARGV && $ARGV[0] !~ m{^-};
839
840         my $c = git_rev_parse shift @ARGV;
841         die unless $n =~ m/^$extra_orig_namepart_re$/;
842         $newpiece->($n, New => $c);
843     }
844
845     # now we need to investigate the branch this generates the
846     # laundered version but we don't switch to it yet
847     my $old_head = get_head();
848     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
849
850     my $old_bw_cl = classify $old_bw;
851     my $old_upstream_update_cl = classify $old_upstream_update;
852     confess unless $old_upstream_update_cl->{OrigParents};
853     my $old_upstream = parsecommit
854         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
855
856     my $problems = 0;
857     my $problem = sub {
858         my ($msg) = @_;
859         $problems++;
860         print STDERR "preflight check failed: $msg\n";
861     };
862
863     $piece->('', Old => $old_upstream->{CommitId});
864
865     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
866         if ($old_upstream->{Msg} =~
867  m{^\[git-debrebase new-upstream combine \.((?: $extra_orig_namepart_re)+)\]}
868            ) {
869             my @oldpieces = ('', split / /, $1);
870             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
871             foreach my $i (0..$#oldpieces) {
872                 my $n = $oldpieces[$i];
873                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
874             }
875         } else {
876             $problem->("previous upstream $old_upstream->{CommitId} is from".
877                  " git-debrebase but not a \`new-upstream combine' commit");
878         }
879     }
880
881     foreach my $pc (values %pieces) {
882         if (!$pc->{Old}) {
883             $problem->("introducing upstream piece \`$pc->{Name}'");
884         } elsif (!$pc->{New}) {
885             $problem->("dropping upstream piece \`$pc->{Name}'");
886         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
887             $problem->("not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}");
888         }
889     }
890
891     printdebug "%pieces = ", (dd \%pieces), "\n";
892     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
893
894     if ($problems) {
895         if ($opt_force) {
896             printf STDERR
897                 "preflight check failures (%d) overriden by --force\n",
898                 $problems;
899         } else {
900             fail sprintf
901                 "preflight check failures (%d) (you could --force)",
902                 $problems;
903         }
904     }
905
906     my $new_bw;
907
908     fresh_workarea();
909     in_workarea sub {
910         my @upstream_merge_parents;
911
912         if (!$problems) {
913             push @upstream_merge_parents, $old_upstream->{CommitId};
914         }
915
916         foreach my $pc (@newpieces) { # always has '' first
917             if ($pc->{Name}) {
918                 read_tree_subdir $pc->{Name}, $pc->{New};
919             } else {
920                 runcmd @git, qw(read-tree), $pc->{New};
921             }
922             push @upstream_merge_parents, $pc->{New};
923         }
924
925         # index now contains the new upstream
926
927         if (@newpieces > 1) {
928             # need to make the upstream subtree merge commit
929             $new_upstream = make_commit \@upstream_merge_parents,
930                 [ "Combine upstreams for $new_upstream_version",
931                   ("[git-debrebase new-upstream combine . ".
932                    (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
933                    "]"),
934                 ];
935         }
936
937         # $new_upstream is either the single upstream commit, or the
938         # combined commit we just made.  Either way it will be the
939         # "upstream" parent of the breakwater special merge.
940
941         read_tree_subdir 'debian', "$old_bw:debian";
942
943         # index now contains the breakwater merge contents
944         $new_bw = make_commit [ $old_bw, $new_upstream ],
945             [ "Update to upstream $new_upstream_version",
946               "[git-debrebase new-upstream breakwater $new_upstream_version]",
947             ];
948
949         # Now we have to add a changelog stanza so the Debian version
950         # is right.
951         die if unlink "debian";
952         die $! unless $!==ENOENT or $!==ENOTEMPTY;
953         unlink "debian/changelog" or $!==ENOENT or die $!;
954         mkdir "debian" or die $!;
955         open CN, ">", "debian/changelog" or die $!;
956         my $oldclog = git_cat_file ":debian/changelog";
957         $oldclog =~ m/^($package_re) \(\S+\) / or
958             fail "cannot parse old changelog to get package name";
959         my $p = $1;
960         print CN <<END, $oldclog or die $!;
961 $p ($new_version) UNRELEASED; urgency=medium
962
963   * Update to new upstream version $new_upstream_version.
964
965  -- 
966
967 END
968         close CN or die $!;
969         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
970
971         # Now we have the final new breakwater branch in the index
972         $new_bw = make_commit [ $new_bw ],
973             [ "Update changelog for new upstream $new_upstream_version",
974               "[git-debrebase new-upstream changelog $new_upstream_version]",
975             ];
976     };
977
978     # we have constructed the new breakwater. we now need to commit to
979     # the laundering output, because git-rebase can't easily be made
980     # to make a replay list which is based on some other branch
981
982     update_head_postlaunder $old_head, $old_laundered_tip,
983         'launder for new upstream';
984
985     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
986     runcmd @cmd;
987     # now it's for the user to sort out
988 }
989
990 sub cmd_downstream_rebase_launder_v0 () {
991     badusage "needs 1 argument, the baseline" unless @ARGV==1;
992     my ($base) = @ARGV;
993     $base = git_rev_parse $base;
994     my $old_head = get_head();
995     my $current = $old_head;
996     my $topmost_keep;
997     for (;;) {
998         if ($current eq $base) {
999             $topmost_keep //= $current;
1000             print " $current BASE stop\n";
1001             last;
1002         }
1003         my $cl = classify $current;
1004         print " $current $cl->{Type}";
1005         my $keep = 0;
1006         my $p0 = $cl->{Parents}[0]{CommitId};
1007         my $next;
1008         if ($cl->{Type} eq 'Pseudomerge') {
1009             print " ^".($cl->{Contributor}{Ix}+1);
1010             $next = $cl->{Contributor}{CommitId};
1011         } elsif ($cl->{Type} eq 'AddPatches' or
1012                  $cl->{Type} eq 'Changelog') {
1013             print " strip";
1014             $next = $p0;
1015         } else {
1016             print " keep";
1017             $next = $p0;
1018             $keep = 1;
1019         }
1020         print "\n";
1021         if ($keep) {
1022             $topmost_keep //= $current;
1023         } else {
1024             die "to-be stripped changes not on top of the branch\n"
1025                 if $topmost_keep;
1026         }
1027         $current = $next;
1028     }
1029     if ($topmost_keep eq $old_head) {
1030         print "unchanged\n";
1031     } else {
1032         print "updating to $topmost_keep\n";
1033         update_head_checkout
1034             $old_head, $topmost_keep,
1035             'downstream-rebase-launder-v0';
1036     }
1037 }
1038
1039 GetOptions("D+" => \$debuglevel,
1040            'force!') or die badusage "bad options\n";
1041 initdebug('git-debrebase ');
1042 enabledebug if $debuglevel;
1043
1044 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1045 chdir $toplevel or die "chdir $toplevel: $!";
1046
1047 $rd = fresh_playground "$playprefix/misc";
1048
1049 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1050     defaultcmd_rebase();
1051 } else {
1052     my $cmd = shift @ARGV;
1053     my $cmdfn = $cmd;
1054     $cmdfn =~ y/-/_/;
1055     $cmdfn = ${*::}{"cmd_$cmdfn"};
1056
1057     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1058     $cmdfn->();
1059 }