4 #### This application is a CVS emulation layer for git.
5 #### It is intended for clients to connect over SSH.
6 #### See the documentation for more details.
8 #### Copyright The Open University UK - 2006.
10 #### Authors: Martyn Smith <martyn@catalyst.net.nz>
11 #### Martin Langhoff <martin@catalyst.net.nz>
14 #### Released under the GNU Public License, version 2.
23 use File::Temp qw/tempdir tempfile/;
26 my $log = GITCVS::log->new();
44 # Enable autoflush for STDOUT (otherwise the whole thing falls apart)
47 #### Definition and mappings of functions ####
51 'Valid-responses' => \&req_Validresponses,
52 'valid-requests' => \&req_validrequests,
53 'Directory' => \&req_Directory,
54 'Entry' => \&req_Entry,
55 'Modified' => \&req_Modified,
56 'Unchanged' => \&req_Unchanged,
57 'Questionable' => \&req_Questionable,
58 'Argument' => \&req_Argument,
59 'Argumentx' => \&req_Argument,
60 'expand-modules' => \&req_expandmodules,
62 'remove' => \&req_remove,
64 'update' => \&req_update,
69 'tag' => \&req_CATCHALL,
70 'status' => \&req_status,
71 'admin' => \&req_CATCHALL,
72 'history' => \&req_CATCHALL,
73 'watchers' => \&req_CATCHALL,
74 'editors' => \&req_CATCHALL,
75 'annotate' => \&req_annotate,
76 'Global_option' => \&req_Globaloption,
77 #'annotate' => \&req_CATCHALL,
80 ##############################################
83 # $state holds all the bits of information the clients sends us that could
84 # potentially be useful when it comes to actually _doing_ something.
85 my $state = { prependdir => '' };
86 $log->info("--------------- STARTING -----------------");
88 my $TEMP_DIR = tempdir( CLEANUP => 1 );
89 $log->debug("Temporary directory is '$TEMP_DIR'");
91 # if we are called with a pserver argument,
92 # deal with the authentication cat before entering the
94 $state->{method} = 'ext';
95 if (@ARGV && $ARGV[0] eq 'pserver') {
96 $state->{method} = 'pserver';
97 my $line = <STDIN>; chomp $line;
98 unless( $line eq 'BEGIN AUTH REQUEST') {
99 die "E Do not understand $line - expecting BEGIN AUTH REQUEST\n";
101 $line = <STDIN>; chomp $line;
102 req_Root('root', $line) # reuse Root
103 or die "E Invalid root $line \n";
104 $line = <STDIN>; chomp $line;
105 unless ($line eq 'anonymous') {
106 print "E Only anonymous user allowed via pserver\n";
107 print "I HATE YOU\n";
109 $line = <STDIN>; chomp $line; # validate the password?
110 $line = <STDIN>; chomp $line;
111 unless ($line eq 'END AUTH REQUEST') {
112 die "E Do not understand $line -- expecting END AUTH REQUEST\n";
114 print "I LOVE YOU\n";
115 # and now back to our regular programme...
118 # Keep going until the client closes the connection
123 # Check to see if we've seen this method, and call appropriate function.
124 if ( /^([\w-]+)(?:\s+(.*))?$/ and defined($methods->{$1}) )
126 # use the $methods hash to call the appropriate sub for this command
127 #$log->info("Method : $1");
128 &{$methods->{$1}}($1,$2);
130 # log fatal because we don't understand this function. If this happens
131 # we're fairly screwed because we don't know if the client is expecting
132 # a response. If it is, the client will hang, we'll hang, and the whole
133 # thing will be custard.
134 $log->fatal("Don't understand command $_\n");
135 die("Unknown command $_");
139 $log->debug("Processing time : user=" . (times)[0] . " system=" . (times)[1]);
140 $log->info("--------------- FINISH -----------------");
142 # Magic catchall method.
143 # This is the method that will handle all commands we haven't yet
144 # implemented. It simply sends a warning to the log file indicating a
145 # command that hasn't been implemented has been invoked.
148 my ( $cmd, $data ) = @_;
149 $log->warn("Unhandled command : req_$cmd : $data");
154 # Response expected: no. Tell the server which CVSROOT to use. Note that
155 # pathname is a local directory and not a fully qualified CVSROOT variable.
156 # pathname must already exist; if creating a new root, use the init
157 # request, not Root. pathname does not include the hostname of the server,
158 # how to access the server, etc.; by the time the CVS protocol is in use,
159 # connection, authentication, etc., are already taken care of. The Root
160 # request must be sent only once, and it must be sent before any requests
161 # other than Valid-responses, valid-requests, UseUnchanged, Set or init.
164 my ( $cmd, $data ) = @_;
165 $log->debug("req_Root : $data");
167 $state->{CVSROOT} = $data;
169 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
170 unless (-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') {
171 print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
173 print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
177 my @gitvars = `git-config -l`;
179 print "E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n";
181 print "error 1 - problem executing git-config\n";
184 foreach my $line ( @gitvars )
186 next unless ( $line =~ /^(.*?)\.(.*?)(?:\.(.*?))?=(.*)$/ );
190 $cfg->{$1}{$2}{$3} = $4;
194 unless ( defined ( $cfg->{gitcvs}{enabled} ) and $cfg->{gitcvs}{enabled} =~ /^\s*(1|true|yes)\s*$/i )
196 print "E GITCVS emulation needs to be enabled on this repo\n";
197 print "E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n";
199 print "error 1 GITCVS emulation disabled\n";
203 if ( defined ( $cfg->{gitcvs}{logfile} ) )
205 $log->setfile($cfg->{gitcvs}{logfile});
213 # Global_option option \n
214 # Response expected: no. Transmit one of the global options `-q', `-Q',
215 # `-l', `-t', `-r', or `-n'. option must be one of those strings, no
216 # variations (such as combining of options) are allowed. For graceful
217 # handling of valid-requests, it is probably better to make new global
218 # options separate requests, rather than trying to add them to this
222 my ( $cmd, $data ) = @_;
223 $log->debug("req_Globaloption : $data");
224 $state->{globaloptions}{$data} = 1;
227 # Valid-responses request-list \n
228 # Response expected: no. Tell the server what responses the client will
229 # accept. request-list is a space separated list of tokens.
230 sub req_Validresponses
232 my ( $cmd, $data ) = @_;
233 $log->debug("req_Validresponses : $data");
235 # TODO : re-enable this, currently it's not particularly useful
236 #$state->{validresponses} = [ split /\s+/, $data ];
240 # Response expected: yes. Ask the server to send back a Valid-requests
242 sub req_validrequests
244 my ( $cmd, $data ) = @_;
246 $log->debug("req_validrequests");
248 $log->debug("SEND : Valid-requests " . join(" ",keys %$methods));
249 $log->debug("SEND : ok");
251 print "Valid-requests " . join(" ",keys %$methods) . "\n";
255 # Directory local-directory \n
256 # Additional data: repository \n. Response expected: no. Tell the server
257 # what directory to use. The repository should be a directory name from a
258 # previous server response. Note that this both gives a default for Entry
259 # and Modified and also for ci and the other commands; normal usage is to
260 # send Directory for each directory in which there will be an Entry or
261 # Modified, and then a final Directory for the original directory, then the
262 # command. The local-directory is relative to the top level at which the
263 # command is occurring (i.e. the last Directory which is sent before the
264 # command); to indicate that top level, `.' should be sent for
268 my ( $cmd, $data ) = @_;
270 my $repository = <STDIN>;
274 $state->{localdir} = $data;
275 $state->{repository} = $repository;
276 $state->{path} = $repository;
277 $state->{path} =~ s/^$state->{CVSROOT}\///;
278 $state->{module} = $1 if ($state->{path} =~ s/^(.*?)(\/|$)//);
279 $state->{path} .= "/" if ( $state->{path} =~ /\S/ );
281 $state->{directory} = $state->{localdir};
282 $state->{directory} = "" if ( $state->{directory} eq "." );
283 $state->{directory} .= "/" if ( $state->{directory} =~ /\S/ );
285 if ( (not defined($state->{prependdir}) or $state->{prependdir} eq '') and $state->{localdir} eq "." and $state->{path} =~ /\S/ )
287 $log->info("Setting prepend to '$state->{path}'");
288 $state->{prependdir} = $state->{path};
289 foreach my $entry ( keys %{$state->{entries}} )
291 $state->{entries}{$state->{prependdir} . $entry} = $state->{entries}{$entry};
292 delete $state->{entries}{$entry};
296 if ( defined ( $state->{prependdir} ) )
298 $log->debug("Prepending '$state->{prependdir}' to state|directory");
299 $state->{directory} = $state->{prependdir} . $state->{directory}
301 $log->debug("req_Directory : localdir=$data repository=$repository path=$state->{path} directory=$state->{directory} module=$state->{module}");
304 # Entry entry-line \n
305 # Response expected: no. Tell the server what version of a file is on the
306 # local machine. The name in entry-line is a name relative to the directory
307 # most recently specified with Directory. If the user is operating on only
308 # some files in a directory, Entry requests for only those files need be
309 # included. If an Entry request is sent without Modified, Is-modified, or
310 # Unchanged, it means the file is lost (does not exist in the working
311 # directory). If both Entry and one of Modified, Is-modified, or Unchanged
312 # are sent for the same file, Entry must be sent first. For a given file,
313 # one can send Modified, Is-modified, or Unchanged, but not more than one
317 my ( $cmd, $data ) = @_;
319 #$log->debug("req_Entry : $data");
321 my @data = split(/\//, $data);
323 $state->{entries}{$state->{directory}.$data[1]} = {
324 revision => $data[2],
325 conflict => $data[3],
327 tag_or_date => $data[5],
330 $log->info("Received entry line '$data' => '" . $state->{directory} . $data[1] . "'");
333 # Questionable filename \n
334 # Response expected: no. Additional data: no. Tell the server to check
335 # whether filename should be ignored, and if not, next time the server
336 # sends responses, send (in a M response) `?' followed by the directory and
337 # filename. filename must not contain `/'; it needs to be a file in the
338 # directory named by the most recent Directory request.
341 my ( $cmd, $data ) = @_;
343 $log->debug("req_Questionable : $data");
344 $state->{entries}{$state->{directory}.$data}{questionable} = 1;
348 # Response expected: yes. Add a file or directory. This uses any previous
349 # Argument, Directory, Entry, or Modified requests, if they have been sent.
350 # The last Directory sent specifies the working directory at the time of
351 # the operation. To add a directory, send the directory to be added using
352 # Directory and Argument requests.
355 my ( $cmd, $data ) = @_;
361 foreach my $filename ( @{$state->{args}} )
363 $filename = filecleanup($filename);
365 unless ( defined ( $state->{entries}{$filename}{modified_filename} ) )
367 print "E cvs add: nothing known about `$filename'\n";
370 # TODO : check we're not squashing an already existing file
371 if ( defined ( $state->{entries}{$filename}{revision} ) )
373 print "E cvs add: `$filename' has already been entered\n";
377 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
379 print "E cvs add: scheduling file `$filename' for addition\n";
381 print "Checked-in $dirpart\n";
383 my $kopts = kopts_from_path($filepart);
384 print "/$filepart/0//$kopts/\n";
389 if ( $addcount == 1 )
391 print "E cvs add: use `cvs commit' to add this file permanently\n";
393 elsif ( $addcount > 1 )
395 print "E cvs add: use `cvs commit' to add these files permanently\n";
402 # Response expected: yes. Remove a file. This uses any previous Argument,
403 # Directory, Entry, or Modified requests, if they have been sent. The last
404 # Directory sent specifies the working directory at the time of the
405 # operation. Note that this request does not actually do anything to the
406 # repository; the only effect of a successful remove request is to supply
407 # the client with a new entries line containing `-' to indicate a removed
408 # file. In fact, the client probably could perform this operation without
409 # contacting the server, although using remove may cause the server to
410 # perform a few more checks. The client sends a subsequent ci request to
411 # actually record the removal in the repository.
414 my ( $cmd, $data ) = @_;
418 # Grab a handle to the SQLite db and do any necessary updates
419 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
422 #$log->debug("add state : " . Dumper($state));
426 foreach my $filename ( @{$state->{args}} )
428 $filename = filecleanup($filename);
430 if ( defined ( $state->{entries}{$filename}{unchanged} ) or defined ( $state->{entries}{$filename}{modified_filename} ) )
432 print "E cvs remove: file `$filename' still in working directory\n";
436 my $meta = $updater->getmeta($filename);
437 my $wrev = revparse($filename);
439 unless ( defined ( $wrev ) )
441 print "E cvs remove: nothing known about `$filename'\n";
445 if ( defined($wrev) and $wrev < 0 )
447 print "E cvs remove: file `$filename' already scheduled for removal\n";
451 unless ( $wrev == $meta->{revision} )
453 # TODO : not sure if the format of this message is quite correct.
454 print "E cvs remove: Up to date check failed for `$filename'\n";
459 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
461 print "E cvs remove: scheduling `$filename' for removal\n";
463 print "Checked-in $dirpart\n";
465 my $kopts = kopts_from_path($filepart);
466 print "/$filepart/-1.$wrev//$kopts/\n";
473 print "E cvs remove: use `cvs commit' to remove this file permanently\n";
475 elsif ( $rmcount > 1 )
477 print "E cvs remove: use `cvs commit' to remove these files permanently\n";
483 # Modified filename \n
484 # Response expected: no. Additional data: mode, \n, file transmission. Send
485 # the server a copy of one locally modified file. filename is a file within
486 # the most recent directory sent with Directory; it must not contain `/'.
487 # If the user is operating on only some files in a directory, only those
488 # files need to be included. This can also be sent without Entry, if there
489 # is no entry for the file.
492 my ( $cmd, $data ) = @_;
499 # Grab config information
500 my $blocksize = 8192;
501 my $bytesleft = $size;
504 # Get a filehandle/name to write it to
505 my ( $fh, $filename ) = tempfile( DIR => $TEMP_DIR );
507 # Loop over file data writing out to temporary file.
510 $blocksize = $bytesleft if ( $bytesleft < $blocksize );
511 read STDIN, $tmp, $blocksize;
513 $bytesleft -= $blocksize;
518 # Ensure we have something sensible for the file mode
519 if ( $mode =~ /u=(\w+)/ )
526 # Save the file data in $state
527 $state->{entries}{$state->{directory}.$data}{modified_filename} = $filename;
528 $state->{entries}{$state->{directory}.$data}{modified_mode} = $mode;
529 $state->{entries}{$state->{directory}.$data}{modified_hash} = `git-hash-object $filename`;
530 $state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s;
532 #$log->debug("req_Modified : file=$data mode=$mode size=$size");
535 # Unchanged filename \n
536 # Response expected: no. Tell the server that filename has not been
537 # modified in the checked out directory. The filename is a file within the
538 # most recent directory sent with Directory; it must not contain `/'.
541 my ( $cmd, $data ) = @_;
543 $state->{entries}{$state->{directory}.$data}{unchanged} = 1;
545 #$log->debug("req_Unchanged : $data");
549 # Response expected: no. Save argument for use in a subsequent command.
550 # Arguments accumulate until an argument-using command is given, at which
551 # point they are forgotten.
553 # Response expected: no. Append \n followed by text to the current argument
557 my ( $cmd, $data ) = @_;
559 # Argumentx means: append to last Argument (with a newline in front)
561 $log->debug("$cmd : $data");
563 if ( $cmd eq 'Argumentx') {
564 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" . $data;
566 push @{$state->{arguments}}, $data;
571 # Response expected: yes. Expand the modules which are specified in the
572 # arguments. Returns the data in Module-expansion responses. Note that the
573 # server can assume that this is checkout or export, not rtag or rdiff; the
574 # latter do not access the working directory and thus have no need to
575 # expand modules on the client side. Expand may not be the best word for
576 # what this request does. It does not necessarily tell you all the files
577 # contained in a module, for example. Basically it is a way of telling you
578 # which working directories the server needs to know about in order to
579 # handle a checkout of the specified modules. For example, suppose that the
580 # server has a module defined by
581 # aliasmodule -a 1dir
582 # That is, one can check out aliasmodule and it will take 1dir in the
583 # repository and check it out to 1dir in the working directory. Now suppose
584 # the client already has this module checked out and is planning on using
585 # the co request to update it. Without using expand-modules, the client
586 # would have two bad choices: it could either send information about all
587 # working directories under the current directory, which could be
588 # unnecessarily slow, or it could be ignorant of the fact that aliasmodule
589 # stands for 1dir, and neglect to send information for 1dir, which would
590 # lead to incorrect operation. With expand-modules, the client would first
591 # ask for the module to be expanded:
592 sub req_expandmodules
594 my ( $cmd, $data ) = @_;
598 $log->debug("req_expandmodules : " . ( defined($data) ? $data : "[NULL]" ) );
600 unless ( ref $state->{arguments} eq "ARRAY" )
606 foreach my $module ( @{$state->{arguments}} )
608 $log->debug("SEND : Module-expansion $module");
609 print "Module-expansion $module\n";
617 # Response expected: yes. Get files from the repository. This uses any
618 # previous Argument, Directory, Entry, or Modified requests, if they have
619 # been sent. Arguments to this command are module names; the client cannot
620 # know what directories they correspond to except by (1) just sending the
621 # co request, and then seeing what directory names the server sends back in
622 # its responses, and (2) the expand-modules request.
625 my ( $cmd, $data ) = @_;
629 my $module = $state->{args}[0];
630 my $checkout_path = $module;
632 # use the user specified directory if we're given it
633 $checkout_path = $state->{opt}{d} if ( exists ( $state->{opt}{d} ) );
635 $log->debug("req_co : " . ( defined($data) ? $data : "[NULL]" ) );
637 $log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'");
639 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
641 # Grab a handle to the SQLite db and do any necessary updates
642 my $updater = GITCVS::updater->new($state->{CVSROOT}, $module, $log);
645 $checkout_path =~ s|/$||; # get rid of trailing slashes
647 # Eclipse seems to need the Clear-sticky command
648 # to prepare the 'Entries' file for the new directory.
649 print "Clear-sticky $checkout_path/\n";
650 print $state->{CVSROOT} . "/$module/\n";
651 print "Clear-static-directory $checkout_path/\n";
652 print $state->{CVSROOT} . "/$module/\n";
653 print "Clear-sticky $checkout_path/\n"; # yes, twice
654 print $state->{CVSROOT} . "/$module/\n";
655 print "Template $checkout_path/\n";
656 print $state->{CVSROOT} . "/$module/\n";
659 # instruct the client that we're checking out to $checkout_path
660 print "E cvs checkout: Updating $checkout_path\n";
667 my ($dir, $repodir, $remotedir, $seendirs) = @_;
668 my $parent = dirname($dir);
671 $remotedir =~ s|/+$||;
673 $log->debug("announcedir $dir, $repodir, $remotedir" );
675 if ($parent eq '.' || $parent eq './') {
678 # recurse to announce unseen parents first
679 if (length($parent) && !exists($seendirs->{$parent})) {
680 prepdir($parent, $repodir, $remotedir, $seendirs);
682 # Announce that we are going to modify at the parent level
684 print "E cvs checkout: Updating $remotedir/$parent\n";
686 print "E cvs checkout: Updating $remotedir\n";
688 print "Clear-sticky $remotedir/$parent/\n";
689 print "$repodir/$parent/\n";
691 print "Clear-static-directory $remotedir/$dir/\n";
692 print "$repodir/$dir/\n";
693 print "Clear-sticky $remotedir/$parent/\n"; # yes, twice
694 print "$repodir/$parent/\n";
695 print "Template $remotedir/$dir/\n";
696 print "$repodir/$dir/\n";
699 $seendirs->{$dir} = 1;
702 foreach my $git ( @{$updater->gethead} )
704 # Don't want to check out deleted files
705 next if ( $git->{filehash} eq "deleted" );
707 ( $git->{name}, $git->{dir} ) = filenamesplit($git->{name});
709 if (length($git->{dir}) && $git->{dir} ne './'
710 && $git->{dir} ne $lastdir ) {
711 unless (exists($seendirs{$git->{dir}})) {
712 prepdir($git->{dir}, $state->{CVSROOT} . "/$module/",
713 $checkout_path, \%seendirs);
714 $lastdir = $git->{dir};
715 $seendirs{$git->{dir}} = 1;
717 print "E cvs checkout: Updating /$checkout_path/$git->{dir}\n";
720 # modification time of this file
721 print "Mod-time $git->{modified}\n";
723 # print some information to the client
724 if ( defined ( $git->{dir} ) and $git->{dir} ne "./" )
726 print "M U $checkout_path/$git->{dir}$git->{name}\n";
728 print "M U $checkout_path/$git->{name}\n";
731 # instruct client we're sending a file to put in this path
732 print "Created $checkout_path/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "\n";
734 print $state->{CVSROOT} . "/$module/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "$git->{name}\n";
736 # this is an "entries" line
737 my $kopts = kopts_from_path($git->{name});
738 print "/$git->{name}/1.$git->{revision}//$kopts/\n";
740 print "u=$git->{mode},g=$git->{mode},o=$git->{mode}\n";
743 transmitfile($git->{filehash});
752 # Response expected: yes. Actually do a cvs update command. This uses any
753 # previous Argument, Directory, Entry, or Modified requests, if they have
754 # been sent. The last Directory sent specifies the working directory at the
755 # time of the operation. The -I option is not used--files which the client
756 # can decide whether to ignore are not mentioned and the client sends the
757 # Questionable request for others.
760 my ( $cmd, $data ) = @_;
762 $log->debug("req_update : " . ( defined($data) ? $data : "[NULL]" ));
767 # It may just be a client exploring the available heads/modules
768 # in that case, list them as top level directories and leave it
769 # at that. Eclipse uses this technique to offer you a list of
770 # projects (heads in this case) to checkout.
772 if ($state->{module} eq '') {
773 print "E cvs update: Updating .\n";
774 opendir HEADS, $state->{CVSROOT} . '/refs/heads';
775 while (my $head = readdir(HEADS)) {
776 if (-f $state->{CVSROOT} . '/refs/heads/' . $head) {
777 print "E cvs update: New directory `$head'\n";
786 # Grab a handle to the SQLite db and do any necessary updates
787 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
791 argsfromdir($updater);
793 #$log->debug("update state : " . Dumper($state));
795 # foreach file specified on the command line ...
796 foreach my $filename ( @{$state->{args}} )
798 $filename = filecleanup($filename);
800 $log->debug("Processing file $filename");
802 # if we have a -C we should pretend we never saw modified stuff
803 if ( exists ( $state->{opt}{C} ) )
805 delete $state->{entries}{$filename}{modified_hash};
806 delete $state->{entries}{$filename}{modified_filename};
807 $state->{entries}{$filename}{unchanged} = 1;
811 if ( defined($state->{opt}{r}) and $state->{opt}{r} =~ /^1\.(\d+)/ )
813 $meta = $updater->getmeta($filename, $1);
815 $meta = $updater->getmeta($filename);
818 if ( ! defined $meta )
829 my $wrev = revparse($filename);
831 # If the working copy is an old revision, lets get that version too for comparison.
832 if ( defined($wrev) and $wrev != $meta->{revision} )
834 $oldmeta = $updater->getmeta($filename, $wrev);
837 #$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");
839 # Files are up to date if the working copy and repo copy have the same revision,
840 # and the working copy is unmodified _and_ the user hasn't specified -C
841 next if ( defined ( $wrev )
842 and defined($meta->{revision})
843 and $wrev == $meta->{revision}
844 and $state->{entries}{$filename}{unchanged}
845 and not exists ( $state->{opt}{C} ) );
847 # If the working copy and repo copy have the same revision,
848 # but the working copy is modified, tell the client it's modified
849 if ( defined ( $wrev )
850 and defined($meta->{revision})
851 and $wrev == $meta->{revision}
852 and not exists ( $state->{opt}{C} ) )
854 $log->info("Tell the client the file is modified");
855 print "MT text M \n";
856 print "MT fname $filename\n";
857 print "MT newline\n";
861 if ( $meta->{filehash} eq "deleted" )
863 my ( $filepart, $dirpart ) = filenamesplit($filename,1);
865 $log->info("Removing '$filename' from working copy (no longer in the repo)");
867 print "E cvs update: `$filename' is no longer in the repository\n";
868 # Don't want to actually _DO_ the update if -n specified
869 unless ( $state->{globaloptions}{-n} ) {
870 print "Removed $dirpart\n";
874 elsif ( not defined ( $state->{entries}{$filename}{modified_hash} )
875 or $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash}
876 or $meta->{filehash} eq 'added' )
878 # normal update, just send the new revision (either U=Update,
879 # or A=Add, or R=Remove)
880 if ( defined($wrev) && $wrev < 0 )
882 $log->info("Tell the client the file is scheduled for removal");
883 print "MT text R \n";
884 print "MT fname $filename\n";
885 print "MT newline\n";
888 elsif ( (!defined($wrev) || $wrev == 0) && (!defined($meta->{revision}) || $meta->{revision} == 0) )
890 $log->info("Tell the client the file is scheduled for addition");
891 print "MT text A \n";
892 print "MT fname $filename\n";
893 print "MT newline\n";
898 $log->info("Updating '$filename' to ".$meta->{revision});
899 print "MT +updated\n";
900 print "MT text U \n";
901 print "MT fname $filename\n";
902 print "MT newline\n";
903 print "MT -updated\n";
906 my ( $filepart, $dirpart ) = filenamesplit($filename,1);
908 # Don't want to actually _DO_ the update if -n specified
909 unless ( $state->{globaloptions}{-n} )
911 if ( defined ( $wrev ) )
913 # instruct client we're sending a file to put in this path as a replacement
914 print "Update-existing $dirpart\n";
915 $log->debug("Updating existing file 'Update-existing $dirpart'");
917 # instruct client we're sending a file to put in this path as a new file
918 print "Clear-static-directory $dirpart\n";
919 print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
920 print "Clear-sticky $dirpart\n";
921 print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
923 $log->debug("Creating new file 'Created $dirpart'");
924 print "Created $dirpart\n";
926 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
928 # this is an "entries" line
929 my $kopts = kopts_from_path($filepart);
930 $log->debug("/$filepart/1.$meta->{revision}//$kopts/");
931 print "/$filepart/1.$meta->{revision}//$kopts/\n";
934 $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
935 print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
938 transmitfile($meta->{filehash});
941 $log->info("Updating '$filename'");
942 my ( $filepart, $dirpart ) = filenamesplit($meta->{name},1);
944 my $dir = tempdir( DIR => $TEMP_DIR, CLEANUP => 1 ) . "/";
947 my $file_local = $filepart . ".mine";
948 system("ln","-s",$state->{entries}{$filename}{modified_filename}, $file_local);
949 my $file_old = $filepart . "." . $oldmeta->{revision};
950 transmitfile($oldmeta->{filehash}, $file_old);
951 my $file_new = $filepart . "." . $meta->{revision};
952 transmitfile($meta->{filehash}, $file_new);
954 # we need to merge with the local changes ( M=successful merge, C=conflict merge )
955 $log->info("Merging $file_local, $file_old, $file_new");
956 print "M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into $filename\n";
958 $log->debug("Temporary directory for merge is $dir");
960 my $return = system("git", "merge-file", $file_local, $file_old, $file_new);
965 $log->info("Merged successfully");
966 print "M M $filename\n";
967 $log->debug("Merged $dirpart");
969 # Don't want to actually _DO_ the update if -n specified
970 unless ( $state->{globaloptions}{-n} )
972 print "Merged $dirpart\n";
973 $log->debug($state->{CVSROOT} . "/$state->{module}/$filename");
974 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
975 my $kopts = kopts_from_path($filepart);
976 $log->debug("/$filepart/1.$meta->{revision}//$kopts/");
977 print "/$filepart/1.$meta->{revision}//$kopts/\n";
980 elsif ( $return == 1 )
982 $log->info("Merged with conflicts");
983 print "E cvs update: conflicts found in $filename\n";
984 print "M C $filename\n";
986 # Don't want to actually _DO_ the update if -n specified
987 unless ( $state->{globaloptions}{-n} )
989 print "Merged $dirpart\n";
990 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
991 my $kopts = kopts_from_path($filepart);
992 print "/$filepart/1.$meta->{revision}/+/$kopts/\n";
997 $log->warn("Merge failed");
1001 # Don't want to actually _DO_ the update if -n specified
1002 unless ( $state->{globaloptions}{-n} )
1005 $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
1006 print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
1008 # transmit file, format is single integer on a line by itself (file
1009 # size) followed by the file contents
1010 # TODO : we should copy files in blocks
1011 my $data = `cat $file_local`;
1012 $log->debug("File size : " . length($data));
1013 print length($data) . "\n";
1027 my ( $cmd, $data ) = @_;
1031 #$log->debug("State : " . Dumper($state));
1033 $log->info("req_ci : " . ( defined($data) ? $data : "[NULL]" ));
1035 if ( $state->{method} eq 'pserver')
1037 print "error 1 pserver access cannot commit\n";
1041 if ( -e $state->{CVSROOT} . "/index" )
1043 $log->warn("file 'index' already exists in the git repository");
1044 print "error 1 Index already exists in git repo\n";
1048 # Grab a handle to the SQLite db and do any necessary updates
1049 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1052 my $tmpdir = tempdir ( DIR => $TEMP_DIR );
1053 my ( undef, $file_index ) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
1054 $log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");
1056 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
1057 $ENV{GIT_INDEX_FILE} = $file_index;
1059 # Remember where the head was at the beginning.
1060 my $parenthash = `git show-ref -s refs/heads/$state->{module}`;
1062 if ($parenthash !~ /^[0-9a-f]{40}$/) {
1063 print "error 1 pserver cannot find the current HEAD of module";
1069 # populate the temporary index based
1070 system("git-read-tree", $parenthash);
1073 die "Error running git-read-tree $state->{module} $file_index $!";
1075 $log->info("Created index '$file_index' with for head $state->{module} - exit status $?");
1077 my @committedfiles = ();
1080 # foreach file specified on the command line ...
1081 foreach my $filename ( @{$state->{args}} )
1083 my $committedfile = $filename;
1084 $filename = filecleanup($filename);
1086 next unless ( exists $state->{entries}{$filename}{modified_filename} or not $state->{entries}{$filename}{unchanged} );
1088 my $meta = $updater->getmeta($filename);
1089 $oldmeta{$filename} = $meta;
1091 my $wrev = revparse($filename);
1093 my ( $filepart, $dirpart ) = filenamesplit($filename);
1095 # do a checkout of the file if it part of this tree
1097 system('git-checkout-index', '-f', '-u', $filename);
1099 die "Error running git-checkout-index -f -u $filename : $!";
1105 $rmflag = 1 if ( defined($wrev) and $wrev < 0 );
1106 $addflag = 1 unless ( -e $filename );
1108 # Do up to date checking
1109 unless ( $addflag or $wrev == $meta->{revision} or ( $rmflag and -$wrev == $meta->{revision} ) )
1111 # fail everything if an up to date check fails
1112 print "error 1 Up to date check failed for $filename\n";
1117 push @committedfiles, $committedfile;
1118 $log->info("Committing $filename");
1120 system("mkdir","-p",$dirpart) unless ( -d $dirpart );
1124 $log->debug("rename $state->{entries}{$filename}{modified_filename} $filename");
1125 rename $state->{entries}{$filename}{modified_filename},$filename;
1127 # Calculate modes to remove
1129 foreach ( qw (r w x) ) { $invmode .= $_ unless ( $state->{entries}{$filename}{modified_mode} =~ /$_/ ); }
1131 $log->debug("chmod u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode . " $filename");
1132 system("chmod","u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode, $filename);
1137 $log->info("Removing file '$filename'");
1139 system("git-update-index", "--remove", $filename);
1143 $log->info("Adding file '$filename'");
1144 system("git-update-index", "--add", $filename);
1146 $log->info("Updating file '$filename'");
1147 system("git-update-index", $filename);
1151 unless ( scalar(@committedfiles) > 0 )
1153 print "E No files to commit\n";
1159 my $treehash = `git-write-tree`;
1162 $log->debug("Treehash : $treehash, Parenthash : $parenthash");
1164 # write our commit message out if we have one ...
1165 my ( $msg_fh, $msg_filename ) = tempfile( DIR => $TEMP_DIR );
1166 print $msg_fh $state->{opt}{m};# if ( exists ( $state->{opt}{m} ) );
1167 print $msg_fh "\n\nvia git-CVS emulator\n";
1170 my $commithash = `git-commit-tree $treehash -p $parenthash < $msg_filename`;
1172 $log->info("Commit hash : $commithash");
1174 unless ( $commithash =~ /[a-zA-Z0-9]{40}/ )
1176 $log->warn("Commit failed (Invalid commit hash)");
1177 print "error 1 Commit failed (unknown reason)\n";
1182 # Check that this is allowed, just as we would with a receive-pack
1183 my @cmd = ( $ENV{GIT_DIR}.'hooks/update', "refs/heads/$state->{module}",
1184 $parenthash, $commithash );
1186 unless( system( @cmd ) == 0 )
1188 $log->warn("Commit failed (update hook declined to update ref)");
1189 print "error 1 Commit failed (update hook declined)\n";
1195 if (system(qw(git update-ref -m), "cvsserver ci",
1196 "refs/heads/$state->{module}", $commithash, $parenthash)) {
1197 $log->warn("update-ref for $state->{module} failed.");
1198 print "error 1 Cannot commit -- update first\n";
1204 # foreach file specified on the command line ...
1205 foreach my $filename ( @committedfiles )
1207 $filename = filecleanup($filename);
1209 my $meta = $updater->getmeta($filename);
1210 unless (defined $meta->{revision}) {
1211 $meta->{revision} = 1;
1214 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
1216 $log->debug("Checked-in $dirpart : $filename");
1218 print "M $state->{CVSROOT}/$state->{module}/$filename,v <-- $dirpart$filepart\n";
1219 if ( defined $meta->{filehash} && $meta->{filehash} eq "deleted" )
1221 print "M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";
1222 print "Remove-entry $dirpart\n";
1223 print "$filename\n";
1225 if ($meta->{revision} == 1) {
1226 print "M initial revision: 1.1\n";
1228 print "M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";
1230 print "Checked-in $dirpart\n";
1231 print "$filename\n";
1232 my $kopts = kopts_from_path($filepart);
1233 print "/$filepart/1.$meta->{revision}//$kopts/\n";
1243 my ( $cmd, $data ) = @_;
1247 $log->info("req_status : " . ( defined($data) ? $data : "[NULL]" ));
1248 #$log->debug("status state : " . Dumper($state));
1250 # Grab a handle to the SQLite db and do any necessary updates
1251 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1254 # if no files were specified, we need to work out what files we should be providing status on ...
1255 argsfromdir($updater);
1257 # foreach file specified on the command line ...
1258 foreach my $filename ( @{$state->{args}} )
1260 $filename = filecleanup($filename);
1262 my $meta = $updater->getmeta($filename);
1263 my $oldmeta = $meta;
1265 my $wrev = revparse($filename);
1267 # If the working copy is an old revision, lets get that version too for comparison.
1268 if ( defined($wrev) and $wrev != $meta->{revision} )
1270 $oldmeta = $updater->getmeta($filename, $wrev);
1273 # TODO : All possible statuses aren't yet implemented
1275 # Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified
1276 $status = "Up-to-date" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision}
1278 ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
1279 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta->{filehash} ) )
1282 # Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified
1283 $status ||= "Needs Checkout" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev
1285 ( $state->{entries}{$filename}{unchanged}
1286 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash} ) )
1289 # Need checkout if it exists in the repo but doesn't have a working copy
1290 $status ||= "Needs Checkout" if ( not defined ( $wrev ) and defined ( $meta->{revision} ) );
1292 # Locally modified if working copy and repo copy have the same revision but there are local changes
1293 $status ||= "Locally Modified" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision} and $state->{entries}{$filename}{modified_filename} );
1295 # Needs Merge if working copy revision is less than repo copy and there are local changes
1296 $status ||= "Needs Merge" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev and $state->{entries}{$filename}{modified_filename} );
1298 $status ||= "Locally Added" if ( defined ( $state->{entries}{$filename}{revision} ) and not defined ( $meta->{revision} ) );
1299 $status ||= "Locally Removed" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and -$wrev == $meta->{revision} );
1300 $status ||= "Unresolved Conflict" if ( defined ( $state->{entries}{$filename}{conflict} ) and $state->{entries}{$filename}{conflict} =~ /^\+=/ );
1301 $status ||= "File had conflicts on merge" if ( 0 );
1303 $status ||= "Unknown";
1305 print "M ===================================================================\n";
1306 print "M File: $filename\tStatus: $status\n";
1307 if ( defined($state->{entries}{$filename}{revision}) )
1309 print "M Working revision:\t" . $state->{entries}{$filename}{revision} . "\n";
1311 print "M Working revision:\tNo entry for $filename\n";
1313 if ( defined($meta->{revision}) )
1315 print "M Repository revision:\t1." . $meta->{revision} . "\t$state->{CVSROOT}/$state->{module}/$filename,v\n";
1316 print "M Sticky Tag:\t\t(none)\n";
1317 print "M Sticky Date:\t\t(none)\n";
1318 print "M Sticky Options:\t\t(none)\n";
1320 print "M Repository revision:\tNo revision control file\n";
1330 my ( $cmd, $data ) = @_;
1334 $log->debug("req_diff : " . ( defined($data) ? $data : "[NULL]" ));
1335 #$log->debug("status state : " . Dumper($state));
1337 my ($revision1, $revision2);
1338 if ( defined ( $state->{opt}{r} ) and ref $state->{opt}{r} eq "ARRAY" )
1340 $revision1 = $state->{opt}{r}[0];
1341 $revision2 = $state->{opt}{r}[1];
1343 $revision1 = $state->{opt}{r};
1346 $revision1 =~ s/^1\.// if ( defined ( $revision1 ) );
1347 $revision2 =~ s/^1\.// if ( defined ( $revision2 ) );
1349 $log->debug("Diffing revisions " . ( defined($revision1) ? $revision1 : "[NULL]" ) . " and " . ( defined($revision2) ? $revision2 : "[NULL]" ) );
1351 # Grab a handle to the SQLite db and do any necessary updates
1352 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1355 # if no files were specified, we need to work out what files we should be providing status on ...
1356 argsfromdir($updater);
1358 # foreach file specified on the command line ...
1359 foreach my $filename ( @{$state->{args}} )
1361 $filename = filecleanup($filename);
1363 my ( $fh, $file1, $file2, $meta1, $meta2, $filediff );
1365 my $wrev = revparse($filename);
1367 # We need _something_ to diff against
1368 next unless ( defined ( $wrev ) );
1370 # if we have a -r switch, use it
1371 if ( defined ( $revision1 ) )
1373 ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1374 $meta1 = $updater->getmeta($filename, $revision1);
1375 unless ( defined ( $meta1 ) and $meta1->{filehash} ne "deleted" )
1377 print "E File $filename at revision 1.$revision1 doesn't exist\n";
1380 transmitfile($meta1->{filehash}, $file1);
1382 # otherwise we just use the working copy revision
1385 ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1386 $meta1 = $updater->getmeta($filename, $wrev);
1387 transmitfile($meta1->{filehash}, $file1);
1390 # if we have a second -r switch, use it too
1391 if ( defined ( $revision2 ) )
1393 ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1394 $meta2 = $updater->getmeta($filename, $revision2);
1396 unless ( defined ( $meta2 ) and $meta2->{filehash} ne "deleted" )
1398 print "E File $filename at revision 1.$revision2 doesn't exist\n";
1402 transmitfile($meta2->{filehash}, $file2);
1404 # otherwise we just use the working copy
1407 $file2 = $state->{entries}{$filename}{modified_filename};
1410 # if we have been given -r, and we don't have a $file2 yet, lets get one
1411 if ( defined ( $revision1 ) and not defined ( $file2 ) )
1413 ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1414 $meta2 = $updater->getmeta($filename, $wrev);
1415 transmitfile($meta2->{filehash}, $file2);
1418 # We need to have retrieved something useful
1419 next unless ( defined ( $meta1 ) );
1421 # Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified
1422 next if ( not defined ( $meta2 ) and $wrev == $meta1->{revision}
1424 ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
1425 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta1->{filehash} ) )
1428 # Apparently we only show diffs for locally modified files
1429 next unless ( defined($meta2) or defined ( $state->{entries}{$filename}{modified_filename} ) );
1431 print "M Index: $filename\n";
1432 print "M ===================================================================\n";
1433 print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
1434 print "M retrieving revision 1.$meta1->{revision}\n" if ( defined ( $meta1 ) );
1435 print "M retrieving revision 1.$meta2->{revision}\n" if ( defined ( $meta2 ) );
1437 foreach my $opt ( keys %{$state->{opt}} )
1439 if ( ref $state->{opt}{$opt} eq "ARRAY" )
1441 foreach my $value ( @{$state->{opt}{$opt}} )
1443 print "-$opt $value ";
1447 print "$state->{opt}{$opt} " if ( defined ( $state->{opt}{$opt} ) );
1450 print "$filename\n";
1452 $log->info("Diffing $filename -r $meta1->{revision} -r " . ( $meta2->{revision} or "workingcopy" ));
1454 ( $fh, $filediff ) = tempfile ( DIR => $TEMP_DIR );
1456 if ( exists $state->{opt}{u} )
1458 system("diff -u -L '$filename revision 1.$meta1->{revision}' -L '$filename " . ( defined($meta2->{revision}) ? "revision 1.$meta2->{revision}" : "working copy" ) . "' $file1 $file2 > $filediff");
1460 system("diff $file1 $file2 > $filediff");
1475 my ( $cmd, $data ) = @_;
1479 $log->debug("req_log : " . ( defined($data) ? $data : "[NULL]" ));
1480 #$log->debug("log state : " . Dumper($state));
1482 my ( $minrev, $maxrev );
1483 if ( defined ( $state->{opt}{r} ) and $state->{opt}{r} =~ /([\d.]+)?(::?)([\d.]+)?/ )
1488 $minrev =~ s/^1\.// if ( defined ( $minrev ) );
1489 $maxrev =~ s/^1\.// if ( defined ( $maxrev ) );
1490 $minrev++ if ( defined($minrev) and $control eq "::" );
1493 # Grab a handle to the SQLite db and do any necessary updates
1494 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1497 # if no files were specified, we need to work out what files we should be providing status on ...
1498 argsfromdir($updater);
1500 # foreach file specified on the command line ...
1501 foreach my $filename ( @{$state->{args}} )
1503 $filename = filecleanup($filename);
1505 my $headmeta = $updater->getmeta($filename);
1507 my $revisions = $updater->getlog($filename);
1508 my $totalrevisions = scalar(@$revisions);
1510 if ( defined ( $minrev ) )
1512 $log->debug("Removing revisions less than $minrev");
1513 while ( scalar(@$revisions) > 0 and $revisions->[-1]{revision} < $minrev )
1518 if ( defined ( $maxrev ) )
1520 $log->debug("Removing revisions greater than $maxrev");
1521 while ( scalar(@$revisions) > 0 and $revisions->[0]{revision} > $maxrev )
1527 next unless ( scalar(@$revisions) );
1530 print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
1531 print "M Working file: $filename\n";
1532 print "M head: 1.$headmeta->{revision}\n";
1533 print "M branch:\n";
1534 print "M locks: strict\n";
1535 print "M access list:\n";
1536 print "M symbolic names:\n";
1537 print "M keyword substitution: kv\n";
1538 print "M total revisions: $totalrevisions;\tselected revisions: " . scalar(@$revisions) . "\n";
1539 print "M description:\n";
1541 foreach my $revision ( @$revisions )
1543 print "M ----------------------------\n";
1544 print "M revision 1.$revision->{revision}\n";
1545 # reformat the date for log output
1546 $revision->{modified} = sprintf('%04d/%02d/%02d %s', $3, $DATE_LIST->{$2}, $1, $4 ) if ( $revision->{modified} =~ /(\d+)\s+(\w+)\s+(\d+)\s+(\S+)/ and defined($DATE_LIST->{$2}) );
1547 $revision->{author} =~ s/\s+.*//;
1548 $revision->{author} =~ s/^(.{8}).*/$1/;
1549 print "M date: $revision->{modified}; author: $revision->{author}; state: " . ( $revision->{filehash} eq "deleted" ? "dead" : "Exp" ) . "; lines: +2 -3\n";
1550 my $commitmessage = $updater->commitmessage($revision->{commithash});
1551 $commitmessage =~ s/^/M /mg;
1552 print $commitmessage . "\n";
1554 print "M =============================================================================\n";
1562 my ( $cmd, $data ) = @_;
1564 argsplit("annotate");
1566 $log->info("req_annotate : " . ( defined($data) ? $data : "[NULL]" ));
1567 #$log->debug("status state : " . Dumper($state));
1569 # Grab a handle to the SQLite db and do any necessary updates
1570 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1573 # if no files were specified, we need to work out what files we should be providing annotate on ...
1574 argsfromdir($updater);
1576 # we'll need a temporary checkout dir
1577 my $tmpdir = tempdir ( DIR => $TEMP_DIR );
1578 my ( undef, $file_index ) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
1579 $log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");
1581 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
1582 $ENV{GIT_INDEX_FILE} = $file_index;
1586 # foreach file specified on the command line ...
1587 foreach my $filename ( @{$state->{args}} )
1589 $filename = filecleanup($filename);
1591 my $meta = $updater->getmeta($filename);
1593 next unless ( $meta->{revision} );
1595 # get all the commits that this file was in
1596 # in dense format -- aka skip dead revisions
1597 my $revisions = $updater->gethistorydense($filename);
1598 my $lastseenin = $revisions->[0][2];
1600 # populate the temporary index based on the latest commit were we saw
1601 # the file -- but do it cheaply without checking out any files
1602 # TODO: if we got a revision from the client, use that instead
1603 # to look up the commithash in sqlite (still good to default to
1604 # the current head as we do now)
1605 system("git-read-tree", $lastseenin);
1608 die "Error running git-read-tree $lastseenin $file_index $!";
1610 $log->info("Created index '$file_index' with commit $lastseenin - exit status $?");
1612 # do a checkout of the file
1613 system('git-checkout-index', '-f', '-u', $filename);
1615 die "Error running git-checkout-index -f -u $filename : $!";
1618 $log->info("Annotate $filename");
1620 # Prepare a file with the commits from the linearized
1621 # history that annotate should know about. This prevents
1622 # git-jsannotate telling us about commits we are hiding
1625 open(ANNOTATEHINTS, ">$tmpdir/.annotate_hints") or die "Error opening > $tmpdir/.annotate_hints $!";
1626 for (my $i=0; $i < @$revisions; $i++)
1628 print ANNOTATEHINTS $revisions->[$i][2];
1629 if ($i+1 < @$revisions) { # have we got a parent?
1630 print ANNOTATEHINTS ' ' . $revisions->[$i+1][2];
1632 print ANNOTATEHINTS "\n";
1635 print ANNOTATEHINTS "\n";
1636 close ANNOTATEHINTS;
1638 my $annotatecmd = 'git-annotate';
1639 open(ANNOTATE, "-|", $annotatecmd, '-l', '-S', "$tmpdir/.annotate_hints", $filename)
1640 or die "Error invoking $annotatecmd -l -S $tmpdir/.annotate_hints $filename : $!";
1642 print "E Annotations for $filename\n";
1643 print "E ***************\n";
1644 while ( <ANNOTATE> )
1646 if (m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)
1648 my $commithash = $1;
1650 unless ( defined ( $metadata->{$commithash} ) )
1652 $metadata->{$commithash} = $updater->getmeta($filename, $commithash);
1653 $metadata->{$commithash}{author} =~ s/\s+.*//;
1654 $metadata->{$commithash}{author} =~ s/^(.{8}).*/$1/;
1655 $metadata->{$commithash}{modified} = sprintf("%02d-%s-%02d", $1, $2, $3) if ( $metadata->{$commithash}{modified} =~ /^(\d+)\s(\w+)\s\d\d(\d\d)/ );
1657 printf("M 1.%-5d (%-8s %10s): %s\n",
1658 $metadata->{$commithash}{revision},
1659 $metadata->{$commithash}{author},
1660 $metadata->{$commithash}{modified},
1664 $log->warn("Error in annotate output! LINE: $_");
1665 print "E Annotate error \n";
1672 # done; get out of the tempdir
1679 # This method takes the state->{arguments} array and produces two new arrays.
1680 # The first is $state->{args} which is everything before the '--' argument, and
1681 # the second is $state->{files} which is everything after it.
1684 return unless( defined($state->{arguments}) and ref $state->{arguments} eq "ARRAY" );
1688 $state->{args} = [];
1689 $state->{files} = [];
1692 if ( defined($type) )
1695 $opt = { A => 0, N => 0, P => 0, R => 0, c => 0, f => 0, l => 0, n => 0, p => 0, s => 0, r => 1, D => 1, d => 1, k => 1, j => 1, } if ( $type eq "co" );
1696 $opt = { v => 0, l => 0, R => 0 } if ( $type eq "status" );
1697 $opt = { A => 0, P => 0, C => 0, d => 0, f => 0, l => 0, R => 0, p => 0, k => 1, r => 1, D => 1, j => 1, I => 1, W => 1 } if ( $type eq "update" );
1698 $opt = { l => 0, R => 0, k => 1, D => 1, D => 1, r => 2 } if ( $type eq "diff" );
1699 $opt = { c => 0, R => 0, l => 0, f => 0, F => 1, m => 1, r => 1 } if ( $type eq "ci" );
1700 $opt = { k => 1, m => 1 } if ( $type eq "add" );
1701 $opt = { f => 0, l => 0, R => 0 } if ( $type eq "remove" );
1702 $opt = { l => 0, b => 0, h => 0, R => 0, t => 0, N => 0, S => 0, r => 1, d => 1, s => 1, w => 1 } if ( $type eq "log" );
1705 while ( scalar ( @{$state->{arguments}} ) > 0 )
1707 my $arg = shift @{$state->{arguments}};
1709 next if ( $arg eq "--" );
1710 next unless ( $arg =~ /\S/ );
1712 # if the argument looks like a switch
1713 if ( $arg =~ /^-(\w)(.*)/ )
1715 # if it's a switch that takes an argument
1718 # If this switch has already been provided
1719 if ( $opt->{$1} > 1 and exists ( $state->{opt}{$1} ) )
1721 $state->{opt}{$1} = [ $state->{opt}{$1} ];
1722 if ( length($2) > 0 )
1724 push @{$state->{opt}{$1}},$2;
1726 push @{$state->{opt}{$1}}, shift @{$state->{arguments}};
1729 # if there's extra data in the arg, use that as the argument for the switch
1730 if ( length($2) > 0 )
1732 $state->{opt}{$1} = $2;
1734 $state->{opt}{$1} = shift @{$state->{arguments}};
1738 $state->{opt}{$1} = undef;
1743 push @{$state->{args}}, $arg;
1751 foreach my $value ( @{$state->{arguments}} )
1753 if ( $value eq "--" )
1758 push @{$state->{args}}, $value if ( $mode == 0 );
1759 push @{$state->{files}}, $value if ( $mode == 1 );
1764 # This method uses $state->{directory} to populate $state->{args} with a list of filenames
1767 my $updater = shift;
1769 $state->{args} = [] if ( scalar(@{$state->{args}}) == 1 and $state->{args}[0] eq "." );
1771 return if ( scalar ( @{$state->{args}} ) > 1 );
1773 my @gethead = @{$updater->gethead};
1776 foreach my $file (keys %{$state->{entries}}) {
1777 if ( exists $state->{entries}{$file}{revision} &&
1778 $state->{entries}{$file}{revision} == 0 )
1780 push @gethead, { name => $file, filehash => 'added' };
1784 if ( scalar(@{$state->{args}}) == 1 )
1786 my $arg = $state->{args}[0];
1787 $arg .= $state->{prependdir} if ( defined ( $state->{prependdir} ) );
1789 $log->info("Only one arg specified, checking for directory expansion on '$arg'");
1791 foreach my $file ( @gethead )
1793 next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
1794 next unless ( $file->{name} =~ /^$arg\// or $file->{name} eq $arg );
1795 push @{$state->{args}}, $file->{name};
1798 shift @{$state->{args}} if ( scalar(@{$state->{args}}) > 1 );
1800 $log->info("Only one arg specified, populating file list automatically");
1802 $state->{args} = [];
1804 foreach my $file ( @gethead )
1806 next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
1807 next unless ( $file->{name} =~ s/^$state->{prependdir}// );
1808 push @{$state->{args}}, $file->{name};
1813 # This method cleans up the $state variable after a command that uses arguments has run
1816 $state->{files} = [];
1817 $state->{args} = [];
1818 $state->{arguments} = [];
1819 $state->{entries} = {};
1824 my $filename = shift;
1826 return undef unless ( defined ( $state->{entries}{$filename}{revision} ) );
1828 return $1 if ( $state->{entries}{$filename}{revision} =~ /^1\.(\d+)/ );
1829 return -$1 if ( $state->{entries}{$filename}{revision} =~ /^-1\.(\d+)/ );
1834 # This method takes a file hash and does a CVS "file transfer" which transmits the
1835 # size of the file, and then the file contents.
1836 # If a second argument $targetfile is given, the file is instead written out to
1837 # a file by the name of $targetfile
1840 my $filehash = shift;
1841 my $targetfile = shift;
1843 if ( defined ( $filehash ) and $filehash eq "deleted" )
1845 $log->warn("filehash is 'deleted'");
1849 die "Need filehash" unless ( defined ( $filehash ) and $filehash =~ /^[a-zA-Z0-9]{40}$/ );
1851 my $type = `git-cat-file -t $filehash`;
1854 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ( $type ) and $type eq "blob" );
1856 my $size = `git-cat-file -s $filehash`;
1859 $log->debug("transmitfile($filehash) size=$size, type=$type");
1861 if ( open my $fh, '-|', "git-cat-file", "blob", $filehash )
1863 if ( defined ( $targetfile ) )
1865 open NEWFILE, ">", $targetfile or die("Couldn't open '$targetfile' for writing : $!");
1866 print NEWFILE $_ while ( <$fh> );
1870 print while ( <$fh> );
1872 close $fh or die ("Couldn't close filehandle for transmitfile()");
1874 die("Couldn't execute git-cat-file");
1878 # This method takes a file name, and returns ( $dirpart, $filepart ) which
1879 # refers to the directory portion and the file portion of the filename
1883 my $filename = shift;
1884 my $fixforlocaldir = shift;
1886 my ( $filepart, $dirpart ) = ( $filename, "." );
1887 ( $filepart, $dirpart ) = ( $2, $1 ) if ( $filename =~ /(.*)\/(.*)/ );
1890 if ( $fixforlocaldir )
1892 $dirpart =~ s/^$state->{prependdir}//;
1895 return ( $filepart, $dirpart );
1900 my $filename = shift;
1902 return undef unless(defined($filename));
1903 if ( $filename =~ /^\// )
1905 print "E absolute filenames '$filename' not supported by server\n";
1909 $filename =~ s/^\.\///g;
1910 $filename = $state->{prependdir} . $filename;
1914 # Given a path, this function returns a string containing the kopts
1915 # that should go into that path's Entries line. For example, a binary
1916 # file should get -kb.
1921 # Once it exists, the git attributes system should be used to look up
1922 # what attributes apply to this path.
1924 # Until then, take the setting from the config file
1925 unless ( defined ( $cfg->{gitcvs}{allbinary} ) and $cfg->{gitcvs}{allbinary} =~ /^\s*(1|true|yes)\s*$/i )
1927 # Return "" to give no special treatment to any path
1930 # Alternatively, to have all files treated as if they are binary (which
1931 # is more like git itself), always return the "-kb" option
1936 package GITCVS::log;
1939 #### Copyright The Open University UK - 2006.
1941 #### Authors: Martyn Smith <martyn@catalyst.net.nz>
1942 #### Martin Langhoff <martin@catalyst.net.nz>
1955 This module provides very crude logging with a similar interface to
1964 Creates a new log object, optionally you can specify a filename here to
1965 indicate the file to log to. If no log file is specified, you can specify one
1966 later with method setfile, or indicate you no longer want logging with method
1969 Until one of these methods is called, all log calls will buffer messages ready
1976 my $filename = shift;
1980 bless $self, $class;
1982 if ( defined ( $filename ) )
1984 open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
1992 This methods takes a filename, and attempts to open that file as the log file.
1993 If successful, all buffered data is written out to the file, and any further
1994 logging is written directly to the file.
2000 my $filename = shift;
2002 if ( defined ( $filename ) )
2004 open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
2007 return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
2009 while ( my $line = shift @{$self->{buffer}} )
2011 print {$self->{fh}} $line;
2017 This method indicates no logging is going to be used. It flushes any entries in
2018 the internal buffer, and sets a flag to ensure no further data is put there.
2027 return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
2029 $self->{buffer} = [];
2034 Internal method. Returns true if the log file is open, false otherwise.
2041 return 1 if ( defined ( $self->{fh} ) and ref $self->{fh} eq "GLOB" );
2045 =head2 debug info warn fatal
2047 These four methods are wrappers to _log. They provide the actual interface for
2051 sub debug { my $self = shift; $self->_log("debug", @_); }
2052 sub info { my $self = shift; $self->_log("info" , @_); }
2053 sub warn { my $self = shift; $self->_log("warn" , @_); }
2054 sub fatal { my $self = shift; $self->_log("fatal", @_); }
2058 This is an internal method called by the logging functions. It generates a
2059 timestamp and pushes the logged line either to file, or internal buffer.
2067 return if ( $self->{nolog} );
2069 my @time = localtime;
2070 my $timestring = sprintf("%4d-%02d-%02d %02d:%02d:%02d : %-5s",
2080 if ( $self->_logopen )
2082 print {$self->{fh}} $timestring . " - " . join(" ",@_) . "\n";
2084 push @{$self->{buffer}}, $timestring . " - " . join(" ",@_) . "\n";
2090 This method simply closes the file handle if one is open
2097 if ( $self->_logopen )
2103 package GITCVS::updater;
2106 #### Copyright The Open University UK - 2006.
2108 #### Authors: Martyn Smith <martyn@catalyst.net.nz>
2109 #### Martin Langhoff <martin@catalyst.net.nz>
2131 die "Need to specify a git repository" unless ( defined($config) and -d $config );
2132 die "Need to specify a module" unless ( defined($module) );
2134 $class = ref($class) || $class;
2138 bless $self, $class;
2140 $self->{dbdir} = $config . "/";
2141 die "Database dir '$self->{dbdir}' isn't a directory" unless ( defined($self->{dbdir}) and -d $self->{dbdir} );
2143 $self->{module} = $module;
2144 $self->{file} = $self->{dbdir} . "/gitcvs.$module.sqlite";
2146 $self->{git_path} = $config . "/";
2148 $self->{log} = $log;
2150 die "Git repo '$self->{git_path}' doesn't exist" unless ( -d $self->{git_path} );
2152 $self->{dbh} = DBI->connect("dbi:SQLite:dbname=" . $self->{file},"","");
2154 $self->{tables} = {};
2155 foreach my $table ( $self->{dbh}->tables )
2159 $self->{tables}{$table} = 1;
2162 # Construct the revision table if required
2163 unless ( $self->{tables}{revision} )
2166 CREATE TABLE revision (
2168 revision INTEGER NOT NULL,
2169 filehash TEXT NOT NULL,
2170 commithash TEXT NOT NULL,
2171 author TEXT NOT NULL,
2172 modified TEXT NOT NULL,
2177 CREATE INDEX revision_ix1
2178 ON revision (name,revision)
2181 CREATE INDEX revision_ix2
2182 ON revision (name,commithash)
2186 # Construct the head table if required
2187 unless ( $self->{tables}{head} )
2192 revision INTEGER NOT NULL,
2193 filehash TEXT NOT NULL,
2194 commithash TEXT NOT NULL,
2195 author TEXT NOT NULL,
2196 modified TEXT NOT NULL,
2201 CREATE INDEX head_ix1
2206 # Construct the properties table if required
2207 unless ( $self->{tables}{properties} )
2210 CREATE TABLE properties (
2211 key TEXT NOT NULL PRIMARY KEY,
2217 # Construct the commitmsgs table if required
2218 unless ( $self->{tables}{commitmsgs} )
2221 CREATE TABLE commitmsgs (
2222 key TEXT NOT NULL PRIMARY KEY,
2238 # first lets get the commit list
2239 $ENV{GIT_DIR} = $self->{git_path};
2241 my $commitsha1 = `git rev-parse $self->{module}`;
2244 my $commitinfo = `git cat-file commit $self->{module} 2>&1`;
2245 unless ( $commitinfo =~ /tree\s+[a-zA-Z0-9]{40}/ )
2247 die("Invalid module '$self->{module}'");
2252 my $lastcommit = $self->_get_prop("last_commit");
2254 if (defined $lastcommit && $lastcommit eq $commitsha1) { # up-to-date
2258 # Start exclusive lock here...
2259 $self->{dbh}->begin_work() or die "Cannot lock database for BEGIN";
2261 # TODO: log processing is memory bound
2262 # if we can parse into a 2nd file that is in reverse order
2263 # we can probably do something really efficient
2264 my @git_log_params = ('--pretty', '--parents', '--topo-order');
2266 if (defined $lastcommit) {
2267 push @git_log_params, "$lastcommit..$self->{module}";
2269 push @git_log_params, $self->{module};
2271 # git-rev-list is the backend / plumbing version of git-log
2272 open(GITLOG, '-|', 'git-rev-list', @git_log_params) or die "Cannot call git-rev-list: $!";
2281 if (m/^commit\s+(.*)$/) {
2282 # on ^commit lines put the just seen commit in the stack
2283 # and prime things for the next one
2286 unshift @commits, \%copy;
2289 my @parents = split(m/\s+/, $1);
2290 $commit{hash} = shift @parents;
2291 $commit{parents} = \@parents;
2292 } elsif (m/^(\w+?):\s+(.*)$/ && !exists($commit{message})) {
2293 # on rfc822-like lines seen before we see any message,
2294 # lowercase the entry and put it in the hash as key-value
2295 $commit{lc($1)} = $2;
2297 # message lines - skip initial empty line
2298 # and trim whitespace
2299 if (!exists($commit{message}) && m/^\s*$/) {
2300 # define it to mark the end of headers
2301 $commit{message} = '';
2304 s/^\s+//; s/\s+$//; # trim ws
2305 $commit{message} .= $_ . "\n";
2310 unshift @commits, \%commit if ( keys %commit );
2312 # Now all the commits are in the @commits bucket
2313 # ordered by time DESC. for each commit that needs processing,
2314 # determine whether it's following the last head we've seen or if
2315 # it's on its own branch, grab a file list, and add whatever's changed
2316 # NOTE: $lastcommit refers to the last commit from previous run
2317 # $lastpicked is the last commit we picked in this run
2320 if (defined $lastcommit) {
2321 $lastpicked = $lastcommit;
2324 my $committotal = scalar(@commits);
2325 my $commitcount = 0;
2327 # Load the head table into $head (for cached lookups during the update process)
2328 foreach my $file ( @{$self->gethead()} )
2330 $head->{$file->{name}} = $file;
2333 foreach my $commit ( @commits )
2335 $self->{log}->debug("GITCVS::updater - Processing commit $commit->{hash} (" . (++$commitcount) . " of $committotal)");
2336 if (defined $lastpicked)
2338 if (!in_array($lastpicked, @{$commit->{parents}}))
2340 # skip, we'll see this delta
2341 # as part of a merge later
2342 # warn "skipping off-track $commit->{hash}\n";
2344 } elsif (@{$commit->{parents}} > 1) {
2345 # it is a merge commit, for each parent that is
2346 # not $lastpicked, see if we can get a log
2347 # from the merge-base to that parent to put it
2348 # in the message as a merge summary.
2349 my @parents = @{$commit->{parents}};
2350 foreach my $parent (@parents) {
2351 # git-merge-base can potentially (but rarely) throw
2352 # several candidate merge bases. let's assume
2353 # that the first one is the best one.
2354 if ($parent eq $lastpicked) {
2357 open my $p, 'git-merge-base '. $lastpicked . ' '
2359 my @output = (<$p>);
2361 my $base = join('', @output);
2365 # print "want to log between $base $parent \n";
2366 open(GITLOG, '-|', 'git-log', "$base..$parent")
2367 or die "Cannot call git-log: $!";
2371 if (!defined $mergedhash) {
2372 if (m/^commit\s+(.+)$/) {
2378 # grab the first line that looks non-rfc822
2379 # aka has content after leading space
2380 if (m/^\s+(\S.*)$/) {
2382 $title = substr($title,0,100); # truncate
2383 unshift @merged, "$mergedhash $title";
2390 $commit->{mergemsg} = $commit->{message};
2391 $commit->{mergemsg} .= "\nSummary of merged commits:\n\n";
2392 foreach my $summary (@merged) {
2393 $commit->{mergemsg} .= "\t$summary\n";
2395 $commit->{mergemsg} .= "\n\n";
2396 # print "Message for $commit->{hash} \n$commit->{mergemsg}";
2403 # convert the date to CVS-happy format
2404 $commit->{date} = "$2 $1 $4 $3 $5" if ( $commit->{date} =~ /^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/ );
2406 if ( defined ( $lastpicked ) )
2408 my $filepipe = open(FILELIST, '-|', 'git-diff-tree', '-z', '-r', $lastpicked, $commit->{hash}) or die("Cannot call git-diff-tree : $!");
2410 while ( <FILELIST> )
2413 unless ( /^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o )
2415 die("Couldn't process git-diff-tree line : $_");
2417 my ($mode, $hash, $change) = ($1, $2, $3);
2418 my $name = <FILELIST>;
2421 # $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");
2424 $git_perms .= "r" if ( $mode & 4 );
2425 $git_perms .= "w" if ( $mode & 2 );
2426 $git_perms .= "x" if ( $mode & 1 );
2427 $git_perms = "rw" if ( $git_perms eq "" );
2429 if ( $change eq "D" )
2431 #$log->debug("DELETE $name");
2434 revision => $head->{$name}{revision} + 1,
2435 filehash => "deleted",
2436 commithash => $commit->{hash},
2437 modified => $commit->{date},
2438 author => $commit->{author},
2441 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
2443 elsif ( $change eq "M" )
2445 #$log->debug("MODIFIED $name");
2448 revision => $head->{$name}{revision} + 1,
2450 commithash => $commit->{hash},
2451 modified => $commit->{date},
2452 author => $commit->{author},
2455 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
2457 elsif ( $change eq "A" )
2459 #$log->debug("ADDED $name");
2464 commithash => $commit->{hash},
2465 modified => $commit->{date},
2466 author => $commit->{author},
2469 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
2473 $log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");
2479 # this is used to detect files removed from the repo
2480 my $seen_files = {};
2482 my $filepipe = open(FILELIST, '-|', 'git-ls-tree', '-z', '-r', $commit->{hash}) or die("Cannot call git-ls-tree : $!");
2484 while ( <FILELIST> )
2487 unless ( /^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o )
2489 die("Couldn't process git-ls-tree line : $_");
2492 my ( $git_perms, $git_type, $git_hash, $git_filename ) = ( $1, $2, $3, $4 );
2494 $seen_files->{$git_filename} = 1;
2496 my ( $oldhash, $oldrevision, $oldmode ) = (
2497 $head->{$git_filename}{filehash},
2498 $head->{$git_filename}{revision},
2499 $head->{$git_filename}{mode}
2502 if ( $git_perms =~ /^\d\d\d(\d)\d\d/o )
2505 $git_perms .= "r" if ( $1 & 4 );
2506 $git_perms .= "w" if ( $1 & 2 );
2507 $git_perms .= "x" if ( $1 & 1 );
2512 # unless the file exists with the same hash, we need to update it ...
2513 unless ( defined($oldhash) and $oldhash eq $git_hash and defined($oldmode) and $oldmode eq $git_perms )
2515 my $newrevision = ( $oldrevision or 0 ) + 1;
2517 $head->{$git_filename} = {
2518 name => $git_filename,
2519 revision => $newrevision,
2520 filehash => $git_hash,
2521 commithash => $commit->{hash},
2522 modified => $commit->{date},
2523 author => $commit->{author},
2528 $self->insert_rev($git_filename, $newrevision, $git_hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
2533 # Detect deleted files
2534 foreach my $file ( keys %$head )
2536 unless ( exists $seen_files->{$file} or $head->{$file}{filehash} eq "deleted" )
2538 $head->{$file}{revision}++;
2539 $head->{$file}{filehash} = "deleted";
2540 $head->{$file}{commithash} = $commit->{hash};
2541 $head->{$file}{modified} = $commit->{date};
2542 $head->{$file}{author} = $commit->{author};
2544 $self->insert_rev($file, $head->{$file}{revision}, $head->{$file}{filehash}, $commit->{hash}, $commit->{date}, $commit->{author}, $head->{$file}{mode});
2547 # END : "Detect deleted files"
2551 if (exists $commit->{mergemsg})
2553 $self->insert_mergelog($commit->{hash}, $commit->{mergemsg});
2556 $lastpicked = $commit->{hash};
2558 $self->_set_prop("last_commit", $commit->{hash});
2561 $self->delete_head();
2562 foreach my $file ( keys %$head )
2566 $head->{$file}{revision},
2567 $head->{$file}{filehash},
2568 $head->{$file}{commithash},
2569 $head->{$file}{modified},
2570 $head->{$file}{author},
2571 $head->{$file}{mode},
2574 # invalidate the gethead cache
2575 $self->{gethead_cache} = undef;
2578 # Ending exclusive lock here
2579 $self->{dbh}->commit() or die "Failed to commit changes to SQLite";
2586 my $revision = shift;
2587 my $filehash = shift;
2588 my $commithash = shift;
2589 my $modified = shift;
2593 my $insert_rev = $self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
2594 $insert_rev->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
2603 my $insert_mergelog = $self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);
2604 $insert_mergelog->execute($key, $value);
2611 my $delete_head = $self->{dbh}->prepare_cached("DELETE FROM head",{},1);
2612 $delete_head->execute();
2619 my $revision = shift;
2620 my $filehash = shift;
2621 my $commithash = shift;
2622 my $modified = shift;
2626 my $insert_head = $self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
2627 $insert_head->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
2633 my $filename = shift;
2635 my $db_query = $self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);
2636 $db_query->execute($filename);
2637 my ( $hash, $revision, $mode ) = $db_query->fetchrow_array;
2639 return ( $hash, $revision, $mode );
2647 my $db_query = $self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);
2648 $db_query->execute($key);
2649 my ( $value ) = $db_query->fetchrow_array;
2660 my $db_query = $self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);
2661 $db_query->execute($value, $key);
2663 unless ( $db_query->rows )
2665 $db_query = $self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);
2666 $db_query->execute($key, $value);
2680 return $self->{gethead_cache} if ( defined ( $self->{gethead_cache} ) );
2682 my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);
2683 $db_query->execute();
2686 while ( my $file = $db_query->fetchrow_hashref )
2691 $self->{gethead_cache} = $tree;
2703 my $filename = shift;
2705 my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);
2706 $db_query->execute($filename);
2709 while ( my $file = $db_query->fetchrow_hashref )
2719 This function takes a filename (with path) argument and returns a hashref of
2720 metadata for that file.
2727 my $filename = shift;
2728 my $revision = shift;
2731 if ( defined($revision) and $revision =~ /^\d+$/ )
2733 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);
2734 $db_query->execute($filename, $revision);
2736 elsif ( defined($revision) and $revision =~ /^[a-zA-Z0-9]{40}$/ )
2738 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);
2739 $db_query->execute($filename, $revision);
2741 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);
2742 $db_query->execute($filename);
2745 return $db_query->fetchrow_hashref;
2748 =head2 commitmessage
2750 this function takes a commithash and returns the commit message for that commit
2756 my $commithash = shift;
2758 die("Need commithash") unless ( defined($commithash) and $commithash =~ /^[a-zA-Z0-9]{40}$/ );
2761 $db_query = $self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);
2762 $db_query->execute($commithash);
2764 my ( $message ) = $db_query->fetchrow_array;
2766 if ( defined ( $message ) )
2768 $message .= " " if ( $message =~ /\n$/ );
2772 my @lines = safe_pipe_capture("git-cat-file", "commit", $commithash);
2773 shift @lines while ( $lines[0] =~ /\S/ );
2774 $message = join("",@lines);
2775 $message .= " " if ( $message =~ /\n$/ );
2781 This function takes a filename (with path) argument and returns an arrayofarrays
2782 containing revision,filehash,commithash ordered by revision descending
2788 my $filename = shift;
2791 $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);
2792 $db_query->execute($filename);
2794 return $db_query->fetchall_arrayref;
2797 =head2 gethistorydense
2799 This function takes a filename (with path) argument and returns an arrayofarrays
2800 containing revision,filehash,commithash ordered by revision descending.
2802 This version of gethistory skips deleted entries -- so it is useful for annotate.
2803 The 'dense' part is a reference to a '--dense' option available for git-rev-list
2804 and other git tools that depend on it.
2810 my $filename = shift;
2813 $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);
2814 $db_query->execute($filename);
2816 return $db_query->fetchall_arrayref;
2821 from Array::PAT - mimics the in_array() function
2822 found in PHP. Yuck but works for small arrays.
2827 my ($check, @array) = @_;
2829 foreach my $test (@array){
2830 if($check eq $test){
2837 =head2 safe_pipe_capture
2839 an alternative to `command` that allows input to be passed as an array
2840 to work around shell problems with weird characters in arguments
2843 sub safe_pipe_capture {
2847 if (my $pid = open my $child, '-|') {
2848 @output = (<$child>);
2849 close $child or die join(' ',@_).": $! $?";
2851 exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
2853 return wantarray ? @output : join('',@output);