chiark / gitweb /
git-debrebase(5): Document commit message annotations
[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>] breakwater      # prints breakwater tip only
32 #    git-debrebase [<options>] stitch [--prose=<for commit message>]
33 #    git-debrebase [<options>] launder-v0      # prints breakwater tip etc.
34 #    git-debrebase [<options>] downstream-rebase-launder-v0  # experimental
35 #
36 #    git-debrebase [<options>] convert-from-gbp [<upstream-git-rev>]
37 #    git-debrebase [<options>] convert-to-gbp
38
39 # problems / outstanding questions:
40 #
41 #  *  dgit push with a `3.0 (quilt)' package means doing quilt
42 #     fixup.  Usually this involves recommitting the whole patch
43 #     series, one at a time, with dpkg-source --commit.  This is
44 #     terribly terribly slow.  (Maybe this should be fixed in dgit.)
45 #
46 #  * dgit push usually needs to (re)make a pseudomerge.  The "first"
47 #    git-debrebase stripped out the previous pseudomerge and could
48 #    have remembeed the HEAD.  But it's not quite clear what history
49 #    ought to be preserved and what should be discarded.  For now
50 #    the user will have to tell dgit --overwrite.
51 #
52 #    To fix this, do we need a new push hook for dgit ?
53 #
54 #  * Workflow is currently clumsy.  Lots of spurious runes to type.
55 #    There's not even a guide.
56 #
57 #  * There are no tests.
58 #
59 #  * new-upstream-v0 has a terrible UI.  You end up with giant
60 #    runic command lines.
61 #
62 #    One consequence of the lack of richness it can need --force in
63 #    fairly sensible situations and there is no way to tell it what
64 #    you are really trying to do, other than just --force.  There
65 #    should be an interface with some default branch names.
66 #
67 #  * There should be a standard convention for the version number,
68 #    and unfinalised or not changelog, after new-upstream.
69 #
70 #  * Handing of multi-orig dgit new-upstream .dsc imports is known to
71 #    be broken.  They may be not recognised, improperly converted, or
72 #    their conversion may be unrecognised.
73 #
74 #  * Docs need writing and updating.  Even README.git-debrebase
75 #    describes a design but may not reflect the implementation.
76 #
77 #  * We need to develop a plausible model that works for derivatives,
78 #    who probably want to maintain their stack on top of Debian's.
79 #    downstream-rebase-launder-v0 may be a starting point?
80
81 use strict;
82
83 use Debian::Dgit qw(:DEFAULT :playground);
84 setup_sigwarn();
85
86 use Memoize;
87 use Carp;
88 use POSIX;
89 use Data::Dumper;
90 use Getopt::Long qw(:config posix_default gnu_compat bundling);
91 use Dpkg::Version;
92 use File::FnMatch qw(:fnmatch);
93
94 our ($opt_force, $opt_noop_ok, @opt_anchors);
95
96 our $us = qw(git-debrebase);
97
98 sub badusage ($) {
99     my ($m) = @_;
100     die "bad usage: $m\n";
101 }
102
103 sub cfg ($;$) {
104     my ($k, $optional) = @_;
105     local $/ = "\0";
106     my @cmd = qw(git config -z);
107     push @cmd, qw(--get-all) if wantarray;
108     push @cmd, $k;
109     my $out = cmdoutput_errok @cmd;
110     if (!defined $out) {
111         fail "missing required git config $k" unless $optional;
112         return ();
113     }
114     my @l = split /\0/, $out;
115     return wantarray ? @l : $l[0];
116 }
117
118 memoize('cfg');
119
120 sub dd ($) {
121     my ($v) = @_;
122     my $dd = new Data::Dumper [ $v ];
123     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
124     return Dump $dd;
125 }
126
127 sub get_commit ($) {
128     my ($objid) = @_;
129     my $data = (git_cat_file $objid, 'commit');
130     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
131     return ($`,$');
132 }
133
134 sub D_UPS ()      { 0x02; } # upstream files
135 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
136 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
137 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
138 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
139 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
140
141 our $playprefix = 'debrebase';
142 our $rd;
143 our $workarea;
144
145 our @git = qw(git);
146
147 sub in_workarea ($) {
148     my ($sub) = @_;
149     changedir $workarea;
150     my $r = eval { $sub->(); };
151     { local $@; changedir $maindir; }
152     die $@ if $@;
153 }
154
155 sub fresh_workarea () {
156     $workarea = fresh_playground "$playprefix/work";
157     in_workarea sub { playtree_setup };
158 }
159
160 our @deferred_updates;
161 our @deferred_update_messages;
162
163 sub run_deferred_updates ($) {
164     my ($mrest) = @_;
165
166     my @upd_cmd = (@git, qw(update-ref --stdin -m), "debrebase: $mrest");
167     debugcmd '>|', @upd_cmd;
168     open U, "|-", @upd_cmd or die $!;
169     foreach (@deferred_updates) {
170         printdebug ">= ", $_, "\n";
171         print U $_, "\n" or die $!;
172     }
173     printdebug ">\$\n";
174     close U or failedcmd @upd_cmd;
175
176     print $_, "\n" foreach @deferred_update_messages;
177
178     @deferred_updates = ();
179     @deferred_update_messages = ();
180 }
181
182 sub get_differs ($$) {
183     my ($x,$y) = @_;
184     # This resembles quiltify_trees_differ, in dgit, a bit.
185     # But we don't care about modes, or dpkg-source-unrepresentable
186     # changes, and we don't need the plethora of different modes.
187     # Conversely we need to distinguish different kinds of changes to
188     # debian/ and debian/patches/.
189
190     my $differs = 0;
191
192     my $rundiff = sub {
193         my ($opts, $limits, $fn) = @_;
194         my @cmd = (@git, qw(diff-tree -z --no-renames));
195         push @cmd, @$opts;
196         push @cmd, "$_:" foreach $x, $y;
197         push @cmd, '--', @$limits;
198         my $diffs = cmdoutput @cmd;
199         foreach (split /\0/, $diffs) { $fn->(); }
200     };
201
202     $rundiff->([qw(--name-only)], [], sub {
203         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
204     });
205
206     if ($differs & DS_DEB) {
207         $differs &= ~DS_DEB;
208         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
209             $differs |=
210                 m{^debian/patches/}      ? D_PAT_OTH  :
211                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
212                                            D_DEB_OTH;
213         });
214         die "mysterious debian changes $x..$y"
215             unless $differs & (D_PAT_OTH|DS_DEB);
216     }
217
218     if ($differs & D_PAT_OTH) {
219         my $mode;
220         $differs &= ~D_PAT_OTH;
221         my $pat_oth = sub {
222             $differs |= D_PAT_OTH;
223             no warnings qw(exiting);  last;
224         };
225         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
226             no warnings qw(exiting);
227             if (!defined $mode) {
228                 $mode = $_;  next;
229             }
230             die unless s{^debian/patches/}{};
231             my $ok;
232             if ($mode eq 'A' && !m/\.series$/s) {
233                 $ok = 1;
234             } elsif ($mode eq 'M' && $_ eq 'series') {
235                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
236                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
237                 chomp $x_s;  $x_s .= "\n";
238                 $ok = $x_s eq substr($y_s, 0, length $x_s);
239             } else {
240                 # nope
241             }
242             $mode = undef;
243             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
244         });
245         die "mysterious debian/patches changes $x..$y"
246             unless $differs & (D_PAT_ADD|D_PAT_OTH);
247     }
248
249     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
250
251     return $differs;
252 }
253
254 sub commit_pr_info ($) {
255     my ($r) = @_;
256     return Data::Dumper->dump([$r], [qw(commit)]);
257 }
258
259 sub calculate_committer_authline () {
260     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
261         'DUMMY COMMIT (git-debrebase)', "HEAD:";
262     my ($h,$m) = get_commit $c;
263     $h =~ m/^committer .*$/m or confess "($h) ?";
264     return $&;
265 }
266
267 sub rm_subdir_cached ($) {
268     my ($subdir) = @_;
269     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
270 }
271
272 sub read_tree_subdir ($$) {
273     my ($subdir, $new_tree_object) = @_;
274     rm_subdir_cached $subdir;
275     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
276 }
277
278 sub make_commit ($$) {
279     my ($parents, $message_paras) = @_;
280     my $tree = cmdoutput @git, qw(write-tree);
281     my @cmd = (@git, qw(commit-tree), $tree);
282     push @cmd, qw(-p), $_ foreach @$parents;
283     push @cmd, qw(-m), $_ foreach @$message_paras;
284     return cmdoutput @cmd;
285 }
286
287 our @fproblem_force_opts;
288 our $fproblems_forced;
289 our $fproblems_tripped;
290 sub fproblem ($$) {
291     my ($tag,$msg) = @_;
292     if (grep { $_ eq $tag } @fproblem_force_opts) {
293         $fproblems_forced++;
294         print STDERR "git-debrebase: safety catch overridden (-f$tag): $msg\n";
295     } else {
296         $fproblems_tripped++;
297         print STDERR "git-debrebase: safety catch tripped (-f$tag): $msg\n";
298     }
299 }
300
301 sub fproblems_maybe_bail () {
302     if ($fproblems_forced) {
303         printf STDERR
304             "%s: safety catch trips: %d overriden by individual -f options\n",
305             $us, $fproblems_forced;
306     }
307     if ($fproblems_tripped) {
308         if ($opt_force) {
309             printf STDERR
310                 "%s: safety catch trips: %d overriden by global --force\n",
311                 $us, $fproblems_tripped;
312         } else {
313             fail sprintf
314   "%s: safety catch trips: %d blockers (you could -f<tag>, or --force)",
315                 $us, $fproblems_tripped;
316         }
317     }
318 }
319 sub any_fproblems () {
320     return $fproblems_forced || $fproblems_tripped;
321 }
322
323 # classify returns an info hash like this
324 #   CommitId => $objid
325 #   Hdr => # commit headers, including 1 final newline
326 #   Msg => # commit message (so one newline is dropped)
327 #   Tree => $treeobjid
328 #   Type => (see below)
329 #   Parents = [ {
330 #       Ix => $index # ie 0, 1, 2, ...
331 #       CommitId
332 #       Differs => return value from get_differs
333 #       IsOrigin
334 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
335 #     } ...]
336 #   NewMsg => # commit message, but with any [dgit import ...] edited
337 #             # to say "[was: ...]"
338 #
339 # Types:
340 #   Packaging
341 #   Changelog
342 #   Upstream
343 #   AddPatches
344 #   Mixed
345 #
346 #   Pseudomerge
347 #     has additional entres in classification result
348 #       Overwritten = [ subset of Parents ]
349 #       Contributor = $the_remaining_Parent
350 #
351 #   DgitImportUnpatched
352 #     has additional entry in classification result
353 #       OrigParents = [ subset of Parents ]
354 #
355 #   Anchor
356 #     has additional entry in classification result
357 #       OrigParents = [ subset of Parents ]  # singleton list
358 #
359 #   TreatAsAnchor
360 #
361 #   BreakwaterStart
362 #
363 #   Unknown
364 #     has additional entry in classification result
365 #       Why => "prose"
366
367 sub parsecommit ($;$) {
368     my ($objid, $p_ref) = @_;
369     # => hash with                   CommitId Hdr Msg Tree Parents
370     #    Parents entries have only   Ix CommitId
371     #    $p_ref, if provided, must be [] and is used as a base for Parents
372
373     $p_ref //= [];
374     die if @$p_ref;
375
376     my ($h,$m) = get_commit $objid;
377
378     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
379     my (@ph) = $h =~ m/^parent (\w+)$/mg;
380
381     my $r = {
382         CommitId => $objid,
383         Hdr => $h,
384         Msg => $m,
385         Tree => $t,
386         Parents => $p_ref,
387     };
388
389     foreach my $ph (@ph) {
390         push @$p_ref, {
391             Ix => scalar @$p_ref,
392             CommitId => $ph,
393         };
394     }
395
396     return $r;
397 }    
398
399 sub classify ($) {
400     my ($objid) = @_;
401
402     my @p;
403     my $r = parsecommit($objid, \@p);
404     my $t = $r->{Tree};
405
406     foreach my $p (@p) {
407         $p->{Differs} = (get_differs $p->{CommitId}, $t),
408     }
409
410     printdebug "classify $objid \$t=$t \@p",
411         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
412         "\n";
413
414     my $classify = sub {
415         my ($type, @rest) = @_;
416         $r = { %$r, Type => $type, @rest };
417         if ($debuglevel) {
418             printdebug " = $type ".(dd $r)."\n";
419         }
420         return $r;
421     };
422     my $unknown = sub {
423         my ($why) = @_;
424         $r = { %$r, Type => qw(Unknown), Why => $why };
425         printdebug " ** Unknown\n";
426         return $r;
427     };
428
429     if (grep { $_ eq $objid } @opt_anchors) {
430         return $classify->('TreatAsAnchor');
431     }
432
433     my @identical = grep { !$_->{Differs} } @p;
434     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
435     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
436
437     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
438         # multi-orig upstreams are represented with an anchor merge
439         # from a single upstream commit which combines the orig tarballs
440
441         # Every anchor tagged this way must be a merge.
442         # We are relying on the
443         #     [git-debrebase anchor: ...]
444         # commit message annotation in "declare" anchor merges (which
445         # do not have any upstream changes), to distinguish those
446         # anchor merges from ordinary pseudomerges (which we might
447         # just try to strip).
448         #
449         # However, the user is going to be doing git-rebase a lot.  We
450         # really don't want them to rewrite an anchor commit.
451         # git-rebase trips up on merges, so that is a useful safety
452         # catch.
453         #
454         # BreakwaterStart commits are also anchors in the terminology
455         # of git-debrebase(5), but they are untagged (and always
456         # manually generated).
457
458         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
459         @p == 2 or return $badanchor->("has other than two parents");
460         $haspatches and return $badanchor->("contains debian/patches");
461
462         # How to decide about l/r ordering of anchors ?  git
463         # --topo-order prefers to expand 2nd parent first.  There's
464         # already an easy rune to look for debian/ history anyway (git log
465         # debian/) so debian breakwater branch should be 1st parent; that
466         # way also there's also an easy rune to look for the upstream
467         # patches (--topo-order).
468
469         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
470         $p[1]{Differs} & ~DS_DEB and
471             $badanchor->("upstream files differ from left parent");
472         $p[0]{Differs} & ~D_UPS and
473             $badanchor->("debian/ differs from right parent");
474
475         return $classify->(qw(Anchor),
476                            OrigParents => [ $p[1] ]);
477     }
478
479     if (@p == 1) {
480         my $d = $r->{Parents}[0]{Differs};
481         if ($d == D_PAT_ADD) {
482             return $classify->(qw(AddPatches));
483         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
484             return $unknown->("edits debian/patches");
485         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
486             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
487             if ($ty eq 'tree') {
488                 if ($d == D_DEB_CLOG) {
489                     return $classify->(qw(Changelog));
490                 } else {
491                     return $classify->(qw(Packaging));
492                 }
493             } elsif ($ty eq 'missing') {
494                 return $classify->(qw(BreakwaterStart));
495             } else {
496                 return $unknown->("parent's debian is not a directory");
497             }
498         } elsif ($d == D_UPS) {
499             return $classify->(qw(Upstream));
500         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
501             return $classify->(qw(Mixed));
502         } elsif ($d == 0) {
503             return $unknown->("no changes");
504         } else {
505             confess "internal error $objid ?";
506         }
507     }
508     if (!@p) {
509         return $unknown->("origin commit");
510     }
511
512     if (@p == 2 && @identical == 1) {
513         my @overwritten = grep { $_->{Differs} } @p;
514         confess "internal error $objid ?" unless @overwritten==1;
515         return $classify->(qw(Pseudomerge),
516                            Overwritten => [ $overwritten[0] ],
517                            Contributor => $identical[0]);
518     }
519     if (@p == 2 && @identical == 2) {
520         my $get_t = sub {
521             my ($ph,$pm) = get_commit $_[0]{CommitId};
522             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
523             $1;
524         };
525         my @bytime = @p;
526         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
527         if ($order > 0) { # newer first
528         } elsif ($order < 0) {
529             @bytime = reverse @bytime;
530         } else {
531             # same age, default to order made by -s ours
532             # that is, commit was made by someone who preferred L
533         }
534         return $classify->(qw(Pseudomerge),
535                            SubType => qw(Ambiguous),
536                            Contributor => $bytime[0],
537                            Overwritten => [ $bytime[1] ]);
538     }
539     foreach my $p (@p) {
540         my ($p_h, $p_m) = get_commit $p->{CommitId};
541         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
542         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
543     }
544     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
545     my $m2 = $r->{Msg};
546     if (!(grep { !$_->{IsOrigin} } @p) and
547         (@orig_ps >= @p - 1) and
548         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
549         $r->{NewMsg} = $m2;
550         return $classify->(qw(DgitImportUnpatched),
551                            OrigParents => \@orig_ps);
552     }
553
554     return $unknown->("complex merge");
555 }
556
557 sub breakwater_of ($) {
558     my ($head) = @_; # must be laundered
559     my $breakwater;
560     my $unclean = sub {
561         my ($why) = @_;
562         fail "branch needs laundering (run git-debrebase): $why";
563     };
564     for (;;) {
565         my $cl = classify $head;
566         my $ty = $cl->{Type};
567         if ($ty eq 'Packaging' or
568             $ty eq 'Changelog') {
569             $breakwater //= $head;
570         } elsif ($ty eq 'Anchor' or
571                  $ty eq 'TreatAsAnchor' or
572                  $ty eq 'BreakwaterStart') {
573             $breakwater //= $head;
574             last;
575         } elsif ($ty eq 'Upstream') {
576             $unclean->("packaging change ($breakwater)".
577                        " follows upstream change (eg $head)")
578                 if defined $breakwater;
579         } elsif ($ty eq 'Mixed') {
580             $unclean->('found mixed upstream/packaging commit ($head)');
581         } elsif ($ty eq 'Pseudomerge' or
582                  $ty eq 'AddPatches') {
583             $unclean->("found interchange conversion commit ($ty, $head)");
584         } elsif ($ty eq 'DgitImportUnpatched') {
585             $unclean->("found dgit dsc import ($head)");
586         } else {
587             fail "found unprocessable commit, cannot cope: $head; $cl->{Why}";
588         }
589         $head = $cl->{Parents}[0]{CommitId};
590     }
591     return $breakwater;
592 }
593
594 sub walk ($;$$);
595 sub walk ($;$$) {
596     my ($input,
597         $nogenerate,$report) = @_;
598     # => ($tip, $breakwater_tip, $last_anchor)
599     # (or nothing, if $nogenerate)
600
601     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
602
603     # go through commits backwards
604     # we generate two lists of commits to apply:
605     # breakwater branch and upstream patches
606     my (@brw_cl, @upp_cl, @processed);
607     my %found;
608     my $upp_limit;
609     my @pseudomerges;
610
611     my $cl;
612     my $xmsg = sub {
613         my ($prose, $info) = @_;
614         my $ms = $cl->{Msg};
615         chomp $ms;
616         $info //= '';
617         $ms .= "\n\n[git-debrebase$info: $prose]\n";
618         return (Msg => $ms);
619     };
620     my $rewrite_from_here = sub {
621         my ($cl) = @_;
622         my $sp_cl = { SpecialMethod => 'StartRewrite' };
623         push @$cl, $sp_cl;
624         push @processed, $sp_cl;
625     };
626     my $cur = $input;
627
628     my $prdelim = "";
629     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
630
631     my $prline = sub {
632         return unless $report;
633         print $report $prdelim, @_;
634         $prdelim = "\n";
635     };
636
637     my $bomb = sub { # usage: return $bomb->();
638         print $report " Unprocessable" if $report;
639         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
640         $prprdelim->();
641         if ($nogenerate) {
642             return (undef,undef);
643         }
644         die "commit $cur: Cannot cope with this commit (d.".
645             (join ' ', map { sprintf "%#x", $_->{Differs} }
646              @{ $cl->{Parents} }).
647             (defined $cl->{Why} ? "; $cl->{Why}": '').
648                  ")";
649     };
650
651     my $build;
652     my $breakwater;
653
654     my $build_start = sub {
655         my ($msg, $parent) = @_;
656         $prline->(" $msg");
657         $build = $parent;
658         no warnings qw(exiting); last;
659     };
660
661     my $last_anchor;
662
663     for (;;) {
664         $cl = classify $cur;
665         my $ty = $cl->{Type};
666         my $st = $cl->{SubType};
667         $prline->("$cl->{CommitId} $cl->{Type}");
668         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
669         push @processed, $cl;
670         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
671         if ($ty eq 'AddPatches') {
672             $cur = $p0;
673             $rewrite_from_here->(\@upp_cl);
674             next;
675         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
676             push @brw_cl, $cl;
677             $cur = $p0;
678             next;
679         } elsif ($ty eq 'BreakwaterStart') {
680             $last_anchor = $cur;
681             $build_start->('FirstPackaging', $cur);
682         } elsif ($ty eq 'Upstream') {
683             push @upp_cl, $cl;
684             $cur = $p0;
685             next;
686         } elsif ($ty eq 'Mixed') {
687             my $queue = sub {
688                 my ($q, $wh) = @_;
689                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
690                 push @$q, $cls;
691             };
692             $queue->(\@brw_cl, "debian");
693             $queue->(\@upp_cl, "upstream");
694             $rewrite_from_here->(\@brw_cl);
695             $cur = $p0;
696             next;
697         } elsif ($ty eq 'Pseudomerge') {
698             my $contrib = $cl->{Contributor}{CommitId};
699             print $report " Contributor=$contrib" if $report;
700             push @pseudomerges, $cl;
701             $rewrite_from_here->(\@upp_cl);
702             $cur = $contrib;
703             next;
704         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
705             $last_anchor = $cur;
706             $build_start->("Anchor", $cur);
707         } elsif ($ty eq 'DgitImportUnpatched') {
708             my $pm = $pseudomerges[-1];
709             if (defined $pm) {
710                 # To an extent, this is heuristic.  Imports don't have
711                 # a useful history of the debian/ branch.  We assume
712                 # that the first pseudomerge after an import has a
713                 # useful history of debian/, and ignore the histories
714                 # from later pseudomerges.  Often the first pseudomerge
715                 # will be the dgit import of the upload to the actual
716                 # suite intended by the non-dgit NMUer, and later
717                 # pseudomerges may represent in-archive copies.
718                 my $ovwrs = $pm->{Overwritten};
719                 printf $report " PM=%s \@Overwr:%d",
720                     $pm->{CommitId}, (scalar @$ovwrs)
721                     if $report;
722                 if (@$ovwrs != 1) {
723                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
724                     return $bomb->();
725                 }
726                 my $ovwr = $ovwrs->[0]{CommitId};
727                 printf $report " Overwr=%s", $ovwr if $report;
728                 # This import has a tree which is just like a
729                 # breakwater tree, but it has the wrong history.  It
730                 # ought to have the previous breakwater (which the
731                 # pseudomerge overwrote) as an ancestor.  That will
732                 # make the history of the debian/ files correct.  As
733                 # for the upstream version: either it's the same as
734                 # was ovewritten (ie, same as the previous
735                 # breakwater), in which case that history is precisely
736                 # right; or, otherwise, it was a non-gitish upload of a
737                 # new upstream version.  We can tell these apart by
738                 # looking at the tree of the supposed upstream.
739                 push @brw_cl, {
740                     %$cl,
741                     SpecialMethod => 'DgitImportDebianUpdate',
742                     $xmsg->("convert dgit import: debian changes")
743                 }, {
744                     %$cl,
745                     SpecialMethod => 'DgitImportUpstreamUpdate',
746                     $xmsg->("convert dgit import: upstream update",
747                             " anchor")
748                 };
749                 $prline->(" Import");
750                 $rewrite_from_here->(\@brw_cl);
751                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
752                 $cur = $ovwr;
753                 next;
754             } else {
755                 # Everything is from this import.  This kind of import
756                 # is already in valid breakwater format, with the
757                 # patches as commits.
758                 printf $report " NoPM" if $report;
759                 # last thing we processed will have been the first patch,
760                 # if there is one; which is fine, so no need to rewrite
761                 # on account of this import
762                 $build_start->("ImportOrigin", $cur);
763             }
764             die "$ty ?";
765         } else {
766             printdebug "*** WALK BOMB unrecognised\n";
767             return $bomb->();
768         }
769     }
770     $prprdelim->();
771
772     printdebug "*** WALK prep done cur=$cur".
773         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
774
775     return if $nogenerate;
776
777     # Now we build it back up again
778
779     fresh_workarea();
780
781     my $rewriting = 0;
782
783     my $read_tree_debian = sub {
784         my ($treeish) = @_;
785         read_tree_subdir 'debian', "$treeish:debian";
786         rm_subdir_cached 'debian/patches';
787     };
788     my $read_tree_upstream = sub {
789         my ($treeish) = @_;
790         runcmd @git, qw(read-tree), $treeish;
791         $read_tree_debian->($build);
792     };
793
794     $#upp_cl = $upp_limit if defined $upp_limit;
795  
796     my $committer_authline = calculate_committer_authline();
797
798     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
799
800     confess "internal error" unless $build eq (pop @processed)->{CommitId};
801
802     in_workarea sub {
803         mkdir $rd or $!==EEXIST or die $!;
804         my $current_method;
805         runcmd @git, qw(read-tree), $build;
806         foreach my $cl (qw(Debian), (reverse @brw_cl),
807                         { SpecialMethod => 'RecordBreakwaterTip' },
808                         qw(Upstream), (reverse @upp_cl)) {
809             if (!ref $cl) {
810                 $current_method = $cl;
811                 next;
812             }
813             my $method = $cl->{SpecialMethod} // $current_method;
814             my @parents = ($build);
815             my $cltree = $cl->{CommitId};
816             printdebug "WALK BUILD ".($cltree//'undef').
817                 " $method (rewriting=$rewriting)\n";
818             if ($method eq 'Debian') {
819                 $read_tree_debian->($cltree);
820             } elsif ($method eq 'Upstream') {
821                 $read_tree_upstream->($cltree);
822             } elsif ($method eq 'StartRewrite') {
823                 $rewriting = 1;
824                 next;
825             } elsif ($method eq 'RecordBreakwaterTip') {
826                 $breakwater = $build;
827                 next;
828             } elsif ($method eq 'DgitImportDebianUpdate') {
829                 $read_tree_debian->($cltree);
830             } elsif ($method eq 'DgitImportUpstreamUpdate') {
831                 confess unless $rewriting;
832                 my $differs = (get_differs $build, $cltree);
833                 next unless $differs & D_UPS;
834                 $read_tree_upstream->($cltree);
835                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
836             } else {
837                 confess "$method ?";
838             }
839             if (!$rewriting) {
840                 my $procd = (pop @processed) // 'UNDEF';
841                 if ($cl ne $procd) {
842                     $rewriting = 1;
843                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
844                 }
845             }
846             my $newtree = cmdoutput @git, qw(write-tree);
847             my $ch = $cl->{Hdr};
848             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
849             $ch =~ s{^parent .*\n}{}mg;
850             $ch =~ s{(?=^author)}{
851                 join '', map { "parent $_\n" } @parents
852             }me or confess "$ch ?";
853             if ($rewriting) {
854                 $ch =~ s{^committer .*$}{$committer_authline}m
855                     or confess "$ch ?";
856             }
857             my $cf = "$rd/m$rewriting";
858             open CD, ">", $cf or die $!;
859             print CD $ch, "\n", $cl->{Msg} or die $!;
860             close CD or die $!;
861             my @cmd = (@git, qw(hash-object));
862             push @cmd, qw(-w) if $rewriting;
863             push @cmd, qw(-t commit), $cf;
864             my $newcommit = cmdoutput @cmd;
865             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
866             $build = $newcommit;
867             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
868                 $last_anchor = $cur;
869             }
870         }
871     };
872
873     my $final_check = get_differs $build, $input;
874     die sprintf "internal error %#x %s %s", $final_check, $build, $input
875         if $final_check & ~D_PAT_ADD;
876
877     my @r = ($build, $breakwater, $last_anchor);
878     printdebug "*** WALK RETURN @r\n";
879     return @r
880 }
881
882 sub get_head () {
883     git_check_unmodified();
884     return git_rev_parse qw(HEAD);
885 }
886
887 sub update_head ($$$) {
888     my ($old, $new, $mrest) = @_;
889     push @deferred_updates, "update HEAD $new $old";
890     run_deferred_updates $mrest;
891 }
892
893 sub update_head_checkout ($$$) {
894     my ($old, $new, $mrest) = @_;
895     update_head $old, $new, $mrest;
896     runcmd @git, qw(reset --hard);
897 }
898
899 sub update_head_postlaunder ($$$) {
900     my ($old, $tip, $reflogmsg) = @_;
901     return if $tip eq $old;
902     print "git-debrebase: laundered (head was $old)\n";
903     update_head $old, $tip, $reflogmsg;
904     # no tree changes except debian/patches
905     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
906 }
907
908 sub cmd_launder_v0 () {
909     badusage "no arguments to launder-v0 allowed" if @ARGV;
910     my $old = get_head();
911     my ($tip,$breakwater,$last_anchor) = walk $old;
912     update_head_postlaunder $old, $tip, 'launder';
913     printf "# breakwater tip\n%s\n", $breakwater;
914     printf "# working tip\n%s\n", $tip;
915     printf "# last anchor\n%s\n", $last_anchor;
916 }
917
918 sub defaultcmd_rebase () {
919     my $old = get_head();
920     record_ffq_auto();
921     my ($tip,$breakwater) = walk $old;
922     update_head_postlaunder $old, $tip, 'launder for rebase';
923     runcmd @git, qw(rebase), @ARGV, $breakwater;
924 }
925
926 sub cmd_analyse () {
927     die if ($ARGV[0]//'') =~ m/^-/;
928     badusage "too many arguments to analyse" if @ARGV>1;
929     my ($old) = @ARGV;
930     if (defined $old) {
931         $old = git_rev_parse $old;
932     } else {
933         $old = git_rev_parse 'HEAD';
934     }
935     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
936     STDOUT->error and die $!;
937 }
938
939 sub ffq_prev_branchinfo () {
940     # => ('status', "message", [$current, $ffq_prev])
941     # 'status' may be
942     #    branch         message is undef
943     #    weird-symref   } no $current,
944     #    notbranch      }  no $ffq_prev
945     my $current = git_get_symref();
946     return ('detached', 'detached HEAD') unless defined $current;
947     return ('weird-symref', 'HEAD symref is not to refs/')
948         unless $current =~ m{^refs/};
949     my $ffq_prev = "refs/$ffq_refprefix/$'";
950     printdebug "ffq_prev_branchinfo branch current $current\n";
951     return ('branch', undef, $current, $ffq_prev);
952 }
953
954 sub record_ffq_prev_deferred () {
955     # => ('status', "message")
956     # 'status' may be
957     #    deferred          message is undef
958     #    exists
959     #    detached
960     #    weird-symref
961     #    notbranch
962     # if not ff from some branch we should be ff from, is an fproblem
963     # if "deferred", will have added something about that to
964     #   @deferred_update_messages, and also maybe printed (already)
965     #   some messages about ff checks
966     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
967     return ($status, $message) unless $status eq 'branch';
968
969     my $currentval = get_head();
970
971     my $exists = git_get_ref $ffq_prev;
972     return ('exists',"$ffq_prev already exists") if $exists;
973
974     return ('not-branch', 'HEAD symref is not to refs/heads/')
975         unless $current =~ m{^refs/heads/};
976     my $branch = $';
977
978     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
979     my %checked;
980
981     printdebug "ffq check_specs @check_specs\n";
982
983     my $check = sub {
984         my ($lrref, $desc) = @_;
985         printdebug "ffq might check $lrref ($desc)\n";
986         my $invert;
987         for my $chk (@check_specs) {
988             my $glob = $chk;
989             $invert = $glob =~ s{^[!^]}{};
990             last if fnmatch $glob, $lrref;
991         }
992         return if $invert;
993         my $lrval = git_get_ref $lrref;
994         return unless defined $lrval;
995
996         if (is_fast_fwd $lrval, $currentval) {
997             print "OK, you are ahead of $lrref\n" or die $!;
998             $checked{$lrref} = 1;
999         } elsif (is_fast_fwd $currentval, $lrval) {
1000             $checked{$lrref} = -1;
1001             fproblem 'behind', "you are behind $lrref, divergence risk";
1002         } else {
1003             $checked{$lrref} = -1;
1004             fproblem 'diverged', "you have diverged from $lrref";
1005         }
1006     };
1007
1008     my $merge = cfg "branch.$branch.merge",1;
1009     if (defined $merge and $merge =~ m{^refs/heads/}) {
1010         my $rhs = $';
1011         printdebug "ffq merge $rhs\n";
1012         my $check_remote = sub {
1013             my ($remote, $desc) = @_;
1014             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1015             return unless defined $remote;
1016             $check->("refs/remotes/$remote/$rhs", $desc);
1017         };
1018         $check_remote->((scalar cfg "branch.$branch.remote",1),
1019                         'remote fetch/merge branch');
1020         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1021                         (scalar cfg "branch.$branch.pushDefault",1),
1022                         'remote push branch');
1023     }
1024     if ($branch =~ m{^dgit/}) {
1025         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1026     } elsif ($branch =~ m{^master$}) {
1027         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1028     }
1029
1030     fproblems_maybe_bail();
1031
1032     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1033     push @deferred_update_messages, "Recorded current head for preservation";
1034     return ('deferred', undef);
1035 }
1036
1037 sub record_ffq_auto () {
1038     my ($status, $message) = record_ffq_prev_deferred();
1039     if ($status eq 'deferred' || $status eq 'exists') {
1040     } else {
1041         fproblem $status, "could not record ffq-prev: $message";
1042         fproblems_maybe_bail();
1043     }
1044 }
1045
1046 sub cmd_new_upstream_v0 () {
1047     # automatically and unconditionally launders before rebasing
1048     # if rebase --abort is used, laundering has still been done
1049
1050     my %pieces;
1051
1052     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1053
1054     # parse args - low commitment
1055     my $new_version = (new Dpkg::Version scalar(shift @ARGV), check => 1);
1056     my $new_upstream_version = $new_version->version();
1057
1058     my $new_upstream = git_rev_parse (shift @ARGV // 'upstream');
1059
1060     record_ffq_auto();
1061
1062     my $piece = sub {
1063         my ($n, @x) = @_; # may be ''
1064         my $pc = $pieces{$n} //= {
1065             Name => $n,
1066             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1067         };
1068         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1069         $pc;
1070     };
1071
1072     my @newpieces;
1073     my $newpiece = sub {
1074         my ($n, @x) = @_; # may be ''
1075         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1076         push @newpieces, $pc;
1077     };
1078
1079     $newpiece->('',
1080         OldIx => 0,
1081         New => $new_upstream,
1082     );
1083     while (@ARGV && $ARGV[0] !~ m{^-}) {
1084         my $n = shift @ARGV;
1085
1086         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1087             unless @ARGV && $ARGV[0] !~ m{^-};
1088
1089         my $c = git_rev_parse shift @ARGV;
1090         die unless $n =~ m/^$extra_orig_namepart_re$/;
1091         $newpiece->($n, New => $c);
1092     }
1093
1094     # now we need to investigate the branch this generates the
1095     # laundered version but we don't switch to it yet
1096     my $old_head = get_head();
1097     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1098
1099     my $old_bw_cl = classify $old_bw;
1100     my $old_anchor_cl = classify $old_anchor;
1101     my $old_upstream;
1102     if (!$old_anchor_cl->{OrigParents}) {
1103         fproblem 'anchor-treated',
1104             'old anchor is recognised due to --anchor, cannot check upstream';
1105     } else {
1106         $old_upstream = parsecommit
1107             $old_anchor_cl->{OrigParents}[0]{CommitId};
1108         $piece->('', Old => $old_upstream->{CommitId});
1109     }
1110
1111     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1112         if ($old_upstream->{Msg} =~
1113  m{^\[git-debrebase upstream-combine \.((?: $extra_orig_namepart_re)+)\:.*\]$}m
1114            ) {
1115             my @oldpieces = ('', split / /, $1);
1116             my $parentix = -1 + scalar @{ $old_upstream->{Parents} };
1117             foreach my $i (0..$#oldpieces) {
1118                 my $n = $oldpieces[$i];
1119                 $piece->($n, Old => $old_upstream->{CommitId}.'^'.$parentix);
1120             }
1121         } else {
1122             fproblem 'upstream-confusing',
1123                 "previous upstream $old_upstream->{CommitId} is from".
1124                " git-debrebase but not an \`upstream-combine' commit";
1125         }
1126     }
1127
1128     foreach my $pc (values %pieces) {
1129         if (!$old_upstream) {
1130             # we have complained already
1131         } elsif (!$pc->{Old}) {
1132             fproblem 'upstream-new-piece',
1133                 "introducing upstream piece \`$pc->{Name}'";
1134         } elsif (!$pc->{New}) {
1135             fproblem 'upstream-rm-piece',
1136                 "dropping upstream piece \`$pc->{Name}'";
1137         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1138             fproblem 'upstream-not-ff',
1139                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1140         }
1141     }
1142
1143     printdebug "%pieces = ", (dd \%pieces), "\n";
1144     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1145
1146     fproblems_maybe_bail();
1147
1148     my $new_bw;
1149
1150     fresh_workarea();
1151     in_workarea sub {
1152         my @upstream_merge_parents;
1153
1154         if (!any_fproblems()) {
1155             push @upstream_merge_parents, $old_upstream->{CommitId};
1156         }
1157
1158         foreach my $pc (@newpieces) { # always has '' first
1159             if ($pc->{Name}) {
1160                 read_tree_subdir $pc->{Name}, $pc->{New};
1161             } else {
1162                 runcmd @git, qw(read-tree), $pc->{New};
1163             }
1164             push @upstream_merge_parents, $pc->{New};
1165         }
1166
1167         # index now contains the new upstream
1168
1169         if (@newpieces > 1) {
1170             # need to make the upstream subtree merge commit
1171             $new_upstream = make_commit \@upstream_merge_parents,
1172                 [ "Combine upstreams for $new_upstream_version",
1173  ("[git-debrebase upstream-combine . ".
1174  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1175  ": new upstream]"),
1176                 ];
1177         }
1178
1179         # $new_upstream is either the single upstream commit, or the
1180         # combined commit we just made.  Either way it will be the
1181         # "upstream" parent of the anchor merge.
1182
1183         read_tree_subdir 'debian', "$old_bw:debian";
1184
1185         # index now contains the anchor merge contents
1186         $new_bw = make_commit [ $old_bw, $new_upstream ],
1187             [ "Update to upstream $new_upstream_version",
1188  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1189             ];
1190
1191         # Now we have to add a changelog stanza so the Debian version
1192         # is right.
1193         die if unlink "debian";
1194         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1195         unlink "debian/changelog" or $!==ENOENT or die $!;
1196         mkdir "debian" or die $!;
1197         open CN, ">", "debian/changelog" or die $!;
1198         my $oldclog = git_cat_file ":debian/changelog";
1199         $oldclog =~ m/^($package_re) \(\S+\) / or
1200             fail "cannot parse old changelog to get package name";
1201         my $p = $1;
1202         print CN <<END, $oldclog or die $!;
1203 $p ($new_version) UNRELEASED; urgency=medium
1204
1205   * Update to new upstream version $new_upstream_version.
1206
1207  -- 
1208
1209 END
1210         close CN or die $!;
1211         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1212
1213         # Now we have the final new breakwater branch in the index
1214         $new_bw = make_commit [ $new_bw ],
1215             [ "Update changelog for new upstream $new_upstream_version",
1216               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1217             ];
1218     };
1219
1220     # we have constructed the new breakwater. we now need to commit to
1221     # the laundering output, because git-rebase can't easily be made
1222     # to make a replay list which is based on some other branch
1223
1224     update_head_postlaunder $old_head, $old_laundered_tip,
1225         'launder for new upstream';
1226
1227     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1228     runcmd @cmd;
1229     # now it's for the user to sort out
1230 }
1231
1232 sub cmd_record_ffq_prev () {
1233     badusage "no arguments allowed" if @ARGV;
1234     my ($status, $msg) = record_ffq_prev_deferred();
1235     if ($status eq 'exists' && $opt_noop_ok) {
1236         print "Previous head already recorded\n" or die $!;
1237     } elsif ($status eq 'deferred') {
1238         run_deferred_updates 'record-ffq-prev';
1239     } else {
1240         fail "Could not preserve: $msg";
1241     }
1242 }
1243
1244 sub cmd_breakwater () {
1245     badusage "no arguments allowed" if @ARGV;
1246     my $bw = breakwater_of git_rev_parse 'HEAD';
1247     print "$bw\n" or die $!;
1248 }
1249
1250 sub cmd_stitch () {
1251     my $prose = '';
1252     GetOptions('prose=s', \$prose) or die badusage("bad options to stitch");
1253     badusage "no arguments allowed" if @ARGV;
1254     my ($status, $message, $current, $ffq_prev) = ffq_prev_branchinfo();
1255     if ($status ne 'branch') {
1256         fproblem $status, "could not check ffq-prev: $message";
1257         fproblems_maybe_bail();
1258     }
1259     my $prev = $ffq_prev && git_get_ref $ffq_prev;
1260     if (!$prev) {
1261         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1262     }
1263     push @deferred_updates, "delete $ffq_prev $prev";
1264
1265     my $old_head = get_head();
1266     if (is_fast_fwd $old_head, $prev) {
1267         my $differs = get_differs $old_head, $prev;
1268         unless ($differs & ~D_PAT_ADD) {
1269             # ffq-prev is ahead of us, and the only tree changes it has
1270             # are possibly addition of things in debian/patches/.
1271             # Just wind forwards rather than making a pointless pseudomerge.
1272             update_head_checkout $old_head, $prev, "stitch (fast forward)";
1273             return;
1274         }
1275     }
1276     fresh_workarea();
1277     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1278         'Declare fast forward / record previous work',
1279         "[git-debrebase pseudomerge: stitch$prose]",
1280     ];
1281     update_head $old_head, $new_head, "stitch";
1282 }
1283
1284 sub cmd_convert_from_gbp () {
1285     badusage "needs 1 optional argument, the upstream git rev"
1286         unless @ARGV<=1;
1287     my ($upstream_spec) = @ARGV;
1288     $upstream_spec //= 'refs/heads/upstream';
1289     my $upstream = git_rev_parse $upstream_spec;
1290     my $old_head = get_head();
1291
1292     my $upsdiff = get_differs $upstream, $old_head;
1293     if ($upsdiff & D_UPS) {
1294         runcmd @git, qw(--no-pager diff),
1295             $upstream, $old_head,
1296             qw( -- :!/debian :/);
1297  fail "upstream ($upstream_spec) and HEAD are not identical in upstream files";
1298     }
1299
1300     if (!is_fast_fwd $upstream, $old_head) {
1301         fproblem 'upstream-not-ancestor',
1302             "upstream ($upstream) is not an ancestor of HEAD";
1303     } else {
1304         my $wrong = cmdoutput
1305             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
1306              qw(-- :/ :!/debian));
1307         if (length $wrong) {
1308             fproblem 'unexpected-upstream-changes',
1309                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
1310             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
1311         }
1312     }
1313
1314     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
1315         fproblem 'upstream-has-debian',
1316             "upstream ($upstream) contains debian/ directory";
1317     }
1318
1319     fproblems_maybe_bail();
1320
1321     my $work;
1322
1323     fresh_workarea();
1324     in_workarea sub {
1325         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
1326         # make a branch out of the patch queue - we'll want this in a mo
1327         runcmd qw(gbp pq import);
1328         # strip the patches out
1329         runcmd @git, qw(checkout -q gdr-internal~0);
1330         rm_subdir_cached 'debian/patches';
1331         $work = make_commit ['HEAD'], [
1332  'git-debrebase convert-from-gbp: drop patches from tree',
1333  'Delete debian/patches, as part of converting to git-debrebase format.',
1334  '[git-debrebase convert-from-gbp: drop patches from tree]'
1335                               ];
1336         # make the anchor merge
1337         # the tree is already exactly right
1338         $work = make_commit [$work, $upstream], [
1339  'git-debrebase import: declare upstream',
1340  'First breakwater merge.',
1341  '[git-debrebase anchor: declare upstream]'
1342                               ];
1343
1344         # rebase the patch queue onto the new breakwater
1345         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
1346         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
1347         $work = git_rev_parse 'HEAD';
1348     };
1349
1350     update_head_checkout $old_head, $work, 'convert-from-gbp';
1351 }
1352
1353 sub cmd_convert_to_gbp () {
1354     badusage "no arguments allowed" if @ARGV;
1355     my $head = get_head();
1356     my $ffq = (ffq_prev_branchinfo())[3];
1357     my $bw = breakwater_of $head;
1358     fresh_workarea();
1359     my $out;
1360     in_workarea sub {
1361         runcmd @git, qw(checkout -q -b bw), $bw;
1362         runcmd @git, qw(checkout -q -b patch-queue/bw), $head;
1363         runcmd qw(gbp pq export);
1364         runcmd @git, qw(add debian/patches);
1365         $out = make_commit ['HEAD'], [
1366             'Commit patch queue (converted from git-debrebase format)',
1367             '[git-debrebase convert-to-gbp: commit patches]',
1368         ];
1369     };
1370     if (defined $ffq) {
1371         push @deferred_updates, "delete $ffq";
1372     }
1373     update_head_checkout $head, $out, "convert to gbp (v0)";
1374     print <<END or die $!;
1375 git-debrebase: converted to git-buildpackage branch format
1376 git-debrebase: WARNING: do not now run "git-debrebase" any more
1377 git-debrebase: WARNING: doing so would drop all upstream patches!
1378 END
1379 }
1380
1381 sub cmd_downstream_rebase_launder_v0 () {
1382     badusage "needs 1 argument, the baseline" unless @ARGV==1;
1383     my ($base) = @ARGV;
1384     $base = git_rev_parse $base;
1385     my $old_head = get_head();
1386     my $current = $old_head;
1387     my $topmost_keep;
1388     for (;;) {
1389         if ($current eq $base) {
1390             $topmost_keep //= $current;
1391             print " $current BASE stop\n";
1392             last;
1393         }
1394         my $cl = classify $current;
1395         print " $current $cl->{Type}";
1396         my $keep = 0;
1397         my $p0 = $cl->{Parents}[0]{CommitId};
1398         my $next;
1399         if ($cl->{Type} eq 'Pseudomerge') {
1400             print " ^".($cl->{Contributor}{Ix}+1);
1401             $next = $cl->{Contributor}{CommitId};
1402         } elsif ($cl->{Type} eq 'AddPatches' or
1403                  $cl->{Type} eq 'Changelog') {
1404             print " strip";
1405             $next = $p0;
1406         } else {
1407             print " keep";
1408             $next = $p0;
1409             $keep = 1;
1410         }
1411         print "\n";
1412         if ($keep) {
1413             $topmost_keep //= $current;
1414         } else {
1415             die "to-be stripped changes not on top of the branch\n"
1416                 if $topmost_keep;
1417         }
1418         $current = $next;
1419     }
1420     if ($topmost_keep eq $old_head) {
1421         print "unchanged\n";
1422     } else {
1423         print "updating to $topmost_keep\n";
1424         update_head_checkout
1425             $old_head, $topmost_keep,
1426             'downstream-rebase-launder-v0';
1427     }
1428 }
1429
1430 GetOptions("D+" => \$debuglevel,
1431            'noop-ok', => \$opt_noop_ok,
1432            'f=s' => \@fproblem_force_opts,
1433            'anchor=s' => \@opt_anchors,
1434            'force!') or die badusage "bad options\n";
1435 initdebug('git-debrebase ');
1436 enabledebug if $debuglevel;
1437
1438 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1439 chdir $toplevel or die "chdir $toplevel: $!";
1440
1441 $rd = fresh_playground "$playprefix/misc";
1442
1443 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
1444
1445 if (!@ARGV || $ARGV[0] =~ m{^-}) {
1446     defaultcmd_rebase();
1447 } else {
1448     my $cmd = shift @ARGV;
1449     my $cmdfn = $cmd;
1450     $cmdfn =~ y/-/_/;
1451     $cmdfn = ${*::}{"cmd_$cmdfn"};
1452
1453     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1454     $cmdfn->();
1455 }