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