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