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