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