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