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