11 use File::Path qw(make_path remove_tree);
16 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
20 @EXPORT = qw(debug $tiprefs $baserefs %known_metadata
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 check_no_metadata foreach_unknown_metadata
27 current_branch parse_patch_name parse_patch_spec
30 metafile_process depsfile_add_dep
31 wf_start wf wf_abort wf_done wf_contents
37 our $git_command = 'git';
43 print STDERR "DEBUG: $msg\n" or die $!;
46 #----- general interaction with git -----
49 # takes optional prefix arguments:
50 # coderef hook to call for each line read,
51 # with $_ containing chomped line; if not supplied,
53 # scalarref place to store exit status; if not supplied,
54 # nonzero exit status is fatal
55 my ($estatusr,$linecallr);
58 if (ref $ref eq 'SCALAR') {
60 } elsif (ref $ref eq 'CODE') {
63 die ref($ref)." @_ ?";
66 open GIT, "-|", $git_command, @_ or die $!;
69 chomp or die "$git_command @_ gave $_ ?";
75 die "$git_command @_ $!" if $!;
77 die "$git_command @_ ($?)" unless $estatusr;
80 $$estatusr = 0 if $estatusr;
86 run_git(sub { $l = $_; }, @_);
87 die "git @_ ?" unless defined $l;
91 sub run_git_check_nooutput {
92 my ($what) = shift @_;
93 run_git(sub { die "$what $_\n"; }, @_);
96 sub run_git_test_anyoutput {
98 run_git(sub { $any=1; }, @_);
102 sub git_get_object ($) {
104 our ($gro_pid, $gro_out, $gro_in);
106 $gro_pid = open2($gro_out, $gro_in, $git_command, qw(cat-file --batch))
109 #debug("git_get_object $objname");
110 $SIG{'PIPE'} = 'IGN';
111 print $gro_in $objname,"\n" or die $!;
112 $gro_in->flush or die "$objname $!";
113 $SIG{'PIPE'} = 'DFL';
115 chomp $l or die "$objname $l ?";
116 #debug("git_get_object $objname => $l");
117 if ($l =~ m/ missing$/) {
119 } elsif (my ($type,$bytes) = $l =~ m/^\S+ (\w+) (\d+)$/) {
122 (read $gro_out, $data, $bytes) == $bytes or die "$objname $!";
125 (read $gro_out, $nl, 1) == 1 or die "$objname $!";
126 $nl eq "\n" or die "$objname ?";
127 return ($type, $data);
133 sub git_config ($$) {
134 my ($cfgvar, $default) = @_;
136 run_git(\$estatus, sub {
139 qw(config), $cfgvar);
141 die "$cfgvar ($estatus)" if $estatus;
144 die "$cfgvar ($estatus)" unless $estatus==0 || $estatus==256;
151 if (!defined $git_dir) {
152 $git_dir = run_git_1line(qw(rev-parse --git-dir));
157 #----- specific interactions with git -----
159 sub chdir_toplevel () {
161 run_git(sub { $toplevel = $_; },
162 qw(rev-parse --show-toplevel));
163 die "not in working tree?\n" unless defined $toplevel;
164 chdir $toplevel or die "chdir toplevel $toplevel: $!\n";
167 sub enable_reflog ($) {
168 my ($branchref) = @_;
169 $branchref =~ m#^refs/# or die;
170 my $logsdir = git_dir().'/logs/';
171 my $dirname = $logsdir.dirname($branchref);
172 make_path($dirname) or die "$dirname $!";
173 open REFLOG, '>>', $logsdir.$branchref or die "$logsdir$branchref $!";
174 close REFLOG or die $!;
177 sub check_no_metadata ($) {
178 # for checking foreign branches aren't contaminated
179 my ($gitbranch) = @_;
180 run_git_check_nooutput('foreign unexpectedly contains',
181 qw(ls-tree --name-only),
186 sub foreach_unknown_metadata ($$) {
187 my ($ref, $code) = @_;
189 # Executes $code for each tolerable unknown metadata found, with
190 # $_ being the (leaf) name of the metadata file
192 die unless s#^\.topbloke/##;
193 next if $known_metadata{$_};
194 m/-$/ or die "found unsupported metadata in $ref; you must upgrade\n";
197 qw(ls-tree --name-only -r HEAD: .topbloke));
200 sub check_clean_tree ($) {
201 run_git_check_nooutput("operation requires working tree to be clean",
202 qw(diff --name-only HEAD --));
203 run_git_check_nooutput("operation cannot proceed with staged changes",
204 qw(diff --cached --name-only HEAD --));
207 $known_metadata{$_}=1 foreach qw(msg patch base deps deleted
210 #----- configuring a tree -----
212 sub setup_config () {
213 my (@files) = (qw(lwildcard- msg patch base deps deleted
214 +iwildcard- +included +ends));
222 foreach my $iteration (qw(0 1)) {
223 foreach my $file (@files) {
224 my $cfgname = "merge.topbloke-".$drvname->($file);
225 my ($current, $current_estatus);
226 run_git(\$current_estatus,
227 sub { $current = $_; },
228 qw(config), "$cfgname.driver");
229 $current = "## failed $current_estatus" if $current_estatus;
230 next if $current =~ m/^topbloke-merge-driver --v$version /o;
231 die "$file $current ?" if $iteration;
232 debug("setting merge driver $file");
233 run_git(qw(config), "$cfgname.name",
234 "topbloke merge driver for $file");
235 run_git(qw(config), "$cfgname.driver",
236 "topbloke-merge-driver --v$version".
237 " $file %O %A %B %L");
239 my ($newattrsprefix, $newattrs, $attrsfile);
243 foreach my $file (@files) {
244 my ($pat,$check) = ($file, $file);
245 if ($file =~ m/wildcard/) {
246 $pat = ($file =~ m/^\+/ ? '+' : '[^+]').'*';
247 $check =~ s/\w.*/xxxunknown/ or die;
249 $pat = ".topbloke/$pat";
250 $check = ".topbloke/$check";
251 my $want = "topbloke-".$drvname->($file);
252 $attrs .= "$pat\tmerge=$want\n";
253 my $current = run_git_1line(qw(check-attr merge), $check);
254 $current =~ s#^\Q$check\E: merge: ## or die "$file $current ?";
255 next if $current eq $want;
256 die "$file $current ?" unless
257 $current eq 'unspecified' ||
258 $current =~ m/^topbloke-\wwildcard$/;
259 push @needupdate, "$file=$current";
262 $attrsfile = git_dir()."/info/attributes";
263 my $newattrsf = new IO::File "$attrsfile.tmp", 'w'
264 or die "$attrsfile.tmp: $!";
265 die "@needupdate ?" if $iteration;
266 if (!open OA, '<', "$attrsfile") {
267 die "$attrsfile $!" unless $!==ENOENT;
270 next if m#^\.topbloke/#;
271 print $newattrsf $_ or die $!;
272 print $newattrsf "\n" or die $! unless chomp;
275 die $! unless close OA;
277 print $newattrsf $attrs or die $!;
278 close $newattrsf or die $!;
279 rename "$attrsfile.tmp", "$attrsfile" or die $!;
284 #----- branch and patch specs and parsed patch names -----
286 our $tiprefs = 'refs/topbloke-tips';
287 our $baserefs = 'refs/topbloke-bases';
289 sub current_branch () {
290 open R, git_dir().'/HEAD' or die "open HEAD $!";
291 my $ref = <R>; defined $ref or die $!;
294 if ($ref !~ s#^ref: ##) {
300 if ($ref =~ m#^refs/topbloke-(tip|base)s/([^/\@]*)\@([^/\@]*)/([^/]*)/#) {
301 my $fullname = "$2\@$3/$4/$'";
309 DepSpec => $fullname,
310 Fullname => $fullname,
313 } elsif ($ref =~ m#^refs/heads/#) {
327 sub parse_patch_name ($) {
329 my ($eaddr, $date, $nick) = split /\//, $patch, 3;
330 defined $nick && length $nick or die "$patch ?";
331 my ($email, $domain) = $eaddr =~ m/^(.*)\@([^\@]+)$/
332 or die "$patch eaddr ?";
341 Ref => "refs/topbloke-tips/$patch",
345 sub parse_patch_spec ($) {
348 warn 'FORMAT has new spec syntax nyi';
349 my $spec = { }; # Email Domain DatePrefix DateNear Nick
351 my ($key,$val,$whats) = @_;
352 die "multiple $whats in patch spec\n" if exists $spec->{$key};
353 $spec->{$key} = $val;
357 if (s#([^/\@]*)\@([^/\@]*)/##) {
358 $set->('Email', $1, "email local parts") if length $1;
359 $set->('Domain', $2, "email domains") if length $1;
360 } elsif (s#([^/]*\~[^/]*)/##) {
363 open DATE, "-|", 'date','+%s','-d',$dspec or die $!;
365 close DATE or die "date parsing failed\n";
367 $set->('DateNear', $l, 'nearby dates');
368 } elsif (s#^([0-9][^/]*)/##) {
371 m/^\d{4}(?:-\d\d(?:-\d\d(?:T(?:\d\d(?:\d\d(?:\d\d(?:Z)?)?)?)?)?)?)?$/
372 or die "bad date prefix \`$dspec'\n";
373 $set->('DatePrefix', $dspec, 'date prefixes');
376 } elsif (s#^\.\./##) {
383 if (defined $rel_levels) {
384 my $branch = current_branch();
385 if (!defined $branch->{Nick}) {
386 die "relative patch spec \`$orig',".
387 " but current branch not a topbloke patch\n";
389 my ($ceaddr,$cdate,@l) = split /\//, $branch->{Nick};
391 die "relative patch spec \`$orig' has too many ../s\n";
392 $_ = (join '/', @l[0..$#l-$rel_levels]).'/'.$_;
399 sub patch_matches_spec ($$) {
400 my ($parsedname, $spec) = @_;
401 foreach my $k (qw(Email Domain Nick)) {
402 debug("patch_matches_spec mismatch $k"), return 0
403 if defined $spec->{$k} &&
404 $parsedname->{$k} ne $spec->{$k};
406 debug("patch_matches_spec mismatch DatePrefix"), return 0
407 if defined $spec->{DatePrefix} &&
408 substr($parsedname->{Date}, 0, length $spec->{DatePrefix})
409 ne $spec->{DatePrefix};
410 debug("patch_matches_spec match"), return 1;
413 #----- reading topbloke metadata -----
415 sub foreach_patch ($$$$) {
416 my ($spec, $deleted_ok, $want, $body) = @_;
417 # runs $body->($patch, $parsedname, \%meta)
418 # where $meta{<metadata filename>} is, for <metadata filename> in @$want:
419 # undefined if metadata file doesn't exist
420 # defined with contents of file
421 # and $parsedname is only valid if $spec is not undef
422 # (say $spec { } if you want the name parsed but no restrictions)
423 # entries in want may also be "<metadata filename>_"
424 # which means "strip trailing newlines" (result key in %meta is the same)
425 # <metadata filename> may instead be "B_<metadata filename>"
426 # which means to look in the corresponding base branch
430 @want = ($thing, grep { $_ ne $thing } @want);
432 $atfront->(' patch');
433 $atfront->('deleted') unless $deleted_ok;
435 debug("foreach_patch considering $_");
440 my $patch = substr($',19); #');
442 foreach my $wantent (@want) {
444 my $stripnl = ($file =~ s/_$//);
446 my $inbase = ($file =~ s/^B_//);
448 if ($file eq ' patch') {
450 $parsedname = parse_patch_name($patch);
451 if (!patch_matches_spec($parsedname, $spec)) {
452 debug("foreach_patch mismatch");
459 my $objkey = (!$inbase ? "$objname" :
460 "$baserefs/$patch").":.topbloke/$file";
461 my ($got, $data) = git_get_object($objkey);
462 if ($got eq 'missing') {
464 } elsif ($got eq 'blob') {
466 if ($file eq 'deleted' && !$deleted_ok) {
467 debug("foreach_patch Deleted");
471 warn "patch $patch object $objkey has unexpected type $got!\n";
475 debug("foreach_patch YES $patch");
476 $body->($patch, $parsedname, \%meta);
478 qw(for-each-ref --format), '%(objectname) %(refname)',
479 qw(refs/topbloke-tips));
482 #----- updating topbloke metadata -----
484 sub metafile_process ($$$$$) {
485 my ($metafile, $startcode, $linecode, $endcode, $enoentcode) = @_;
486 # runs $startcode->($outwf) at start
487 # runs $linecode->($outwf) for each old line, with $_ the chomped line
488 # may modify $_, which will be written to $outf
489 # at end runs $endcode->($outwf);
490 # runs $enoentcode->($outwf) instead of ever calling $linecode
491 # if the existing file does not exist;
492 # if it's false dies instead
493 # any of these may return false, in which case we quit immediately
494 # any of these except enoentcode may be undef to mean "noop"
495 # if they all return true, we install the new file
496 my $wf = wf_start(".topbloke/$metafile");
498 return 1 unless $_->[0];
499 return 1 if $_->[0]($wf);
504 return unless $call->($startcode);
505 if (!open FI, '<', ".topbloke/$metafile") {
506 die "$metafile $!" unless $!==ENOENT;
507 die "$metafile $!" unless $enoentcode;
508 return unless $call->($enoentcode);
512 return unless $call->($linecode);
515 FI->error and die $!;
518 return unless $call->($endcode);
523 sub depsfile_add_dep ($$) {
524 my ($depsfile, $depspec) = @_;
525 metafile_process($depsfile, undef, sub {
526 die "dep $depspec already set in $depsfile ?!" if $_ eq $depspec;
528 wf($_->[0], "$depspec\n");
532 #----- general utilities -----
536 my $fh = new IO::File "$path.tmp", '>' or die "create $path.tmp: $!\n";
537 return [ $fh, $path ];
541 my ($wf, $data) = @_;
542 my ($fh, $path) = @$wf;
543 print $fh $data or die "write $path.tmp: $!\n";
548 my ($fh, $path) = @$wf;
550 unlink "$path.tmp" or die "remove $path.tmp: $!\n";
555 my ($fh, $path) = @$wf;
556 close $fh or die "finish writing $path.tmp: $!\n";
557 rename "$path.tmp", $path or die "install new $path: $!\n";
560 sub wf_contents ($$) {
561 my ($path,$contents) = @_;
562 my $wf = wf_start($path);
568 STDOUT->error and die $!;
569 close STDOUT or die $!;