chiark / gitweb /
0a73bdc849d1637ec787199c368d8720837f4d4c
[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 our ($opt_force);
121
122 sub badusage ($) {
123     my ($m) = @_;
124     die "bad usage: $m\n";
125 }
126
127 sub cfg ($) {
128     my ($k) = @_;
129     $/ = "\0";
130     my @cmd = qw(git config -z);
131     push @cmd, qw(--get-all) if wantarray;
132     push @cmd, $k;
133     my $out = cmdoutput @cmd;
134     return split /\0/, $out;
135 }
136
137 memoize('cfg');
138
139 sub get_commit ($) {
140     my ($objid) = @_;
141     my $data = git_cat_file $objid, 'commit';
142     $data =~ m/(?<=\n)\n/ or die "$objid ($data) ?";
143     return ($`,$');
144 }
145
146 sub D_UPS ()      { 0x02; } # upstream files
147 sub D_PAT_ADD ()  { 0x04; } # debian/patches/ extra patches at end
148 sub D_PAT_OTH ()  { 0x08; } # debian/patches other changes
149 sub D_DEB_CLOG () { 0x10; } # debian/ (not patches/ or changelog)
150 sub D_DEB_OTH ()  { 0x20; } # debian/changelog
151 sub DS_DEB ()     { D_DEB_CLOG | D_DEB_OTH; } # debian/ (not patches/)
152
153 our $playprefix = 'debrebase';
154 our $rd;
155 our $workarea;
156
157 our @git = qw(git);
158
159 sub in_workarea ($) {
160     my ($sub) = @_;
161     changedir $workarea;
162     my $r = eval { $sub->(); };
163     { local $@; changedir $maindir; }
164     die $@ if $@;
165 }
166
167 sub fresh_workarea () {
168     $workarea = fresh_playground "$playprefix/work";
169     in_workarea sub { playtree_setup };
170 }
171
172 sub get_differs ($$) {
173     my ($x,$y) = @_;
174     # This resembles quiltify_trees_differ, in dgit, a bit.
175     # But we don't care about modes, or dpkg-source-unrepresentable
176     # changes, and we don't need the plethora of different modes.
177     # Conversely we need to distinguish different kinds of changes to
178     # debian/ and debian/patches/.
179
180     my $differs = 0;
181
182     my $rundiff = sub {
183         my ($opts, $limits, $fn) = @_;
184         my @cmd = (@git, qw(diff-tree -z --no-renames));
185         push @cmd, @$opts;
186         push @cmd, "$_:" foreach $x, $y;
187         push @cmd, @$limits;
188         my $diffs = cmdoutput @cmd;
189         foreach (split /\0/, $diffs) { $fn->(); }
190     };
191
192     $rundiff->([qw(--name-only)], [], sub {
193         $differs |= $_ eq 'debian' ? DS_DEB : D_UPS;
194     });
195
196     if ($differs & DS_DEB) {
197         $differs &= ~DS_DEB;
198         $rundiff->([qw(--name-only -r)], [qw(debian)], sub {
199             $differs |=
200                 m{^debian/patches/}      ? D_PAT_OTH  :
201                 $_ eq 'debian/changelog' ? D_DEB_CLOG :
202                                            D_DEB_OTH;
203         });
204         die "mysterious debian changes $x..$y"
205             unless $differs & (D_PAT_OTH|DS_DEB);
206     }
207
208     if ($differs & D_PAT_OTH) {
209         my $mode;
210         $differs &= ~D_PAT_OTH;
211         my $pat_oth = sub {
212             $differs |= D_PAT_OTH;
213             no warnings qw(exiting);  last;
214         };
215         $rundiff->([qw(--name-status -r)], [qw(debian/patches/)], sub {
216             no warnings qw(exiting);
217             if (!defined $mode) {
218                 $mode = $_;  next;
219             }
220             die unless s{^debian/patches/}{};
221             my $ok;
222             if ($mode eq 'A' && !m/\.series$/s) {
223                 $ok = 1;
224             } elsif ($mode eq 'M' && $_ eq 'series') {
225                 my $x_s = git_cat_file "$x:debian/patches/series", 'blob';
226                 my $y_s = git_cat_file "$y:debian/patches/series", 'blob';
227                 chomp $x_s;  $x_s .= "\n";
228                 $ok = $x_s eq substr($y_s, 0, length $x_s);
229             } else {
230                 # nope
231             }
232             $mode = undef;
233             $differs |= $ok ? D_PAT_ADD : D_PAT_OTH;
234         });
235         die "mysterious debian/patches changes $x..$y"
236             unless $differs & (D_PAT_ADD|D_PAT_OTH);
237     }
238
239     printdebug sprintf "get_differs %s, %s = %#x\n", $x, $y, $differs;
240
241     return $differs;
242 }
243
244 sub commit_pr_info ($) {
245     my ($r) = @_;
246     return Data::Dumper->dump([$r], [qw(commit)]);
247 }
248
249 sub calculate_committer_authline () {
250     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
251         'DUMMY COMMIT (git-debrebase)', "HEAD:";
252     my ($h,$m) = get_commit $c;
253     $h =~ m/^committer .*$/m or confess "($h) ?";
254     return $&;
255 }
256
257 sub rm_subdir_cached ($) {
258     my ($subdir) = @_;
259     runcmd @git, qw(rm --quiet -rf --cached --ignore-unmatch), $subdir;
260 }
261
262 sub read_tree_subdir ($$) {
263     my ($subdir, $new_tree_object) = @_;
264     rm_subdir_cached $subdir;
265     runcmd @git, qw(read-tree), "--prefix=$subdir/";
266 }
267
268 # classify returns an info hash like this
269 #   CommitId => $objid
270 #   Hdr => # commit headers, including 1 final newline
271 #   Msg => # commit message (so one newline is dropped)
272 #   Tree => $treeobjid
273 #   Type => (see below)
274 #   Parents = [ {
275 #       Ix => $index # ie 0, 1, 2, ...
276 #       CommitId
277 #       Differs => return value from get_differs
278 #       IsOrigin
279 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
280 #     } ...]
281 #   NewMsg => # commit message, but with any [dgit import ...] edited
282 #             # to say "[was: ...]"
283 #
284 # Types:
285 #   Packaging
286 #   Changelog
287 #   Upstream
288 #   AddPatches
289 #   Mixed
290 #   Unknown
291 #
292 #   Pseudomerge
293 #     has additional entres in classification result
294 #       Overwritten = [ subset of Parents ]
295 #       Contributor = $the_remaining_Parent
296 #
297 #   DgitImportUnpatched
298 #     has additional entry in classification result
299 #       OrigParents = [ subset of Parents ]
300 #
301 #   BreakwaterUpstreamMerge
302 #     has additional entry in classification result
303 #       OrigParents = [ subset of Parents ]  # singleton list
304
305 sub parsecommit ($;$) {
306     my ($objid, $p_ref) = @_;
307     # => hash with                   CommitId Hdr Msg Tree Parents
308     #    Parents entries have only   Ix CommitId
309     #    $p_ref, if provided, must be [] and is used as a base for Parents
310
311     $p_ref //= [];
312     die if @$p_ref;
313
314     my ($h,$m) = get_commit $objid;
315
316     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
317     my (@ph) = $h =~ m/^parent (\w+)$/mg;
318
319     my $r = {
320         CommitId => $objid,
321         Hdr => $h,
322         Msg => $m,
323         Tree => $t,
324         Parents => $p_ref,
325     };
326
327     foreach my $ph (@ph) {
328         push @$p_ref, {
329             Ix => $#$p_ref,
330             CommitId => $ph,
331         };
332     }
333
334     return $r;
335 }    
336
337 sub classify ($) {
338     my ($objid) = @_;
339
340     my @p;
341     my $r = parsecommit($objid, \@p);
342     my $t = $r->{Tree};
343
344     foreach my $p (@p) {
345         $p->{Differs} => (get_differs $p->{CommitId}, $t),
346     }
347
348     printdebug "classify $objid \$t=$t \@p",
349         (map { sprintf " %s/%#x", $_->{CommitId}, $_->{Differs} } @p),
350         "\n";
351
352     my $classify = sub {
353         my ($type, @rest) = @_;
354         $r = { %$r, Type => $type, @rest };
355         if ($debuglevel) {
356             my $dd = new Data::Dumper [ $r ];
357             Terse $dd 1; Indent $dd 0; Useqq $dd 1;
358             printdebug " = $type ".(Dump $dd)."\n";
359         }
360         return $r;
361     };
362     my $unknown = sub {
363         my ($why) = @_;
364         $r = { %$r, Type => qw(Unknown) };
365         printdebug " ** Unknown\n";
366         return $r;
367     };
368
369     if (@p == 1) {
370         my $d = $r->{Parents}[0]{Differs};
371         if ($d == D_PAT_ADD) {
372             return $classify->(qw(AddPatches));
373         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
374             return $unknown->("edits debian/patches");
375         } elsif ($d & DS_DEB and !($d & ~DS_DEB)) {
376             my ($ty,$dummy) = git_cat_file "$ph[0]:debian";
377             if ($ty eq 'tree') {
378                 if ($d == D_DEB_CLOG) {
379                     return $classify->(qw(Changelog));
380                 } else {
381                     return $classify->(qw(Packaging));
382                 }
383             } elsif ($ty eq 'missing') {
384                 return $classify->(qw(BreakwaterStart));
385             } else {
386                 return $unknown->("parent's debian is not a directory");
387             }
388         } elsif ($d == D_UPS) {
389             return $classify->(qw(Upstream));
390         } elsif ($d & DS_DEB and $d & D_UPS and !($d & ~(DS_DEB|D_UPS))) {
391             return $classify->(qw(Mixed));
392         } elsif ($d == 0) {
393             return $unknown->("no changes");
394         } else {
395             confess "internal error $objid ?";
396         }
397     }
398     if (!@p) {
399         return $unknown->("origin commit");
400     }
401
402     my @identical = grep { !$_->{Differs} } @p;
403     if (@p == 2 && @identical == 1) {
404         my @overwritten = grep { $_->{Differs} } @p;
405         confess "internal error $objid ?" unless @overwritten==1;
406         return $classify->(qw(Pseudomerge),
407                            Overwritten => $overwritten[0],
408                            Contributor => $identical[0]);
409     }
410     if (@p == 2 && @identical == 2) {
411         my @bytime = nsort_by {
412             my ($ph,$pm) = get_commit $_->{CommitId};
413             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
414             $1;
415         } @p;
416         return $classify->(qw(Pseudomerge),
417                            SubType => qw(Ambiguous),
418                            Overwritten => $bytime[0],
419                            Contributor => $bytime[1]);
420     }
421     foreach my $p (@p) {
422         my ($p_h, $p_m) = get_commit $p->{CommitId};
423         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
424         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
425     }
426     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
427     my $m2 = $r->{Msg};
428     if (!(grep { !$_->{IsOrigin} } @p) and
429         (@orig_ps >= @p - 1) and
430         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
431         $r->{NewMsg} = $m2;
432         return $classify->(qw(DgitImportUnpatched),
433                            OrigParents => \@orig_ps);
434     }
435
436     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
437     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
438
439     # How to decide about l/r ordering of breakwater merges ?  git
440     # --topo-order prefers to expand 2nd parent first.  There's
441     # already an easy rune to look for debian/ history anyway (git log
442     # debian/) so debian breakwater branch should be 1st parent; that
443     # way also there's also an easy rune to look for the upstream
444     # patches (--topo-order).
445
446     # The above tells us which way *we* will generate them.  But we
447     # might encounter ad-hoc breakwater merges generated manually,
448     # which might be the other way around.  In principle, in some odd
449     # situations, a breakwater merge might have two identical parents.
450     # In that case we guess which way round it is (ie, which parent
451     # has the upstream history).  The order of the 2-iteration loop
452     # controls which guess we make.
453
454     foreach my $prevbrw (qw(0 1)) {
455         if (@p == 2 &&
456             !$haspatches &&
457             !$p[$prevbrw]{IsOrigin} && # breakwater never starts with an origin
458             !($p[$prevbrw]{Differs} & ~DS_DEB) &&
459             !($p[!$prevbrw]{Differs} & ~D_UPS)) {
460             return $classify->(qw(BreakwaterUpstreamMerge),
461                                OrigParents => [ $p[!$prevbrw] ]);
462         }
463     }
464
465     # multi-orig upstreams are represented with a breakwater merge
466     # from a single upstream commit which combines the orig tarballs
467
468     return $unknown->("complex merge");
469 }
470
471 sub walk ($;$$);
472 sub walk ($;$$) {
473     my ($input,
474         $nogenerate,$report) = @_;
475     # => ($tip, $breakwater_tip)
476     # (or nothing, if $nogenerate)
477
478     # go through commits backwards
479     # we generate two lists of commits to apply:
480     # breakwater branch and upstream patches
481     my (@brw_cl, @upp_cl, @processed);
482     my %found;
483     my $upp_limit;
484     my @pseudomerges;
485
486     my $cl;
487     my $xmsg = sub {
488         my ($appendinfo) = @_;
489         my $ms = $cl->{Msg};
490         chomp $ms;
491         $ms .= "\n\n[git-debrebase $appendinfo]\n";
492         return (Msg => $ms);
493     };
494     my $rewrite_from_here = sub {
495         my $sp_cl = { SpecialMethod => 'StartRewrite' };
496         push @brw_cl, $sp_cl;
497         push @processed, $sp_cl;
498     };
499     my $cur = $input;
500
501     my $prdelim = "";
502     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
503
504     my $prline = sub {
505         return unless $report;
506         print $report $prdelim, @_;
507         $prdelim = "\n";
508     };
509
510     my $bomb = sub { # usage: return $bomb->();
511         print $report " Unprocessable" if $report;
512         $prprdelim->();
513         if ($nogenerate) {
514             return (undef,undef);
515         }
516         die "commit $cur: Cannot cope with this commit (d.".
517             (join ' ', map { sprintf "%#x", $_->{Differs} }
518              @{ $cl->{Parents} }). ")";
519     };
520
521     my $build;
522     my $breakwater;
523
524     my $build_start = sub {
525         my ($msg, $parent) = @_;
526         $prline->(" $msg");
527         $build = $parent;
528         no warnings qw(exiting); last;
529     };
530
531     for (;;) {
532         $cl = classify $cur;
533         my $ty = $cl->{Type};
534         my $st = $cl->{SubType};
535         $prline->("$cl->{CommitId} $cl->{Type}");
536         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
537         push @processed, $cl;
538         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
539         if ($ty eq 'AddPatches') {
540             $cur = $p0;
541             $rewrite_from_here->();
542             next;
543         } elsif ($ty eq 'Packaging' or $ty eq 'Changelog') {
544             push @brw_cl, $cl;
545             $cur = $p0;
546             next;
547         } elsif ($ty eq 'BreakwaterStart') {
548             $build_start->('FirstPackaging', $cur);
549         } elsif ($ty eq 'Upstream') {
550             push @upp_cl, $cl;
551             $cur = $p0;
552             next;
553         } elsif ($ty eq 'Mixed') {
554             my $queue = sub {
555                 my ($q, $wh) = @_;
556                 my $cls = { %$cl, $xmsg->("split mixed commit: $wh part") };
557                 push @$q, $cls;
558             };
559             $queue->(\@brw_cl, "debian");
560             $queue->(\@upp_cl, "upstream");
561             $rewrite_from_here->();
562             $cur = $p0;
563             next;
564         } elsif ($ty eq 'Pseudomerge') {
565             my $contrib = $cl->{Contributor}{CommitId};
566             print $report " Contributor=$contrib" if $report;
567             push @pseudomerges, $cl;
568             $rewrite_from_here->();
569             $cur = $contrib;
570             next;
571         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
572             $build_start->("PreviousBreakwater", $cur);
573         } elsif ($ty eq 'DgitImportUnpatched') {
574             my $pm = $pseudomerges[-1];
575             if (defined $pm) {
576                 # To an extent, this is heuristic.  Imports don't have
577                 # a useful history of the debian/ branch.  We assume
578                 # that the first pseudomerge after an import has a
579                 # useful history of debian/, and ignore the histories
580                 # from later pseudomerges.  Often the first pseudomerge
581                 # will be the dgit import of the upload to the actual
582                 # suite intended by the non-dgit NMUer, and later
583                 # pseudomerges may represent in-archive copies.
584                 my $ovwrs = $pm->{Overwritten};
585                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
586                     if $report;
587                 if (@$ovwrs != 1) {
588                     return $bomb->();
589                 }
590                 my $ovwr = $ovwrs->[0]{CommitId};
591                 printf $report " Overwr=%s", $ovwr if $report;
592                 # This import has a tree which is just like a
593                 # breakwater tree, but it has the wrong history.  It
594                 # ought to have the previous breakwater (which the
595                 # pseudomerge overwrote) as an ancestor.  That will
596                 # make the history of the debian/ files correct.  As
597                 # for the upstream version: either it's the same as
598                 # was ovewritten (ie, same as the previous
599                 # breakwater), in which case that history is precisely
600                 # right; or, otherwise, it was a non-gitish upload of a
601                 # new upstream version.  We can tell these apart by
602                 # looking at the tree of the supposed upstream.
603                 push @brw_cl, {
604                     %$cl,
605                     SpecialMethod => 'DgitImportDebianUpdate',
606                     $xmsg->("convert dgit import: debian changes")
607                 };
608                 my $differs = (get_differs $ovwr, $cl->{Tree});
609                 printf $report " Differs=%#x", $differs if $report;
610                 if ($differs & D_UPS) {
611                     printf $report " D_UPS" if $report;
612                     # This will also trigger if a non-dgit git-based NMU
613                     # deleted .gitignore (which is a thing that some of
614                     # the existing git tools do if the user doesn't
615                     # somehow tell them not to).  Ah well.
616                     push @brw_cl, {
617                         %$cl,
618                         SpecialMethod => 'DgitImportUpstreamUpdate',
619                         $xmsg->("convert dgit import: upstream changes")
620                     };
621                 }
622                 $prline->(" Import");
623                 $rewrite_from_here->();
624                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
625                 $cur = $ovwr;
626                 next;
627             } else {
628                 # Everything is from this import.  This kind of import
629                 # is already in valid breakwater format, with the
630                 # patches as commits.
631                 printf $report " NoPM" if $report;
632                 # last thing we processed will have been the first patch,
633                 # if there is one; which is fine, so no need to rewrite
634                 # on account of this import
635                 $build_start->("ImportOrigin", $cur);
636             }
637             die "$ty ?";
638         } else {
639             return $bomb->();
640         }
641     }
642     $prprdelim->();
643     return if $nogenerate;
644
645     # Now we build it back up again
646
647     fresh_workarea();
648
649     my $rewriting = 0;
650
651     my $read_tree_debian = sub {
652         my ($treeish) = @_;
653         read_tree_subdir 'debian', "$treeish:debian";
654     };
655     my $read_tree_upstream = sub {
656         my ($treeish) = @_;
657         runcmd @git, qw(read-tree), $treeish;
658         $read_tree_debian->($build);
659     };
660  
661     my $committer_authline = calculate_committer_authline();
662
663     printdebug "WALK REBUILD $build ".(scalar @processed)."\n";
664
665     confess "internal error" unless $build eq (pop @processed)->{CommitId};
666
667     in_workarea sub {
668         mkdir $rd or $!==EEXIST or die $!;
669         my $current_method;
670         runcmd @git, qw(read-tree), $build;
671         foreach my $cl (qw(Debian), (reverse @brw_cl),
672                         { SpecialMethod => 'RecordBreakwaterTip' },
673                         qw(Upstream), (reverse @upp_cl)) {
674             if (!ref $cl) {
675                 $current_method = $cl;
676                 next;
677             }
678             my $method = $cl->{SpecialMethod} // $current_method;
679             my @parents = ($build);
680             my $cltree = $cl->{CommitId};
681             printdebug "WALK BUILD ".($cltree//'undef').
682                 " $method (rewriting=$rewriting)\n";
683             if ($method eq 'Debian') {
684                 $read_tree_debian->($cltree);
685             } elsif ($method eq 'Upstream') {
686                 $read_tree_upstream->($cltree);
687             } elsif ($method eq 'StartRewrite') {
688                 $rewriting = 1;
689                 next;
690             } elsif ($method eq 'RecordBreakwaterTip') {
691                 $breakwater = $build;
692                 next;
693             } elsif ($method eq 'DgitImportDebianUpdate') {
694                 $read_tree_debian->($cltree);
695                 rm_subdir_cached qw(debian/patches);
696             } elsif ($method eq 'DgitImportUpstreamUpdate') {
697                 $read_tree_upstream->($cltree);
698                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
699             } else {
700                 confess "$method ?";
701             }
702             if (!$rewriting) {
703                 my $procd = (pop @processed) // 'UNDEF';
704                 if ($cl ne $procd) {
705                     $rewriting = 1;
706                     printdebug "WALK REWRITING NOW cl=$cl procd=$procd\n";
707                 }
708             }
709             my $newtree = cmdoutput @git, qw(write-tree);
710             my $ch = $cl->{Hdr};
711             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
712             $ch =~ s{^parent .*\n}{}m;
713             $ch =~ s{(?=^author)}{
714                 join '', map { "parent $_\n" } @parents
715             }me or confess "$ch ?";
716             if ($rewriting) {
717                 $ch =~ s{^committer .*$}{$committer_authline}m
718                     or confess "$ch ?";
719             }
720             my $cf = "$rd/m$rewriting";
721             open CD, ">", $cf or die $!;
722             print CD $ch, "\n", $cl->{Msg} or die $!;
723             close CD or die $!;
724             my @cmd = (@git, qw(hash-object));
725             push @cmd, qw(-w) if $rewriting;
726             push @cmd, qw(-t commit), $cf;
727             my $newcommit = cmdoutput @cmd;
728             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
729             $build = $newcommit;
730         }
731     };
732
733     my $final_check = get_differs $build, $input;
734     die sprintf "internal error %#x %s %s", $final_check, $build, $input
735         if $final_check & ~D_PAT_ADD;
736
737     return ($build, $breakwater);
738 }
739
740 sub get_head () { return git_rev_parse qw(HEAD); }
741
742 sub update_head ($$$) {
743     my ($old, $new, $mrest) = @_;
744     runcmd @git, qw(update-ref -m), "debrebase: $mrest", 'HEAD', $new, $old;
745 }
746
747 sub update_head_checkout ($$$) {
748     my ($old, $new, $mrest) = @_;
749     my $symref = git_get_symref();
750     runcmd @git, qw(checkout), $new, qw(.);
751     update_head $old, $new, $mrest;
752 }
753
754 sub cmd_launder () {
755     badusage "no arguments to launder allowed" if @ARGV;
756     my $old = get_head();
757     my ($tip,$breakwater) = walk $old;
758     update_head $old, $tip, 'launder';
759     # no tree changes except debian/patches
760     runcmd @git, qw(rm --quiet --ignore-unmatch -rf debian/patches);
761     printf "# breakwater tip\n%s\n", $breakwater;
762     printf "# working tip\n%s\n", $tip;
763 }
764
765 sub cmd_analyse () {
766     die if ($ARGV[0]//'') =~ m/^-/;
767     badusage "too many arguments to analyse" if @ARGV>1;
768     my ($old) = @ARGV;
769     if (defined $old) {
770         $old = git_rev_parse $old;
771     } else {
772         $old = get_head();
773     }
774     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
775     STDOUT->error and die $!;
776 }
777
778 sub cmd_new_upstream_v0 () {
779     # xxx would like to support more git-rebase options
780     badusage
781  "need NEW-VERSION UPS-COMMITISH [EXTRA-UPS-NAME EXTRA-UPS-COMMITISH...]"
782         unless @ARGV % 2 == 0 and @ARGV >= 2;
783     # tree should be clean and this is not checked
784     # automatically and unconditionally launders before rebasing
785     # if rebase --abort is used, laundering has still been done
786
787     my %pieces;
788
789     # parse args - low commitment
790     my $new_version = (new Dpkg::Version scalar(shift @ARGV), 1);
791     my $new_upstream_version = $new_version->version();
792
793     my $new_upstream = git_rev_parse shift @ARGV;
794
795     my $piece = sub {
796         my ($n, @x) = @_; # may be ''
797         my $pc = $pieces{$n} //= {
798             Name => $n,
799             Desc => ($n ? "upstream piece $n" : "upstream (main piece"),
800         };
801         while (my $k = shift @x) { $pc->{$k} = shift @x; }
802     };
803
804     my @newpieces;
805     my $newpiece = sub {
806         my ($n, @x) = @_; # may be ''
807         $pc = $piece->($n, @x, NewIx => (scalar @newpieces));
808         push @newpieces, $pc;
809     };
810
811     $newpiece->('',
812         OldIx => 0,
813         New => $new_upstream,
814     };
815     while (@ARGV) {
816         my $n = shift @ARGV;
817         my $c = git_rev_parse shift @ARGV;
818         die unless $n =~ m/^$extra_orig_namepart_re$/;
819         $newpiece->($n, New => $c);
820     }
821
822     # now we need to investigate the branch this generates the
823     # laundered version but we don't switch to it yet
824     my $old_head = get_head();
825     my ($old_laundered_tip,$old_bw) = walk $old_head;
826
827     my $old_bw_cl = classify $old_bw;
828     my $old_ups = parsecommit $old_bw_cl->{OrigParents}[0]{CommitId};
829
830     my $problems = 0;
831     my $problem = sub {
832         my ($msg) = @_;
833         $problems++;
834         print STDERR "preflight check failed: $msg\n";
835     };
836
837     $piece->('', Old => $old_orig);
838
839     if ($old_orig_ci =~ m{^\[git-debrebase }m) {
840         if ($old_orig_ci =~
841  m{^\[git-debrebase new-upstream combine \.((?: $extra_orig_namepart_re)+)\]}
842            ) {
843             my @oldpieces = ('', split / /, $1);
844             my $parentix = -1 + scalar @{ $old_orig->{Parents} };
845             foreach my $i (0..$#$oldpieces) {
846                 my $n = $oldpieces[$i];
847                 $piece->($n, Old => $old_orig.'^'.$parentix);
848             }
849         } else {
850             $problem->("previous upstream $old_orig->{CommitId} is from".
851                  " git-debrebase but not a \`new-upstream combine' commit");
852         }
853     }
854
855     foreach my $pc (values %pieces) {
856         if (!$pc->{Old}) {
857             $problem->("introducing upstream piece $pc->{Name}");
858         } elsif (!$pc->{New}) {
859             $problem->("dropping upstream piece $pc->{Name}");
860         } elsif (!is_fast_fwd $pc->{Old}, $pc->{New}) {
861             $problem->("not fast forward: $pc->{Name} $pc->{Old}..$pc->{New}");
862         }
863     }
864
865     if ($problems) {
866         if ($opt_force) {
867             printf STDERR
868                 "preflight check failures (%d) overriden by --force\n",
869                 $problems;
870         } else {
871             fail sprintf
872                 "preflight check failures (%d) (you could --force)",
873                 $problems;
874         }
875     }
876
877     fresh_workarea();
878     in_workarea sub {
879         my @upstream_merge_parents;
880
881         if (!$problems) {
882             push @upstream_merge_parents, $old_orig->{CommitId};
883         }
884
885         foreach my $pc (@newpieces) { # always has '' first
886             if ($pc->{Name}) {
887                 read_tree_subdir $pcname, $pc->{New];
888             } else {
889                 runcmd @git, qw(read-tree), $pc->{New};
890             }
891             push @upstream_merge_parents, $pc->{New};
892         }
893
894         # index now contains the new upstream
895
896         if (@newpieces > 1) {
897             # need to make the upstream subtree merge commit
898             my $us_tree = cmdoutput @git, qw(write-tree);
899             my @cmd = (@git, qw(commit-tree), $us_tree);
900             push @cmd, qw(-p), $_ foreach @upstream_merge_parents;
901             push @cmd, qw(-m), "Combine upstreams for $new_upstream_version";
902             push @cmd, qw(-m),
903                 "[git-debrebase new-upstream combine . ".
904                 (join " ", map { $_->{Name} } @newpieces[1..$#newpieces]).
905                  "]";
906             $new_upstream = cmdoutput @cmd;
907         }
908
909         # $new_upstream is either the single upstream commit, or the
910         # combined commit we just made.  Either way it will be the
911         # "upstream" parent of the breakwater special merge.
912
913         read_tree_subdir 'debian', "$old_bw:debian";
914
915         # index now contains the breakwater merge contents
916
917         my $bw_tree = cmdoutput @git, qw(write_tree);
918         my @cmd = (@git, qw(commit-tree), $bw_tree);
919         push @cmd, qw(-p), $old_bw, qw(-p), $new_upstream;
920         push @cmd, qw(-m), "Update to upstream $new_upstream_version";
921         push @cmd, qw(-m),
922             "[git-debrebase new-upstream breakwater $new_upstream_version]";
923         my $new_bw = cmdoutput @git;
924
925         # Now we have to add a changelog stanza so the Debian version
926         # is right.
927
928         die if unlink "debian";
929         die unless $!==ENOTEMPTY;
930         unlink "debian/changelog" or die $!;
931         open CN, ">", "debian/changelog" or die $!;
932         my $oldclog = git_cat_file ":debian/changelog";
933         $oldclog =~ m/^($package_re) \(\S+\) / or
934             fail "cannot parse old changelog to get package name";
935         my $p = $1;
936         print CN, <<END, $oldclog or die $!;
937 $p ($new_version) UNRELEASED; urgency=medium
938
939   * Update to new upstream version $new_upstream_version.
940
941  -- 
942
943 END
944         close CN or die $!;
945         runcmd @git, qw(update-index --add --replace), 'debian/changelog';
946
947         # Now we have the final new breakwater branch in the index
948
949         $bw_tree = cmdoutput @git, qw(write_tree);
950         @cmd = (@git, qw(commit-tree), $bw_tree);
951         push @cmd, qw(-p), $new_bw;
952         push @cmd, qw(-m),
953             "Update changelog for new upstream $new_upstream_version";
954         push @cmd, qw(-m),
955             "[git-debrebase new-upstream changelog $new_upstream_version]";
956         $new_bw = cmdoutput @git;
957     };
958
959     # we have constructed the new breakwater. we now need to commit to
960     # the laundering output, because git-rebase can't easily be made
961     # to make a replay list which is based on some other branch
962
963     update_head $old_head, $old_laundered;
964
965     my @cmd = (@git, qw(rebase --onto), $new_bw, $old_bw);
966     runcmd @cmd;
967     # now it's for the user to sort out
968 }
969
970 sub cmd_downstream_rebase_launder_v0 () {
971     badusage "needs 1 argument, the baseline" unless @ARGV==1;
972     my ($base) = @ARGV;
973     $base = git_rev_parse $base;
974     my $old_head = get_head();
975     my $current = $old_head;
976     my $topmost_keep;
977     for (;;) {
978         if ($current eq $base) {
979             $topmost_keep //= $current;
980             print " $current BASE stop\n";
981             last;
982         }
983         my $cl = classify $current;
984         print " $current $cl->{Type}";
985         my $keep = 0;
986         my $p0 = $cl->{Parents}[0]{CommitId};
987         my $next;
988         if ($cl->{Type} eq 'Pseudomerge') {
989             print " ^".($cl->{Contributor}{Ix}+1);
990             $next = $cl->{Contributor}{CommitId};
991         } elsif ($cl->{Type} eq 'AddPatches' or
992                  $cl->{Type} eq 'Changelog') {
993             print " strip";
994             $next = $p0;
995         } else {
996             print " keep";
997             $next = $p0;
998             $keep = 1;
999         }
1000         print "\n";
1001         if ($keep) {
1002             $topmost_keep //= $current;
1003         } else {
1004             die "to-be stripped changes not on top of the branch\n"
1005                 if $topmost_keep;
1006         }
1007         $current = $next;
1008     }
1009     if ($topmost_keep eq $old_head) {
1010         print "unchanged\n";
1011     } else {
1012         print "updating to $topmost_keep\n";
1013         update_head_checkout
1014             $old_head, $topmost_keep,
1015             'downstream-rebase-launder-v0';
1016     }
1017 }
1018
1019 GetOptions("D+" => \$debuglevel,
1020            'force!') or die badusage "bad options\n";
1021 initdebug('git-debrebase ');
1022 enabledebug if $debuglevel;
1023
1024 my $toplevel = cmdoutput @git, qw(rev-parse --show-toplevel);
1025 chdir $toplevel or die "chdir $toplevel: $!";
1026
1027 $rd = fresh_playground "$playprefix/misc";
1028
1029 my $cmd = shift @ARGV;
1030 my $cmdfn = $cmd;
1031 $cmdfn =~ y/-/_/;
1032 $cmdfn = ${*::}{"cmd_$cmdfn"};
1033
1034 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
1035 $cmdfn->();