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