chiark / gitweb /
Results of testing git merging
[topbloke.git] / Topbloke.pm
1 # -*- perl -*-
2
3 package Topbloke;
4
5 use strict;
6 use warnings;
7
8 use POSIX;
9 use IO::File;
10 use IPC::Open2;
11 use File::Path qw(make_path remove_tree);
12 use File::Basename;
13
14 BEGIN {
15     use Exporter   ();
16     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
17
18     $VERSION     = 1.00;
19     @ISA         = qw(Exporter);
20     @EXPORT      = qw(debug
21                       run_git run_git_1line run_git_check_nooutput
22                       run_git_test_anyoutput git_get_object
23                       git_config git_dir chdir_toplevel enable_reflog
24                       current_branch parse_patch_spec parse_patch_name
25                       setup_config check_no_unwanted_metadata
26                       patch_matches_spec
27                       foreach_patch
28                       propsfile_add_prop depsfile_add_dep
29                       wf_start wf wf_abort wf_done wf_contents
30                       closeout);
31     %EXPORT_TAGS = ( );
32     @EXPORT_OK   = qw();
33 }
34
35 our $git_command = 'git';
36
37 sub debug ($) {
38     my ($msg) = @_;
39     print STDERR "DEBUG: $msg\n" or die $!;
40 }
41
42 #----- general interaction with git -----
43
44 sub run_git {
45     # takes optional prefix arguments:
46     #    coderef    hook to call for each line read,
47     #                with $_ containing chomped line; if not supplied,
48     #                output is not read
49     #    scalarref  place to store exit status; if not supplied,
50     #                nonzero exit status is fatal
51     my ($estatusr,$linecallr);
52     while (ref $_[0]) {
53         my $ref = shift @_;
54         if (ref $ref eq 'SCALAR') {
55             $estatusr = $ref;
56         } elsif (ref $ref eq 'CODE') {
57             $linecallr = $ref;
58         } else {
59             die ref($ref)." @_ ?";
60         }
61     }
62     open GIT, "-|", $git_command, @_ or die $!;
63     if ($linecallr) {
64         while (<GIT>) {
65             chomp or die "$git_command @_ gave $_ ?";
66             $linecallr->();
67         }
68         GIT->eof or die $!;
69     }
70     if (!close GIT) {
71         die "$git_command @_ $!" if $!;
72         die unless $?;
73         die "$git_command @_ ($?)" unless $estatusr;
74         $$estatusr = $?;
75     } else {
76         $$estatusr = 0 if $estatusr;
77     }
78 }
79
80 sub run_git_1line {
81     my $l;
82     run_git(sub { $l = $_; }, @_);
83     die "git @_ ?" unless defined $l;
84     return $l;
85 }
86
87 sub run_git_check_nooutput {
88     my ($what) = shift @_;
89     run_git(sub { die "$what $_\n"; }, @_);
90 }
91
92 sub run_git_test_anyoutput {
93     my $any = 0;
94     run_git(sub { $any=1; }, @_);
95     return $any;
96 }
97
98 sub git_get_object ($) {
99     my ($objname) = @_;
100     our ($gro_pid, $gro_out, $gro_in);
101     if (!$gro_pid) {
102         $gro_pid = open2($gro_out, $gro_in, $git_command, qw(cat-file --batch))
103             or die $!;
104     }
105     #debug("git_get_object $objname");
106     $SIG{'PIPE'} = 'IGN';
107     print $gro_in $objname,"\n" or die $!;
108     $gro_in->flush or die "$objname $!";
109     $SIG{'PIPE'} = 'DFL';
110     my $l = <$gro_out>;
111     chomp $l or die "$objname $l ?";
112     #debug("git_get_object $objname => $l");
113     if ($l =~ m/ missing$/) {
114         return 'missing';
115     } elsif (my ($type,$bytes) = $l =~ m/^\S+ (\w+) (\d+)$/) {
116         my $data = '';
117         if ($bytes) {
118             (read $gro_out, $data, $bytes) == $bytes or die "$objname $!";
119         }
120         my $nl;
121         (read $gro_out, $nl, 1) == 1 or die "$objname $!";
122         $nl eq "\n" or die "$objname ?";
123         return ($type, $data);
124     } else {
125         die "$objname $l";
126     }
127 }
128
129 sub git_config ($$) {
130     my ($cfgvar, $default) = @_;
131     my ($l, $estatus);
132     run_git(\$estatus, sub { 
133         die if defined $l; 
134         $l = $_; },
135             qw(config), $cfgvar);
136     if (defined $l) {
137         die "$cfgvar ($estatus)" if $estatus;
138         return $l;
139     } else {
140         die "$cfgvar ($estatus)" unless $estatus==0 || $estatus==256;
141         return $default;
142     }
143 }
144
145 sub git_dir () {
146     our $git_dir;
147     if (!defined $git_dir) {
148         $git_dir = run_git_1line(qw(rev-parse --git-dir));
149     }
150     return $git_dir;
151 }
152
153 #----- specific interactions with git -----
154
155 sub chdir_toplevel () {
156     my $toplevel;
157     run_git(sub { $toplevel = $_; }, 
158             qw(rev-parse --show-toplevel));
159     die "not in working tree?\n" unless defined $toplevel;
160     chdir $toplevel or die "chdir toplevel $toplevel: $!\n";
161 }
162
163 sub enable_reflog ($) {
164     my ($branchref) = @_;
165     $branchref =~ m#^refs/# or die;
166     my $logsdir = git_dir().'/logs/';
167     my $dirname = $logsdir.dirname($branchref);
168     make_path($dirname) or die "$dirname $!";
169     open REFLOG, '>>', $logsdir.$branchref or die "$logsdir$branchref $!";
170     close REFLOG or die $!;
171 }    
172
173 sub check_no_unwanted_metadata ($) {
174     # for checking foreign branches aren't contaminated
175     my ($gitbranch) = @_;
176     run_git_check_nooutput('foreign unexpectedly contains',
177                            qw(ls-tree --name-only),
178                            "$gitbranch:",
179                            qw(.topbloke));
180 }
181
182 #----- configuring a tree -----
183
184 sub setup_config () {
185     my (@files) = (qw(msg deps included props pprops));
186     my $version = 1;
187     foreach my $iteration (qw(0 1)) {
188         foreach my $file (@files) {
189             my $cfgname = "merge.topbloke-$file";
190             my ($current, $current_estatus);
191             run_git(\$current_estatus,
192                     sub { $current = $_; },
193                     qw(config), "$cfgname.driver");
194             $current = "## failed $current_estatus" if $current_estatus;
195             next if $current =~ m/^topbloke-merge-driver --v$version /o;
196             die "$file $current ?" if $iteration;
197             debug("setting merge driver $file");
198             run_git(qw(config), "$cfgname.name",
199                     "topbloke merge driver for $file");
200             run_git(qw(config), "$cfgname.driver",
201                     "topbloke-merge-driver --v$version".
202                     " $file %O %A %B %L");
203         }
204         my ($newattrs, $attrsfile);
205         foreach my $file (@files) {
206             my $path = ".topbloke/$file";
207             my $current = run_git_1line(qw(check-attr merge), $path);
208             $current =~ s#^\Q$path\E: merge: ## or die "$file $current ?";
209             my $want = "topbloke-$file";
210             next if $current eq $want;
211             die "$file $current ?" unless $current eq 'unspecified';
212             die "$file $current ?" if $iteration;
213             if (!$newattrs) {
214                 $attrsfile = git_dir()."/info/attributes";
215                 $newattrs = new IO::File "$attrsfile.tmp", 'w'
216                     or die "$attrsfile.tmp: $!";
217                 if (!open OA, '<', "$attrsfile") {
218                     die "$attrsfile $!" unless $!==&ENOENT;
219                 } else {
220                     while (<OA>) {
221                         print $newattrs $_ or die $!;
222                         print "\n" or die $! unless chomp;
223                     }
224                     die $! if OA->error;
225                     die $! unless close OA;
226                 }
227             }
228             print $newattrs "$path\tmerge=$want\n" or die $!;
229         }
230         last if !$newattrs;
231         close $newattrs or die $!;
232         rename "$attrsfile.tmp", "$attrsfile" or die $!;
233     }
234 }
235
236 #----- branch and patch specs and parsed patch names -----
237
238 sub current_branch () {
239     open R, git_dir().'/HEAD' or die "open HEAD $!";
240     my $ref = <R>;  defined $ref or die $!;
241     close R;
242     chomp $ref or die;
243     if ($ref !~ s#^ref: ##) {
244         return {
245             Kind => 'detached',
246             Ref => $ref,
247         };
248     }
249     if ($ref =~ m#^refs/topbloke-(tip|base)s/([^/\@]*)\@([^/\@]*)/([^/]*)/#) {
250         my $fullname = "$2\@$3/$4/$'";
251         return {
252             Kind => $1,
253             Email => $2,
254             Domain => $3,
255             Date => $4,
256             Nick => $', #',
257             Ref => $ref,
258             DepSpec => $fullname,
259             Fullname => $fullname,
260         };
261     } elsif ($ref =~ m#^refs/heads/#) {
262         return {
263             Kind => 'foreign',
264             Ref => $ref,
265             DepSpec => ".f $ref",
266         };
267     } else {
268         return {
269             Kind => 'weird',
270             Ref => $ref,
271         };
272     }
273 }
274
275 sub parse_patch_name ($) {
276     my ($patch) = @_;
277     my ($eaddr, $date, $nick) = split /\//, $patch, 3;
278     defined $nick && length $nick or die "$patch ?";
279     my ($email, $domain) = $eaddr =~ m/^(.*)\@([^\@]+)$/
280         or die "$patch eaddr ?";
281     return {
282         Email => $email,
283         Domain => $domain,
284         Date => $date,
285         Nick => $nick,
286         Kind => 'tip',
287         DepSpec => $patch,
288         Fullname => $patch,
289         Ref => "refs/topbloke-tips/$patch",
290     };
291 }
292
293 sub parse_patch_spec ($) {
294     my ($orig) = @_;
295     local $_ = $orig;
296     my $spec = { }; # Email Domain DatePrefix DateNear Nick
297     my $set = sub {
298         my ($key,$val,$whats) = @_;
299         die "multiple $whats in patch spec\n" if exists $spec->{$key};
300         $spec->{$key} = $val;
301     };
302     my $rel_levels;
303     for (;;) {
304         if (s#([^/\@]*)\@([^/\@]*)/##) {
305             $set->('Email', $1, "email local parts") if length $1;
306             $set->('Domain', $2, "email domains") if length $1;
307         } elsif (s#([^/]*\~[^/]*)/##) {
308             my $dspec = $1;
309             $dspec =~ y/~/ /;
310             open DATE, "-|", 'date','+%s','-d',$dspec or die $!;
311             my $l = <DATE>;
312             close DATE or die "date parsing failed\n";
313             chomp $l or die;
314             $set->('DateNear', $l, 'nearby dates');
315         } elsif (s#^([0-9][^/]*)/##) {
316             my $dspec = $1;
317             $dspec =~ 
318       m/^\d{4}(?:-\d\d(?:-\d\d(?:T(?:\d\d(?:\d\d(?:\d\d(?:Z)?)?)?)?)?)?)?$/
319                 or die "bad date prefix \`$dspec'\n";
320             $set->('DatePrefix', $dspec, 'date prefixes');
321         } elsif (s#^\./##) {
322             $rel_levels ||= 1;
323         } elsif (s#^\.\./##) {
324             $rel_levels ||= 1;
325             $rel_levels++;
326         } else {
327             last;
328         }
329     }
330     if (defined $rel_levels) {
331         my $branch = current_branch();
332         if (!defined $branch->{Nick}) {
333             die "relative patch spec \`$orig',".
334                 " but current branch not a topbloke patch\n";
335         }
336         my ($ceaddr,$cdate,@l) = split /\//, $branch->{Nick};
337         @l >= $rel_levels or
338             die "relative patch spec \`$orig' has too many ../s\n";
339         $_ = (join '/', @l[0..$#l-$rel_levels]).'/'.$_;
340     } elsif (length) {
341         $spec->{Nick} = $_;
342     }
343     return $spec;
344 }
345
346 sub patch_matches_spec ($$) {
347     my ($parsedname, $spec) = @_;
348     foreach my $k (qw(Email Domain Nick)) {
349         debug("patch_matches_spec  mismatch $k"), return 0
350             if defined $spec->{$k} &&
351                $parsedname->{$k} ne $spec->{$k};
352     }
353     debug("patch_matches_spec  mismatch DatePrefix"), return 0
354         if defined $spec->{DatePrefix} &&
355            substr($parsedname->{Date}, 0, length $spec->{DatePrefix})
356                ne $spec->{DatePrefix};
357     debug("patch_matches_spec  match"), return 1;
358 }
359
360 #----- reading topbloke metadata -----
361
362 sub foreach_patch ($$$$) {
363     my ($spec, $deleted_ok, $want, $body) = @_;
364     # runs $body->($patch, $parsedname, \%props, \%deps, \%pprops, \%included)
365     #                                   $want->[0]   1        2         3
366     # where $deps->{$fullname} etc. are 1 for true or nonexistent for false
367     #  and if $want->[$item] is not true, the corresponding item may be undef
368     # and $parsedname is only valid if $spec is not undef
369     #  (say $spec { }  if you want the name parsed but no restrictions)
370     my @want = @$want;
371     $want[0] ||= !$deleted_ok;
372     run_git(sub {
373         debug("foreach_patch considering $_");
374         m/ / or die "$_ ?";
375         my $objname = $`;
376         my @out;
377         my $patch = substr($',19); #');
378         my $wantix = 0;
379         foreach my $file (qw(props deps pprops included)) {
380
381             if ($file eq 'deps') {
382                 # do this check after checking for deleted patches,
383                 # so we don't parse deleted patches' names
384                 # right, check the spec next
385                 if ($spec) {
386                     my $have = parse_patch_name($patch);
387                     debug("foreach_patch  mismatch"), return
388                         unless patch_matches_spec($have, $spec);
389                     unshift @out, $have;
390                 } else {
391                     unshift @out, undef;
392                 }
393             }
394
395             if (!$want[$wantix++]) {
396                 push @out, undef;
397                 next;
398             }
399
400             my ($got, $data) = git_get_object("$objname:.topbloke/$file");
401             die "$patch $file ?" unless defined $data;
402             my %data;
403             if ($file !~ m/props/) {
404                 $data{$_}=1 foreach split /\n/, $data;
405             } elseif {
406                 foreach (split /\n/, $data) {
407                     m/ / or m/$/;
408                     $data{$`} = $'; #';
409                 }
410             }
411
412             if ($file eq 'props') {
413                 debug("foreach_patch  Deleted"), return
414                     if !$deleted_ok && $data{Deleted};
415             }
416
417             push @out, \%data;
418         }
419         debug("foreach_patch  YES ".(join '', map { 0+defined } @out)), return
420         $body->($patch, @out);
421             },
422             qw(for-each-ref --format), '%(objectname) %(refname)',
423                 qw(refs/topbloke-tips));
424 }
425
426 #----- updating topbloke metadata -----
427
428 sub propsfile_set_prop ($$$) {
429     # set $value to undef to delete; returns old value
430     my ($propsfile, $prop, $value) = @_;
431     my $wf = wf_start(".topbloke/$propsfile");
432     my $oldvalue;
433     open FI, '<', ".topbloke/$propsfile" or die $!;
434     while (<FI>) {
435         chomp or die;
436         m/ / or m/$/;
437         if ($` eq $prop) {
438             die "prop $prop repeated in $propsfile ?!" if defined $oldvalue;
439             $oldvalue = $'; #';
440         } else {
441             wf($wf, "$_\n");
442         }
443     }
444     FI->error and die $!;
445     close FI or die $!;
446     wf($wf, "$prop $value\n") if defined $value;
447     wf_done($wf);
448     return $oldvalue;
449 }
450
451 sub depssfile_add_dep ($$) {
452     my ($depsfile, $depspec) = @_;
453     my $wf = wf_start(".topbloke/$depsfile");
454     open FI, '<', ".topbloke/$depsfile" or die $!;
455     while (<FI>) {
456         chomp or die;
457         die "dep $depspec already set in $depsfile ?!" if $_ eq $depspec;
458         wf($wf, "$_\n");
459     }
460     FI->error and die $!;
461     close FI or die $!;
462     wf($wf, "$depspec\n");
463     wf_done($wf);
464 }
465
466 #----- general utilities -----
467
468 sub wf_start ($) {
469     my ($path) = @_;
470     my $fh = new IO::File "$path.tmp", '>' or die "create $path.tmp: $!\n";
471     return [ $fh, $path ];
472 }
473
474 sub wf ($$) {
475     my ($wf, $data) = @_;
476     my ($fh, $path) = @$wf;
477     print $fh $data or die "write $path.tmp: $!\n";
478 }
479
480 sub wf_abort ($) {
481     my ($wf) = @_;
482     my ($fh, $path) = @$wf;
483     close $fh;
484     unlink "$path.tmp" or die "remove $path.tmp: $!\n";
485 }
486
487 sub wf_done ($) {
488     my ($wf) = @_;
489     my ($fh, $path) = @$wf;
490     close $fh or die "finish writing $path.tmp: $!\n";
491     rename "$path.tmp", $path or die "install new $path: $!\n";
492 }
493
494 sub wf_contents ($$) {
495     my ($path,$contents) = @_;
496     my $wf = wf_start($path);
497     wf($wf, $contents);
498     wf_done($wf);
499 }
500
501 sub closeout () {
502     STDOUT->error and die $!;
503     close STDOUT or die $!;
504 }
505
506 1;