chiark / gitweb /
git-debrebase: new-upstream-v0: support passing git-rebase options
[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 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 #    git-debrebase new-upstreams-v0 \
22 #             NEW-VERSION ORIG-COMMITISH
23 #            [EXTRA-ORIG-NAME EXTRA-ORIG-COMMITISH ...]
24 #            [<git-rebase options>]
25
26 # usages:
27 #    git-debrebase status
28 #    git-debrebase start       # like ffqrebase start + debrebase launder
29 #    git-debrebase new-upstream [stuff]  # see below
30 #    git-debrebase <git-rebase options>  # does debrebase start if necessary
31 #
32 #    git-debrebase analyse
33 #    git-debrebase launder     # prints breakwater tip
34 #    git-debrebase create-new-upstream-breakwater [-f] <upstreaminfo>...
35 #
36 # <upstreaminfo> is
37 #    [,][<subdir>:][+]<commitid>[,...]
38 #
39 # if initial comma is supplied, entries are not positional.  Unspecified
40 # <subdir> means root (and there may be only one).
41 # xxx want auto branch names
42 # xxx too complicated
43 # how about for now
44 #    [+]<commit> [<subdir/> [+]<commit>...]
45 # ?  plus options
46 #     --new-upstream-different-subtrees
47 #
48 #  automatic case
49 #       git-debrebase new-upstream
50 #             - previous breakwater merge must be gdr-generated
51 #             - orig set is the same as before
52 #             - implicitly uses upstream branches according to orig set
53 #             - not all upstream branches need be updated
54 #             - insists on fast-forward of each branch, unless
55 #                  --force (or --force=<subdir>[/])
56 #  branch set adjustments
57 #       git-debrebase new-upstream --add <subdir>/
58 #       git-debrebase new-upstream --rm <subdir>/
59 #       git-debrebase new-upstream / [<subdir>/ ...]
60 #             - orig set is adjusted
61 #             - otherwise like auto (--add is not checked for ffness, obv)
62 #             - multiple --add and --rm may be specified
63 #             - --add makes new upstream the last contributor
64 #  explicit
65 #       git-debrebase / [<rootcommitid>] [<subdir>/ [<commitid>] ...]
66 #             - orig set is precisely as specified now
67 #             - previous breakwater merge is irrelevant
68 #             - no fast forward checks
69 #  for now only explicit with commitids
70
71 #         implicitly uses `upstream'
72 #                                     # (or multiple other branches)
73 #       git-debrebase new-upstream \
74 #             [<subdir>/]=<commitid>
75
76 #    UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
77 #    default for SUBDIR: is from previous upstream merge[xxx terminology]
78 #    
79 #
80 #xxx
81 # when starting must record original start (for ff)
82 # and new rebase basis
83 #
84 #    git-ffqrebase start [BASE]
85 #                # records previous HEAD so it can be overwritten
86 #                # records base for future git-ffqrebase
87 #    git-ffqrebase set-base BASE
88 #    git-ffqrebase <git-rebase options>
89 #    git-ffqrebase finish
90 #    git-ffqrebase status [BRANCH]
91 #
92 #  refs/ffqrebase-prev/BRANCH    BRANCH may be refs/...; if not it means
93 #  refs/ffqrebase-base/BRANCH      refs/heads/BRANCH
94 #                               zero, one, or both of these may exist
95 #
96 # git-debrebase without start, if already started, is willing
97 # to strip pseudomerges provided that they overwrite exactly
98 # the previous HEAD
99 #  xxxx is this right ?  what matters is have we pushed
100 #    I think in fact the right answer is:
101 #       git-debrebase always strips out pseudomerges from its branch
102 #       a pseudomerge is put in at the time we want to push
103 #       at that time, we make a pseudomerge of the remote tracking
104 #           branch (if raw git) or the dgit view (if dgit)
105 #       for raw git git-ffqrebase, do want preciseley to record
106 #           value of remote tracking branch or our branch, on start, so we
107 #           overwrite only things we intend to
108 #  the previous pseudomerge    check for tags and remote branches ?
109
110 use strict;
111
112 use Debian::Dgit qw(:DEFAULT :playground);
113 setup_sigwarn();
114
115 use Memoize;
116 use Carp;
117 use POSIX;
118 use Data::Dumper;
119 use Getopt::Long qw(:config posix_default gnu_compat bundling);
120 use Dpkg::Version;
121
122 our ($opt_force);
123
124 sub badusage ($) {
125     my ($m) = @_;
126     die "bad usage: $m\n";
127 }
128
129 sub cfg ($) {
130     my ($k) = @_;
131     $/ = "\0";
132     my @cmd = qw(git config -z);
133     push @cmd, qw(--get-all) if wantarray;
134     push @cmd, $k;
135     my $out = cmdoutput @cmd;
136     return split /\0/, $out;
137 }
138
139 memoize('cfg');
140
141 sub dd ($) {
142     my ($v) = @_;
143     my $dd = new Data::Dumper [ $v ];
144     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
145     return Dump $dd;
146 }
147
148 sub get_commit ($) {
149     my ($objid) = @_;
150     my $data = git_cat_file $objid, 'commit';
151     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
152     return ($`,$');
153 }
154
155 sub D_UPS ()      { 0x02; } # upstream files
156 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
157 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
158 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
159 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
160 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
161
162 our $playprefix = 'debrebase';
163 our $rd;
164 our $workarea;
165
166 our @git = qw(git);
167
168 sub in_workarea ($) {
169     my ($sub) = @_;
170     changedir $workarea;
171     my $r = eval { $sub->(); };
172     { local $@; changedir $maindir; }
173     die $@ if $@;
174 }
175
176 sub fresh_workarea () {
177     $workarea = fresh_playground "$playprefix/work";
178     in_workarea sub { playtree_setup };
179 }
180
181 sub get_differs ($$) {
182     my ($x,$y) = @_;
183     # This resembles quiltify_trees_differ, in dgit, a bit.
184     # But we don't care about modes, or dpkg-source-unrepresentable
185     # changes, and we don't need the plethora of different modes.
186     # Conversely we need to distinguish different kinds of changes to
187     # debian/ and debian/patches/.
188
189     my $differs = 0;
190
191     my $rundiff = sub {
192         my ($opts, $limits, $fn) = @_;
193         my @cmd = (@git, qw(diff-tree -z --no-renames));
194         push @cmd, @$opts;
195         push @cmd, "$_:" foreach $x, $y;
196         push @cmd, @$limits;
197         my $diffs = cmdoutput @cmd;
198         foreach (split /\0/, $diffs) { $fn->(); }
199     };
200
201     $rundiff->([qw(--name-only)], [], sub {
202         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
203     });
204
205     if ($differs & DS_DEB) {
206         $differs &= ~DS_DEB;
207         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
208             $differs |=
209                 m{^debian/patches/}      ? D_PAT_OTH  :
210                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
211                                            D_DEB_OTH;
212         });
213         die "mysterious debian changes $x..$y"
214             unless $differs & (D_PAT_OTH|DS_DEB);
215     }
216
217     if ($differs & D_PAT_OTH) {
218         my $mode;
219         $differs &= ~D_PAT_OTH;
220         my $pat_oth = sub {
221             $differs |= D_PAT_OTH;
222             no warnings qw(exiting);  last;
223         };
224         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
225             no warnings qw(exiting);
226             if (!defined $mode) {
227                 $mode = $_;  next;
228             }
229             die unless s{^debian/patches/}{};
230             my $ok;
231             if ($mode eq 'A' && !m/\.series$/s) {
232                 $ok = 1;
233             } elsif ($mode eq 'M' && $_ eq 'series') {
234                 my $x_s = git_cat_file "$x:debian/patches/series", 'blob';
235                 my $y_s = git_cat_file "$y:debian/patches/series", 'blob';
236                 chomp $x_s;  $x_s .= "\n";
237                 $ok = $x_s eq substr($y_s, 0, length $x_s);
238             } else {
239                 # nope
240             }
241             $mode = undef;
242             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
243         });
244         die "mysterious debian/patches changes $x..$y"
245             unless $differs & (D_PAT_ADD|D_PAT_OTH);
246     }
247
248     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
249
250     return $differs;
251 }
252
253 sub commit_pr_info ($) {
254     my ($r) = @_;
255     return Data::Dumper->dump([$r], [qw(commit)]);
256 }
257
258 sub calculate_committer_authline () {
259     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
260         'DUMMY COMMIT (git-debrebase)', "HEAD:";
261     my ($h,$m) = get_commit $c;
262     $h =~ m/^committer .*$/m or confess "($h) ?";
263     return $&;
264 }
265
266 sub rm_subdir_cached ($) {
267     my ($subdir) = @_;
268     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
269 }
270
271 sub read_tree_subdir ($$) {
272     my ($subdir, $new_tree_object) = @_;
273     rm_subdir_cached $subdir;
274     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
275 }
276
277 sub make_commit ($$) {
278     my ($parents, $message_paras) = @_;
279     my $tree = cmdoutput @git, qw(write-tree);
280     my @cmd = (@git, qw(commit-tree), $tree);
281     push @cmd, qw(-p), $_ foreach @$parents;
282     push @cmd, qw(-m), $_ foreach @$message_paras;
283     return cmdoutput @cmd;
284 }
285
286 # classify returns an info hash like this
287 #   CommitId => $objid
288 #   Hdr => # commit headers, including 1 final newline
289 #   Msg => # commit message (so one newline is dropped)
290 #   Tree => $treeobjid
291 #   Type => (see below)
292 #   Parents = [ {
293 #       Ix => $index # ie 0, 1, 2, ...
294 #       CommitId
295 #       Differs => return value from get_differs
296 #       IsOrigin
297 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
298 #     } ...]
299 #   NewMsg => # commit message, but with any [dgit import ...] edited
300 #             # to say "[was: ...]"
301 #
302 # Types:
303 #   Packaging
304 #   Changelog
305 #   Upstream
306 #   AddPatches
307 #   Mixed
308 #   Unknown
309 #
310 #   Pseudomerge
311 #     has additional entres in classification result
312 #       Overwritten = [ subset of Parents ]
313 #       Contributor = $the_remaining_Parent
314 #
315 #   DgitImportUnpatched
316 #     has additional entry in classification result
317 #       OrigParents = [ subset of Parents ]
318 #
319 #   BreakwaterUpstreamMerge
320 #     has additional entry in classification result
321 #       OrigParents = [ subset of Parents ]  # singleton list
322
323 sub parsecommit ($;$) {
324     my ($objid, $p_ref) = @_;
325     # => hash with                   CommitId Hdr Msg Tree Parents
326     #    Parents entries have only   Ix CommitId
327     #    $p_ref, if provided, must be [] and is used as a base for Parents
328
329     $p_ref //= [];
330     die if @$p_ref;
331
332     my ($h,$m) = get_commit $objid;
333
334     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
335     my (@ph) = $h =~ m/^parent (\w+)$/mg;
336
337     my $r = {
338         CommitId => $objid,
339         Hdr => $h,
340         Msg => $m,
341         Tree => $t,
342         Parents => $p_ref,
343     };
344
345     foreach my $ph (@ph) {
346         push @$p_ref, {
347             Ix => scalar @$p_ref,
348             CommitId => $ph,
349         };
350     }
351
352     return $r;
353 }    
354
355 sub classify ($) {
356     my ($objid) = @_;
357
358     my @p;
359     my $r = parsecommit($objid, \@p);
360     my $t = $r->{Tree};
361
362     foreach my $p (@p) {
363         $p->{Differs} = (get_differs $p->{CommitId}, $t),
364     }
365
366     printdebug "classify $objid \$t=$t \@p",
367         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
368         "\n";
369
370     my $classify = sub {
371         my ($type, @rest) = @_;
372         $r = { %$r, Type => $type, @rest };
373         if ($debuglevel) {
374             printdebug " = $type ".(dd $r)."\n";
375         }
376         return $r;
377     };
378     my $unknown = sub {
379         my ($why) = @_;
380         $r = { %$r, Type => qw(Unknown) };
381         printdebug " ** Unknown\n";
382         return $r;
383     };
384
385     if (@p == 1) {
386         my $d = $r->{Parents}[0]{Differs};
387         if ($d == D_PAT_ADD) {
388             return $classify->(qw(AddPatches));
389         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
390             return $unknown->("edits debian/patches");
391         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
392             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
393             if ($ty eq 'tree') {
394                 if ($d == D_DEB_CLOG) {
395                     return $classify->(qw(Changelog));
396                 } else {
397                     return $classify->(qw(Packaging));
398                 }
399             } elsif ($ty eq 'missing') {
400                 return $classify->(qw(BreakwaterStart));
401             } else {
402                 return $unknown->("parent's debian is not a directory");
403             }
404         } elsif ($d == D_UPS) {
405             return $classify->(qw(Upstream));
406         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
407             return $classify->(qw(Mixed));
408         } elsif ($d == 0) {
409             return $unknown->("no changes");
410         } else {
411             confess "internal error $objid ?";
412         }
413     }
414     if (!@p) {
415         return $unknown->("origin commit");
416     }
417
418     my @identical = grep { !$_->{Differs} } @p;
419     if (@p == 2 && @identical == 1) {
420         my @overwritten = grep { $_->{Differs} } @p;
421         confess "internal error $objid ?" unless @overwritten==1;
422         return $classify->(qw(Pseudomerge),
423                            Overwritten => $overwritten[0],
424                            Contributor => $identical[0]);
425     }
426     if (@p == 2 && @identical == 2) {
427         my @bytime = nsort_by {
428             my ($ph,$pm) = get_commit $_->{CommitId};
429             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
430             $1;
431         } @p;
432         return $classify->(qw(Pseudomerge),
433                            SubType => qw(Ambiguous),
434                            Overwritten => $bytime[0],
435                            Contributor => $bytime[1]);
436     }
437     foreach my $p (@p) {
438         my ($p_h, $p_m) = get_commit $p->{CommitId};
439         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
440         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
441     }
442     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
443     my $m2 = $r->{Msg};
444     if (!(grep { !$_->{IsOrigin} } @p) and
445         (@orig_ps >= @p - 1) and
446         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
447         $r->{NewMsg} = $m2;
448         return $classify->(qw(DgitImportUnpatched),
449                            OrigParents => \@orig_ps);
450     }
451
452     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
453     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
454
455     # How to decide about l/r ordering of breakwater merges ?  git
456     # --topo-order prefers to expand 2nd parent first.  There's
457     # already an easy rune to look for debian/ history anyway (git log
458     # debian/) so debian breakwater branch should be 1st parent; that
459     # way also there's also an easy rune to look for the upstream
460     # patches (--topo-order).
461
462     # The above tells us which way *we* will generate them.  But we
463     # might encounter ad-hoc breakwater merges generated manually,
464     # which might be the other way around.  In principle, in some odd
465     # situations, a breakwater merge might have two identical parents.
466     # In that case we guess which way round it is (ie, which parent
467     # has the upstream history).  The order of the 2-iteration loop
468     # controls which guess we make.
469
470     foreach my $prevbrw (qw(0 1)) {
471         if (@p == 2 &&
472             !$haspatches &&
473             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
474             !($p[!$prevbrw]{Differs} & ~DS_DEB) && # no non-debian changess
475             !($p[$prevbrw]{Differs} & ~D_UPS)) { # no non-upstream changes
476             return $classify->(qw(BreakwaterUpstreamMerge),
477                                OrigParents => [ $p[!$prevbrw] ]);
478         }
479     }
480
481     # multi-orig upstreams are represented with a breakwater merge
482     # from a single upstream commit which combines the orig tarballs
483
484     return $unknown->("complex merge");
485 }
486
487 sub walk ($;$$);
488 sub walk ($;$$) {
489     my ($input,
490         $nogenerate,$report) = @_;
491     # => ($tip, $breakwater_tip, $last_upstream_merge_in_breakwater)
492     # (or nothing, if $nogenerate)
493
494     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
495
496     # go through commits backwards
497     # we generate two lists of commits to apply:
498     # breakwater branch and upstream patches
499     my (@brw_cl, @upp_cl, @processed);
500     my %found;
501     my $upp_limit;
502     my @pseudomerges;
503
504     my $cl;
505     my $xmsg = sub {
506         my ($appendinfo) = @_;
507         my $ms = $cl->{Msg};
508         chomp $ms;
509         $ms .= "\n\n[git-debrebase $appendinfo]\n";
510         return (Msg => $ms);
511     };
512     my $rewrite_from_here = sub {
513         my $sp_cl = { SpecialMethod => 'StartRewrite' };
514         push @brw_cl, $sp_cl;
515         push @processed, $sp_cl;
516     };
517     my $cur = $input;
518
519     my $prdelim = "";
520     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
521
522     my $prline = sub {
523         return unless $report;
524         print $report $prdelim, @_;
525         $prdelim = "\n";
526     };
527
528     my $bomb = sub { # usage: return $bomb->();
529         print $report " Unprocessable" if $report;
530         $prprdelim->();
531         if ($nogenerate) {
532             return (undef,undef);
533         }
534         die "commit $cur: Cannot cope with this commit (d.".
535             (join ' ', map { sprintf "%#x", $_->{Differs} }
536              @{ $cl->{Parents} }). ")";
537     };
538
539     my $build;
540     my $breakwater;
541
542     my $build_start = sub {
543         my ($msg, $parent) = @_;
544         $prline->(" $msg");
545         $build = $parent;
546         no warnings qw(exiting); last;
547     };
548
549     my $last_upstream_update;
550
551     for (;;) {
552         $cl = classify $cur;
553         my $ty = $cl->{Type};
554         my $st = $cl->{SubType};
555         $prline->("$cl->{CommitId} $cl->{Type}");
556         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
557         push @processed, $cl;
558         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
559         if ($ty eq 'AddPatches') {
560             $cur = $p0;
561             $rewrite_from_here->();
562             next;
563         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
564             push @brw_cl, $cl;
565             $cur = $p0;
566             next;
567         } elsif ($ty eq 'BreakwaterStart') {
568             $last_upstream_update = $cur;
569             $build_start->('FirstPackaging', $cur);
570         } elsif ($ty eq 'Upstream') {
571             push @upp_cl, $cl;
572             $cur = $p0;
573             next;
574         } elsif ($ty eq 'Mixed') {
575             my $queue = sub {
576                 my ($q, $wh) = @_;
577                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
578                 push @$q, $cls;
579             };
580             $queue->(\@brw_cl, "debian");
581             $queue->(\@upp_cl, "upstream");
582             $rewrite_from_here->();
583             $cur = $p0;
584             next;
585         } elsif ($ty eq 'Pseudomerge') {
586             my $contrib = $cl->{Contributor}{CommitId};
587             print $report " Contributor=$contrib" if $report;
588             push @pseudomerges, $cl;
589             $rewrite_from_here->();
590             $cur = $contrib;
591             next;
592         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
593             $last_upstream_update = $cur;
594             $build_start->("PreviousBreakwater", $cur);
595         } elsif ($ty eq 'DgitImportUnpatched') {
596             my $pm = $pseudomerges[-1];
597             if (defined $pm) {
598                 # To an extent, this is heuristic.  Imports don't have
599                 # a useful history of the debian/ branch.  We assume
600                 # that the first pseudomerge after an import has a
601                 # useful history of debian/, and ignore the histories
602                 # from later pseudomerges.  Often the first pseudomerge
603                 # will be the dgit import of the upload to the actual
604                 # suite intended by the non-dgit NMUer, and later
605                 # pseudomerges may represent in-archive copies.
606                 my $ovwrs = $pm->{Overwritten};
607                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
608                     if $report;
609                 if (@$ovwrs != 1) {
610                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
611                     return $bomb->();
612                 }
613                 my $ovwr = $ovwrs->[0]{CommitId};
614                 printf $report " Overwr=%s", $ovwr if $report;
615                 # This import has a tree which is just like a
616                 # breakwater tree, but it has the wrong history.  It
617                 # ought to have the previous breakwater (which the
618                 # pseudomerge overwrote) as an ancestor.  That will
619                 # make the history of the debian/ files correct.  As
620                 # for the upstream version: either it's the same as
621                 # was ovewritten (ie, same as the previous
622                 # breakwater), in which case that history is precisely
623                 # right; or, otherwise, it was a non-gitish upload of a
624                 # new upstream version.  We can tell these apart by
625                 # looking at the tree of the supposed upstream.
626                 push @brw_cl, {
627                     %$cl,
628                     SpecialMethod => 'DgitImportDebianUpdate',
629                     $xmsg->("convert dgit import: debian changes")
630                 };
631                 my $differs = (get_differs $ovwr, $cl->{Tree});
632                 printf $report " Differs=%#x", $differs if $report;
633                 if ($differs & D_UPS) {
634                     printf $report " D_UPS" if $report;
635                     # This will also trigger if a non-dgit git-based NMU
636                     # deleted .gitignore (which is a thing that some of
637                     # the existing git tools do if the user doesn't
638                     # somehow tell them not to).  Ah well.
639                     push @brw_cl, {
640                         %$cl,
641                         SpecialMethod => 'DgitImportUpstreamUpdate',
642                         $xmsg->("convert dgit import: upstream changes")
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     my $symref = git_get_symref();
785     runcmd @git, qw(checkout), $new, qw(.);
786     update_head $old, $new, $mrest;
787 }
788
789 sub update_head_postlaunder ($$$) {
790     my ($old, $tip, $reflogmsg) = @_;
791     update_head $old, $tip, $reflogmsg;
792     # no tree changes except debian/patches
793     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
794 }
795
796 sub cmd_launder () {
797     badusage "no arguments to launder allowed" if @ARGV;
798     my $old = get_head();
799     my ($tip,$breakwater,$last_upstream_merge) = walk $old;
800     update_head_postlaunder $old, $tip, 'launder';
801     printf "# breakwater tip\n%s\n", $breakwater;
802     printf "# working tip\n%s\n", $tip;
803     printf "# last upstream merge\n%s\n", $last_upstream_merge;
804 }
805
806 sub cmd_analyse () {
807     die if ($ARGV[0]//'') =~ m/^-/;
808     badusage "too many arguments to analyse" if @ARGV>1;
809     my ($old) = @ARGV;
810     if (defined $old) {
811         $old = git_rev_parse $old;
812     } else {
813         $old = get_head();
814     }
815     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
816     STDOUT->error and die $!;
817 }
818
819 sub cmd_new_upstream_v0 () {
820     # tree should be clean and this is not checked
821     # automatically and unconditionally launders before rebasing
822     # if rebase --abort is used, laundering has still been done
823
824     my %pieces;
825
826     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
827
828     # parse args - low commitment
829     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
830     my $new_upstream_version = $new_version->version();
831
832     my $new_upstream = git_rev_parse shift @ARGV;
833
834     my $piece = sub {
835         my ($n, @x) = @_; # may be ''
836         my $pc = $pieces{$n} //= {
837             Name => $n,
838             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
839         };
840         while (my $k = shift @x) { $pc->{$k} = shift @x; }
841         $pc;
842     };
843
844     my @newpieces;
845     my $newpiece = sub {
846         my ($n, @x) = @_; # may be ''
847         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
848         push @newpieces, $pc;
849     };
850
851     $newpiece->('',
852         OldIx => 0,
853         New => $new_upstream,
854     );
855     while (@ARGV && $ARGV[0] !~ m{^-}) {
856         my $n = shift @ARGV;
857
858         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
859             unless @ARGV && $ARGV[0] !~ m{^-};
860
861         my $c = git_rev_parse shift @ARGV;
862         die unless $n =~ m/^$extra_orig_namepart_re$/;
863         $newpiece->($n, New => $c);
864     }
865
866     # now we need to investigate the branch this generates the
867     # laundered version but we don't switch to it yet
868     my $old_head = get_head();
869     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
870
871     my $old_bw_cl = classify $old_bw;
872     my $old_upstream_update_cl = classify $old_upstream_update;
873     confess unless $old_upstream_update_cl->{OrigParents};
874     my $old_upstream = parsecommit
875         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
876
877     my $problems = 0;
878     my $problem = sub {
879         my ($msg) = @_;
880         $problems++;
881         print STDERR "preflight check failed: $msg\n";
882     };
883
884     $piece->('', Old => $old_upstream->{CommitId});
885
886     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
887         if ($old_upstream->{Msg} =~
888  m{^\[git-debrebase new-upstream combine \.((?: $extra_orig_namepart_re)+)\]}
889            ) {
890             my @oldpieces = ('', split / /, $1);
891             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
892             foreach my $i (0..$#oldpieces) {
893                 my $n = $oldpieces[$i];
894                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
895             }
896         } else {
897             $problem->("previous upstream $old_upstream->{CommitId} is from".
898                  " git-debrebase but not a \`new-upstream combine' commit");
899         }
900     }
901
902     foreach my $pc (values %pieces) {
903         if (!$pc->{Old}) {
904             $problem->("introducing upstream piece \`$pc->{Name}'");
905         } elsif (!$pc->{New}) {
906             $problem->("dropping upstream piece \`$pc->{Name}'");
907         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
908             $problem->("not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}");
909         }
910     }
911
912     printdebug "%pieces = ", (dd \%pieces), "\n";
913     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
914
915     if ($problems) {
916         if ($opt_force) {
917             printf STDERR
918                 "preflight check failures (%d) overriden by --force\n",
919                 $problems;
920         } else {
921             fail sprintf
922                 "preflight check failures (%d) (you could --force)",
923                 $problems;
924         }
925     }
926
927     my $new_bw;
928
929     fresh_workarea();
930     in_workarea sub {
931         my @upstream_merge_parents;
932
933         if (!$problems) {
934             push @upstream_merge_parents, $old_upstream->{CommitId};
935         }
936
937         foreach my $pc (@newpieces) { # always has '' first
938             if ($pc->{Name}) {
939                 read_tree_subdir $pc->{Name}, $pc->{New};
940             } else {
941                 runcmd @git, qw(read-tree), $pc->{New};
942             }
943             push @upstream_merge_parents, $pc->{New};
944         }
945
946         # index now contains the new upstream
947
948         if (@newpieces > 1) {
949             # need to make the upstream subtree merge commit
950             $new_upstream = make_commit \@upstream_merge_parents,
951                 [ "Combine upstreams for $new_upstream_version",
952                   ("[git-debrebase new-upstream combine . ".
953                    (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
954                    "]"),
955                 ];
956         }
957
958         # $new_upstream is either the single upstream commit, or the
959         # combined commit we just made.  Either way it will be the
960         # "upstream" parent of the breakwater special merge.
961
962         read_tree_subdir 'debian', "$old_bw:debian";
963
964         # index now contains the breakwater merge contents
965         $new_bw = make_commit [ $old_bw, $new_upstream ],
966             [ "Update to upstream $new_upstream_version",
967               "[git-debrebase new-upstream breakwater $new_upstream_version]",
968             ];
969
970         # Now we have to add a changelog stanza so the Debian version
971         # is right.
972         die if unlink "debian";
973         die $! unless $!==ENOENT or $!==ENOTEMPTY;
974         unlink "debian/changelog" or $!==ENOENT or die $!;
975         mkdir "debian" or die $!;
976         open CN, ">", "debian/changelog" or die $!;
977         my $oldclog = git_cat_file ":debian/changelog";
978         $oldclog =~ m/^($package_re) \(\S+\) / or
979             fail "cannot parse old changelog to get package name";
980         my $p = $1;
981         print CN <<END, $oldclog or die $!;
982 $p ($new_version) UNRELEASED; urgency=medium
983
984   * Update to new upstream version $new_upstream_version.
985
986  -- 
987
988 END
989         close CN or die $!;
990         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
991
992         # Now we have the final new breakwater branch in the index
993         $new_bw = make_commit [ $new_bw ],
994             [ "Update changelog for new upstream $new_upstream_version",
995               "[git-debrebase new-upstream changelog $new_upstream_version]",
996             ];
997     };
998
999     # we have constructed the new breakwater. we now need to commit to
1000     # the laundering output, because git-rebase can't easily be made
1001     # to make a replay list which is based on some other branch
1002
1003     update_head_postlaunder $old_head, $old_laundered_tip,
1004         'launder for new upstream';
1005
1006     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1007     runcmd @cmd;
1008     # now it's for the user to sort out
1009 }
1010
1011 sub cmd_downstream_rebase_launder_v0 () {
1012     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1013     my ($base) = @ARGV;
1014     $base = git_rev_parse $base;
1015     my $old_head = get_head();
1016     my $current = $old_head;
1017     my $topmost_keep;
1018     for (;;) {
1019         if ($current eq $base) {
1020             $topmost_keep //= $current;
1021             print " $current BASE stop\n";
1022             last;
1023         }
1024         my $cl = classify $current;
1025         print " $current $cl->{Type}";
1026         my $keep = 0;
1027         my $p0 = $cl->{Parents}[0]{CommitId};
1028         my $next;
1029         if ($cl->{Type} eq 'Pseudomerge') {
1030             print " ^".($cl->{Contributor}{Ix}+1);
1031             $next = $cl->{Contributor}{CommitId};
1032         } elsif ($cl->{Type} eq 'AddPatches' or
1033                  $cl->{Type} eq 'Changelog') {
1034             print " strip";
1035             $next = $p0;
1036         } else {
1037             print " keep";
1038             $next = $p0;
1039             $keep = 1;
1040         }
1041         print "\n";
1042         if ($keep) {
1043             $topmost_keep //= $current;
1044         } else {
1045             die "to-be stripped changes not on top of the branch\n"
1046                 if $topmost_keep;
1047         }
1048         $current = $next;
1049     }
1050     if ($topmost_keep eq $old_head) {
1051         print "unchanged\n";
1052     } else {
1053         print "updating to $topmost_keep\n";
1054         update_head_checkout
1055             $old_head, $topmost_keep,
1056             'downstream-rebase-launder-v0';
1057     }
1058 }
1059
1060 GetOptions("D+" => \$debuglevel,
1061            'force!') or die badusage "bad options\n";
1062 initdebug('git-debrebase ');
1063 enabledebug if $debuglevel;
1064
1065 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1066 chdir $toplevel or die "chdir $toplevel: $!";
1067
1068 $rd = fresh_playground "$playprefix/misc";
1069
1070 my $cmd = shift @ARGV;
1071 my $cmdfn = $cmd;
1072 $cmdfn =~ y/-/_/;
1073 $cmdfn = ${*::}{"cmd_$cmdfn"};
1074
1075 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1076 $cmdfn->();