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