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