chiark / gitweb /
git-debrebase: wip cmd_record_ffq_prev
[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 record_ffq_prev () {
848     # => ('status', "message")
849     # 'status' may be
850     #    written          message is undef
851     #    exists
852     #    detached
853     #    weird-symref
854     #    notbranch
855     # if not ff from some branch we should be ff from, is an fproblem
856     # if "written", will have printed something about that to stdout,
857     #   and also some messages about ff checks
858     my $current = git_get_symref();
859     return ('detached', 'detached HEAD') unless defined $current;
860     return ('weird-symref', 'HEAD symref is not to refs/')
861         unless $current =~ m{^refs/};
862     my $ffq_prev = "refs/$ffq_refprefix/$'";
863
864     my $currentval = get_head();
865
866     my $exists = git_get_ref $ffq_prev;
867     return ('exists',"$ffq_prev already exists") if defined $exists;
868
869     return ('not-branch', 'HEAD symref is not to refs/heads/')
870         unless $current =~ m{^refs/heads/};
871     my $branch = $';
872
873     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs") // '*';
874     my %checked;
875
876     my $check = sub {
877         my ($lrref, $desc) = @_;
878         my $invert;
879         for my $chk (@check_specs) {
880             my $glob = $chk;
881             $invert = $glob =~ s{^[^!]}{};
882             last if fnmatch $glob, $lrref;
883         }
884         return if $invert;
885         my $lrval = git_get_ref $lrref;
886         return unless defined $lrval;
887
888         if (is_fast_fwd $lrval, $currentval) {
889             print "OK, you are ahead of $lrref\n" or die $!;
890             $checked{$lrref} = 1;
891         } if (is_fast_fwd $currentval, $lrval) {
892             $checked{$lrref} = -1;
893             fproblem 'behind', "you are behind $lrref, divergence risk";
894         } else {
895             $checked{$lrref} = -1;
896             fproblem 'diverged', "you have diverged from $lrref";
897         }
898     };
899
900     my $merge = cfg "branch.$branch.merge";
901     if (defined $merge && $merge =~ m{^refs/heads/}) {
902         my $rhs = $';
903         my $check_remote = sub {
904             my ($remote, $desc) = (@_);
905             return unless defined $remote;
906             $check->("refs/remotes/$remote/$rhs", $desc);
907         };
908         $check_remote->((cfg "branch.$branch.remote"),
909                         'remote fetch/merge branch');
910         $check_remote->((cfg "branch.$branch.pushRemote") //
911                         (cfg "branch.$branch.pushDefault"),
912                         'remote push branch');
913     }
914     if ($branch =~ m{^dgit/}) {
915         $check->("remotes/dgit/$branch", 'remote dgit branch');
916     }
917
918     fproblems_maybe_fail();
919     runcmd @git, qw(update-ref -m), "record current head for preservation",
920         $ffq_prev, $currentval, $git_null_obj;
921     print "Recorded current head for preservation\n" or die $!;
922     return ('written', undef);
923 }
924
925 sub cmd_new_upstream_v0 () {
926     # tree should be clean and this is not checked
927     # automatically and unconditionally launders before rebasing
928     # if rebase --abort is used, laundering has still been done
929
930     my %pieces;
931
932     badusage "need NEW-VERSION UPS-COMMITTISH" unless @ARGV >= 2;
933
934     # parse args - low commitment
935     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
936     my $new_upstream_version = $new_version->version();
937
938     my $new_upstream = git_rev_parse shift @ARGV;
939
940     my $piece = sub {
941         my ($n, @x) = @_; # may be ''
942         my $pc = $pieces{$n} //= {
943             Name => $n,
944             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
945         };
946         while (my $k = shift @x) { $pc->{$k} = shift @x; }
947         $pc;
948     };
949
950     my @newpieces;
951     my $newpiece = sub {
952         my ($n, @x) = @_; # may be ''
953         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
954         push @newpieces, $pc;
955     };
956
957     $newpiece->('',
958         OldIx => 0,
959         New => $new_upstream,
960     );
961     while (@ARGV && $ARGV[0] !~ m{^-}) {
962         my $n = shift @ARGV;
963
964         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
965             unless @ARGV && $ARGV[0] !~ m{^-};
966
967         my $c = git_rev_parse shift @ARGV;
968         die unless $n =~ m/^$extra_orig_namepart_re$/;
969         $newpiece->($n, New => $c);
970     }
971
972     # now we need to investigate the branch this generates the
973     # laundered version but we don't switch to it yet
974     my $old_head = get_head();
975     my ($old_laundered_tip,$old_bw,$old_upstream_update) = walk $old_head;
976
977     my $old_bw_cl = classify $old_bw;
978     my $old_upstream_update_cl = classify $old_upstream_update;
979     confess unless $old_upstream_update_cl->{OrigParents};
980     my $old_upstream = parsecommit
981         $old_upstream_update_cl->{OrigParents}[0]{CommitId};
982
983     $piece->('', Old => $old_upstream->{CommitId});
984
985     if ($old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
986         if ($old_upstream->{Msg} =~
987  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
988            ) {
989             my @oldpieces = ('', split / /, $1);
990             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
991             foreach my $i (0..$#oldpieces) {
992                 my $n = $oldpieces[$i];
993                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
994             }
995         } else {
996             fproblem 'upstream-confusing',
997                 "previous upstream $old_upstream->{CommitId} is from".
998                " git-debrebase but not an \`upstream-combine' commit";
999         }
1000     }
1001
1002     foreach my $pc (values %pieces) {
1003         if (!$pc->{Old}) {
1004             fproblem 'upstream-new-piece',
1005                 "introducing upstream piece \`$pc->{Name}'";
1006         } elsif (!$pc->{New}) {
1007             fproblem 'upstream-rm-piece',
1008                 "dropping upstream piece \`$pc->{Name}'";
1009         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1010             fproblem 'upstream-not-ff',
1011                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1012         }
1013     }
1014
1015     printdebug "%pieces = ", (dd \%pieces), "\n";
1016     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1017
1018     fproblems_maybe_bail();
1019
1020     my $new_bw;
1021
1022     fresh_workarea();
1023     in_workarea sub {
1024         my @upstream_merge_parents;
1025
1026         if (!any_fproblems()) {
1027             push @upstream_merge_parents, $old_upstream->{CommitId};
1028         }
1029
1030         foreach my $pc (@newpieces) { # always has '' first
1031             if ($pc->{Name}) {
1032                 read_tree_subdir $pc->{Name}, $pc->{New};
1033             } else {
1034                 runcmd @git, qw(read-tree), $pc->{New};
1035             }
1036             push @upstream_merge_parents, $pc->{New};
1037         }
1038
1039         # index now contains the new upstream
1040
1041         if (@newpieces > 1) {
1042             # need to make the upstream subtree merge commit
1043             $new_upstream = make_commit \@upstream_merge_parents,
1044                 [ "Combine upstreams for $new_upstream_version",
1045  ("[git-debrebase upstream-combine . ".
1046  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1047  ": new upstream]"),
1048                 ];
1049         }
1050
1051         # $new_upstream is either the single upstream commit, or the
1052         # combined commit we just made.  Either way it will be the
1053         # "upstream" parent of the breakwater special merge.
1054
1055         read_tree_subdir 'debian', "$old_bw:debian";
1056
1057         # index now contains the breakwater merge contents
1058         $new_bw = make_commit [ $old_bw, $new_upstream ],
1059             [ "Update to upstream $new_upstream_version",
1060  "[git-debrebase breakwater: new upstream $new_upstream_version, merge]",
1061             ];
1062
1063         # Now we have to add a changelog stanza so the Debian version
1064         # is right.
1065         die if unlink "debian";
1066         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1067         unlink "debian/changelog" or $!==ENOENT or die $!;
1068         mkdir "debian" or die $!;
1069         open CN, ">", "debian/changelog" or die $!;
1070         my $oldclog = git_cat_file ":debian/changelog";
1071         $oldclog =~ m/^($package_re) \(\S+\) / or
1072             fail "cannot parse old changelog to get package name";
1073         my $p = $1;
1074         print CN <<END, $oldclog or die $!;
1075 $p ($new_version) UNRELEASED; urgency=medium
1076
1077   * Update to new upstream version $new_upstream_version.
1078
1079  -- 
1080
1081 END
1082         close CN or die $!;
1083         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1084
1085         # Now we have the final new breakwater branch in the index
1086         $new_bw = make_commit [ $new_bw ],
1087             [ "Update changelog for new upstream $new_upstream_version",
1088               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1089             ];
1090     };
1091
1092     # we have constructed the new breakwater. we now need to commit to
1093     # the laundering output, because git-rebase can't easily be made
1094     # to make a replay list which is based on some other branch
1095
1096     update_head_postlaunder $old_head, $old_laundered_tip,
1097         'launder for new upstream';
1098
1099     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1100     runcmd @cmd;
1101     # now it's for the user to sort out
1102 }
1103
1104 sub cmd_record_ffq_prev () {
1105     badusage "no arguments allowed" if @ARGV;
1106     my ($status, $msg) = record_ffq_prev();
1107     if ($status eq 'exists' && $opt_noop_ok) {
1108         print "Previous head already recorded\n" or die $!;
1109     } elsif ($status eq 'written') {
1110     } else {
1111         fail "Could not preserve: $msg";
1112     }
1113 }
1114
1115 sub cmd_gbp2debrebase () {
1116     badusage "needs 1 optional argument, the upstream" unless @ARGV<=1;
1117     my ($upstream_spec) = @ARGV;
1118     $upstream_spec //= 'refs/heads/upstream';
1119     my $upstream = git_rev_parse $upstream_spec;
1120     my $old_head = get_head();
1121
1122     my $upsdiff = get_differs $upstream, $old_head;
1123     if ($upsdiff & D_UPS) {
1124         runcmd @git, qw(--no-pager diff),
1125             $upstream, $old_head,
1126             qw( -- :!/debian :/);
1127  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1128     }
1129
1130     if (!is_fast_fwd $upstream, $old_head) {
1131         fproblem 'upstream-not-ancestor',
1132             "upstream ($upstream) is not an ancestor of HEAD";
1133     } else {
1134         my $wrong = cmdoutput
1135             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1136              qw(-- :/ :!/debian));
1137         if (length $wrong) {
1138             fproblem 'unexpected-upstream-changes',
1139                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1140             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1141         }
1142     }
1143
1144     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1145         fproblem 'upstream-has-debian',
1146             "upstream ($upstream) contains debian/ directory";
1147     }
1148
1149     fproblems_maybe_bail();
1150
1151     my $work;
1152
1153     fresh_workarea();
1154     in_workarea sub {
1155         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1156         # make a branch out of the patch queue - we'll want this in a mo
1157         runcmd qw(gbp pq import);
1158         # strip the patches out
1159         runcmd @git, qw(checkout -q gdr-internal~0);
1160         rm_subdir_cached 'debian/patches';
1161         $work = make_commit ['HEAD'], [
1162  'git-debrebase import: drop patch queue',
1163  'Delete debian/patches, as part of converting to git-debrebase format.',
1164  '[git-debrebase: gbp2debrebase, drop patches]'
1165                               ];
1166         # make the breakwater pseudomerge
1167         # the tree is already exactly right
1168         $work = make_commit [$work, $upstream], [
1169  'git-debrebase import: declare upstream',
1170  'First breakwater merge.',
1171  '[git-debrebase breakwater: declare upstream]'
1172                               ];
1173
1174         # rebase the patch queue onto the new breakwater
1175         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1176         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1177         $work = get_head();
1178     };
1179
1180     update_head_checkout $old_head, $work, 'gbp2debrebase';
1181 }
1182
1183 sub cmd_downstream_rebase_launder_v0 () {
1184     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1185     my ($base) = @ARGV;
1186     $base = git_rev_parse $base;
1187     my $old_head = get_head();
1188     my $current = $old_head;
1189     my $topmost_keep;
1190     for (;;) {
1191         if ($current eq $base) {
1192             $topmost_keep //= $current;
1193             print " $current BASE stop\n";
1194             last;
1195         }
1196         my $cl = classify $current;
1197         print " $current $cl->{Type}";
1198         my $keep = 0;
1199         my $p0 = $cl->{Parents}[0]{CommitId};
1200         my $next;
1201         if ($cl->{Type} eq 'Pseudomerge') {
1202             print " ^".($cl->{Contributor}{Ix}+1);
1203             $next = $cl->{Contributor}{CommitId};
1204         } elsif ($cl->{Type} eq 'AddPatches' or
1205                  $cl->{Type} eq 'Changelog') {
1206             print " strip";
1207             $next = $p0;
1208         } else {
1209             print " keep";
1210             $next = $p0;
1211             $keep = 1;
1212         }
1213         print "\n";
1214         if ($keep) {
1215             $topmost_keep //= $current;
1216         } else {
1217             die "to-be stripped changes not on top of the branch\n"
1218                 if $topmost_keep;
1219         }
1220         $current = $next;
1221     }
1222     if ($topmost_keep eq $old_head) {
1223         print "unchanged\n";
1224     } else {
1225         print "updating to $topmost_keep\n";
1226         update_head_checkout
1227             $old_head, $topmost_keep,
1228             'downstream-rebase-launder-v0';
1229     }
1230 }
1231
1232 GetOptions("D+" => \$debuglevel,
1233            'noop-ok', => \$opt_noop_ok,
1234            'f=s' => \@fproblem_force_opts,
1235            'force!') or die badusage "bad options\n";
1236 initdebug('git-debrebase ');
1237 enabledebug if $debuglevel;
1238
1239 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1240 chdir $toplevel or die "chdir $toplevel: $!";
1241
1242 $rd = fresh_playground "$playprefix/misc";
1243
1244 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1245     defaultcmd_rebase();
1246 } else {
1247     my $cmd = shift @ARGV;
1248     my $cmdfn = $cmd;
1249     $cmdfn =~ y/-/_/;
1250     $cmdfn = ${*::}{"cmd_$cmdfn"};
1251
1252     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1253     $cmdfn->();
1254 }