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