chiark / gitweb /
git-debrebase: merge: Get debian/ parts of new patch queue right
[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 END { $? = $Debian::Dgit::ExitStatus::desired // -1; };
22 use Debian::Dgit::GDR;
23 use Debian::Dgit::ExitStatus;
24
25 use strict;
26
27 use Debian::Dgit qw(:DEFAULT :playground);
28 setup_sigwarn();
29
30 use Memoize;
31 use Carp;
32 use POSIX;
33 use Data::Dumper;
34 use Getopt::Long qw(:config posix_default gnu_compat bundling);
35 use Dpkg::Version;
36 use File::FnMatch qw(:fnmatch);
37 use File::Copy;
38
39 $debugcmd_when_debuglevel = 2;
40
41 our ($usage_message) = <<'END';
42 usages:
43   git-debrebase [<options>] [--|-i <git rebase options...>]
44   git-debrebase [<options>] status
45   git-debrebase [<options>] prepush [--prose=...]
46   git-debrebase [<options>] quick|conclude
47   git-debrebase [<options>] new-upstream <new-version> [<details ...>]
48   git-debrebase [<options>] convert-from-gbp [<upstream-commitish>]
49   ...
50 See git-debrebase(1), git-debrebase(5), dgit-maint-debrebase(7) (in dgit).
51 END
52
53 our ($opt_force, $opt_noop_ok, @opt_anchors);
54 our ($opt_defaultcmd_interactive);
55
56 our $us = qw(git-debrebase);
57
58 $|=1;
59
60 sub badusage ($) {
61     my ($m) = @_;
62     print STDERR "$us: bad usage: $m\n";
63     finish 8;
64 }
65
66 sub getoptions_main {
67     my $m = shift;
68     local $SIG{__WARN__}; # GetOptions calls `warn' to print messages
69     GetOptions @_ or badusage $m;
70 }
71 sub getoptions {
72     my $sc = shift;
73     getoptions_main "bad options follow \`git-debrebase $sc'", @_;
74 }
75
76 sub cfg ($;$) {
77     my ($k, $optional) = @_;
78     local $/ = "\0";
79     my @cmd = qw(git config -z);
80     push @cmd, qw(--get-all) if wantarray;
81     push @cmd, $k;
82     my $out = cmdoutput_errok @cmd;
83     if (!defined $out) {
84         fail "missing required git config $k" unless $optional;
85         return ();
86     }
87     my @l = split /\0/, $out;
88     return wantarray ? @l : $l[0];
89 }
90
91 memoize('cfg');
92
93 sub dd ($) {
94     my ($v) = @_;
95     my $dd = new Data::Dumper [ $v ];
96     Terse $dd 1; Indent $dd 0; Useqq $dd 1;
97     return Dump $dd;
98 }
99
100 sub get_commit ($) {
101     my ($objid) = @_;
102     my $data = (git_cat_file $objid, 'commit');
103     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
104     return ($`,$');
105 }
106
107 sub D_UPS ()      { 0x02; } # upstream files
108 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
109 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
110 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
111 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
112 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
113
114 our $playprefix = 'debrebase';
115 our $rd;
116 our $workarea;
117
118 our @git = qw(git);
119 our @dgit = qw(dgit);
120
121 sub in_workarea ($) {
122     my ($sub) = @_;
123     changedir $workarea;
124     my $r = eval { $sub->(); };
125     { local $@; changedir $maindir; }
126     die $@ if $@;
127 }
128
129 sub fresh_workarea () {
130     $workarea = fresh_playground "$playprefix/work";
131     in_workarea sub { playtree_setup };
132 }
133
134 our $snags_forced = 0;
135 our $snags_tripped = 0;
136 our $snags_summarised = 0;
137 our @deferred_updates;
138 our @deferred_update_messages;
139
140 sub all_snags_summarised () {
141     $snags_forced + $snags_tripped == $snags_summarised;
142 }
143 sub run_deferred_updates ($) {
144     my ($mrest) = @_;
145
146     confess 'dangerous internal error' unless all_snags_summarised();
147
148     my @upd_cmd = (git_update_ref_cmd "debrebase: $mrest", qw(--stdin));
149     debugcmd '>|', @upd_cmd;
150     open U, "|-", @upd_cmd or die $!;
151     foreach (@deferred_updates) {
152         printdebug ">= ", $_, "\n";
153         print U $_, "\n" or die $!;
154     }
155     printdebug ">\$\n";
156     close U or failedcmd @upd_cmd;
157
158     print $_, "\n" foreach @deferred_update_messages;
159
160     @deferred_updates = ();
161     @deferred_update_messages = ();
162 }
163
164 sub get_differs ($$) {
165     my ($x,$y) = @_;
166     # This resembles quiltify_trees_differ, in dgit, a bit.
167     # But we don't care about modes, or dpkg-source-unrepresentable
168     # changes, and we don't need the plethora of different modes.
169     # Conversely we need to distinguish different kinds of changes to
170     # debian/ and debian/patches/.
171
172     my $differs = 0;
173
174     my $rundiff = sub {
175         my ($opts, $limits, $fn) = @_;
176         my @cmd = (@git, qw(diff-tree -z --no-renames));
177         push @cmd, @$opts;
178         push @cmd, "$_:" foreach $x, $y;
179         push @cmd, '--', @$limits;
180         my $diffs = cmdoutput @cmd;
181         foreach (split /\0/, $diffs) { $fn->(); }
182     };
183
184     $rundiff->([qw(--name-only)], [], sub {
185         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
186     });
187
188     if ($differs & DS_DEB) {
189         $differs &= ~DS_DEB;
190         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
191             $differs |=
192                 m{^debian/patches/}      ? D_PAT_OTH  :
193                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
194                                            D_DEB_OTH;
195         });
196         die "mysterious debian changes $x..$y"
197             unless $differs & (D_PAT_OTH|DS_DEB);
198     }
199
200     if ($differs & D_PAT_OTH) {
201         my $mode;
202         $differs &= ~D_PAT_OTH;
203         my $pat_oth = sub {
204             $differs |= D_PAT_OTH;
205             no warnings qw(exiting);  last;
206         };
207         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
208             no warnings qw(exiting);
209             if (!defined $mode) {
210                 $mode = $_;  next;
211             }
212             die unless s{^debian/patches/}{};
213             my $ok;
214             if ($mode eq 'A' && !m/\.series$/s) {
215                 $ok = 1;
216             } elsif ($mode eq 'M' && $_ eq 'series') {
217                 my $x_s = (git_cat_file "$x:debian/patches/series", 'blob');
218                 my $y_s = (git_cat_file "$y:debian/patches/series", 'blob');
219                 chomp $x_s;  $x_s .= "\n";
220                 $ok = $x_s eq substr($y_s, 0, length $x_s);
221             } else {
222                 # nope
223             }
224             $mode = undef;
225             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
226         });
227         die "mysterious debian/patches changes $x..$y"
228             unless $differs & (D_PAT_ADD|D_PAT_OTH);
229     }
230
231     printdebug sprintf "get_differs %s %s = %#x\n", $x, $y, $differs;
232
233     return $differs;
234 }
235
236 sub commit_pr_info ($) {
237     my ($r) = @_;
238     return Data::Dumper->dump([$r], [qw(commit)]);
239 }
240
241 sub calculate_committer_authline () {
242     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
243         'DUMMY COMMIT (git-debrebase)', "HEAD:";
244     my ($h,$m) = get_commit $c;
245     $h =~ m/^committer .*$/m or confess "($h) ?";
246     return $&;
247 }
248
249 sub rm_subdir_cached ($) {
250     my ($subdir) = @_;
251     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
252 }
253
254 sub read_tree_subdir ($$) {
255     my ($subdir, $new_tree_object) = @_;
256     rm_subdir_cached $subdir;
257     runcmd @git, qw(read-tree), "--prefix=$subdir/", $new_tree_object;
258 }
259
260 sub read_tree_debian ($) {
261     my ($treeish) = @_;
262     read_tree_subdir 'debian', "$treeish:debian";
263     rm_subdir_cached 'debian/patches';
264 }
265
266 sub read_tree_upstream ($;$$) {
267     my ($treeish, $keep_patches, $tree_with_debian) = @_;
268     # if $tree_with_debian is supplied, will use that for debian/
269     # otherwise will save and restore it.
270     my $debian =
271         $tree_with_debian ? "$tree_with_debian:debian"
272         : cmdoutput @git, qw(write-tree --prefix=debian/);
273     runcmd @git, qw(read-tree), $treeish;
274     read_tree_subdir 'debian', $debian;
275     rm_subdir_cached 'debian/patches' unless $keep_patches;
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 @snag_force_opts;
288 sub snag ($$;@) {
289     my ($tag,$msg) = @_; # ignores extra args, for benefit of keycommits
290     if (grep { $_ eq $tag } @snag_force_opts) {
291         $snags_forced++;
292         print STDERR "git-debrebase: snag ignored (-f$tag): $msg\n";
293     } else {
294         $snags_tripped++;
295         print STDERR "git-debrebase: snag detected (-f$tag): $msg\n";
296     }
297 }
298
299 # Important: all mainline code must call snags_maybe_bail after
300 # any point where snag might be called, but before making changes
301 # (eg before any call to run_deferred_updates).  snags_maybe_bail
302 # may be called more than once if necessary (but this is not ideal
303 # because then the messages about number of snags may be confusing).
304 sub snags_maybe_bail () {
305     return if all_snags_summarised();
306     if ($snags_forced) {
307         printf STDERR
308             "%s: snags: %d overriden by individual -f options\n",
309             $us, $snags_forced;
310     }
311     if ($snags_tripped) {
312         if ($opt_force) {
313             printf STDERR
314                 "%s: snags: %d overriden by global --force\n",
315                 $us, $snags_tripped;
316         } else {
317             fail sprintf
318   "%s: snags: %d blocker(s) (you could -f<tag>, or --force)",
319                 $us, $snags_tripped;
320         }
321     }
322     $snags_summarised = $snags_forced + $snags_tripped;
323 }
324 sub snags_maybe_bail_early () {
325     # useful to bail out early without doing a lot of work;
326     # not a substitute for snags_maybe_bail.
327     snags_maybe_bail() if $snags_tripped && !$opt_force;
328 }
329 sub any_snags () {
330     return $snags_forced || $snags_tripped;
331 }
332
333 sub gbp_pq_export ($$$) {
334     my ($bname, $base, $tip) = @_;
335     # must be run in a workarea.  $bname and patch-queue/$bname
336     # ought not to exist.  Leaves you on patch-queue/$bname with
337     # the patches staged but not committed.
338     printdebug "gbp_pq_export $bname $base $tip\n";
339     runcmd @git, qw(checkout -q -b), $bname, $base;
340     runcmd @git, qw(checkout -q -b), "patch-queue/$bname", $tip;
341     my @gbp_cmd = (qw(gbp pq export));
342     my $r = system shell_cmd 'exec >../gbp-pq-err 2>&1', @gbp_cmd;
343     if ($r) {
344         { local ($!,$?); copy('../gbp-pq-err', \*STDERR); }
345         failedcmd @gbp_cmd;
346     }
347     runcmd @git, qw(add -f debian/patches);
348 }
349
350
351 # xxx allow merge resolution separately from laundering, before git merge
352 #
353 # xxx general gdr docs highlight forbidden things
354 # xxx general gdr docs list allowable things ?
355 # xxx general gdr docs explicitly forbid some rebase
356 #
357 # xxx provide a way for the user to help
358 # xxx (eg, provide wreckage provide way to continue)
359
360 # later/rework?
361 #  use git-format-patch?
362 #  our own patch identification algorithm?
363 #  this is an alternative strategy
364
365 sub merge_series ($$;@) {
366     my ($newbase, $base_q, @input_qs) = @_;
367     # $base_q{SeriesBase}  $input_qs[]{SeriesBase}
368     # $base_q{SeriesTip}   $input_qs[]{SeriesTip}
369     # ^ specifies several patch series (currently we only support exactly 2)
370     # return value is a commit which is the result of
371     # merging the two versions of the same topic branch
372     #   $input_q[0] and $input_q[1]
373     # with respect to the old version
374     #   $base_q
375     # all onto $newbase.
376
377     # Creates, in *_q, a key MR for its private use
378
379     printdebug "merge_series newbase=$newbase\n";
380
381     $input_qs[$_]{MR}{S} = $_ foreach (0..$#input_qs);
382     $base_q->{MR}{S} = 'base';
383
384     my %prereq;
385     # $prereq{<patch filename>}{<possible prereq}{<S>} = 1 or absent
386     # $prereq{<patch filename>}{<possible prereq}  exists or not (later)
387     # $prereq{<patch filename>}               exists or not (even later)
388
389     my $result;
390
391     local $workarea = fresh_playground "$playprefix/merge";
392     my $seriesfile = "debian/patches/series";
393     in_workarea sub {
394         playtree_setup();
395         foreach my $q ($base_q, reverse @input_qs) {
396             my $s = $q->{MR}{S};
397             gbp_pq_export "p-$s", $q->{SeriesBase}, $q->{SeriesTip};
398             if (open S, $seriesfile) {
399                 my @earlier;
400                 while (my $patch = <S>) {
401                     chomp $patch or die $!;
402                     $prereq{$patch} //= {};
403                     foreach my $earlier (@earlier) {
404                         $prereq{$patch}{$earlier}{$s}++ and die;
405                     }
406                     push @earlier, $patch;
407                     stat "debian/patches/$patch" or die "$patch ?";
408                 }
409                 S->error and die "$seriesfile $!";
410                 close S;
411             } else {
412                 die "$seriesfile $!" unless $!==ENOENT;
413             }
414             read_tree_upstream $newbase, 1;
415             my $pec = make_commit [ grep { defined } $base_q->{MR}{PEC} ], [
416                 "Convert $s to patch queue for merging",
417                 "[git-debrebase merge-innards patch-queue import:".
418                 " $q->{SeriesTip}]"
419             ];
420             printdebug "merge_series  pec $pec ";
421             runcmd @git, qw(rm -q --cached), $seriesfile;
422             $pec = make_commit [ $pec ], [
423                 "Drop series file from $s to avoid merge trouble",
424                 "[git-debrebase merge-innards patch-queue prep:".
425                 " $q->{SeriesTip}]"
426             ];
427             printdebug "pec' $pec\n";
428             runcmd @git, qw(reset -q --hard), $pec;
429             $q->{MR}{PEC} = $pec;
430         }
431         # now, because of reverse, we are on $input_q->{MR}{OQC}
432         runcmd @git, qw(checkout -q -b merge);
433         printdebug "merge_series merging...\n";
434         my @mergecmd = (@git, qw(merge --quiet --no-edit), "p-1");
435         debugcmd '+', @mergecmd;
436         $!=0; $?=-1;
437         if (system @mergecmd) {
438             failedcmd @mergecmd;
439         }
440
441         printdebug "merge_series merge ok, series...\n";
442         # We need to construct a new series file
443         # Firstly, resolve prereq
444         foreach my $f (sort keys %prereq) {
445             printdebug "merge_series  patch\t$f\t";
446             if (!stat_exists "debian/patches/$f") {
447                 print DEBUG " drop\n" if $debuglevel;
448                 # git merge deleted it; that's how we tell it's not wanted
449                 delete $prereq{$f};
450                 next;
451             }
452             print DEBUG " keep\n" if $debuglevel;
453             foreach my $g (sort keys %{ $prereq{$f} }) {
454                 my $gfp = $prereq{$f}{$g};
455                 printdebug "merge_series  prereq\t$f\t-> $g\t";
456                 if (!!$gfp->{0} == !!$gfp->{1}
457                     ? $gfp->{0}
458                     : !$gfp->{base}) {
459                     print DEBUG "\tkeep\n" if $debuglevel;
460                 } else {
461                     print DEBUG "\tdrop\n" if $debuglevel;
462                     delete $prereq{$f}{$g};
463                 }
464             }
465         }
466
467         my $unsat = sub {
468             my ($f) = @_;
469             return scalar keys %{ $prereq{$f} };
470         };
471
472         my $nodate = time + 1;
473         my %authordate;
474         # $authordate{<patch filename>};
475         my $authordate = sub {
476             my ($f) = @_;
477             $authordate{$f} //= do {
478                 open PF, "<", "debian/patches/$f" or die "$f $!";
479                 while (<PF>) {
480                     return $nodate if m/^$/;
481                     last if s{^Date: }{};
482                 }
483                 chomp;
484                 return cmdoutput qw(date +%s -d), $_;
485             };
486         };
487
488         open NS, '>', $seriesfile or die $!;
489
490         while (keys %prereq) {
491             my $best;
492             foreach my $try (sort keys %prereq) {
493                 if ($best) {
494                     next if (
495                              $unsat->($try) <=> $unsat->($best) or
496                              $authordate->($try) <=> $authordate->($best) or
497                              $try cmp $best
498                             ) >= 0;
499                 }
500                 $best = $try;
501             }
502             printdebug "merge_series series next $best\n";
503             print NS "$best\n" or die $!;
504             delete $prereq{$best};
505             foreach my $gp (values %prereq) {
506                 delete $gp->{$best};
507             }
508         }
509
510         runcmd @git, qw(add), $seriesfile;
511         runcmd @git, qw(commit --quiet -m), 'Merged series';
512
513         printdebug "merge_series series gbp pq import\n";
514         runcmd qw(gbp pq import);
515
516         # OK now we are on patch-queue/merge, and we need to rebase
517         # onto the intended parent and drop the patches from each one
518
519         printdebug "merge_series series ok, building...\n";
520         my $build = $newbase;
521         my @lcmd = (@git, qw(rev-list --reverse merge..patch-queue/merge));
522         foreach my $c (grep /./, split /\n/, cmdoutput @lcmd) {
523             my $commit = git_cat_file $c, 'commit';
524             printdebug "merge_series series ok, building $c\n";
525             read_tree_upstream $c, 0, $newbase;
526             my $tree = cmdoutput @git, qw(write-tree);
527             $commit =~ s{^parent (\S+)$}{parent $build}m or confess;
528             $commit =~ s{^tree (\S+)$}{tree $tree}m      or confess;
529             open C, ">", "../mcommit" or die $!;
530             print C $commit or die $!;
531             close C or die $!;
532             $build = cmdoutput @git, qw(hash-object -w -t commit ../mcommit);
533         }
534         $result = $build;
535         runcmd @git, qw(update-ref refs/heads/result), $result;
536
537         runcmd @git, qw(checkout -q -b debug);
538         runcmd @git, qw(commit --allow-empty -q -m M-INDEX);
539         runcmd @git, qw(add .);
540         runcmd @git, qw(commit --allow-empty -q -m M-WORKTREE);
541         printdebug sprintf "merge_series done debug=%s\n",
542             git_rev_parse 'HEAD';
543     };
544     printdebug "merge_series returns $result\n";
545     return $result;
546 }
547
548 # classify returns an info hash like this
549 #   CommitId => $objid
550 #   Hdr => # commit headers, including 1 final newline
551 #   Msg => # commit message (so one newline is dropped)
552 #   Tree => $treeobjid
553 #   Type => (see below)
554 #   Parents = [ {
555 #       Ix => $index # ie 0, 1, 2, ...
556 #       CommitId
557 #       Differs => return value from get_differs
558 #       IsOrigin
559 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
560 #     } ...]
561 #   NewMsg => # commit message, but with any [dgit import ...] edited
562 #             # to say "[was: ...]"
563 #
564 # Types:
565 #   Packaging
566 #   Changelog
567 #   Upstream
568 #   AddPatches
569 #   Mixed
570 #
571 #   Pseudomerge
572 #     has additional entres in classification result
573 #       Overwritten = [ subset of Parents ]
574 #       Contributor = $the_remaining_Parent
575 #
576 #   DgitImportUnpatched
577 #     has additional entry in classification result
578 #       OrigParents = [ subset of Parents ]
579 #
580 #   Anchor
581 #     has additional entry in classification result
582 #       OrigParents = [ subset of Parents ]  # singleton list
583 #
584 #   TreatAsAnchor
585 #
586 #   BreakwaterStart
587 #
588 #   Unknown
589 #     has additional entry in classification result
590 #       Why => "prose"
591
592 sub parsecommit ($;$) {
593     my ($objid, $p_ref) = @_;
594     # => hash with                   CommitId Hdr Msg Tree Parents
595     #    Parents entries have only   Ix CommitId
596     #    $p_ref, if provided, must be [] and is used as a base for Parents
597
598     $p_ref //= [];
599     die if @$p_ref;
600
601     my ($h,$m) = get_commit $objid;
602
603     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
604     my (@ph) = $h =~ m/^parent (\w+)$/mg;
605
606     my $r = {
607         CommitId => $objid,
608         Hdr => $h,
609         Msg => $m,
610         Tree => $t,
611         Parents => $p_ref,
612     };
613
614     foreach my $ph (@ph) {
615         push @$p_ref, {
616             Ix => scalar @$p_ref,
617             CommitId => $ph,
618         };
619     }
620
621     return $r;
622 }    
623
624 sub classify ($) {
625     my ($objid) = @_;
626
627     my @p;
628     my $r = parsecommit($objid, \@p);
629     my $t = $r->{Tree};
630
631     foreach my $p (@p) {
632         $p->{Differs} = (get_differs $p->{CommitId}, $t),
633     }
634
635     printdebug "classify $objid \$t=$t \@p",
636         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
637         "\n";
638
639     my $classify = sub {
640         my ($type, @rest) = @_;
641         $r = { %$r, Type => $type, @rest };
642         if ($debuglevel) {
643             printdebug " = $type ".(dd $r)."\n";
644         }
645         return $r;
646     };
647     my $unknown = sub {
648         my ($why) = @_;
649         $r = { %$r, Type => qw(Unknown), Why => $why };
650         printdebug " ** Unknown\n";
651         return $r;
652     };
653
654     if (grep { $_ eq $objid } @opt_anchors) {
655         return $classify->('TreatAsAnchor');
656     }
657
658     my @identical = grep { !$_->{Differs} } @p;
659     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
660     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
661
662     if ($r->{Msg} =~ m{^\[git-debrebase anchor.*\]$}m) {
663         # multi-orig upstreams are represented with an anchor merge
664         # from a single upstream commit which combines the orig tarballs
665
666         # Every anchor tagged this way must be a merge.
667         # We are relying on the
668         #     [git-debrebase anchor: ...]
669         # commit message annotation in "declare" anchor merges (which
670         # do not have any upstream changes), to distinguish those
671         # anchor merges from ordinary pseudomerges (which we might
672         # just try to strip).
673         #
674         # However, the user is going to be doing git-rebase a lot.  We
675         # really don't want them to rewrite an anchor commit.
676         # git-rebase trips up on merges, so that is a useful safety
677         # catch.
678         #
679         # BreakwaterStart commits are also anchors in the terminology
680         # of git-debrebase(5), but they are untagged (and always
681         # manually generated).
682         #
683         # We cannot not tolerate any tagged linear commit (ie,
684         # BreakwaterStart commits tagged `[anchor:') because such a
685         # thing could result from an erroneous linearising raw git
686         # rebase of a merge anchor.  That would represent a corruption
687         # of the branch. and we want to detect and reject the results
688         # of such corruption before it makes it out anywhere.  If we
689         # reject it here then we avoid making the pseudomerge which
690         # would be needed to push it.
691
692         my $badanchor = sub { $unknown->("git-debrebase \`anchor' but @_"); };
693         @p == 2 or return $badanchor->("has other than two parents");
694         $haspatches and return $badanchor->("contains debian/patches");
695
696         # How to decide about l/r ordering of anchors ?  git
697         # --topo-order prefers to expand 2nd parent first.  There's
698         # already an easy rune to look for debian/ history anyway (git log
699         # debian/) so debian breakwater branch should be 1st parent; that
700         # way also there's also an easy rune to look for the upstream
701         # patches (--topo-order).
702
703         # Also this makes --first-parent be slightly more likely to
704         # be useful - it makes it provide a linearised breakwater history.
705
706         # Of course one can say somthing like
707         #  gitk -- ':/' ':!/debian'
708         # to get _just_ the commits touching upstream files, and by
709         # the TREESAME logic in git-rev-list this will leave the
710         # breakwater into upstream at the first anchor.  But that
711         # doesn't report debian/ changes at all.
712
713         # Other observations about gitk: by default, gitk seems to
714         # produce output in a different order to git-rev-list.  I
715         # can't seem to find this documented anywhere.  gitk
716         # --date-order DTRT.  But, gitk always seems to put the
717         # parents from left to right, in order, so it's easy to see
718         # which way round a pseudomerge is.
719
720         $p[0]{IsOrigin} and $badanchor->("is an origin commit");
721         $p[1]{Differs} & ~DS_DEB and
722             $badanchor->("upstream files differ from left parent");
723         $p[0]{Differs} & ~D_UPS and
724             $badanchor->("debian/ differs from right parent");
725
726         return $classify->(qw(Anchor),
727                            OrigParents => [ $p[1] ]);
728     }
729
730     if (@p == 1) {
731         my $d = $r->{Parents}[0]{Differs};
732         if ($d == D_PAT_ADD) {
733             return $classify->(qw(AddPatches));
734         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
735             return $unknown->("edits debian/patches");
736         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
737             my ($ty,$dummy) = git_cat_file "$p[0]{CommitId}:debian";
738             if ($ty eq 'tree') {
739                 if ($d == D_DEB_CLOG) {
740                     return $classify->(qw(Changelog));
741                 } else {
742                     return $classify->(qw(Packaging));
743                 }
744             } elsif ($ty eq 'missing') {
745                 return $classify->(qw(BreakwaterStart));
746             } else {
747                 return $unknown->("parent's debian is not a directory");
748             }
749         } elsif ($d == D_UPS) {
750             return $classify->(qw(Upstream));
751         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
752             return $classify->(qw(Mixed));
753         } elsif ($d == 0) {
754             return $unknown->("no changes");
755         } else {
756             confess "internal error $objid ?";
757         }
758     }
759     if (!@p) {
760         return $unknown->("origin commit");
761     }
762
763     if (@p == 2 && @identical == 1) {
764         my @overwritten = grep { $_->{Differs} } @p;
765         confess "internal error $objid ?" unless @overwritten==1;
766         return $classify->(qw(Pseudomerge),
767                            Overwritten => [ $overwritten[0] ],
768                            Contributor => $identical[0]);
769     }
770     if (@p == 2 && @identical == 2) {
771         my $get_t = sub {
772             my ($ph,$pm) = get_commit $_[0]{CommitId};
773             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
774             $1;
775         };
776         my @bytime = @p;
777         my $order = $get_t->($bytime[0]) <=> $get_t->($bytime[1]);
778         if ($order > 0) { # newer first
779         } elsif ($order < 0) {
780             @bytime = reverse @bytime;
781         } else {
782             # same age, default to order made by -s ours
783             # that is, commit was made by someone who preferred L
784         }
785         return $classify->(qw(Pseudomerge),
786                            SubType => qw(Ambiguous),
787                            Contributor => $bytime[0],
788                            Overwritten => [ $bytime[1] ]);
789     }
790     foreach my $p (@p) {
791         my ($p_h, $p_m) = get_commit $p->{CommitId};
792         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
793         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
794     }
795     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
796     my $m2 = $r->{Msg};
797     if (!(grep { !$_->{IsOrigin} } @p) and
798         (@orig_ps >= @p - 1) and
799         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
800         $r->{NewMsg} = $m2;
801         return $classify->(qw(DgitImportUnpatched),
802                            OrigParents => \@orig_ps);
803     }
804
805     if (@p == 2 and
806         $r->{Msg} =~ m{^\[git-debrebase merged-breakwater.*\]$}m) {
807         # xxx ^ metadata tag needs adding to (5)
808         return $classify->("MergedBreakwaters");
809     }
810     if ($r->{Msg} =~ m{^\[(git-debrebase|dgit)[: ].*\]$}m) {
811         return $unknown->("unknown kind of merge from $1");
812     }
813     if (@p > 2) {
814         return $unknown->("octopus merge");
815     }
816
817     if (!$ENV{GIT_DEBREBASE_EXPERIMENTAL_MERGE}) {
818         return $unknown->("general two-parent merge");
819     }
820
821     return $classify->("VanillaMerge");
822 }
823
824 sub keycommits ($;$$$$$);
825
826 sub mergedbreakwaters_anchor ($) {
827     my ($cl) = @_;
828     my $best_anchor;
829     foreach my $p (@{ $cl->{Parents} }) {
830         my ($panchor, $pbw) = keycommits $p->{CommitId},
831             undef,undef,undef,undef, 1;
832         $best_anchor = $panchor
833             if !defined $best_anchor
834             or is_fast_fwd $best_anchor, $panchor;
835     }
836     return $best_anchor;
837 }
838
839 sub keycommits ($;$$$$$) {
840     my ($head, $furniture, $unclean, $trouble, $fatal, $claimed_bw) = @_;
841     # => ($anchor, $breakwater)
842
843     # $unclean->("unclean-$tagsfx", $msg, $cl)
844     # $furniture->("unclean-$tagsfx", $msg, $cl)
845     # $dgitimport->("unclean-$tagsfx", $msg, $cl))
846     #   is callled for each situation or commit that
847     #   wouldn't be found in a laundered branch
848     # $furniture is for furniture commits such as might be found on an
849     #   interchange branch (pseudomerge, d/patches, changelog)
850     # $trouble is for things whnich prevent the return of
851     #   anchor and breakwater information; if that is ignored,
852     #   then keycommits returns (undef, undef) instead.
853     # $fatal is for unprocessable commits, and should normally cause
854     #    a failure.  If ignored, agaion, (undef, undef) is returned.
855     #
856     # If $claimed_bw, this is supposed to be a breakwater commit.
857     #
858     # If a callback is undef, fail is called instead.
859     # If a callback is defined but false, the situation is ignored.
860     # Callbacks may say:
861     #   no warnings qw(exiting); last;
862     # if the answer is no longer wanted.
863
864     my ($anchor, $breakwater);
865     $breakwater = $head if $claimed_bw;
866     my $clogonly;
867     my $cl;
868     my $found_pm;
869     $fatal //= sub { fail $_[1]; };
870     my $x = sub {
871         my ($cb, $tagsfx, $mainwhy, $xwhy) = @_;
872         my $why = $mainwhy.$xwhy;
873         my $m = "branch needs laundering (run git-debrebase): $why";
874         fail $m unless defined $cb;
875         return unless $cb;
876         $cb->("unclean-$tagsfx", $why, $cl, $mainwhy);
877     };
878     my $found_anchor = sub {
879         ($anchor) = @_;
880         $breakwater //= $clogonly;
881         $breakwater //= $head;
882         no warnings qw(exiting);
883         last;
884     };
885     for (;;) {
886         $cl = classify $head;
887         my $ty = $cl->{Type};
888         if ($ty eq 'Packaging') {
889             $breakwater //= $clogonly;
890             $breakwater //= $head;
891         } elsif ($ty eq 'Changelog') {
892             # this is going to count as the tip of the breakwater
893             # only if it has no upstream stuff before it
894             $clogonly //= $head;
895         } elsif ($ty eq 'Anchor' or
896                  $ty eq 'TreatAsAnchor' or
897                  $ty eq 'BreakwaterStart') {
898             $found_anchor->($head);
899         } elsif ($ty eq 'Upstream') {
900             $x->($unclean, 'ordering',
901  "packaging change ($breakwater) follows upstream change"," (eg $head)")
902                 if defined $breakwater;
903             $clogonly = undef;
904             $breakwater = undef;
905         } elsif ($ty eq 'Mixed') {
906             $x->($unclean, 'mixed',
907                  "found mixed upstream/packaging commit"," ($head)");
908             $clogonly = undef;
909             $breakwater = undef;
910         } elsif ($ty eq 'Pseudomerge' or
911                  $ty eq 'AddPatches') {
912             my $found_pm = 1;
913             $x->($furniture, (lc $ty),
914                  "found interchange bureaucracy commit ($ty)"," ($head)");
915         } elsif ($ty eq 'DgitImportUnpatched') {
916             if ($found_pm) {
917                 $x->($trouble, 'dgitimport',
918                      "found dgit dsc import"," ($head)");
919                 return (undef,undef);
920             } else {
921                 $x->($fatal, 'unprocessable',
922                      "found bare dgit dsc import with no prior history",
923                      " ($head)");
924                 return (undef,undef);
925             }
926         } elsif ($ty eq 'VanillaMerge') {
927             $x->($trouble, 'vanillamerge',
928                  "found vanilla merge"," ($head)");
929             return (undef,undef);
930         } elsif ($ty eq 'MergedBreakwaters') {
931             $found_anchor->(mergedbreakwaters_anchor $cl);
932         } else {
933             $x->($fatal, 'unprocessable',
934                  "found unprocessable commit, cannot cope: $cl->{Why}",
935                  " ($head)");
936             return (undef,undef);
937         }
938         $head = $cl->{Parents}[0]{CommitId};
939     }
940     return ($anchor, $breakwater);
941 }
942
943 sub walk ($;$$$);
944 sub walk ($;$$$) {
945     my ($input,
946         $nogenerate,$report, $report_lprefix) = @_;
947     # => ($tip, $breakwater_tip, $last_anchor)
948     # (or nothing, if $nogenerate)
949
950     printdebug "*** WALK $input ".($nogenerate//0)." ".($report//'-')."\n";
951     $report_lprefix //= '';
952
953     # go through commits backwards
954     # we generate two lists of commits to apply:
955     # breakwater branch and upstream patches
956     my (@brw_cl, @upp_cl, @processed);
957     my %found;
958     my $upp_limit;
959     my @pseudomerges;
960
961     my $cl;
962     my $xmsg = sub {
963         my ($prose, $info) = @_;
964         my $ms = $cl->{Msg};
965         chomp $ms;
966         $info //= '';
967         $ms .= "\n\n[git-debrebase$info: $prose]\n";
968         return (Msg => $ms);
969     };
970     my $rewrite_from_here = sub {
971         my ($cl) = @_;
972         my $sp_cl = { SpecialMethod => 'StartRewrite' };
973         push @$cl, $sp_cl;
974         push @processed, $sp_cl;
975     };
976     my $cur = $input;
977
978     my $prdelim = "";
979     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
980
981     my $prline = sub {
982         return unless $report;
983         print $report $prdelim, $report_lprefix, @_;
984         $prdelim = "\n";
985     };
986
987     my $bomb = sub { # usage: return $bomb->();
988         print $report " Unprocessable" if $report;
989         print $report " ($cl->{Why})" if $report && defined $cl->{Why};
990         $prprdelim->();
991         if ($nogenerate) {
992             return (undef,undef);
993         }
994         fail "found unprocessable commit, cannot cope".
995             (defined $cl->{Why} ? "; $cl->{Why}:": ':').
996             " (commit $cur) (d.".
997             (join ' ', map { sprintf "%#x", $_->{Differs} }
998              @{ $cl->{Parents} }).
999                  ")";
1000     };
1001
1002     my $build;
1003     my $breakwater;
1004
1005     my $build_start = sub {
1006         my ($msg, $parent) = @_;
1007         $prline->(" $msg");
1008         $build = $parent;
1009         no warnings qw(exiting); last;
1010     };
1011
1012     my $nomerge = sub {
1013         fail "something useful about failed merge attempt @_ xxx".Dumper($cl);
1014     };
1015
1016     my $last_anchor;
1017
1018     for (;;) {
1019         $cl = classify $cur;
1020         my $ty = $cl->{Type};
1021         my $st = $cl->{SubType};
1022         $prline->("$cl->{CommitId} $cl->{Type}");
1023         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
1024         push @processed, $cl;
1025         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
1026         if ($ty eq 'AddPatches') {
1027             $cur = $p0;
1028             $rewrite_from_here->(\@upp_cl);
1029             next;
1030         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
1031             push @brw_cl, $cl;
1032             $cur = $p0;
1033             next;
1034         } elsif ($ty eq 'BreakwaterStart') {
1035             $last_anchor = $cur;
1036             $build_start->('FirstPackaging', $cur);
1037         } elsif ($ty eq 'Upstream') {
1038             push @upp_cl, $cl;
1039             $cur = $p0;
1040             next;
1041         } elsif ($ty eq 'Mixed') {
1042             my $queue = sub {
1043                 my ($q, $wh) = @_;
1044                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
1045                 push @$q, $cls;
1046             };
1047             $queue->(\@brw_cl, "debian");
1048             $queue->(\@upp_cl, "upstream");
1049             $rewrite_from_here->(\@brw_cl);
1050             $cur = $p0;
1051             next;
1052         } elsif ($ty eq 'Pseudomerge') {
1053             my $contrib = $cl->{Contributor}{CommitId};
1054             print $report " Contributor=$contrib" if $report;
1055             push @pseudomerges, $cl;
1056             $rewrite_from_here->(\@upp_cl);
1057             $cur = $contrib;
1058             next;
1059         } elsif ($ty eq 'Anchor' or $ty eq 'TreatAsAnchor') {
1060             $last_anchor = $cur;
1061             $build_start->("Anchor", $cur);
1062         } elsif ($ty eq 'DgitImportUnpatched') {
1063             my $pm = $pseudomerges[-1];
1064             if (defined $pm) {
1065                 # To an extent, this is heuristic.  Imports don't have
1066                 # a useful history of the debian/ branch.  We assume
1067                 # that the first pseudomerge after an import has a
1068                 # useful history of debian/, and ignore the histories
1069                 # from later pseudomerges.  Often the first pseudomerge
1070                 # will be the dgit import of the upload to the actual
1071                 # suite intended by the non-dgit NMUer, and later
1072                 # pseudomerges may represent in-archive copies.
1073                 my $ovwrs = $pm->{Overwritten};
1074                 printf $report " PM=%s \@Overwr:%d",
1075                     $pm->{CommitId}, (scalar @$ovwrs)
1076                     if $report;
1077                 if (@$ovwrs != 1) {
1078                     printdebug "*** WALK BOMB DgitImportUnpatched\n";
1079                     return $bomb->();
1080                 }
1081                 my $ovwr = $ovwrs->[0]{CommitId};
1082                 printf $report " Overwr=%s", $ovwr if $report;
1083                 # This import has a tree which is just like a
1084                 # breakwater tree, but it has the wrong history.  It
1085                 # ought to have the previous breakwater (which the
1086                 # pseudomerge overwrote) as an ancestor.  That will
1087                 # make the history of the debian/ files correct.  As
1088                 # for the upstream version: either it's the same as
1089                 # was ovewritten (ie, same as the previous
1090                 # breakwater), in which case that history is precisely
1091                 # right; or, otherwise, it was a non-gitish upload of a
1092                 # new upstream version.  We can tell these apart by
1093                 # looking at the tree of the supposed upstream.
1094                 push @brw_cl, {
1095                     %$cl,
1096                     SpecialMethod => 'DgitImportDebianUpdate',
1097                     $xmsg->("convert dgit import: debian changes")
1098                 }, {
1099                     %$cl,
1100                     SpecialMethod => 'DgitImportUpstreamUpdate',
1101                     $xmsg->("convert dgit import: upstream update",
1102                             " anchor")
1103                 };
1104                 $prline->(" Import");
1105                 $rewrite_from_here->(\@brw_cl);
1106                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
1107                 $cur = $ovwr;
1108                 next;
1109             } else {
1110                 # Everything is from this import.  This kind of import
1111                 # is already nearly in valid breakwater format, with the
1112                 # patches as commits.  Unfortunately it contains
1113                 # debian/patches/.
1114                 printdebug "*** WALK BOMB bare dgit import\n";
1115                 $cl->{Why} = "bare dgit dsc import";
1116                 return $bomb->();
1117             }
1118             die "$ty ?";
1119         } elsif ($ty eq 'VanillaMerge' or $ty eq 'MergedBreakwaters') {
1120             # User may have merged unstitched branch(es).  We will
1121             # have now lost what ffq-prev was then (since the later
1122             # pseudomerge may introduce further changes).  The effect
1123             # of resolving such a merge is that we may have to go back
1124             # further in history to find a merge base, since the one
1125             # which was reachable via ffq-prev is no longer findable.
1126             # This is suboptimal, but if it all works we'll have done
1127             # the right thing.
1128             # xxx we should warn the user in the docs about this
1129
1130             my $ok=1;
1131             my $best_anchor;
1132             # We expect to find a dominating anchor amongst the
1133             # inputs' anchors.  That will be the new anchor.
1134             #
1135             # More complicated is finding a merge base for the
1136             # breakwaters.  We need a merge base that is a breakwater
1137             # commit.  The ancestors of breakwater commits are more
1138             # breakwater commits and possibly upstream commits and the
1139             # ancestors of those upstream.  Upstreams might have
1140             # arbitrary ancestors.  But any upstream commit U is
1141             # either included in both anchors, in which case the
1142             # earlier anchor is a better merge base than any of U's
1143             # ancestors; or U is not included in the older anchor, in
1144             # which case U is not an ancestor of the vanilla merge at
1145             # all.  So no upstream commit, nor any ancestor thereof,
1146             # is a best merge base.  As for non-breakwater Debian
1147             # commits: these are never ancestors of any breakwater.
1148             #
1149             # So any best merge base as found by git-merge-base
1150             # is a suitable breakwater anchor.  Usually there will
1151             # be only one.
1152
1153             printdebug "*** MERGE\n";
1154
1155             # xxx avoid calling walk without nogenerate when
1156             # we have a MergedBreakwater; instead call keycommits ?
1157
1158             my @bwbcmd = (@git, qw(merge-base));
1159             my @ibcmd = (@git, qw(merge-base --all));
1160             my $might_be_in_bw = 1;
1161
1162             my $ps = $cl->{Parents};
1163
1164             foreach my $p (@$ps) {
1165                 $prline->(" VanillaMerge ".$p->{Ix});
1166                 $prprdelim->();
1167                 my ($ptip, $pbw, $panchor) =
1168                     walk $p->{CommitId}, 0, $report,
1169                          $report_lprefix.'  ';
1170                 $p->{Laundered} = $p->{SeriesTip} = $ptip;
1171                 $p->{Breakwater} = $p->{SeriesBase} = $pbw;
1172                 $p->{Anchor} = $panchor;
1173
1174                 $best_anchor = $panchor if
1175                     !defined $best_anchor or
1176                     is_fast_fwd $best_anchor, $panchor;
1177
1178                 printdebug " MERGE BA best=".($best_anchor//'-').
1179                     " p=$panchor\n";
1180             }
1181
1182             foreach my $p (@$ps) {
1183                 $prline->(" VanillaMerge ".$p->{Ix});
1184                 if (!is_fast_fwd $p->{Anchor}, $best_anchor) {
1185                     $nomerge->('DivergentAnchor');
1186                 } elsif ($p->{Anchor} eq $best_anchor) {
1187                     print $report " SameAnchor" if $report;
1188                 } else {
1189                     print $report " SupersededAnchor" if $report;
1190                 }
1191                 if ($p->{Breakwater} eq $p->{CommitId}) {
1192                     # this parent commit was its own breakwater,
1193                     # ie it is part of the breakwater
1194                     print $report " Breakwater" if $report;
1195                 } else {
1196                     $might_be_in_bw = 0;
1197                 }
1198                 push @bwbcmd, $p->{Breakwater};
1199                 push @ibcmd, $p->{CommitId};
1200             }
1201
1202             if ($ok && $might_be_in_bw) {
1203                 $prline->(" VanillaMerge MergedBreakwaters");
1204                 $last_anchor = $best_anchor;
1205                 $build_start->('MergedBreakwaters', $cur);
1206             }
1207
1208             $nomerge->("alleged merged-breakwater is not a breakwater")
1209                 unless $ty eq 'VanillaMerge';
1210
1211             my $bwb = cmdoutput @bwbcmd;
1212
1213             # OK, now we have a breakwater base, but we need the merge
1214             # base for the interchange branch because we need the delta
1215             # queue.
1216             #
1217             # This a the best merge base of our inputs which has the
1218             # breakwater merge base as an ancestor.
1219
1220             my @ibs =
1221                 grep { is_fast_fwd $bwb, $_ }
1222                 grep /./,
1223                 split /\n/,
1224                 cmdoutput @ibcmd;
1225             my ($ib) = @ibs
1226                 or $nomerge->("no suitable interchange merge base");
1227
1228             $prline->("  VanillaMerge Base");
1229             $prprdelim->();
1230             my ($btip, $bbw, $banchor) =
1231                 walk $ib, 0, $report, $report_lprefix.'  ';
1232
1233             my $ibinfo = { SeriesTip => $btip,
1234                            SeriesBase => $bbw,
1235                            Anchor => $banchor };
1236             $bbw eq $bwb
1237                 or $nomerge->("interchange merge-base ($ib)'s".
1238                               " breakwater ($bbw)".
1239                               " != breakwaters' merge-base ($bwb)");
1240             grep { $_->{Anchor} eq $ibinfo->{Anchor} } @$ps
1241                  or $nomerge->("interchange merge-base ($ib)'s".
1242                                " anchor ($ibinfo->{SeriesBase})".
1243                                " != any merge input's anchor (".
1244                                (join ' ', map { $_->{Anchor} } @$ps).
1245                                ")");
1246
1247
1248             $cl->{MergeInterchangeBaseInfo} = $ibinfo;
1249             $cl->{MergeBestAnchor} = $best_anchor;
1250             push @brw_cl, {
1251                 %$cl,
1252                 SpecialMethod => 'MergeCreateMergedBreakwaters',
1253                 $xmsg->('constructed from vanilla merge',
1254                         ' merged-breakwater'),
1255             };
1256             push @upp_cl, {
1257                 %$cl,
1258                 SpecialMethod => 'MergeMergeSeries',
1259             };
1260             $build_start->('MergeBreakwaters', $cur);
1261         } else {
1262             printdebug "*** WALK BOMB unrecognised\n";
1263             return $bomb->();
1264         }
1265     }
1266     $prprdelim->();
1267
1268     printdebug "*** WALK prep done cur=$cur".
1269         " brw $#brw_cl upp $#upp_cl proc $#processed pm $#pseudomerges\n";
1270
1271     return if $nogenerate;
1272
1273     # Now we build it back up again
1274
1275     fresh_workarea();
1276
1277     my $rewriting = 0;
1278
1279     $#upp_cl = $upp_limit if defined $upp_limit;
1280  
1281     my $committer_authline = calculate_committer_authline();
1282
1283     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
1284
1285     confess "internal error" unless $build eq (pop @processed)->{CommitId};
1286
1287     in_workarea sub {
1288         mkdir $rd or $!==EEXIST or die $!;
1289         my $current_method;
1290         runcmd @git, qw(read-tree), $build;
1291         foreach my $cl (qw(Debian), (reverse @brw_cl),
1292                         { SpecialMethod => 'RecordBreakwaterTip' },
1293                         qw(Upstream), (reverse @upp_cl)) {
1294             if (!ref $cl) {
1295                 $current_method = $cl;
1296                 next;
1297             }
1298             my $method = $cl->{SpecialMethod} // $current_method;
1299             my @parents = ($build);
1300             my $cltree = $cl->{CommitId};
1301             printdebug "WALK BUILD ".($cltree//'undef').
1302                 " $method (rewriting=$rewriting)\n";
1303             if ($method eq 'Debian') {
1304                 read_tree_debian($cltree);
1305             } elsif ($method eq 'Upstream') {
1306                 read_tree_upstream($cltree);
1307             } elsif ($method eq 'StartRewrite') {
1308                 $rewriting = 1;
1309                 next;
1310             } elsif ($method eq 'RecordBreakwaterTip') {
1311                 $breakwater = $build;
1312                 next;
1313             } elsif ($method eq 'DgitImportDebianUpdate') {
1314                 read_tree_debian($cltree);
1315             } elsif ($method eq 'DgitImportUpstreamUpdate') {
1316                 confess unless $rewriting;
1317                 my $differs = (get_differs $build, $cltree);
1318                 next unless $differs & D_UPS;
1319                 read_tree_upstream($cltree);
1320                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
1321             } elsif ($method eq 'MergeCreateMergedBreakwaters') {
1322                 print "Found a general merge, will try to tidy it up.\n";
1323                 $rewriting = 1;
1324                 read_tree_upstream($cl->{MergeBestAnchor});
1325                 read_tree_upstream($cl->{MergeBestAnchor});
1326                 read_tree_debian($cltree);
1327                 @parents = map { $_->{Breakwater} } @{ $cl->{Parents} };
1328             } elsif ($method eq 'MergeMergeSeries') {
1329                 print "Running merge resolution for $cl->{CommitId}...\n";
1330                 $build = merge_series
1331                     $build,
1332                     $cl->{MergeInterchangeBaseInfo},
1333                     @{ $cl->{Parents} };
1334                 $last_anchor = $cl->{MergeBestAnchor};
1335
1336                 # Check for mismerges:
1337                 my $check = sub {
1338                     my ($against, $allow, $what) = @_;
1339                     my $differs = get_differs $build, $against;
1340                     $nomerge->(sprintf
1341        "merge misresolved: %s are not the same (%s %s d.%#x)",
1342                                $what, $against, $build, $differs)
1343                         if $differs & ~($allow | D_PAT_ADD);
1344                 };
1345
1346                 # Breakwater changes which were in each side of the
1347                 # merge will have been incorporated into the
1348                 # MergeCreateMergedBreakwaters output.  Because the
1349                 # upstream series was rebased onto the new breakwater,
1350                 # so should all of the packaging changes which were in
1351                 # the input.
1352                 $check->($input, D_UPS, 'debian files');
1353
1354                 # Upstream files are merge_series, which ought to
1355                 # have been identical to the original merge.
1356                 $check->($cl->{CommitId}, DS_DEB, 'upstream files');
1357
1358                 print "Merge resolution successful.\n";
1359                 next;
1360             } else {
1361                 confess "$method ?";
1362             }
1363             if (!$rewriting) {
1364                 my $procd = (pop @processed) // 'UNDEF';
1365                 if ($cl ne $procd) {
1366                     $rewriting = 1;
1367                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
1368                 }
1369             }
1370             my $newtree = cmdoutput @git, qw(write-tree);
1371             my $ch = $cl->{Hdr};
1372             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
1373             $ch =~ s{^parent .*\n}{}mg;
1374             $ch =~ s{(?=^author)}{
1375                 join '', map { "parent $_\n" } @parents
1376             }me or confess "$ch ?";
1377             if ($rewriting) {
1378                 $ch =~ s{^committer .*$}{$committer_authline}m
1379                     or confess "$ch ?";
1380             }
1381             my $cf = "$rd/m$rewriting";
1382             open CD, ">", $cf or die $!;
1383             print CD $ch, "\n", $cl->{Msg} or die $!;
1384             close CD or die $!;
1385             my @cmd = (@git, qw(hash-object));
1386             push @cmd, qw(-w) if $rewriting;
1387             push @cmd, qw(-t commit), $cf;
1388             my $newcommit = cmdoutput @cmd;
1389             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
1390             $build = $newcommit;
1391             if (grep { $method eq $_ } qw(DgitImportUpstreamUpdate)) {
1392                 $last_anchor = $cur;
1393             }
1394         }
1395     };
1396
1397     my $final_check = get_differs $build, $input;
1398     die sprintf "internal error %#x %s %s", $final_check, $input, $build
1399         if $final_check & ~D_PAT_ADD;
1400
1401     my @r = ($build, $breakwater, $last_anchor);
1402     printdebug "*** WALK RETURN @r\n";
1403     return @r
1404 }
1405
1406 sub get_head () {
1407     git_check_unmodified();
1408     return git_rev_parse qw(HEAD);
1409 }
1410
1411 sub update_head ($$$) {
1412     my ($old, $new, $mrest) = @_;
1413     push @deferred_updates, "update HEAD $new $old";
1414     run_deferred_updates $mrest;
1415 }
1416
1417 sub update_head_checkout ($$$) {
1418     my ($old, $new, $mrest) = @_;
1419     update_head $old, $new, $mrest;
1420     runcmd @git, qw(reset --hard);
1421 }
1422
1423 sub update_head_postlaunder ($$$) {
1424     my ($old, $tip, $reflogmsg) = @_;
1425     return if $tip eq $old;
1426     print "git-debrebase: laundered (head was $old)\n";
1427     update_head $old, $tip, $reflogmsg;
1428     # no tree changes except debian/patches
1429     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
1430 }
1431
1432 sub currently_rebasing() {
1433     foreach (qw(rebase-merge rebase-apply)) {
1434         return 1 if stat_exists "$maindir_gitdir/$_";
1435     }
1436     return 0;
1437 }
1438
1439 sub bail_if_rebasing() {
1440     fail "you are in the middle of a git-rebase already"
1441         if currently_rebasing();
1442 }
1443
1444 sub do_launder_head ($) {
1445     my ($reflogmsg) = @_;
1446     my $old = get_head();
1447     record_ffq_auto();
1448     my ($tip,$breakwater) = walk $old;
1449     snags_maybe_bail();
1450     update_head_postlaunder $old, $tip, $reflogmsg;
1451     return ($tip,$breakwater);
1452 }
1453
1454 sub cmd_launder_v0 () {
1455     badusage "no arguments to launder-v0 allowed" if @ARGV;
1456     my $old = get_head();
1457     my ($tip,$breakwater,$last_anchor) = walk $old;
1458     update_head_postlaunder $old, $tip, 'launder';
1459     printf "# breakwater tip\n%s\n", $breakwater;
1460     printf "# working tip\n%s\n", $tip;
1461     printf "# last anchor\n%s\n", $last_anchor;
1462 }
1463
1464 sub defaultcmd_rebase () {
1465     push @ARGV, @{ $opt_defaultcmd_interactive // [] };
1466     my ($tip,$breakwater) = do_launder_head 'launder for rebase';
1467     runcmd @git, qw(rebase), @ARGV, $breakwater if @ARGV;
1468 }
1469
1470 sub cmd_analyse () {
1471     badusage "analyse does not support any options"
1472         if @ARGV and $ARGV[0] =~ m/^-/;
1473     badusage "too many arguments to analyse" if @ARGV>1;
1474     my ($old) = @ARGV;
1475     if (defined $old) {
1476         $old = git_rev_parse $old;
1477     } else {
1478         $old = git_rev_parse 'HEAD';
1479     }
1480     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
1481     STDOUT->error and die $!;
1482 }
1483
1484 sub ffq_prev_branchinfo () {
1485     my $current = git_get_symref();
1486     return gdr_ffq_prev_branchinfo($current);
1487 }
1488
1489 sub ffq_check ($;$$) {
1490     # calls $ff and/or $notff zero or more times
1491     # then returns either (status,message) where status is
1492     #    exists
1493     #    detached
1494     #    weird-symref
1495     #    notbranch
1496     # or (undef,undef, $ffq_prev,$gdrlast)
1497     # $ff and $notff are called like this:
1498     #   $ff->("message for stdout\n");
1499     #   $notff->('snag-name', $message);
1500     # normally $currentval should be HEAD
1501     my ($currentval, $ff, $notff) =@_;
1502
1503     $ff //= sub { print $_[0] or die $!; };
1504     $notff //= \&snag;
1505
1506     my ($status, $message, $current, $ffq_prev, $gdrlast)
1507         = ffq_prev_branchinfo();
1508     return ($status, $message) unless $status eq 'branch';
1509
1510     my $exists = git_get_ref $ffq_prev;
1511     return ('exists',"$ffq_prev already exists") if $exists;
1512
1513     return ('not-branch', 'HEAD symref is not to refs/heads/')
1514         unless $current =~ m{^refs/heads/};
1515     my $branch = $';
1516
1517     my @check_specs = split /\;/, (cfg "branch.$branch.ffq-ffrefs",1) // '*';
1518     my %checked;
1519
1520     printdebug "ffq check_specs @check_specs\n";
1521
1522     my $check = sub {
1523         my ($lrref, $desc) = @_;
1524         printdebug "ffq might check $lrref ($desc)\n";
1525         my $invert;
1526         for my $chk (@check_specs) {
1527             my $glob = $chk;
1528             $invert = $glob =~ s{^[!^]}{};
1529             last if fnmatch $glob, $lrref;
1530         }
1531         return if $invert;
1532         my $lrval = git_get_ref $lrref;
1533         return unless length $lrval;
1534
1535         if (is_fast_fwd $lrval, $currentval) {
1536             $ff->("OK, you are ahead of $lrref\n");
1537             $checked{$lrref} = 1;
1538         } elsif (is_fast_fwd $currentval, $lrval) {
1539             $checked{$lrref} = -1;
1540             $notff->('behind', "you are behind $lrref, divergence risk");
1541         } else {
1542             $checked{$lrref} = -1;
1543             $notff->('diverged', "you have diverged from $lrref");
1544         }
1545     };
1546
1547     my $merge = cfg "branch.$branch.merge",1;
1548     if (defined $merge and $merge =~ m{^refs/heads/}) {
1549         my $rhs = $';
1550         printdebug "ffq merge $rhs\n";
1551         my $check_remote = sub {
1552             my ($remote, $desc) = @_;
1553             printdebug "ffq check_remote ".($remote//'undef')." $desc\n";
1554             return unless defined $remote;
1555             $check->("refs/remotes/$remote/$rhs", $desc);
1556         };
1557         $check_remote->((scalar cfg "branch.$branch.remote",1),
1558                         'remote fetch/merge branch');
1559         $check_remote->((scalar cfg "branch.$branch.pushRemote",1) //
1560                         (scalar cfg "branch.$branch.pushDefault",1),
1561                         'remote push branch');
1562     }
1563     if ($branch =~ m{^dgit/}) {
1564         $check->("refs/remotes/dgit/$branch", 'remote dgit branch');
1565     } elsif ($branch =~ m{^master$}) {
1566         $check->("refs/remotes/dgit/dgit/sid", 'remote dgit branch for sid');
1567     }
1568     return (undef, undef, $ffq_prev, $gdrlast);
1569 }
1570
1571 sub record_ffq_prev_deferred () {
1572     # => ('status', "message")
1573     # 'status' may be
1574     #    deferred          message is undef
1575     #    exists
1576     #    detached
1577     #    weird-symref
1578     #    notbranch
1579     # if not ff from some branch we should be ff from, is an snag
1580     # if "deferred", will have added something about that to
1581     #   @deferred_update_messages, and also maybe printed (already)
1582     #   some messages about ff checks
1583     bail_if_rebasing();
1584     my $currentval = get_head();
1585
1586     my ($status,$message, $ffq_prev,$gdrlast) = ffq_check $currentval;
1587     return ($status,$message) if defined $status;
1588
1589     snags_maybe_bail();
1590
1591     push @deferred_updates, "update $ffq_prev $currentval $git_null_obj";
1592     push @deferred_updates, "delete $gdrlast";
1593     push @deferred_update_messages, "Recorded previous head for preservation";
1594     return ('deferred', undef);
1595 }
1596
1597 sub record_ffq_auto () {
1598     my ($status, $message) = record_ffq_prev_deferred();
1599     if ($status eq 'deferred' || $status eq 'exists') {
1600     } else {
1601         snag $status, "could not record ffq-prev: $message";
1602         snags_maybe_bail();
1603     }
1604 }
1605
1606 sub ffq_prev_info () {
1607     bail_if_rebasing();
1608     # => ($ffq_prev, $gdrlast, $ffq_prev_commitish)
1609     my ($status, $message, $current, $ffq_prev, $gdrlast)
1610         = ffq_prev_branchinfo();
1611     if ($status ne 'branch') {
1612         snag $status, "could not check ffq-prev: $message";
1613         snags_maybe_bail();
1614     }
1615     my $ffq_prev_commitish = $ffq_prev && git_get_ref $ffq_prev;
1616     return ($ffq_prev, $gdrlast, $ffq_prev_commitish);
1617 }
1618
1619 sub stitch ($$$$$) {
1620     my ($old_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose) = @_;
1621
1622     push @deferred_updates, "delete $ffq_prev $ffq_prev_commitish";
1623
1624     if (is_fast_fwd $old_head, $ffq_prev_commitish) {
1625         my $differs = get_differs $old_head, $ffq_prev_commitish;
1626         unless ($differs & ~D_PAT_ADD) {
1627             # ffq-prev is ahead of us, and the only tree changes it has
1628             # are possibly addition of things in debian/patches/.
1629             # Just wind forwards rather than making a pointless pseudomerge.
1630             push @deferred_updates,
1631                 "update $gdrlast $ffq_prev_commitish $git_null_obj";
1632             update_head_checkout $old_head, $ffq_prev_commitish,
1633                 "stitch (fast forward)";
1634             return;
1635         }
1636     }
1637     fresh_workarea();
1638     # We make pseudomerges with L as the contributing parent.
1639     # This makes git rev-list --first-parent work properly.
1640     my $new_head = make_commit [ $old_head, $ffq_prev ], [
1641         'Declare fast forward / record previous work',
1642         "[git-debrebase pseudomerge: $prose]",
1643     ];
1644     push @deferred_updates, "update $gdrlast $new_head $git_null_obj";
1645     update_head $old_head, $new_head, "stitch: $prose";
1646 }
1647
1648 sub do_stitch ($;$) {
1649     my ($prose, $unclean) = @_;
1650
1651     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
1652     if (!$ffq_prev_commitish) {
1653         fail "No ffq-prev to stitch." unless $opt_noop_ok;
1654         return;
1655     }
1656     my $dangling_head = get_head();
1657
1658     keycommits $dangling_head, $unclean,$unclean,$unclean;
1659     snags_maybe_bail();
1660
1661     stitch($dangling_head, $ffq_prev, $gdrlast, $ffq_prev_commitish, $prose);
1662 }
1663
1664 sub upstream_commitish_search ($$) {
1665     my ($upstream_version, $tried) = @_;
1666     # todo: at some point maybe use git-deborig to do this
1667     foreach my $tagpfx ('', 'v', 'upstream/') {
1668         my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
1669         my $new_upstream = git_get_ref "refs/tags/$tag";
1670         push @$tried, $tag;
1671         return $new_upstream if length $new_upstream;
1672     }
1673 }
1674
1675 sub resolve_upstream_version ($$) {
1676     my ($new_upstream, $upstream_version) = @_;
1677
1678     if (!defined $new_upstream) {
1679         my @tried;
1680         $new_upstream = upstream_commitish_search $upstream_version, \@tried;
1681         if (!length $new_upstream) {
1682             fail "Could not determine appropriate upstream commitish.\n".
1683                 " (Tried these tags: @tried)\n".
1684                 " Check version, and specify upstream commitish explicitly.";
1685         }
1686     }
1687     $new_upstream = git_rev_parse $new_upstream;
1688
1689     return $new_upstream;
1690 }
1691
1692 sub cmd_new_upstream () {
1693     # automatically and unconditionally launders before rebasing
1694     # if rebase --abort is used, laundering has still been done
1695
1696     my %pieces;
1697
1698     badusage "need NEW-VERSION [UPS-COMMITTISH]" unless @ARGV >= 1;
1699
1700     # parse args - low commitment
1701     my $spec_version = shift @ARGV;
1702     my $new_version = (new Dpkg::Version $spec_version, check => 1);
1703     fail "bad version number \`$spec_version'" unless defined $new_version;
1704     if ($new_version->is_native()) {
1705         $new_version = (new Dpkg::Version "$spec_version-1", check => 1);
1706     }
1707
1708     my $new_upstream = shift @ARGV;
1709     my $new_upstream_version = upstreamversion  $new_version;
1710     $new_upstream =
1711         resolve_upstream_version $new_upstream, $new_upstream_version;
1712
1713     record_ffq_auto();
1714
1715     my $piece = sub {
1716         my ($n, @x) = @_; # may be ''
1717         my $pc = $pieces{$n} //= {
1718             Name => $n,
1719             Desc => ($n ? "upstream piece \`$n'" : "upstream (main piece"),
1720         };
1721         while (my $k = shift @x) { $pc->{$k} = shift @x; }
1722         $pc;
1723     };
1724
1725     my @newpieces;
1726     my $newpiece = sub {
1727         my ($n, @x) = @_; # may be ''
1728         my $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
1729         push @newpieces, $pc;
1730     };
1731
1732     $newpiece->('',
1733         OldIx => 0,
1734         New => $new_upstream,
1735     );
1736     while (@ARGV && $ARGV[0] !~ m{^-}) {
1737         my $n = shift @ARGV;
1738
1739         badusage "for each EXTRA-UPS-NAME need EXTRA-UPS-COMMITISH"
1740             unless @ARGV && $ARGV[0] !~ m{^-};
1741
1742         my $c = git_rev_parse shift @ARGV;
1743         die unless $n =~ m/^$extra_orig_namepart_re$/;
1744         $newpiece->($n, New => $c);
1745     }
1746
1747     # now we need to investigate the branch this generates the
1748     # laundered version but we don't switch to it yet
1749     my $old_head = get_head();
1750     my ($old_laundered_tip,$old_bw,$old_anchor) = walk $old_head;
1751
1752     my $old_bw_cl = classify $old_bw;
1753     my $old_anchor_cl = classify $old_anchor;
1754     my $old_upstream;
1755     if (!$old_anchor_cl->{OrigParents}) {
1756         snag 'anchor-treated',
1757             'old anchor is recognised due to --anchor, cannot check upstream';
1758     } else {
1759         $old_upstream = parsecommit
1760             $old_anchor_cl->{OrigParents}[0]{CommitId};
1761         $piece->('', Old => $old_upstream->{CommitId});
1762     }
1763
1764     if ($old_upstream && $old_upstream->{Msg} =~ m{^\[git-debrebase }m) {
1765         if ($old_upstream->{Msg} =~
1766  m{^\[git-debrebase upstream-combine (\.(?: $extra_orig_namepart_re)+)\:.*\]$}m
1767            ) {
1768             my @oldpieces = (split / /, $1);
1769             my $old_n_parents = scalar @{ $old_upstream->{Parents} };
1770             if ($old_n_parents != @oldpieces &&
1771                 $old_n_parents != @oldpieces + 1) {
1772                 snag 'upstream-confusing', sprintf
1773                     "previous upstream combine %s".
1774                     " mentions %d pieces (each implying one parent)".
1775                     " but has %d parents".
1776                     " (one per piece plus maybe a previous combine)",
1777                     $old_upstream->{CommitId},
1778                     (scalar @oldpieces),
1779                     $old_n_parents;
1780             } elsif ($oldpieces[0] ne '.') {
1781                 snag 'upstream-confusing', sprintf
1782                     "previous upstream combine %s".
1783                     " first piece is not \`.'",
1784                     $oldpieces[0];
1785             } else {
1786                 $oldpieces[0] = '';
1787                 foreach my $i (0..$#oldpieces) {
1788                     my $n = $oldpieces[$i];
1789                     my $hat = 1 + $i + ($old_n_parents - @oldpieces);
1790                     $piece->($n, Old => $old_upstream->{CommitId}.'^'.$hat);
1791                 }
1792             }
1793         } else {
1794             snag 'upstream-confusing',
1795                 "previous upstream $old_upstream->{CommitId} is from".
1796                " git-debrebase but not an \`upstream-combine' commit";
1797         }
1798     }
1799
1800     foreach my $pc (values %pieces) {
1801         if (!$old_upstream) {
1802             # we have complained already
1803         } elsif (!$pc->{Old}) {
1804             snag 'upstream-new-piece',
1805                 "introducing upstream piece \`$pc->{Name}'";
1806         } elsif (!$pc->{New}) {
1807             snag 'upstream-rm-piece',
1808                 "dropping upstream piece \`$pc->{Name}'";
1809         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
1810             snag 'upstream-not-ff',
1811                 "not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}";
1812         }
1813     }
1814
1815     printdebug "%pieces = ", (dd \%pieces), "\n";
1816     printdebug "\@newpieces = ", (dd \@newpieces), "\n";
1817
1818     snags_maybe_bail();
1819
1820     my $new_bw;
1821
1822     fresh_workarea();
1823     in_workarea sub {
1824         my @upstream_merge_parents;
1825
1826         if (!any_snags()) {
1827             push @upstream_merge_parents, $old_upstream->{CommitId};
1828         }
1829
1830         foreach my $pc (@newpieces) { # always has '' first
1831             if ($pc->{Name}) {
1832                 read_tree_subdir $pc->{Name}, $pc->{New};
1833             } else {
1834                 runcmd @git, qw(read-tree), $pc->{New};
1835             }
1836             push @upstream_merge_parents, $pc->{New};
1837         }
1838
1839         # index now contains the new upstream
1840
1841         if (@newpieces > 1) {
1842             # need to make the upstream subtree merge commit
1843             $new_upstream = make_commit \@upstream_merge_parents,
1844                 [ "Combine upstreams for $new_upstream_version",
1845  ("[git-debrebase upstream-combine . ".
1846  (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
1847  ": new upstream]"),
1848                 ];
1849         }
1850
1851         # $new_upstream is either the single upstream commit, or the
1852         # combined commit we just made.  Either way it will be the
1853         # "upstream" parent of the anchor merge.
1854
1855         read_tree_subdir 'debian', "$old_bw:debian";
1856
1857         # index now contains the anchor merge contents
1858         $new_bw = make_commit [ $old_bw, $new_upstream ],
1859             [ "Update to upstream $new_upstream_version",
1860  "[git-debrebase anchor: new upstream $new_upstream_version, merge]",
1861             ];
1862
1863         my $clogsignoff = cmdoutput qw(git show),
1864             '--pretty=format:%an <%ae>  %aD',
1865             $new_bw;
1866
1867         # Now we have to add a changelog stanza so the Debian version
1868         # is right.
1869         die if unlink "debian";
1870         die $! unless $!==ENOENT or $!==ENOTEMPTY;
1871         unlink "debian/changelog" or $!==ENOENT or die $!;
1872         mkdir "debian" or die $!;
1873         open CN, ">", "debian/changelog" or die $!;
1874         my $oldclog = git_cat_file ":debian/changelog";
1875         $oldclog =~ m/^($package_re) \(\S+\) / or
1876             fail "cannot parse old changelog to get package name";
1877         my $p = $1;
1878         print CN <<END, $oldclog or die $!;
1879 $p ($new_version) UNRELEASED; urgency=medium
1880
1881   * Update to new upstream version $new_upstream_version.
1882
1883  -- $clogsignoff
1884
1885 END
1886         close CN or die $!;
1887         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
1888
1889         # Now we have the final new breakwater branch in the index
1890         $new_bw = make_commit [ $new_bw ],
1891             [ "Update changelog for new upstream $new_upstream_version",
1892               "[git-debrebase: new upstream $new_upstream_version, changelog]",
1893             ];
1894     };
1895
1896     # we have constructed the new breakwater. we now need to commit to
1897     # the laundering output, because git-rebase can't easily be made
1898     # to make a replay list which is based on some other branch
1899
1900     update_head_postlaunder $old_head, $old_laundered_tip,
1901         'launder for new upstream';
1902
1903     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw, @ARGV);
1904     local $ENV{GIT_REFLOG_ACTION} = git_reflog_action_msg
1905         "debrebase new-upstream $new_version: rebase";
1906     runcmd @cmd;
1907     # now it's for the user to sort out
1908 }
1909
1910 sub cmd_record_ffq_prev () {
1911     badusage "no arguments allowed" if @ARGV;
1912     my ($status, $msg) = record_ffq_prev_deferred();
1913     if ($status eq 'exists' && $opt_noop_ok) {
1914         print "Previous head already recorded\n" or die $!;
1915     } elsif ($status eq 'deferred') {
1916         run_deferred_updates 'record-ffq-prev';
1917     } else {
1918         fail "Could not preserve: $msg";
1919     }
1920 }
1921
1922 sub cmd_anchor () {
1923     badusage "no arguments allowed" if @ARGV;
1924     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1925     print "$bw\n" or die $!;
1926 }
1927
1928 sub cmd_breakwater () {
1929     badusage "no arguments allowed" if @ARGV;
1930     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'), 0,0;
1931     print "$bw\n" or die $!;
1932 }
1933
1934 sub cmd_status () {
1935     badusage "no arguments allowed" if @ARGV;
1936
1937     # todo: gdr status should print divergence info
1938     # todo: gdr status should print upstream component(s) info
1939     # todo: gdr should leave/maintain some refs with this kind of info ?
1940
1941     my $oldest = { Badness => 0 };
1942     my $newest;
1943     my $note = sub {
1944         my ($badness, $ourmsg, $snagname, $dummy, $cl, $kcmsg) = @_;
1945         if ($oldest->{Badness} < $badness) {
1946             $oldest = $newest = undef;
1947         }
1948         $oldest = {
1949                    Badness => $badness,
1950                    CommitId => $cl->{CommitId},
1951                    OurMsg => $ourmsg,
1952                    KcMsg => $kcmsg,
1953                   };
1954         $newest //= $oldest;
1955     };
1956     my ($anchor, $bw) = keycommits +(git_rev_parse 'HEAD'),
1957         sub { $note->(1, 'branch contains furniture (not laundered)', @_); },
1958         sub { $note->(2, 'branch is unlaundered', @_); },
1959         sub { $note->(3, 'branch needs laundering', @_); },
1960         sub { $note->(4, 'branch not in git-debrebase form', @_); };
1961
1962     my $prcommitinfo = sub {
1963         my ($cid) = @_;
1964         flush STDOUT or die $!;
1965         runcmd @git, qw(--no-pager log -n1),
1966             '--pretty=format:    %h %s%n',
1967             $cid;
1968     };
1969
1970     print "current branch contents, in git-debrebase terms:\n";
1971     if (!$oldest->{Badness}) {
1972         print "  branch is laundered\n";
1973     } else {
1974         print "  $oldest->{OurMsg}\n";
1975         my $printed = '';
1976         foreach my $info ($oldest, $newest) {
1977             my $cid = $info->{CommitId};
1978             next if $cid eq $printed;
1979             $printed = $cid;
1980             print "  $info->{KcMsg}\n";
1981             $prcommitinfo->($cid);
1982         }
1983     }
1984
1985     my $prab = sub {
1986         my ($cid, $what) = @_;
1987         if (!defined $cid) {
1988             print "  $what is not well-defined\n";
1989         } else {
1990             print "  $what\n";
1991             $prcommitinfo->($cid);
1992         }
1993     };
1994     print "key git-debrebase commits:\n";
1995     $prab->($anchor, 'anchor');
1996     $prab->($bw, 'breakwater');
1997
1998     my ($ffqstatus, $ffq_msg, $current, $ffq_prev, $gdrlast) =
1999         ffq_prev_branchinfo();
2000
2001     print "branch and ref status, in git-debrebase terms:\n";
2002     if ($ffq_msg) {
2003         print "  $ffq_msg\n";
2004     } else {
2005         $ffq_prev = git_get_ref $ffq_prev;
2006         $gdrlast = git_get_ref $gdrlast;
2007         if ($ffq_prev) {
2008             print "  unstitched; previous tip was:\n";
2009             $prcommitinfo->($ffq_prev);
2010         } elsif (!$gdrlast) {
2011             print "  stitched? (no record of git-debrebase work)\n";
2012         } elsif (is_fast_fwd $gdrlast, 'HEAD') {
2013             print "  stitched\n";
2014         } else {
2015             print "  not git-debrebase (diverged since last stitch)\n"
2016         }
2017     }
2018     print "you are currently rebasing\n" if currently_rebasing();
2019 }
2020
2021 sub cmd_stitch () {
2022     my $prose = 'stitch';
2023     getoptions("stitch",
2024                'prose=s', \$prose);
2025     badusage "no arguments allowed" if @ARGV;
2026     do_stitch $prose, 0;
2027 }
2028 sub cmd_prepush () { cmd_stitch(); }
2029
2030 sub cmd_quick () {
2031     badusage "no arguments allowed" if @ARGV;
2032     do_launder_head 'launder for git-debrebase quick';
2033     do_stitch 'quick';
2034 }
2035
2036 sub cmd_conclude () {
2037     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2038     if (!$ffq_prev_commitish) {
2039         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2040         return;
2041     }
2042     my $dangling_head = get_head();
2043     
2044     badusage "no arguments allowed" if @ARGV;
2045     do_launder_head 'launder for git-debrebase quick';
2046     do_stitch 'quick';
2047 }
2048
2049 sub cmd_scrap () {
2050     if (currently_rebasing()) {
2051         runcmd @git, qw(rebase --abort);
2052     }
2053     my ($ffq_prev, $gdrlast, $ffq_prev_commitish) = ffq_prev_info();
2054     if (!$ffq_prev_commitish) {
2055         fail "No ongoing git-debrebase session." unless $opt_noop_ok;
2056         finish 0;
2057     }
2058     my $scrapping_head = get_head();
2059     badusage "no arguments allowed" if @ARGV;
2060     push @deferred_updates,
2061         "update $gdrlast $ffq_prev_commitish $git_null_obj",
2062         "update $ffq_prev $git_null_obj $ffq_prev_commitish";
2063     snags_maybe_bail();
2064     update_head_checkout $scrapping_head, $ffq_prev_commitish, "scrap";
2065 }
2066
2067 sub make_patches_staged ($) {
2068     my ($head) = @_;
2069     # Produces the patches that would result from $head if it were
2070     # laundered.
2071     my ($secret_head, $secret_bw, $last_anchor) = walk $head;
2072     fresh_workarea();
2073     in_workarea sub {
2074         gbp_pq_export 'bw', $secret_bw, $secret_head;
2075     };
2076 }
2077
2078 sub make_patches ($) {
2079     my ($head) = @_;
2080     keycommits $head, 0, \&snag;
2081     make_patches_staged $head;
2082     my $out;
2083     in_workarea sub {
2084         my $ptree = cmdoutput @git, qw(write-tree --prefix=debian/patches/);
2085         runcmd @git, qw(read-tree), $head;
2086         read_tree_subdir 'debian/patches', $ptree;
2087         $out = make_commit [$head], [
2088             'Commit patch queue (exported by git-debrebase)',
2089             '[git-debrebase: export and commit patches]',
2090         ];
2091     };
2092     return $out;
2093 }
2094
2095 sub cmd_make_patches () {
2096     my $opt_quiet_would_amend;
2097     getoptions("make-patches",
2098                'quiet-would-amend!', \$opt_quiet_would_amend);
2099     badusage "no arguments allowed" if @ARGV;
2100     bail_if_rebasing();
2101     my $old_head = get_head();
2102     my $new = make_patches $old_head;
2103     my $d = get_differs $old_head, $new;
2104     if ($d == 0) {
2105         fail "No (more) patches to export." unless $opt_noop_ok;
2106         return;
2107     } elsif ($d == D_PAT_ADD) {
2108         snags_maybe_bail();
2109         update_head_checkout $old_head, $new, 'make-patches';
2110     } else {
2111         print STDERR failmsg
2112             "Patch export produced patch amendments".
2113             " (abandoned output commit $new).".
2114             "  Try laundering first."
2115             unless $opt_quiet_would_amend;
2116         finish 7;
2117     }
2118 }
2119
2120 sub cmd_convert_from_gbp () {
2121     badusage "want only 1 optional argument, the upstream git commitish"
2122         unless @ARGV<=1;
2123
2124     my $clogp = parsechangelog();
2125     my $version = $clogp->{'Version'}
2126         // die "missing Version from changelog";
2127
2128     my ($upstream_spec) = @ARGV;
2129
2130     my $upstream_version = upstreamversion $version;
2131     my $upstream =
2132         resolve_upstream_version($upstream_spec, $upstream_version);
2133
2134     my $old_head = get_head();
2135
2136     my $upsdiff = get_differs $upstream, $old_head;
2137     if ($upsdiff & D_UPS) {
2138         runcmd @git, qw(--no-pager diff --stat),
2139             $upstream, $old_head,
2140             qw( -- :!/debian :/);
2141         fail <<END;
2142 upstream ($upstream_spec) and HEAD are not
2143 identical in upstream files.  See diffstat above, or run
2144   git diff $upstream_spec HEAD -- :!/debian :/
2145 END
2146     }
2147
2148     if (!is_fast_fwd $upstream, $old_head) {
2149         snag 'upstream-not-ancestor',
2150             "upstream ($upstream) is not an ancestor of HEAD";
2151     } else {
2152         my $wrong = cmdoutput
2153             (@git, qw(rev-list --ancestry-path), "$upstream..HEAD",
2154              qw(-- :/ :!/debian));
2155         if (length $wrong) {
2156             snag 'unexpected-upstream-changes',
2157                 "history between upstream ($upstream) and HEAD contains direct changes to upstream files - are you sure this is a gbp (patches-unapplied) branch?";
2158             print STDERR "list expected changes with:  git log --stat --ancestry-path $upstream_spec..HEAD -- :/ ':!/debian'\n";
2159         }
2160     }
2161
2162     if ((git_cat_file "$upstream:debian")[0] ne 'missing') {
2163         snag 'upstream-has-debian',
2164             "upstream ($upstream) contains debian/ directory";
2165     }
2166
2167     my $previous_dgit_view = eval {
2168         my @clogcmd = qw(dpkg-parsechangelog --format rfc822 -n2);
2169         my ($lvsn, $suite);
2170         parsechangelog_loop \@clogcmd, 'debian/changelog', sub {
2171             my ($stz, $desc) = @_;
2172             no warnings qw(exiting);
2173             printdebug 'CHANGELOG ', Dumper($desc, $stz);
2174             next unless $stz->{Date};
2175             next unless $stz->{Distribution} ne 'UNRELEASED';
2176             $lvsn = $stz->{Version};
2177             $suite = $stz->{Distribution};
2178             last;
2179         };
2180         die "neither of the first two changelog entries are released\n"
2181             unless defined $lvsn;
2182         print "last finished-looking changelog entry: ($lvsn) $suite\n";
2183         my $mtag_pat = debiantag_maintview $lvsn, '*';
2184         my $mtag = cmdoutput @git, qw(describe --always --abbrev=0 --match),
2185             $mtag_pat;
2186         die "could not find suitable maintainer view tag $mtag_pat\n"
2187             unless $mtag_pat =~ m{/};
2188         is_fast_fwd $mtag, 'HEAD' or
2189             die "HEAD is not FF from maintainer tag $mtag!";
2190         my $dtag = "archive/$mtag";
2191         is_fast_fwd $mtag, $dtag or
2192             die "dgit view tag $dtag is not FF from maintainer tag $mtag";
2193         print "will stitch in dgit view, $dtag\n";
2194         git_rev_parse $dtag;
2195     };
2196     if (!$previous_dgit_view) {
2197         $@ =~ s/^\n+//;
2198         chomp $@;
2199         print STDERR "cannot stitch in dgit view: $@\n";
2200     }
2201
2202     snags_maybe_bail_early();
2203
2204     my $work;
2205
2206     fresh_workarea();
2207     in_workarea sub {
2208         runcmd @git, qw(checkout -q -b gdr-internal), $old_head;
2209         # make a branch out of the patch queue - we'll want this in a mo
2210         runcmd qw(gbp pq import);
2211         # strip the patches out
2212         runcmd @git, qw(checkout -q gdr-internal~0);
2213         rm_subdir_cached 'debian/patches';
2214         $work = make_commit ['HEAD'], [
2215  'git-debrebase convert-from-gbp: drop patches from tree',
2216  'Delete debian/patches, as part of converting to git-debrebase format.',
2217  '[git-debrebase convert-from-gbp: drop patches from tree]'
2218                               ];
2219         # make the anchor merge
2220         # the tree is already exactly right
2221         $work = make_commit [$work, $upstream], [
2222  'git-debrebase import: declare upstream',
2223  'First breakwater merge.',
2224  '[git-debrebase anchor: declare upstream]'
2225                               ];
2226
2227         # rebase the patch queue onto the new breakwater
2228         runcmd @git, qw(reset --quiet --hard patch-queue/gdr-internal);
2229         runcmd @git, qw(rebase --quiet --onto), $work, qw(gdr-internal);
2230         $work = git_rev_parse 'HEAD';
2231
2232         if ($previous_dgit_view) {
2233             $work = make_commit [$work, $previous_dgit_view], [
2234  'git-debrebase import: declare ff from dgit archive view',
2235  '[git-debrebase pseudomerge: import-from-gbp]',
2236             ];
2237         }
2238     };
2239
2240     ffq_check $work;
2241     snags_maybe_bail();
2242     update_head_checkout $old_head, $work, 'convert-from-gbp';
2243 }
2244
2245 sub cmd_convert_to_gbp () {
2246     badusage "no arguments allowed" if @ARGV;
2247     my $head = get_head();
2248     my (undef, undef, undef, $ffq, $gdrlast) = ffq_prev_branchinfo();
2249     keycommits $head, 0;
2250     my $out;
2251     make_patches_staged $head;
2252     in_workarea sub {
2253         $out = make_commit ['HEAD'], [
2254             'Commit patch queue (converted from git-debrebase format)',
2255             '[git-debrebase convert-to-gbp: commit patches]',
2256         ];
2257     };
2258     if (defined $ffq) {
2259         push @deferred_updates, "delete $ffq";
2260         push @deferred_updates, "delete $gdrlast";
2261     }
2262     snags_maybe_bail();
2263     update_head_checkout $head, $out, "convert to gbp (v0)";
2264     print <<END or die $!;
2265 git-debrebase: converted to git-buildpackage branch format
2266 git-debrebase: WARNING: do not now run "git-debrebase" any more
2267 git-debrebase: WARNING: doing so would drop all upstream patches!
2268 END
2269 }
2270
2271 sub cmd_convert_from_dgit_view () { 
2272     my $clogp = parsechangelog();
2273
2274     my $bpd = (cfg 'dgit.default.build-products-dir',1) // '..';
2275     my $do_origs = 1;
2276     my $do_tags = 1;
2277     my $always = 0;
2278     my $diagnose = 0;
2279
2280     getoptions("convert-from-dgit-view",
2281                'diagnose!', \$diagnose,
2282                'build-products-dir:s', \$bpd,
2283                'origs!', \$do_origs,
2284                'tags!', \$do_tags,
2285                'always-convert-anyway!', \$always);
2286     fail "takes 1 optional argument, the upstream commitish" if @ARGV>1;
2287
2288     my @upstreams;
2289
2290     if (@ARGV) {
2291         my $spec = shift @ARGV;
2292         my $commit = git_rev_parse "$spec^{commit}";
2293         push @upstreams, { Commit => $commit,
2294                            Source => "$ARGV[0], from command line",
2295                            Only => 1,
2296                          };
2297     }
2298
2299     my $head = get_head();
2300
2301     if (!$always) {
2302         my $troubles = 0;
2303         my $trouble = sub { $troubles++; };
2304         keycommits $head, sub{}, sub{}, $trouble, $trouble;
2305         printdebug "troubles=$troubles\n";
2306         if (!$troubles) {
2307             print STDERR <<END;
2308 $us: Branch already seems to be in git-debrebase format!
2309 $us: --always-convert-anyway would do the conversion operation anyway
2310 $us: but is probably a bad idea.  Probably, you wanted to do nothing.
2311 END
2312             fail "Branch already in git-debrebase format." unless $opt_noop_ok;
2313             finish 0;
2314         }
2315     }
2316
2317     snags_maybe_bail_early();
2318
2319     my $version = upstreamversion $clogp->{Version};
2320     print STDERR "Considering possible commits corresponding to upstream:\n";
2321
2322     if (!@upstreams) {
2323         if ($do_tags) {
2324             my @tried;
2325             my $ups_tag = upstream_commitish_search $version, \@tried;
2326             if ($ups_tag) {
2327                 my $this = "git tag $tried[-1]";
2328                 push @upstreams, { Commit => $ups_tag,
2329                                    Source => $this,
2330                                  };
2331             } else {
2332                 printf STDERR
2333                     " git tag: no suitable tag found (tried %s)\n",
2334                     "@tried";
2335             }
2336         }
2337         if ($do_origs) {
2338             my $p = $clogp->{'Source'};
2339             # we do a quick check to see if there are plausible origs
2340             my $something=0;
2341             if (!opendir BPD, $bpd) {
2342                 die "$bpd: opendir: $!" unless $!==ENOENT;
2343             } else {
2344                 while ($!=0, my $f = readdir BPD) {
2345                     next unless is_orig_file_of_p_v $f, $p, $version;
2346                     printf STDERR
2347                         " orig: found what looks like a .orig, %s\n",
2348                         "$bpd/$f";
2349                     $something=1;
2350                     last;
2351                 }
2352                 die "read $bpd: $!" if $!;
2353                 closedir BPD;
2354             }
2355             if ($something) {
2356                 my $tree = cmdoutput
2357                     @dgit, qw(--build-products-dir), $bpd,
2358                     qw(print-unapplied-treeish);
2359                 fresh_workarea();
2360                 in_workarea sub {
2361                     runcmd @git, qw(reset --quiet), $tree, qw(-- .);
2362                     rm_subdir_cached 'debian';
2363                     $tree = cmdoutput @git, qw(write-tree);
2364                     my $ups_synth = make_commit [], [ <<END, <<END,
2365 Import effective orig tree for upstream version $version
2366 END
2367 This includes the contents of the .orig(s), minus any debian/ directory.
2368
2369 [git-debrebase import-from-dgit-view upstream-import-convert: $version]
2370 END
2371                                                     ];
2372                     push @upstreams, { Commit => $ups_synth,
2373                                        Source => "orig(s) imported via dgit",
2374                                      };
2375                 }
2376             } else {
2377                 printf STDERR
2378                     " orig: no suitable origs found (looked for %s in %s)\n",
2379                     "${p}_".(stripeoch $version)."...", $bpd;
2380             }
2381         }
2382     }
2383
2384     my $some_patches = stat_exists 'debian/patches/series';
2385
2386     print STDERR "Evaluating possible commits corresponding to upstream:\n";
2387
2388     my $result;
2389     foreach my $u (@upstreams) {
2390         my $work = $head;
2391         fresh_workarea();
2392         in_workarea sub {
2393             runcmd @git, qw(reset --quiet), $u->{Commit}, qw(-- .);
2394             runcmd @git, qw(checkout), $u->{Commit}, qw(-- .);
2395             runcmd @git, qw(clean -xdff);
2396             runcmd @git, qw(checkout), $head, qw(-- debian);
2397             if ($some_patches) {
2398                 rm_subdir_cached 'debian/patches';
2399                 $work = make_commit [ $work ], [
2400  'git-debrebase convert-from-dgit-view: drop upstream changes from breakwater',
2401  "Drop upstream changes, and delete debian/patches, as part of converting\n".
2402  "to git-debrebase format.  Upstream changes will appear as commits.",
2403  '[git-debrebase convert-from-dgit-view: drop patches from tree]'
2404                                            ];
2405             }
2406             $work = make_commit [ $work, $u->{Commit} ], [
2407  'git-debrebase convert-from-dgit-view: declare upstream',
2408  '(Re)constructed breakwater merge.',
2409  '[git-debrebase anchor: declare upstream]'
2410                                                          ];
2411             runcmd @git, qw(checkout --quiet -b mk), $work;
2412             if ($some_patches) {
2413                 runcmd @git, qw(checkout), $head, qw(-- debian/patches);
2414                 runcmd @git, qw(reset --quiet);
2415                 my @gbp_cmd = (qw(gbp pq import));
2416                 if (!$diagnose) {
2417                     my $gbp_err = "../gbp-pq-err";
2418                     @gbp_cmd = shell_cmd "exec >$gbp_err 2>&1", @gbp_cmd;
2419                 }
2420                 my $r = system @gbp_cmd;
2421                 if ($r) {
2422                     printf STDERR
2423                         " %s: couldn't apply patches: gbp pq %s",
2424                         $u->{Source}, waitstatusmsg();
2425                     return;
2426                 }
2427             }
2428             my $work = git_rev_parse qw(HEAD);
2429             my $diffout = cmdoutput @git, qw(diff-tree --stat HEAD), $work;
2430             if (length $diffout) {
2431                 print STDERR
2432                     " $u->{Source}: applying patches gives different tree\n";
2433                 print STDERR $diffout if $diagnose;
2434                 return;
2435             }
2436             # OMG!
2437             $u->{Result} = $work;
2438             $result = $u;
2439         };
2440         last if $result;
2441     }
2442
2443     if (!$result) {
2444         fail <<END;
2445 Could not find or construct a suitable upstream commit.
2446 Rerun adding --diagnose after convert-from-dgit-view, or pass a
2447 upstream commmit explicitly or provide suitable origs.
2448 END
2449     }
2450
2451     printf STDERR "Yes, will base new branch on %s\n", $result->{Source};
2452
2453     ffq_check $result->{Result};
2454     snags_maybe_bail();
2455     update_head_checkout $head, $result->{Result},
2456         'convert-from-dgit-view';
2457 }
2458
2459 sub cmd_downstream_rebase_launder_v0 () {
2460     badusage "needs 1 argument, the baseline" unless @ARGV==1;
2461     my ($base) = @ARGV;
2462     $base = git_rev_parse $base;
2463     my $old_head = get_head();
2464     my $current = $old_head;
2465     my $topmost_keep;
2466     for (;;) {
2467         if ($current eq $base) {
2468             $topmost_keep //= $current;
2469             print " $current BASE stop\n";
2470             last;
2471         }
2472         my $cl = classify $current;
2473         print " $current $cl->{Type}";
2474         my $keep = 0;
2475         my $p0 = $cl->{Parents}[0]{CommitId};
2476         my $next;
2477         if ($cl->{Type} eq 'Pseudomerge') {
2478             print " ^".($cl->{Contributor}{Ix}+1);
2479             $next = $cl->{Contributor}{CommitId};
2480         } elsif ($cl->{Type} eq 'AddPatches' or
2481                  $cl->{Type} eq 'Changelog') {
2482             print " strip";
2483             $next = $p0;
2484         } else {
2485             print " keep";
2486             $next = $p0;
2487             $keep = 1;
2488         }
2489         print "\n";
2490         if ($keep) {
2491             $topmost_keep //= $current;
2492         } else {
2493             die "to-be stripped changes not on top of the branch\n"
2494                 if $topmost_keep;
2495         }
2496         $current = $next;
2497     }
2498     if ($topmost_keep eq $old_head) {
2499         print "unchanged\n";
2500     } else {
2501         print "updating to $topmost_keep\n";
2502         update_head_checkout
2503             $old_head, $topmost_keep,
2504             'downstream-rebase-launder-v0';
2505     }
2506 }
2507
2508 getoptions_main
2509           ("bad options\n",
2510            "D+" => \$debuglevel,
2511            'noop-ok', => \$opt_noop_ok,
2512            'f=s' => \@snag_force_opts,
2513            'anchor=s' => \@opt_anchors,
2514            '--dgit=s' => \($dgit[0]),
2515            'force!',
2516            '-i:s' => sub {
2517                my ($opt,$val) = @_;
2518                badusage "git-debrebase: no cuddling to -i for git-rebase"
2519                    if length $val;
2520                die if $opt_defaultcmd_interactive; # should not happen
2521                $opt_defaultcmd_interactive = [ qw(-i) ];
2522                # This access to @ARGV is excessive familiarity with
2523                # Getopt::Long, but there isn't another sensible
2524                # approach.  '-i=s{0,}' does not work with bundling.
2525                push @$opt_defaultcmd_interactive, @ARGV;
2526                @ARGV=();
2527            },
2528            'help' => sub { print $usage_message or die $!; finish 0; },
2529            );
2530
2531 initdebug('git-debrebase ');
2532 enabledebug if $debuglevel;
2533
2534 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
2535 chdir $toplevel or die "chdir $toplevel: $!";
2536
2537 $rd = fresh_playground "$playprefix/misc";
2538
2539 @opt_anchors = map { git_rev_parse $_ } @opt_anchors;
2540
2541 if (!@ARGV || $opt_defaultcmd_interactive || $ARGV[0] =~ m{^-}) {
2542     defaultcmd_rebase();
2543 } else {
2544     my $cmd = shift @ARGV;
2545     my $cmdfn = $cmd;
2546     $cmdfn =~ y/-/_/;
2547     $cmdfn = ${*::}{"cmd_$cmdfn"};
2548
2549     $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
2550     $cmdfn->();
2551 }
2552
2553 finish 0;