chiark / gitweb /
git-debrebase: rebase fixes
[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 # usages:
22 #    git-debrebase status
23 #    git-debrebase start       # like ffqrebase start + debrebase launder
24 #    git-debrebase new-upstream [stuff]  # see below
25 #    git-debrebase <git-rebase options>  # does debrebase start if necessary
26 #
27 #    git-debrebase analyse
28 #    git-debrebase launder     # prints breakwater tip
29 #    git-debrebase create-new-upstream-breakwater [-f] <upstreaminfo>...
30 #
31 # <upstreaminfo> is
32 #    [,][<subdir>:][+]<commitid>[,...]
33 #
34 # if initial comma is supplied, entries are not positional.  Unspecified
35 # <subdir> means root (and there may be only one).
36 # xxx want auto branch names
37 # xxx too complicated
38 # how about for now
39 #    [+]<commit> [<subdir/> [+]<commit>...]
40 # ?  plus options
41 #     --new-upstream-different-subtrees
42 #
43 #  automatic case
44 #       git-debrebase new-upstream
45 #             - previous breakwater merge must be gdr-generated
46 #             - orig set is the same as before
47 #             - implicitly uses upstream branches according to orig set
48 #             - not all upstream branches need be updated
49 #             - insists on fast-forward of each branch, unless
50 #                  --force (or --force=<subdir>[/])
51 #  branch set adjustments
52 #       git-debrebase new-upstream --add <subdir>/
53 #       git-debrebase new-upstream --rm <subdir>/
54 #       git-debrebase new-upstream / [<subdir>/ ...]
55 #             - orig set is adjusted
56 #             - otherwise like auto (--add is not checked for ffness, obv)
57 #             - multiple --add and --rm may be specified
58 #             - --add makes new upstream the last contributor
59 #  explicit
60 #       git-debrebase / [<rootcommitid>] [<subdir>/ [<commitid>] ...]
61 #             - orig set is precisely as specified now
62 #             - previous breakwater merge is irrelevant
63 #             - no fast forward checks
64 #  for now only explicit with commitids
65
66 #         implicitly uses `upstream'
67 #                                     # (or multiple other branches)
68 #       git-debrebase new-upstream \
69 #             [<subdir>/]=<commitid>
70
71 #    UPSTREAM[,[[SUBDIR:]SUBUPSTREAM]
72 #    default for SUBDIR: is from previous upstream merge[xxx terminology]
73 #    
74 #
75 #xxx
76 # when starting must record original start (for ff)
77 # and new rebase basis
78 #
79 #    git-ffqrebase start [BASE]
80 #                # records previous HEAD so it can be overwritten
81 #                # records base for future git-ffqrebase
82 #    git-ffqrebase set-base BASE
83 #    git-ffqrebase <git-rebase options>
84 #    git-ffqrebase finish
85 #    git-ffqrebase status [BRANCH]
86 #
87 #  refs/ffqrebase-prev/BRANCH    BRANCH may be refs/...; if not it means
88 #  refs/ffqrebase-base/BRANCH      refs/heads/BRANCH
89 #                               zero, one, or both of these may exist
90 #
91 # git-debrebase without start, if already started, is willing
92 # to strip pseudomerges provided that they overwrite exactly
93 # the previous HEAD
94 #  xxxx is this right ?  what matters is have we pushed
95 #    I think in fact the right answer is:
96 #       git-debrebase always strips out pseudomerges from its branch
97 #       a pseudomerge is put in at the time we want to push
98 #       at that time, we make a pseudomerge of the remote tracking
99 #           branch (if raw git) or the dgit view (if dgit)
100 #       for raw git git-ffqrebase, do want preciseley to record
101 #           value of remote tracking branch or our branch, on start, so we
102 #           overwrite only things we intend to
103 #  the previous pseudomerge    check for tags and remote branches ?
104
105 use strict;
106
107 use Memoize;
108 use Carp;
109 use POSIX;
110 use Data::Dumper;
111
112 use Debian::Dgit qw(:DEFAULT $wa);
113
114 sub badusage ($) {
115     my ($m) = @_;
116     die "bad usage: $m\n";
117 }
118
119 sub cfg ($) {
120     my ($k) = @_;
121     $/ = "\0";
122     my @cmd = qw(git config -z);
123     push @cmd, qw(--get-all) if wantarray;
124     push @cmd, $k;
125     my $out = cmdoutput @cmd;
126     return split /\0/, $out;
127 }
128
129 memoize('cfg');
130
131 sub get_commit ($) {
132     my ($objid) = @_;
133     my ($type,$data) = git_cat_file $objid;
134     die unless $type eq 'commit';
135     $data =~ m/(?<=\n)\n/;
136     return ($`,$');
137 }
138
139 sub D_DEB ()     { return 0x1; } # debian/ (not including debian/patches/)
140 sub D_UPS ()     { return 0x2; } # upstream files
141 sub D_PAT_ADD () { return 0x4; } # debian/patches/ extra patches at end
142 sub D_PAT_OTH () { return 0x8; } # debian/patches other changes
143
144 our $rd = ".git/git-debrebase";
145 our $ud = "$rd/work";
146 our @git = qw(git);
147
148 sub commit_pr_info ($) {
149     my ($r) = @_;
150     return Data::Dumper->dump([$r], [qw(commit)]);
151 }
152
153 sub calculate_committer_authline () {
154     my $c = cmdoutput @git, qw(commit-tree --no-gpg-sign -m),
155         'DUMMY COMMIT (git-debrebase)', "HEAD:";
156     my ($h,$m) = get_commit $c;
157     $h =~ m/^committer .*$/m or confess "($h) ?";
158     return $&;
159 }
160
161 # classify returns an info hash like this
162 #   CommitId => $objid
163 #   Hdr => # commit headers, including 1 final newline
164 #   Msg => # commit message (so one newline is dropped)
165 #   Tree => $treeobjid
166 #   Type => (see below)
167 #   Parents = [ {
168 #       Ix => $index # ie 0, 1, 2, ...
169 #       CommitId
170 #       Differs => return value from get_differs
171 #       IsOrigin
172 #       IsDggitImport => 'orig' 'tarball' 'unpatched' 'package' (as from dgit)
173 #     } ...]
174 #   NewMsg => # commit message, but with any [dgit import ...] edited
175 #             # to say "[was: ...]"
176 #
177 # Types:
178 #   Packaging
179 #   Upstream
180 #   AddPatches
181 #   Mixed
182 #   Unknown
183 #
184 #   Pseudomerge
185 #     has additional entres in classification result
186 #       Overwritten = [ subset of Parents ]
187 #       Contributor = $the_remaining_Parent
188 #
189 #   DgitImportUnpatched
190 #     has additional entry in classification result
191 #       OrigParents = [ subset of Parents ]
192 #
193 #   BreakwaterUpstreamMerge
194 #     has additional entry in classification result
195 #       OrigParents = [ subset of Parents ]
196
197 sub classify ($) {
198     my ($objid) = @_;
199
200     my ($h,$m) = get_commit $objid;
201
202     my ($t) = $h =~ m/^tree (\w+)$/m or die $objid;
203     my (@ph) = $h =~ m/^parent (\w+)$/m;
204     my @p;
205
206     my $r = {
207         CommitId => $objid,
208         Hdr => $h,
209         Msg => $m,
210         Tree => $t,
211         Parents => \@p,
212     };
213
214     foreach my $ph (@ph) {
215         push @p, {
216             Ix => $#p,
217             CommitId => $ph,
218             Differs => (get_differs $t, $ph),
219         };
220     }
221
222     my $classify = sub {
223         my ($type, @rest) = @_;
224         $r = { %$r, Type => $type, @rest };
225         return $r;
226     };
227     my $unknown = sub {
228         my ($why) = @_;
229         $r = { %$r, Type => qw(Unknown) };
230         return $r;
231     };
232
233     if (@p == 1) {
234         my $d = $r->{Parents}[0]{Differs};
235         if ($d == D_PAT_ADD) {
236             return $classify->(qw(AddPatches));
237         } elsif ($d & (D_PAT_ADD|D_PAT_OTH)) {
238             return $unknown->("edits debian/patches");
239         } elsif ($d == D_DEB) {
240             my ($ty,$dummy) = git_cat_file "$ph[0]:debian";
241             if ($ty eq 'tree') {
242                 return $classify->(qw(Packaging));
243             } elsif ($ty eq 'missing') {
244                 return $classify->(qw(BreakwaterStart));
245             } else {
246                 return $unknown->("parent's debian is not a directory");
247             }
248         } elsif ($d == D_UPS) {
249             return $classify->(qw(Upstream));
250         } elsif ($d == (D_DEB|D_UPS)) {
251             return $classify->(qw(Mixed));
252         } elsif ($d == 0) {
253             return $unknown->("no changes");
254         } else {
255             confess "internal error $objid ?";
256         }
257     }
258     if (!@p) {
259         return $unknown->("origin commit");
260     }
261
262     my @identical = grep { !$_->{Differs} } @p;
263     if (@p == 2 && @identical == 1) {
264         my @overwritten = grep { $_->{Differs} } @p;
265         confess "internal error $objid ?" unless @overwritten==1;
266         return $classify->(qw(Pseudomerge),
267                            Overwritten => $overwritten[0],
268                            Contributor => $identical[0]);
269     }
270     if (@p == 2 && @identical == 2) {
271         my @bytime = nsort_by {
272             my ($ph,$pm) = get_commit $_->{CommitId};
273             $ph =~ m/^committer .* (\d+) [-+]\d+$/m or die "$_->{CommitId} ?";
274             $1;
275         } @p;
276         return $classify->(qw(Pseudomerge),
277                            SubType => qw(Ambiguous),
278                            Overwritten => $bytime[0],
279                            Contributor => $bytime[1]);
280     }
281     foreach my $p (@p) {
282         my ($p_h, $p_m) = get_commit $p;
283         $p->{IsOrigin} = $p_h !~ m/^parent \w+$/m;
284         ($p->{IsDgitImport},) = $p_m =~ m/^\[dgit import ([0-9a-z]+) .*\]$/m;
285     }
286     my @orig_ps = grep { ($_->{IsDgitImport}//'X') eq 'orig' } @p;
287     my $m2 = $m;
288     if (!(grep { !$_->{IsOrigin} } @p) and
289         (@orig_ps >= @p - 1) and
290         $m2 =~ s{^\[(dgit import unpatched .*)\]$}{[was: $1]}m) {
291         $r->{NewMsg} = $m2;
292         return $classify->(qw(DgitImportUnpatched),
293                            OrigParents => \@orig_ps);
294     }
295
296     my ($stype, $series) = git_cat_file "$t:debian/patches/series";
297     my $haspatches = $stype ne 'missing' && $series =~ m/^\s*[^#\n\t ]/m;
298
299     # How to decide about l/r ordering of breakwater merges ?  git
300     # --topo-order prefers to expand 2nd parent first.  There's
301     # already an easy rune to look for debian/ history anyway (git log
302     # debian/) so debian breakwater branch should be 1st parent; that
303     # way also there's also an easy rune to look for the upstream
304     # patches (--topo-order).
305     if (@p == 2 &&
306         !$haspatches &&
307         !$p[0]{IsOrigin} && # breakwater merge never starts with an origin
308         !($p[0]{Differs} & ~D_DEB) &&
309         !($p[1]{Differs} & ~D_UPS)) {
310         return $classify->(qw(BreakwaterUpstreamMerge),
311                            OrigParents => [ $p[1] ]);
312     }
313     # xxx multi-.orig upstreams
314
315     return $unknown->("complex merge");
316 }
317
318 sub walk ($;$$);
319 sub walk {
320     my ($input,
321         $nogenerate,$report) = @_;
322     # => ($tip, $breakwater_tip)
323     # (or nothing, if $nogenerate)
324
325     # go through commits backwards
326     # we generate two lists of commits to apply:
327     # breakwater branch and upstream patches
328     my (@brw_cl, @upp_cl, @processed);
329     my %found;
330     my $upp_limit;
331     my @pseudomerges;
332
333     my $cl;
334     my $xmsg = sub {
335         my ($appendinfo) = @_;
336         my $ms = $cl->{Msg};
337         chomp $ms;
338         $ms .= "\n\n[git-debrebase $appendinfo]\n";
339         return (Msg => $ms);
340     };
341     my $rewrite_from_here = sub {
342         my $sp_cl = { SpecialMethod => 'StartRewrite' };
343         push @brw_cl, $sp_cl;
344         push @processed, $sp_cl;
345     };
346     my $cur = $input;
347
348     my $prdelim = "";
349     my $prprdelim = sub { print $report $prdelim if $report; $prdelim=""; };
350
351     my $prline = sub {
352         return unless $report;
353         print $report $prdelim, @_;
354         $prdelim = "\n";
355     };
356
357     my $bomb = sub { # usage: return $bomb->();
358         print $report " Unprocessable" if $report;
359         $prprdelim->();
360         if ($nogenerate) {
361             return (undef,undef);
362         }
363         die "commit $cur: Cannot cope with this commit";
364     };
365
366     my $build;
367     my $breakwater;
368
369     my $build_start = sub {
370         my ($msg, $parent) = @_;
371         $prline->(" $msg");
372         $build = $parent;
373         no warnings qw(exiting); last;
374     };
375
376     for (;;) {
377         $cl = classify $cur;
378         my $ty = $cl->{Type};
379         my $st = $cl->{SubType};
380         $prline->("$cl->{CommitId} $cl->{Type}");
381         $found{$ty. ( defined($st) ? "-$st" : '' )}++;
382         push @processed, $cl;
383         my $p0 = @{ $cl->{Parents} }==1 ? $cl->{Parents}[0]{CommitId} : undef;
384         if ($ty eq 'AddPatches') {
385             $cur = $p0;
386             $rewrite_from_here->();
387             next;
388         } elsif ($ty eq 'Packaging') {
389             push @brw_cl, $cl;
390             $cur = $p0;
391             next;
392         } elsif ($ty eq 'BreakwaterStart') {
393             $build_start->('FirstPackaging', $cur);
394         } elsif ($ty eq 'Upstream') {
395             push @upp_cl, $cl;
396             $cur = $p0;
397             next;
398         } elsif ($ty eq 'Mixed') {
399             my $queue = sub {
400                 my ($q, $wh) = @_;
401                 my $cls = { $cl, $xmsg->("split mixed commit: $wh part") };
402                 push @$q, $cls;
403             };
404             $queue->(\@brw_cl, "debian");
405             $queue->(\@upp_cl, "upstream");
406             $rewrite_from_here->();
407             $cur = $p0;
408             next;
409         } elsif ($ty eq 'Pseudomerge') {
410             print $report " Contributor=$ty->{Contributor}" if $report;
411             push @pseudomerges, $cl;
412             $rewrite_from_here->();
413             $cur = $ty->{Contributor};
414             next;
415         } elsif ($ty eq 'BreakwaterUpstreamMerge') {
416             $build_start->("PreviousBreakwater", $cur);
417         } elsif ($ty eq 'DgitImportUnpatched') {
418             my $pm = $pseudomerges[-1];
419             if (defined $pm) {
420                 # To an extent, this is heuristic.  Imports don't have
421                 # a useful history of the debian/ branch.  We assume
422                 # that the first pseudomerge after an import has a
423                 # useful history of debian/, and ignore the histories
424                 # from later pseudomerges.  Often the first pseudomerge
425                 # will be the dgit import of the upload to the actual
426                 # suite intended by the non-dgit NMUer, and later
427                 # pseudomerges may represent in-archive copies.
428                 my $ovwrs = $pm->{Overwritten};
429                 printf $report " PM=%s \@Overwr:%d", $pm, (scalar @$ovwrs)
430                     if $report;
431                 if (@$ovwrs != 1) {
432                     return $bomb->();
433                 }
434                 my $ovwr = $ovwrs->[0]{CommitId};
435                 printf $report " Overwr=%s", $ovwr if $report;
436                 # This import has a tree which is just like a
437                 # breakwater tree, but it has the wrong history.  It
438                 # ought to have the previous breakwater (which the
439                 # pseudomerge overwrote) as an ancestor.  That will
440                 # make the history of the debian/ files correct.  As
441                 # for the upstream version: either it's the same as
442                 # was ovewritten (ie, same as the previous
443                 # breakwater), in which case that history is precisely
444                 # right; or, otherwise, it was a non-gitish upload of a
445                 # new upstream version.  We can tell these apart by
446                 # looking at the tree of the supposed upstream.
447                 push @brw_cl, {
448                     %$cl,
449                     SpecialMethod => 'DgitImportDebianUpdate',
450                     $xmsg->("convert dgit import: debian changes")
451                 };
452                 my $differs = (get_differs $ovwr, $cl->{Tree});
453                 printf $report " Differs=%#x", $differs if $report;
454                 if ($differs & D_UPS) {
455                     printf $report " D_UPS" if $report;
456                     # This will also trigger if a non-dgit git-based NMU
457                     # deleted .gitignore (which is a thing that some of
458                     # the existing git tools do if the user doesn't
459                     # somehow tell them not to).  Ah well.
460                     push @brw_cl, {
461                         %$cl,
462                         SpecialMethod => 'DgitImportUpstreamUpdate',
463                         $xmsg->("convert dgit import: upstream changes")
464                     };
465                 }
466                 $prline->(" Import");
467                 $rewrite_from_here->();
468                 $upp_limit //= $#upp_cl; # further, deeper, patches discarded
469                 $cur = $ovwr;
470                 next;
471             } else {
472                 # Everything is from this import.  This kind of import
473                 # is already in valid breakwater format, with the
474                 # patches as commits.
475                 printf $report " NoPM" if $report;
476                 # last thing we processed will have been the first patch,
477                 # if there is one; which is fine, so no need to rewrite
478                 # on account of this import
479                 $build_start->("ImportOrigin", $cur);
480             }
481             die "$ty ?";
482         } else {
483             return $bomb->();
484         }
485     }
486     $prprdelim->();
487     return if $nogenerate;
488
489     # Now we build it back up again
490
491     workarea_fresh();
492
493     my $rewriting = 0;
494
495     my $rm_tree_cached = sub {
496         my ($subdir) = @_;
497         runcmd @git, qw(rm --quiet -rf --cached), $subdir;
498     };
499     my $read_tree_debian = sub {
500         my ($treeish) = @_;
501         $rm_tree_cached->(qw(debian));
502         runcmd @git, qw(read-tree --prefix=debian/), "$treeish:debian";
503     };
504     my $read_tree_upstream = sub {
505         my ($treeish) = @_;
506         runcmd @git, qw(read-tree), $treeish;
507         $read_tree_debian->($build);
508     };
509  
510     my $committer_authline = calculate_committer_authline();
511
512     in_workarea sub {
513         mkdir $rd or $!==EEXIST or die $!;
514         my $current_method;
515         foreach my $cl (qw(Debian), (reverse @brw_cl),
516                         { SpecialMethod => 'RecordBreakwaterTip' },
517                         qw(Upstream), (reverse @upp_cl)) {
518             if (!ref $cl) {
519                 $current_method = $cl;
520                 next;
521             }
522             my $method = $cl->{SpecialMethod} // $current_method;
523             my @parents = ($build);
524             my $cltree = $cl->{CommitId};
525             if ($method eq 'Debian') {
526                 $read_tree_debian->($cltree);
527             } elsif ($method eq 'Upstream') {
528                 $read_tree_upstream->($cltree);
529             } elsif ($method eq 'StartRewrite') {
530                 $rewriting = 1;
531                 next;
532             } elsif ($method eq 'RecordBreakwaterTip') {
533                 $breakwater = $build;
534                 next;
535             } elsif ($method eq 'DgitImportDebianUpdate') {
536                 $read_tree_debian->($cltree);
537                 $rm_tree_cached->(qw(debian/patches));
538             } elsif ($method eq 'DgitImportUpstreamUpdate') {
539                 $read_tree_upstream->($cltree);
540                 push @parents, map { $_->{CommitId} } @{ $cl->{OrigParents} };
541             } else {
542                 confess "$method ?";
543             }
544             $rewriting ||= $cl ne pop @processed;
545             my $newtree = cmdoutput @git, qw(write-tree);
546             my $ch = $cl->{Hdr};
547             $ch =~ s{^tree .*}{tree $newtree}m or confess "$ch ?";
548             $ch =~ s{^parent .*\n}{}m;
549             $ch =~ s{(?=^author)}{
550                 map { "parent $_\n" } @parents
551             }me or confess "$ch ?";
552             if ($rewriting) {
553                 $ch =~ s{^committer .*$}{$committer_authline}m
554                     or confess "$ch ?";
555             }
556             my $cf = "$rd/m$rewriting";
557             open CD, ">", $cf or die $!;
558             print CD $ch, "\n", $cl->{Msg} or die $!;
559             close CD or die $!;
560             my @cmd = (@git, qw(hash-object));
561             push @cmd, qw(-w) if $rewriting;
562             push @cmd, qw(-t commit), $cf;
563             my $newcommit = cmdoutput @cmd;
564             confess "$ch ?" unless $rewriting or $newcommit eq $cl->{CommitId};
565             $build = $newcommit;
566         }
567     };
568
569     runcmd @git, qw(diff-tree --quiet), $input, $build;
570
571     return ($build, $breakwater);
572 }
573
574 sub get_head () { return git_rev_parse qw(HEAD); }
575
576 sub update_head ($$) {
577     my ($old, $new, $mrest) = @_;
578     runcmd @git, qw(update-ref -m), "git-debrebase $mrest", $new, $old;
579 }
580
581 sub cmd_launder () {
582     badusage "no arguments to launder allowed";
583     my $old = get_head();
584     my ($tip,$breakwater) = walk $old;
585     update_head $old, $tip, 'launder';
586     # no tree changes except debian/patches
587     runcmd @git, qw(rm --quiet -rf debian/patches);
588     printf "# breakwater tip\n%s\n", $breakwater;
589 }
590
591 sub cmd_analyse () {
592     die if ($ARGV[0]//'') =~ m/^-/;
593     badusage "too many arguments to analyse" if @ARGV>1;
594     my ($old) = @ARGV;
595     if (defined $old) {
596         $old = git_rev_parse $old;
597     } else {
598         $old = get_head();
599     }
600     my ($dummy,$breakwater) = walk $old, 1,*STDOUT;
601     print "$breakwater BREAKWATER\n";
602     STDOUT->error and die $!;
603 }
604
605 my $toplevel = runcmd @git, qw(rev-parse --show-toplevel);
606 chdir $toplevel or die "chdir $toplevel: $!";
607
608 my $cmd = shift @ARGV;
609 my $cmdfn = $cmd;
610 $cmdfn =~ y/-/_/;
611 $cmdfn = ${*::}{"cmd_$cmdfn"};
612
613 $cmdfn or badusage "unknown git-debrebase sub-operation $cmd";
614 $cmdfn->();