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