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