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