chiark / gitweb /
Unwanted dep removal search - difficulties
[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 $tiprefs $baserefs
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 sub check_clean_tree ($) {
183     run_git_check_nooutput("operation requires working tree to be clean",
184                            qw(diff --name-only HEAD --));
185     run_git_check_nooutput("operation cannot proceed with staged changes",
186                            qw(diff --cached --name-only HEAD --));
187 }
188
189 #----- configuring a tree -----
190
191 sub setup_config () {
192     my (@files) = (qw(msg deps included props pprops));
193     my $version = 1;
194     foreach my $iteration (qw(0 1)) {
195         foreach my $file (@files) {
196             my $cfgname = "merge.topbloke-$file";
197             my ($current, $current_estatus);
198             run_git(\$current_estatus,
199                     sub { $current = $_; },
200                     qw(config), "$cfgname.driver");
201             $current = "## failed $current_estatus" if $current_estatus;
202             next if $current =~ m/^topbloke-merge-driver --v$version /o;
203             die "$file $current ?" if $iteration;
204             debug("setting merge driver $file");
205             run_git(qw(config), "$cfgname.name",
206                     "topbloke merge driver for $file");
207             run_git(qw(config), "$cfgname.driver",
208                     "topbloke-merge-driver --v$version".
209                     " $file %O %A %B %L");
210         }
211         my ($newattrs, $attrsfile);
212         foreach my $file (@files) {
213             my $path = ".topbloke/$file";
214             my $current = run_git_1line(qw(check-attr merge), $path);
215             $current =~ s#^\Q$path\E: merge: ## or die "$file $current ?";
216             my $want = "topbloke-$file";
217             next if $current eq $want;
218             die "$file $current ?" unless $current eq 'unspecified';
219             die "$file $current ?" if $iteration;
220             if (!$newattrs) {
221                 $attrsfile = git_dir()."/info/attributes";
222                 $newattrs = new IO::File "$attrsfile.tmp", 'w'
223                     or die "$attrsfile.tmp: $!";
224                 if (!open OA, '<', "$attrsfile") {
225                     die "$attrsfile $!" unless $!==&ENOENT;
226                 } else {
227                     while (<OA>) {
228                         print $newattrs $_ or die $!;
229                         print "\n" or die $! unless chomp;
230                     }
231                     die $! if OA->error;
232                     die $! unless close OA;
233                 }
234             }
235             print $newattrs "$path\tmerge=$want\n" or die $!;
236         }
237         last if !$newattrs;
238         close $newattrs or die $!;
239         rename "$attrsfile.tmp", "$attrsfile" or die $!;
240     }
241 }
242
243 #----- branch and patch specs and parsed patch names -----
244
245 our $tiprefs = 'refs/topbloke-tips';
246 our $baserefs = 'refs/topbloke-bases';
247
248 sub current_branch () {
249     open R, git_dir().'/HEAD' or die "open HEAD $!";
250     my $ref = <R>;  defined $ref or die $!;
251     close R;
252     chomp $ref or die;
253     if ($ref !~ s#^ref: ##) {
254         return {
255             Kind => 'detached',
256             Ref => $ref,
257         };
258     }
259     if ($ref =~ m#^refs/topbloke-(tip|base)s/([^/\@]*)\@([^/\@]*)/([^/]*)/#) {
260         my $fullname = "$2\@$3/$4/$'";
261         return {
262             Kind => $1,
263             Email => $2,
264             Domain => $3,
265             Date => $4,
266             Nick => $', #',
267             Ref => $ref,
268             DepSpec => $fullname,
269             Fullname => $fullname,
270         };
271     } elsif ($ref =~ m#^refs/heads/#) {
272         return {
273             Kind => 'foreign',
274             Ref => $ref,
275             DepSpec => ".f $ref",
276         };
277     } else {
278         return {
279             Kind => 'weird',
280             Ref => $ref,
281         };
282     }
283 }
284
285 sub parse_patch_name ($) {
286     my ($patch) = @_;
287     my ($eaddr, $date, $nick) = split /\//, $patch, 3;
288     defined $nick && length $nick or die "$patch ?";
289     my ($email, $domain) = $eaddr =~ m/^(.*)\@([^\@]+)$/
290         or die "$patch eaddr ?";
291     return {
292         Email => $email,
293         Domain => $domain,
294         Date => $date,
295         Nick => $nick,
296         Kind => 'tip',
297         DepSpec => $patch,
298         Fullname => $patch,
299         Ref => "refs/topbloke-tips/$patch",
300     };
301 }
302
303 sub parse_patch_spec ($) {
304     my ($orig) = @_;
305     local $_ = $orig;
306     die 'FORMAT has new spec syntax nyi';
307     my $spec = { }; # Email Domain DatePrefix DateNear Nick
308     my $set = sub {
309         my ($key,$val,$whats) = @_;
310         die "multiple $whats in patch spec\n" if exists $spec->{$key};
311         $spec->{$key} = $val;
312     };
313     my $rel_levels;
314     for (;;) {
315         if (s#([^/\@]*)\@([^/\@]*)/##) {
316             $set->('Email', $1, "email local parts") if length $1;
317             $set->('Domain', $2, "email domains") if length $1;
318         } elsif (s#([^/]*\~[^/]*)/##) {
319             my $dspec = $1;
320             $dspec =~ y/~/ /;
321             open DATE, "-|", 'date','+%s','-d',$dspec or die $!;
322             my $l = <DATE>;
323             close DATE or die "date parsing failed\n";
324             chomp $l or die;
325             $set->('DateNear', $l, 'nearby dates');
326         } elsif (s#^([0-9][^/]*)/##) {
327             my $dspec = $1;
328             $dspec =~ 
329       m/^\d{4}(?:-\d\d(?:-\d\d(?:T(?:\d\d(?:\d\d(?:\d\d(?:Z)?)?)?)?)?)?)?$/
330                 or die "bad date prefix \`$dspec'\n";
331             $set->('DatePrefix', $dspec, 'date prefixes');
332         } elsif (s#^\./##) {
333             $rel_levels ||= 1;
334         } elsif (s#^\.\./##) {
335             $rel_levels ||= 1;
336             $rel_levels++;
337         } else {
338             last;
339         }
340     }
341     if (defined $rel_levels) {
342         my $branch = current_branch();
343         if (!defined $branch->{Nick}) {
344             die "relative patch spec \`$orig',".
345                 " but current branch not a topbloke patch\n";
346         }
347         my ($ceaddr,$cdate,@l) = split /\//, $branch->{Nick};
348         @l >= $rel_levels or
349             die "relative patch spec \`$orig' has too many ../s\n";
350         $_ = (join '/', @l[0..$#l-$rel_levels]).'/'.$_;
351     } elsif (length) {
352         $spec->{Nick} = $_;
353     }
354     return $spec;
355 }
356
357 sub patch_matches_spec ($$) {
358     my ($parsedname, $spec) = @_;
359     foreach my $k (qw(Email Domain Nick)) {
360         debug("patch_matches_spec  mismatch $k"), return 0
361             if defined $spec->{$k} &&
362                $parsedname->{$k} ne $spec->{$k};
363     }
364     debug("patch_matches_spec  mismatch DatePrefix"), return 0
365         if defined $spec->{DatePrefix} &&
366            substr($parsedname->{Date}, 0, length $spec->{DatePrefix})
367                ne $spec->{DatePrefix};
368     debug("patch_matches_spec  match"), return 1;
369 }
370
371 #----- reading topbloke metadata -----
372
373 sub foreach_patch ($$$$) {
374     my ($spec, $deleted_ok, $want, $body) = @_;
375     # runs $body->($patch, $parsedname, \%props, \%deps, \%pprops, \%included)
376     #                                   $want->[0]   1        2         3
377     # where $deps->{$fullname} etc. are 1 for true or nonexistent for false
378     #  and if $want->[$item] is not true, the corresponding item may be undef
379     # and $parsedname is only valid if $spec is not undef
380     #  (say $spec { }  if you want the name parsed but no restrictions)
381     my @want = @$want;
382     $want[0] ||= !$deleted_ok;
383     run_git(sub {
384         debug("foreach_patch considering $_");
385         m/ / or die "$_ ?";
386         my $objname = $`;
387         my @out;
388         my $patch = substr($',19); #');
389         my $wantix = 0;
390         foreach my $file (qw(props deps pprops included)) {
391
392             if ($file eq 'deps') {
393                 # do this check after checking for deleted patches,
394                 # so we don't parse deleted patches' names
395                 # right, check the spec next
396                 if ($spec) {
397                     my $have = parse_patch_name($patch);
398                     debug("foreach_patch  mismatch"), return
399                         unless patch_matches_spec($have, $spec);
400                     unshift @out, $have;
401                 } else {
402                     unshift @out, undef;
403                 }
404             }
405
406             if (!$want[$wantix++]) {
407                 push @out, undef;
408                 next;
409             }
410
411             my ($got, $data) = git_get_object("$objname:.topbloke/$file");
412             die "$patch $file ?" unless defined $data;
413             my %data;
414             if ($file !~ m/props/) {
415                 $data{$_}=1 foreach split /\n/, $data;
416             } elseif {
417                 foreach (split /\n/, $data) {
418                     m/ / or m/$/;
419                     $data{$`} = $'; #';
420                 }
421             }
422
423             if ($file eq 'props') {
424                 debug("foreach_patch  Deleted"), return
425                     if !$deleted_ok && $data{Deleted};
426             }
427
428             push @out, \%data;
429         }
430         debug("foreach_patch  YES ".(join '', map { 0+defined } @out)), return
431         $body->($patch, @out);
432             },
433             qw(for-each-ref --format), '%(objectname) %(refname)',
434                 qw(refs/topbloke-tips));
435 }
436
437 #----- updating topbloke metadata -----
438
439 sub propsfile_set_prop ($$$) {
440     # set $value to undef to delete; returns old value
441     my ($propsfile, $prop, $value) = @_;
442     my $wf = wf_start(".topbloke/$propsfile");
443     my $oldvalue;
444     open FI, '<', ".topbloke/$propsfile" or die $!;
445     while (<FI>) {
446         chomp or die;
447         m/ / or m/$/;
448         if ($` eq $prop) {
449             die "prop $prop repeated in $propsfile ?!" if defined $oldvalue;
450             $oldvalue = $'; #';
451         } else {
452             wf($wf, "$_\n");
453         }
454     }
455     FI->error and die $!;
456     close FI or die $!;
457     wf($wf, "$prop $value\n") if defined $value;
458     wf_done($wf);
459     return $oldvalue;
460 }
461
462 sub depssfile_add_dep ($$) {
463     my ($depsfile, $depspec) = @_;
464     my $wf = wf_start(".topbloke/$depsfile");
465     open FI, '<', ".topbloke/$depsfile" or die $!;
466     while (<FI>) {
467         chomp or die;
468         die "dep $depspec already set in $depsfile ?!" if $_ eq $depspec;
469         wf($wf, "$_\n");
470     }
471     FI->error and die $!;
472     close FI or die $!;
473     wf($wf, "$depspec\n");
474     wf_done($wf);
475 }
476
477 #----- general utilities -----
478
479 sub wf_start ($) {
480     my ($path) = @_;
481     my $fh = new IO::File "$path.tmp", '>' or die "create $path.tmp: $!\n";
482     return [ $fh, $path ];
483 }
484
485 sub wf ($$) {
486     my ($wf, $data) = @_;
487     my ($fh, $path) = @$wf;
488     print $fh $data or die "write $path.tmp: $!\n";
489 }
490
491 sub wf_abort ($) {
492     my ($wf) = @_;
493     my ($fh, $path) = @$wf;
494     close $fh;
495     unlink "$path.tmp" or die "remove $path.tmp: $!\n";
496 }
497
498 sub wf_done ($) {
499     my ($wf) = @_;
500     my ($fh, $path) = @$wf;
501     close $fh or die "finish writing $path.tmp: $!\n";
502     rename "$path.tmp", $path or die "install new $path: $!\n";
503 }
504
505 sub wf_contents ($$) {
506     my ($path,$contents) = @_;
507     my $wf = wf_start($path);
508     wf($wf, $contents);
509     wf_done($wf);
510 }
511
512 sub closeout () {
513     STDOUT->error and die $!;
514     close STDOUT or die $!;
515 }
516
517 1;