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