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