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