chiark / gitweb /
git-debrebase: wip new-upstream
[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 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 #    git-debrebase new-upstreams-v0 \
22 #             NEW-VERSION ORIG-COMMITISH
23 #            [EXTRA-ORIG-NAME EXTRA-ORIG-COMMITISH ...]
24
25 # usages:
26 #    git-debrebase status
27 #    git-debrebase start       # like ffqrebase start + debrebase launder
28 #    git-debrebase new-upstream [stuff]  # see below
29 #    git-debrebase <git-rebase options>  # does debrebase start if necessary
30 #
31 #    git-debrebase analyse
32 #    git-debrebase launder     # prints breakwater tip
33 #    git-debrebase create-new-upstream-breakwater [-f] <upstreaminfo>...
34 #
35 # <upstreaminfo> is
36 #    [,][<subdir>:][+]<commitid>[,...]
37 #
38 # if initial comma is supplied, entries are not positional.  Unspecified
39 # <subdir> means root (and there may be only one).
40 # xxx want auto branch names
41 # xxx too complicated
42 # how about for now
43 #    [+]<commit> [<subdir/> [+]<commit>...]
44 # ?  plus options
45 #     --new-upstream-different-subtrees
46 #
47 #  automatic case
48 #       git-debrebase new-upstream
49 #             - previous breakwater merge must be gdr-generated
50 #             - orig set is the same as before
51 #             - implicitly uses upstream branches according to orig set
52 #             - not all upstream branches need be updated
53 #             - insists on fast-forward of each branch, unless
54 #                  --force (or --force=<subdir>[/])
55 #  branch set adjustments
56 #       git-debrebase new-upstream --add <subdir>/
57 #       git-debrebase new-upstream --rm <subdir>/
58 #       git-debrebase new-upstream / [<subdir>/ ...]
59 #             - orig set is adjusted
60 #             - otherwise like auto (--add is not checked for ffness, obv)
61 #             - multiple --add and --rm may be specified
62 #             - --add makes new upstream the last contributor
63 #  explicit
64 #       git-debrebase / [<rootcommitid>] [<subdir>/ [<commitid>] ...]
65 #             - orig set is precisely as specified now
66 #             - previous breakwater merge is irrelevant
67 #             - no fast forward checks
68 #  for now only explicit with commitids
69
70 #         implicitly uses `upstream'
71 #                                     # (or multiple other branches)
72 #       git-debrebase new-upstream \
73 #             [<subdir>/]=<commitid>
74
75 #    UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
76 #    default for SUBDIR: is from previous upstream merge[xxx terminology]
77 #    
78 #
79 #xxx
80 # when starting must record original start (for ff)
81 # and new rebase basis
82 #
83 #    git-ffqrebase start [BASE]
84 #                # records previous HEAD so it can be overwritten
85 #                # records base for future git-ffqrebase
86 #    git-ffqrebase set-base BASE
87 #    git-ffqrebase <git-rebase options>
88 #    git-ffqrebase finish
89 #    git-ffqrebase status [BRANCH]
90 #
91 #  refs/ffqrebase-prev/BRANCH    BRANCH may be refs/...; if not it means
92 #  refs/ffqrebase-base/BRANCH      refs/heads/BRANCH
93 #                               zero, one, or both of these may exist
94 #
95 # git-debrebase without start, if already started, is willing
96 # to strip pseudomerges provided that they overwrite exactly
97 # the previous HEAD
98 #  xxxx is this right ?  what matters is have we pushed
99 #    I think in fact the right answer is:
100 #       git-debrebase always strips out pseudomerges from its branch
101 #       a pseudomerge is put in at the time we want to push
102 #       at that time, we make a pseudomerge of the remote tracking
103 #           branch (if raw git) or the dgit view (if dgit)
104 #       for raw git git-ffqrebase, do want preciseley to record
105 #           value of remote tracking branch or our branch, on start, so we
106 #           overwrite only things we intend to
107 #  the previous pseudomerge    check for tags and remote branches ?
108
109 use strict;
110
111 use Debian::Dgit qw(:DEFAULT :playground);
112 setup_sigwarn();
113
114 use Memoize;
115 use Carp;
116 use POSIX;
117 use Data::Dumper;
118 use Getopt::Long qw(:config posix_default gnu_compat bundling);
119
120 sub badusage ($) {
121     my ($m) = @_;
122     die "bad usage: $m\n";
123 }
124
125 sub cfg ($) {
126     my ($k) = @_;
127     $/ = "\0";
128     my @cmd = qw(git config -z);
129     push @cmd, qw(--get-all) if wantarray;
130     push @cmd, $k;
131     my $out = cmdoutput @cmd;
132     return split /\0/, $out;
133 }
134
135 memoize('cfg');
136
137 sub get_commit ($) {
138     my ($objid) = @_;
139     my $data = git_cat_file $objid, 'commit';
140     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
141     return ($`,$');
142 }
143
144 sub D_UPS ()      { 0x02; } # upstream files
145 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
146 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
147 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
148 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
149 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
150
151 our $playprefix = 'debrebase';
152 our $rd;
153 our $workarea;
154
155 our @git = qw(git);
156
157 sub in_workarea ($) {
158     my ($sub) = @_;
159     changedir $workarea;
160     my $r = eval { $sub->(); };
161     { local $@; changedir $maindir; }
162     die $@ if $@;
163 }
164
165 sub fresh_workarea () {
166     $workarea = fresh_playground "$playprefix/work";
167     in_workarea sub { playtree_setup };
168 }
169
170 sub get_differs ($$) {
171     my ($x,$y) = @_;
172     # This resembles quiltify_trees_differ, in dgit, a bit.
173     # But we don't care about modes, or dpkg-source-unrepresentable
174     # changes, and we don't need the plethora of different modes.
175     # Conversely we need to distinguish different kinds of changes to
176     # debian/ and debian/patches/.
177
178     my $differs = 0;
179
180     my $rundiff = sub {
181         my ($opts, $limits, $fn) = @_;
182         my @cmd = (@git, qw(diff-tree -z --no-renames));
183         push @cmd, @$opts;
184         push @cmd, "$_:" foreach $x, $y;
185         push @cmd, @$limits;
186         my $diffs = cmdoutput @cmd;
187         foreach (split /\0/, $diffs) { $fn->(); }
188     };
189
190     $rundiff->([qw(--name-only)], [], sub {
191         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
192     });
193
194     if ($differs & DS_DEB) {
195         $differs &= ~DS_DEB;
196         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
197             $differs |=
198                 m{^debian/patches/}      ? D_PAT_OTH  :
199                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
200                                            D_DEB_OTH;
201         });
202         die "mysterious debian changes $x..$y"
203             unless $differs & (D_PAT_OTH|DS_DEB);
204     }
205
206     if ($differs & D_PAT_OTH) {
207         my $mode;
208         $differs &= ~D_PAT_OTH;
209         my $pat_oth = sub {
210             $differs |= D_PAT_OTH;
211             no warnings qw(exiting);  last;
212         };
213         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
214             no warnings qw(exiting);
215             if (!defined $mode) {
216                 $mode = $_;  next;
217             }
218             die unless s{^debian/patches/}{};
219             my $ok;
220             if ($mode eq 'A' && !m/\.series$/s) {
221                 $ok = 1;
222             } elsif ($mode eq 'M' && $_ eq 'series') {
223                 my $x_s = git_cat_file "$x:debian/patches/series", 'blob';
224                 my $y_s = git_cat_file "$y:debian/patches/series", 'blob';
225                 chomp $x_s;  $x_s .= "\n";
226                 $ok = $x_s eq substr($y_s, 0, length $x_s);
227             } else {
228                 # nope
229             }
230             $mode = undef;
231             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
232         });
233         die "mysterious debian/patches changes $x..$y"
234             unless $differs & (D_PAT_ADD|D_PAT_OTH);
235     }
236
237     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
238
239     return $differs;
240 }
241
242 sub commit_pr_info ($) {
243     my ($r) = @_;
244     return Data::Dumper->dump([$r], [qw(commit)]);
245 }
246
247 sub calculate_committer_authline () {
248     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
249         'DUMMY COMMIT (git-debrebase)', "HEAD:";
250     my ($h,$m) = get_commit $c;
251     $h =~ m/^committer .*$/m or confess "($h) ?";
252     return $&;
253 }
254
255 # classify returns an info hash like this
256 #   CommitId => $objid
257 #   Hdr => # commit headers, including 1 final newline
258 #   Msg => # commit message (so one newline is dropped)
259 #   Tree => $treeobjid
260 #   Type => (see below)
261 #   Parents = [ {
262 #       Ix => $index # ie 0, 1, 2, ...
263 #       CommitId
264 #       Differs => return value from get_differs
265 #       IsOrigin
266 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
267 #     } ...]
268 #   NewMsg => # commit message, but with any [dgit import ...] edited
269 #             # to say "[was: ...]"
270 #
271 # Types:
272 #   Packaging
273 #   Changelog
274 #   Upstream
275 #   AddPatches
276 #   Mixed
277 #   Unknown
278 #
279 #   Pseudomerge
280 #     has additional entres in classification result
281 #       Overwritten = [ subset of Parents ]
282 #       Contributor = $the_remaining_Parent
283 #
284 #   DgitImportUnpatched
285 #     has additional entry in classification result
286 #       OrigParents = [ subset of Parents ]
287 #
288 #   BreakwaterUpstreamMerge
289 #     has additional entry in classification result
290 #       OrigParents = [ subset of Parents ]  # singleton list
291
292 sub parsecommit ($;$) {
293     my ($objid, $p_ref) = @_;
294     # => hash with                   CommitId Hdr Msg Tree Parents
295     #    Parents entries have only   Ix CommitId
296     #    $p_ref, if provided, must be [] and is used as a base for Parents
297
298     $p_ref //= [];
299     die if @$p_ref;
300
301     my ($h,$m) = get_commit $objid;
302
303     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
304     my (@ph) = $h =~ m/^parent (\w+)$/mg;
305
306     my $r = {
307         CommitId => $objid,
308         Hdr => $h,
309         Msg => $m,
310         Tree => $t,
311         Parents => $p_ref,
312     };
313
314     foreach my $ph (@ph) {
315         push @$p_ref, {
316             Ix => $#$p_ref,
317             CommitId => $ph,
318         };
319     }
320
321     return $r;
322 }    
323
324 sub classify ($) {
325     my ($objid) = @_;
326
327     my @p;
328     my $r = parsecommit($objid, \@p);
329     my $t = $r->{Tree};
330
331     foreach my $p (@p) {
332         $p->{Differs} => (get_differs $p->{CommitId}, $t),
333     }
334
335     printdebug "classify $objid \$t=$t \@p",
336         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
337         "\n";
338
339     my $classify = sub {
340         my ($type, @rest) = @_;
341         $r = { %$r, Type => $type, @rest };
342         if ($debuglevel) {
343             my $dd = new Data::Dumper [ $r ];
344             Terse $dd 1; Indent $dd 0; Useqq $dd 1;
345             printdebug " = $type ".(Dump $dd)."\n";
346         }
347         return $r;
348     };
349     my $unknown = sub {
350         my ($why) = @_;
351         $r = { %$r, Type => qw(Unknown) };
352         printdebug " ** Unknown\n";
353         return $r;
354     };
355
356     if (@p == 1) {
357         my $d = $r->{Parents}[0]{Differs};
358         if ($d == D_PAT_ADD) {
359             return $classify->(qw(AddPatches));
360         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
361             return $unknown->("edits debian/patches");
362         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
363             my ($ty,$dummy) = git_cat_file "$ph[0]:debian";
364             if ($ty eq 'tree') {
365                 if ($d == D_DEB_CLOG) {
366                     return $classify->(qw(Changelog));
367                 } else {
368                     return $classify->(qw(Packaging));
369                 }
370             } elsif ($ty eq 'missing') {
371                 return $classify->(qw(BreakwaterStart));
372             } else {
373                 return $unknown->("parent's debian is not a directory");
374             }
375         } elsif ($d == D_UPS) {
376             return $classify->(qw(Upstream));
377         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
378             return $classify->(qw(Mixed));
379         } elsif ($d == 0) {
380             return $unknown->("no changes");
381         } else {
382             confess "internal error $objid ?";
383         }
384     }
385     if (!@p) {
386         return $unknown->("origin commit");
387     }
388
389     my @identical = grep { !$_->{Differs} } @p;
390     if (@p == 2 && @identical == 1) {
391         my @overwritten = grep { $_->{Differs} } @p;
392         confess "internal error $objid ?" unless @overwritten==1;
393         return $classify->(qw(Pseudomerge),
394                            Overwritten => $overwritten[0],
395                            Contributor => $identical[0]);
396     }
397     if (@p == 2 && @identical == 2) {
398         my @bytime = nsort_by {
399             my ($ph,$pm) = get_commit $_->{CommitId};
400             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
401             $1;
402         } @p;
403         return $classify->(qw(Pseudomerge),
404                            SubType => qw(Ambiguous),
405                            Overwritten => $bytime[0],
406                            Contributor => $bytime[1]);
407     }
408     foreach my $p (@p) {
409         my ($p_h, $p_m) = get_commit $p->{CommitId};
410         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
411         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
412     }
413     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
414     my $m2 = $r->{Msg};
415     if (!(grep { !$_->{IsOrigin} } @p) and
416         (@orig_ps >= @p - 1) and
417         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
418         $r->{NewMsg} = $m2;
419         return $classify->(qw(DgitImportUnpatched),
420                            OrigParents => \@orig_ps);
421     }
422
423     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
424     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
425
426     # How to decide about l/r ordering of breakwater merges ?  git
427     # --topo-order prefers to expand 2nd parent first.  There's
428     # already an easy rune to look for debian/ history anyway (git log
429     # debian/) so debian breakwater branch should be 1st parent; that
430     # way also there's also an easy rune to look for the upstream
431     # patches (--topo-order).
432
433     # The above tells us which way *we* will generate them.  But we
434     # might encounter ad-hoc breakwater merges generated manually,
435     # which might be the other way around.  In principle, in some odd
436     # situations, a breakwater merge might have two identical parents.
437     # In that case we guess which way round it is (ie, which parent
438     # has the upstream history).  The order of the 2-iteration loop
439     # controls which guess we make.
440
441     foreach my $prevbrw (qw(0 1)) {
442         if (@p == 2 &&
443             !$haspatches &&
444             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
445             !($p[$prevbrw]{Differs} & ~DS_DEB) &&
446             !($p[!$prevbrw]{Differs} & ~D_UPS)) {
447             return $classify->(qw(BreakwaterUpstreamMerge),
448                                OrigParents => [ $p[!$prevbrw] ]);
449         }
450     }
451
452     # multi-orig upstreams are represented with a breakwater merge
453     # from a single upstream commit which combines the orig tarballs
454
455     return $unknown->("complex merge");
456 }
457
458 sub walk ($;$$);
459 sub walk ($;$$) {
460     my ($input,
461         $nogenerate,$report) = @_;
462     # => ($tip, $breakwater_tip)
463     # (or nothing, if $nogenerate)
464
465     # go through commits backwards
466     # we generate two lists of commits to apply:
467     # breakwater branch and upstream patches
468     my (@brw_cl, @upp_cl, @processed);
469     my %found;
470     my $upp_limit;
471     my @pseudomerges;
472
473     my $cl;
474     my $xmsg = sub {
475         my ($appendinfo) = @_;
476         my $ms = $cl->{Msg};
477         chomp $ms;
478         $ms .= "\n\n[git-debrebase $appendinfo]\n";
479         return (Msg => $ms);
480     };
481     my $rewrite_from_here = sub {
482         my $sp_cl = { SpecialMethod => 'StartRewrite' };
483         push @brw_cl, $sp_cl;
484         push @processed, $sp_cl;
485     };
486     my $cur = $input;
487
488     my $prdelim = "";
489     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
490
491     my $prline = sub {
492         return unless $report;
493         print $report $prdelim, @_;
494         $prdelim = "\n";
495     };
496
497     my $bomb = sub { # usage: return $bomb->();
498         print $report " Unprocessable" if $report;
499         $prprdelim->();
500         if ($nogenerate) {
501             return (undef,undef);
502         }
503         die "commit $cur: Cannot cope with this commit (d.".
504             (join ' ', map { sprintf "%#x", $_->{Differs} }
505              @{ $cl->{Parents} }). ")";
506     };
507
508     my $build;
509     my $breakwater;
510
511     my $build_start = sub {
512         my ($msg, $parent) = @_;
513         $prline->(" $msg");
514         $build = $parent;
515         no warnings qw(exiting); last;
516     };
517
518     for (;;) {
519         $cl = classify $cur;
520         my $ty = $cl->{Type};
521         my $st = $cl->{SubType};
522         $prline->("$cl->{CommitId} $cl->{Type}");
523         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
524         push @processed, $cl;
525         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
526         if ($ty eq 'AddPatches') {
527             $cur = $p0;
528             $rewrite_from_here->();
529             next;
530         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
531             push @brw_cl, $cl;
532             $cur = $p0;
533             next;
534         } elsif ($ty eq 'BreakwaterStart') {
535             $build_start->('FirstPackaging', $cur);
536         } elsif ($ty eq 'Upstream') {
537             push @upp_cl, $cl;
538             $cur = $p0;
539             next;
540         } elsif ($ty eq 'Mixed') {
541             my $queue = sub {
542                 my ($q, $wh) = @_;
543                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
544                 push @$q, $cls;
545             };
546             $queue->(\@brw_cl, "debian");
547             $queue->(\@upp_cl, "upstream");
548             $rewrite_from_here->();
549             $cur = $p0;
550             next;
551         } elsif ($ty eq 'Pseudomerge') {
552             my $contrib = $cl->{Contributor}{CommitId};
553             print $report " Contributor=$contrib" if $report;
554             push @pseudomerges, $cl;
555             $rewrite_from_here->();
556             $cur = $contrib;
557             next;
558         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
559             $build_start->("PreviousBreakwater", $cur);
560         } elsif ($ty eq 'DgitImportUnpatched') {
561             my $pm = $pseudomerges[-1];
562             if (defined $pm) {
563                 # To an extent, this is heuristic.  Imports don't have
564                 # a useful history of the debian/ branch.  We assume
565                 # that the first pseudomerge after an import has a
566                 # useful history of debian/, and ignore the histories
567                 # from later pseudomerges.  Often the first pseudomerge
568                 # will be the dgit import of the upload to the actual
569                 # suite intended by the non-dgit NMUer, and later
570                 # pseudomerges may represent in-archive copies.
571                 my $ovwrs = $pm->{Overwritten};
572                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
573                     if $report;
574                 if (@$ovwrs != 1) {
575                     return $bomb->();
576                 }
577                 my $ovwr = $ovwrs->[0]{CommitId};
578                 printf $report " Overwr=%s", $ovwr if $report;
579                 # This import has a tree which is just like a
580                 # breakwater tree, but it has the wrong history.  It
581                 # ought to have the previous breakwater (which the
582                 # pseudomerge overwrote) as an ancestor.  That will
583                 # make the history of the debian/ files correct.  As
584                 # for the upstream version: either it's the same as
585                 # was ovewritten (ie, same as the previous
586                 # breakwater), in which case that history is precisely
587                 # right; or, otherwise, it was a non-gitish upload of a
588                 # new upstream version.  We can tell these apart by
589                 # looking at the tree of the supposed upstream.
590                 push @brw_cl, {
591                     %$cl,
592                     SpecialMethod => 'DgitImportDebianUpdate',
593                     $xmsg->("convert dgit import: debian changes")
594                 };
595                 my $differs = (get_differs $ovwr, $cl->{Tree});
596                 printf $report " Differs=%#x", $differs if $report;
597                 if ($differs & D_UPS) {
598                     printf $report " D_UPS" if $report;
599                     # This will also trigger if a non-dgit git-based NMU
600                     # deleted .gitignore (which is a thing that some of
601                     # the existing git tools do if the user doesn't
602                     # somehow tell them not to).  Ah well.
603                     push @brw_cl, {
604                         %$cl,
605                         SpecialMethod => 'DgitImportUpstreamUpdate',
606                         $xmsg->("convert dgit import: upstream changes")
607                     };
608                 }
609                 $prline->(" Import");
610                 $rewrite_from_here->();
611                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
612                 $cur = $ovwr;
613                 next;
614             } else {
615                 # Everything is from this import.  This kind of import
616                 # is already in valid breakwater format, with the
617                 # patches as commits.
618                 printf $report " NoPM" if $report;
619                 # last thing we processed will have been the first patch,
620                 # if there is one; which is fine, so no need to rewrite
621                 # on account of this import
622                 $build_start->("ImportOrigin", $cur);
623             }
624             die "$ty ?";
625         } else {
626             return $bomb->();
627         }
628     }
629     $prprdelim->();
630     return if $nogenerate;
631
632     # Now we build it back up again
633
634     fresh_workarea();
635
636     my $rewriting = 0;
637
638     my $rm_tree_cached = sub {
639         my ($subdir) = @_;
640         runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
641     };
642     my $read_tree_debian = sub {
643         my ($treeish) = @_;
644         $rm_tree_cached->(qw(debian));
645         runcmd @git, qw(read-tree --prefix=debian/), "$treeish:debian";
646     };
647     my $read_tree_upstream = sub {
648         my ($treeish) = @_;
649         runcmd @git, qw(read-tree), $treeish;
650         $read_tree_debian->($build);
651     };
652  
653     my $committer_authline = calculate_committer_authline();
654
655     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
656
657     confess "internal error" unless $build eq (pop @processed)->{CommitId};
658
659     in_workarea sub {
660         mkdir $rd or $!==EEXIST or die $!;
661         my $current_method;
662         runcmd @git, qw(read-tree), $build;
663         foreach my $cl (qw(Debian), (reverse @brw_cl),
664                         { SpecialMethod => 'RecordBreakwaterTip' },
665                         qw(Upstream), (reverse @upp_cl)) {
666             if (!ref $cl) {
667                 $current_method = $cl;
668                 next;
669             }
670             my $method = $cl->{SpecialMethod} // $current_method;
671             my @parents = ($build);
672             my $cltree = $cl->{CommitId};
673             printdebug "WALK BUILD ".($cltree//'undef').
674                 " $method (rewriting=$rewriting)\n";
675             if ($method eq 'Debian') {
676                 $read_tree_debian->($cltree);
677             } elsif ($method eq 'Upstream') {
678                 $read_tree_upstream->($cltree);
679             } elsif ($method eq 'StartRewrite') {
680                 $rewriting = 1;
681                 next;
682             } elsif ($method eq 'RecordBreakwaterTip') {
683                 $breakwater = $build;
684                 next;
685             } elsif ($method eq 'DgitImportDebianUpdate') {
686                 $read_tree_debian->($cltree);
687                 $rm_tree_cached->(qw(debian/patches));
688             } elsif ($method eq 'DgitImportUpstreamUpdate') {
689                 $read_tree_upstream->($cltree);
690                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
691             } else {
692                 confess "$method ?";
693             }
694             if (!$rewriting) {
695                 my $procd = (pop @processed) // 'UNDEF';
696                 if ($cl ne $procd) {
697                     $rewriting = 1;
698                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
699                 }
700             }
701             my $newtree = cmdoutput @git, qw(write-tree);
702             my $ch = $cl->{Hdr};
703             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
704             $ch =~ s{^parent .*\n}{}m;
705             $ch =~ s{(?=^author)}{
706                 join '', map { "parent $_\n" } @parents
707             }me or confess "$ch ?";
708             if ($rewriting) {
709                 $ch =~ s{^committer .*$}{$committer_authline}m
710                     or confess "$ch ?";
711             }
712             my $cf = "$rd/m$rewriting";
713             open CD, ">", $cf or die $!;
714             print CD $ch, "\n", $cl->{Msg} or die $!;
715             close CD or die $!;
716             my @cmd = (@git, qw(hash-object));
717             push @cmd, qw(-w) if $rewriting;
718             push @cmd, qw(-t commit), $cf;
719             my $newcommit = cmdoutput @cmd;
720             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
721             $build = $newcommit;
722         }
723     };
724
725     my $final_check = get_differs $build, $input;
726     die sprintf "internal error %#x %s %s", $final_check, $build, $input
727         if $final_check & ~D_PAT_ADD;
728
729     return ($build, $breakwater);
730 }
731
732 sub get_head () { return git_rev_parse qw(HEAD); }
733
734 sub update_head ($$$) {
735     my ($old, $new, $mrest) = @_;
736     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
737 }
738
739 sub update_head_checkout ($$$) {
740     my ($old, $new, $mrest) = @_;
741     my $symref = git_get_symref();
742     runcmd @git, qw(checkout), $new, qw(.);
743     update_head $old, $new, $mrest;
744 }
745
746 sub cmd_launder () {
747     badusage "no arguments to launder allowed" if @ARGV;
748     my $old = get_head();
749     my ($tip,$breakwater) = walk $old;
750     update_head $old, $tip, 'launder';
751     # no tree changes except debian/patches
752     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
753     printf "# breakwater tip\n%s\n", $breakwater;
754     printf "# working tip\n%s\n", $tip;
755 }
756
757 sub cmd_analyse () {
758     die if ($ARGV[0]//'') =~ m/^-/;
759     badusage "too many arguments to analyse" if @ARGV>1;
760     my ($old) = @ARGV;
761     if (defined $old) {
762         $old = git_rev_parse $old;
763     } else {
764         $old = get_head();
765     }
766     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
767     STDOUT->error and die $!;
768 }
769
770 sub cmd_new_upstream_v0 () {
771     badusage
772  "need NEW-VERSION ORIG-COMMITISH [EXTRA-ORIG-NAME EXTRA-ORIG-COMMITISH...]"
773         unless @ARGV % 2 == 0 and @ARGV >= 2;
774     # tree should be clean and this is not checked
775     # automatically and unconditionally launders before rebasing
776     # if rebase --abort is used, laundering has still been done
777
778     # parse args - low commitment
779     my $new_version = new Dpkg::Version scalar(shift @ARGV), 1;
780     my $new_upstream_version = $new_version->version();
781     my $new_orig_commitish = git_rev_parse shift @ARGV;
782     my @extra_origs;
783     while (@ARGV) {
784         my $xo = {
785             Name => shift @ARGV,
786             New => git_rev_parse shift @ARGV,
787                  };
788         die unless $xo->{Name} =~ m/^$extra_orig_namepart_re$/;
789         push @extra_origs, $xo;
790     }
791
792     # now we need to investigate the branch this generates the
793     # laundered version but we don't switch to it yet
794     my $old = get_head();
795     my ($laundered_tip,$breakwater) = walk $old;
796
797     my $breakwater_cl = classify $breakwater;
798     my $old_orig_pi = $breakwater_cl->{OrigParents}[0];
799
800     fresh_workarea();
801     in_workarea sub {
802         my $ff_still_ok = 1;
803
804         my $ffnot = sub {
805             my ($msg) = @_;
806             $ff_still_ok = 0;
807             print STDERR "upstream not fast forward: $msg\n";
808         };
809
810         if (@extra_origs) {
811             # check fast forward, and make new combined-orig commit
812             my $old_orig_ci = parsecommit $old_orig_pi->{CommitId};
813             my $n_old_origs = scalar @{ $old_orig_cp->{Parents} };
814             @{ $n_old_origs } == @extra_origs+1 or
815                 $ffnot->(sprintf
816                          "previous breakwater upstream has %d parents".
817                          " but new upstream has %d pieces, cannot check ff",
818                          $n_old_origs,
819                          (1 + scalar @extra_origs));
820         }
821
822         my @upstream_merge_parents;
823
824         foreach my $piece_ix (0..$n_old_origs-1) {
825             my $prevpc = $breakwater.'^'.($old_orig_pi->{Ix} + 1);
826             if (@extra_origs) {
827                 $prevpc .= '^'.($piece_ix + 1);
828             }
829             die unless $ git_rev_parse $prevpc;
830             my ($newpc,$newdesc,$pcname);
831             if (!$piece_ix) {
832                 $newpc = $new_orig_commitish;
833                 $newdesc = 'new main upstream piece';
834             } else {
835                 $newpc = $extra_origs[$piece_ix+1]{New};
836                 $pcname = $extra_origs[$piece_ix-1]{Name}
837                 $newdesc = "new upstream extra piece \`$pcname";
838             }
839             $ffwant->($prevpc, "previous upstream piece ($prevpc)",
840                       $newpc, "newdesc ($newpc)");
841
842             push @upstream_merge_parents, $newpc;
843
844             my @cmd = @git, qw(read-tree);
845             if (defined $pcname) {
846                 push @cmd, "-prefix=$pcname/";
847                 runcmd @git, qw(rm --cached -f --ignore-unmatch), $pcname;
848             }
849             push @cmd, $newpc;
850             runcmd @cmd;
851         }
852
853         # index now contains the new upstream
854         if (!$ff_still_ok) {
855             die "upstreams not fast forward, stopping".
856                 " (xxx should be an override option)";
857         }
858
859         if (@extra_origs) {
860             # need to make the upstream subtree merge commit
861             my $us_tree = cmdoutput @git, qw(write-tree);
862             my @cmd = @git, qw(commit-tree), $us_tree;
863             if ($ff_still_ok) {
864                 push @cmd, qw(-p), 
865             } else {
866                 die 'do we want to make ff from previous upstream comb?"';
867             }
868             push @cmd, qw(-p), $_ foreach @upstream_merge_parents;
869             push @cmd, qw(-m), "Combine upstreams for $new_upstream_version";
870             push @cmd, qw(-m),
871                 "[git-debrebase combine-upstreams . ".
872                 (join " ", map { $_->{Name} } @extra_upstreams)."]";
873             my $combined = cmdoutput @cmd;
874         }
875         
876
877             my $us_txt = "
878             make_commit_te
879
880     update_head
881     xxx check new orig version is reasonable;
882     xxx decorate new orig version to get new debian version;
883         
884
885 sub cmd_downstream_rebase_launder_v0 () {
886     badusage "needs 1 argument, the baseline" unless @ARGV==1;
887     my ($base) = @ARGV;
888     $base = git_rev_parse $base;
889     my $old_head = get_head();
890     my $current = $old_head;
891     my $topmost_keep;
892     for (;;) {
893         if ($current eq $base) {
894             $topmost_keep //= $current;
895             print " $current BASE stop\n";
896             last;
897         }
898         my $cl = classify $current;
899         print " $current $cl->{Type}";
900         my $keep = 0;
901         my $p0 = $cl->{Parents}[0]{CommitId};
902         my $next;
903         if ($cl->{Type} eq 'Pseudomerge') {
904             print " ^".($cl->{Contributor}{Ix}+1);
905             $next = $cl->{Contributor}{CommitId};
906         } elsif ($cl->{Type} eq 'AddPatches' or
907                  $cl->{Type} eq 'Changelog') {
908             print " strip";
909             $next = $p0;
910         } else {
911             print " keep";
912             $next = $p0;
913             $keep = 1;
914         }
915         print "\n";
916         if ($keep) {
917             $topmost_keep //= $current;
918         } else {
919             die "to-be stripped changes not on top of the branch\n"
920                 if $topmost_keep;
921         }
922         $current = $next;
923     }
924     if ($topmost_keep eq $old_head) {
925         print "unchanged\n";
926     } else {
927         print "updating to $topmost_keep\n";
928         update_head_checkout
929             $old_head, $topmost_keep,
930             'downstream-rebase-launder-v0';
931     }
932 }
933
934 GetOptions("D+" => \$debuglevel) or die badusage "bad options\n";
935 initdebug('git-debrebase ');
936 enabledebug if $debuglevel;
937
938 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
939 chdir $toplevel or die "chdir $toplevel: $!";
940
941 $rd = fresh_playground "$playprefix/misc";
942
943 my $cmd = shift @ARGV;
944 my $cmdfn = $cmd;
945 $cmdfn =~ y/-/_/;
946 $cmdfn = ${*::}{"cmd_$cmdfn"};
947
948 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
949 $cmdfn->();