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