]> git.ipfire.org Git - thirdparty/git.git/blame - git-cvsserver.perl
Make 'cvs ci' lockless in git-cvsserver by using git-update-ref
[thirdparty/git.git] / git-cvsserver.perl
CommitLineData
3fda8c4c
ML
1#!/usr/bin/perl
2
3####
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.
7####
8#### Copyright The Open University UK - 2006.
9####
10#### Authors: Martyn Smith <martyn@catalyst.net.nz>
11#### Martin Langhoff <martin@catalyst.net.nz>
12####
13####
14#### Released under the GNU Public License, version 2.
15####
16####
17
18use strict;
19use warnings;
4f88d3e0 20use bytes;
3fda8c4c
ML
21
22use Fcntl;
23use File::Temp qw/tempdir tempfile/;
24use File::Basename;
25
26my $log = GITCVS::log->new();
27my $cfg;
28
29my $DATE_LIST = {
30 Jan => "01",
31 Feb => "02",
32 Mar => "03",
33 Apr => "04",
34 May => "05",
35 Jun => "06",
36 Jul => "07",
37 Aug => "08",
38 Sep => "09",
39 Oct => "10",
40 Nov => "11",
41 Dec => "12",
42};
43
44# Enable autoflush for STDOUT (otherwise the whole thing falls apart)
45$| = 1;
46
47#### Definition and mappings of functions ####
48
49my $methods = {
50 'Root' => \&req_Root,
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,
7172aabb 57 'Questionable' => \&req_Questionable,
3fda8c4c
ML
58 'Argument' => \&req_Argument,
59 'Argumentx' => \&req_Argument,
60 'expand-modules' => \&req_expandmodules,
61 'add' => \&req_add,
62 'remove' => \&req_remove,
63 'co' => \&req_co,
64 'update' => \&req_update,
65 'ci' => \&req_ci,
66 'diff' => \&req_diff,
67 'log' => \&req_log,
7172aabb 68 'rlog' => \&req_log,
3fda8c4c
ML
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,
78};
79
80##############################################
81
82
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.
42217f13 85my $state = { prependdir => '' };
3fda8c4c
ML
86$log->info("--------------- STARTING -----------------");
87
88my $TEMP_DIR = tempdir( CLEANUP => 1 );
89$log->debug("Temporary directory is '$TEMP_DIR'");
90
91a6bf46 91# if we are called with a pserver argument,
5348b6e7 92# deal with the authentication cat before entering the
91a6bf46
ML
93# main loop
94if (@ARGV && $ARGV[0] eq 'pserver') {
95 my $line = <STDIN>; chomp $line;
96 unless( $line eq 'BEGIN AUTH REQUEST') {
97 die "E Do not understand $line - expecting BEGIN AUTH REQUEST\n";
98 }
99 $line = <STDIN>; chomp $line;
100 req_Root('root', $line) # reuse Root
101 or die "E Invalid root $line \n";
102 $line = <STDIN>; chomp $line;
103 unless ($line eq 'anonymous') {
104 print "E Only anonymous user allowed via pserver\n";
105 print "I HATE YOU\n";
106 }
107 $line = <STDIN>; chomp $line; # validate the password?
108 $line = <STDIN>; chomp $line;
109 unless ($line eq 'END AUTH REQUEST') {
110 die "E Do not understand $line -- expecting END AUTH REQUEST\n";
111 }
112 print "I LOVE YOU\n";
113 # and now back to our regular programme...
114}
115
3fda8c4c
ML
116# Keep going until the client closes the connection
117while (<STDIN>)
118{
119 chomp;
120
5348b6e7 121 # Check to see if we've seen this method, and call appropriate function.
3fda8c4c
ML
122 if ( /^([\w-]+)(?:\s+(.*))?$/ and defined($methods->{$1}) )
123 {
124 # use the $methods hash to call the appropriate sub for this command
125 #$log->info("Method : $1");
126 &{$methods->{$1}}($1,$2);
127 } else {
128 # log fatal because we don't understand this function. If this happens
129 # we're fairly screwed because we don't know if the client is expecting
130 # a response. If it is, the client will hang, we'll hang, and the whole
131 # thing will be custard.
132 $log->fatal("Don't understand command $_\n");
133 die("Unknown command $_");
134 }
135}
136
137$log->debug("Processing time : user=" . (times)[0] . " system=" . (times)[1]);
138$log->info("--------------- FINISH -----------------");
139
140# Magic catchall method.
141# This is the method that will handle all commands we haven't yet
142# implemented. It simply sends a warning to the log file indicating a
143# command that hasn't been implemented has been invoked.
144sub req_CATCHALL
145{
146 my ( $cmd, $data ) = @_;
147 $log->warn("Unhandled command : req_$cmd : $data");
148}
149
150
151# Root pathname \n
152# Response expected: no. Tell the server which CVSROOT to use. Note that
153# pathname is a local directory and not a fully qualified CVSROOT variable.
154# pathname must already exist; if creating a new root, use the init
155# request, not Root. pathname does not include the hostname of the server,
156# how to access the server, etc.; by the time the CVS protocol is in use,
157# connection, authentication, etc., are already taken care of. The Root
158# request must be sent only once, and it must be sent before any requests
159# other than Valid-responses, valid-requests, UseUnchanged, Set or init.
160sub req_Root
161{
162 my ( $cmd, $data ) = @_;
163 $log->debug("req_Root : $data");
164
165 $state->{CVSROOT} = $data;
166
167 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
cdb6760e
ML
168 unless (-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') {
169 print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
170 print "E \n";
171 print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
172 return 0;
173 }
3fda8c4c 174
e0d10e1c 175 my @gitvars = `git-config -l`;
cdb6760e 176 if ($?) {
e0d10e1c 177 print "E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n";
cdb6760e 178 print "E \n";
e0d10e1c 179 print "error 1 - problem executing git-config\n";
cdb6760e
ML
180 return 0;
181 }
182 foreach my $line ( @gitvars )
3fda8c4c
ML
183 {
184 next unless ( $line =~ /^(.*?)\.(.*?)=(.*)$/ );
185 $cfg->{$1}{$2} = $3;
186 }
187
188 unless ( defined ( $cfg->{gitcvs}{enabled} ) and $cfg->{gitcvs}{enabled} =~ /^\s*(1|true|yes)\s*$/i )
189 {
190 print "E GITCVS emulation needs to be enabled on this repo\n";
191 print "E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n";
192 print "E \n";
193 print "error 1 GITCVS emulation disabled\n";
91a6bf46 194 return 0;
3fda8c4c
ML
195 }
196
197 if ( defined ( $cfg->{gitcvs}{logfile} ) )
198 {
199 $log->setfile($cfg->{gitcvs}{logfile});
200 } else {
201 $log->nofile();
202 }
91a6bf46
ML
203
204 return 1;
3fda8c4c
ML
205}
206
207# Global_option option \n
208# Response expected: no. Transmit one of the global options `-q', `-Q',
209# `-l', `-t', `-r', or `-n'. option must be one of those strings, no
210# variations (such as combining of options) are allowed. For graceful
211# handling of valid-requests, it is probably better to make new global
212# options separate requests, rather than trying to add them to this
213# request.
214sub req_Globaloption
215{
216 my ( $cmd, $data ) = @_;
217 $log->debug("req_Globaloption : $data");
7d90095a 218 $state->{globaloptions}{$data} = 1;
3fda8c4c
ML
219}
220
221# Valid-responses request-list \n
222# Response expected: no. Tell the server what responses the client will
223# accept. request-list is a space separated list of tokens.
224sub req_Validresponses
225{
226 my ( $cmd, $data ) = @_;
5348b6e7 227 $log->debug("req_Validresponses : $data");
3fda8c4c
ML
228
229 # TODO : re-enable this, currently it's not particularly useful
230 #$state->{validresponses} = [ split /\s+/, $data ];
231}
232
233# valid-requests \n
234# Response expected: yes. Ask the server to send back a Valid-requests
235# response.
236sub req_validrequests
237{
238 my ( $cmd, $data ) = @_;
239
240 $log->debug("req_validrequests");
241
242 $log->debug("SEND : Valid-requests " . join(" ",keys %$methods));
243 $log->debug("SEND : ok");
244
245 print "Valid-requests " . join(" ",keys %$methods) . "\n";
246 print "ok\n";
247}
248
249# Directory local-directory \n
250# Additional data: repository \n. Response expected: no. Tell the server
251# what directory to use. The repository should be a directory name from a
252# previous server response. Note that this both gives a default for Entry
253# and Modified and also for ci and the other commands; normal usage is to
254# send Directory for each directory in which there will be an Entry or
255# Modified, and then a final Directory for the original directory, then the
256# command. The local-directory is relative to the top level at which the
257# command is occurring (i.e. the last Directory which is sent before the
258# command); to indicate that top level, `.' should be sent for
259# local-directory.
260sub req_Directory
261{
262 my ( $cmd, $data ) = @_;
263
264 my $repository = <STDIN>;
265 chomp $repository;
266
267
268 $state->{localdir} = $data;
269 $state->{repository} = $repository;
7d90095a
MS
270 $state->{path} = $repository;
271 $state->{path} =~ s/^$state->{CVSROOT}\///;
272 $state->{module} = $1 if ($state->{path} =~ s/^(.*?)(\/|$)//);
273 $state->{path} .= "/" if ( $state->{path} =~ /\S/ );
274
275 $state->{directory} = $state->{localdir};
276 $state->{directory} = "" if ( $state->{directory} eq "." );
3fda8c4c
ML
277 $state->{directory} .= "/" if ( $state->{directory} =~ /\S/ );
278
d988b822 279 if ( (not defined($state->{prependdir}) or $state->{prependdir} eq '') and $state->{localdir} eq "." and $state->{path} =~ /\S/ )
7d90095a
MS
280 {
281 $log->info("Setting prepend to '$state->{path}'");
282 $state->{prependdir} = $state->{path};
283 foreach my $entry ( keys %{$state->{entries}} )
284 {
285 $state->{entries}{$state->{prependdir} . $entry} = $state->{entries}{$entry};
286 delete $state->{entries}{$entry};
287 }
288 }
289
290 if ( defined ( $state->{prependdir} ) )
291 {
292 $log->debug("Prepending '$state->{prependdir}' to state|directory");
293 $state->{directory} = $state->{prependdir} . $state->{directory}
294 }
82000d74 295 $log->debug("req_Directory : localdir=$data repository=$repository path=$state->{path} directory=$state->{directory} module=$state->{module}");
3fda8c4c
ML
296}
297
298# Entry entry-line \n
299# Response expected: no. Tell the server what version of a file is on the
300# local machine. The name in entry-line is a name relative to the directory
301# most recently specified with Directory. If the user is operating on only
302# some files in a directory, Entry requests for only those files need be
303# included. If an Entry request is sent without Modified, Is-modified, or
304# Unchanged, it means the file is lost (does not exist in the working
305# directory). If both Entry and one of Modified, Is-modified, or Unchanged
306# are sent for the same file, Entry must be sent first. For a given file,
307# one can send Modified, Is-modified, or Unchanged, but not more than one
308# of these three.
309sub req_Entry
310{
311 my ( $cmd, $data ) = @_;
312
7d90095a 313 #$log->debug("req_Entry : $data");
3fda8c4c
ML
314
315 my @data = split(/\//, $data);
316
317 $state->{entries}{$state->{directory}.$data[1]} = {
318 revision => $data[2],
319 conflict => $data[3],
320 options => $data[4],
321 tag_or_date => $data[5],
322 };
7d90095a
MS
323
324 $log->info("Received entry line '$data' => '" . $state->{directory} . $data[1] . "'");
325}
326
327# Questionable filename \n
328# Response expected: no. Additional data: no. Tell the server to check
329# whether filename should be ignored, and if not, next time the server
330# sends responses, send (in a M response) `?' followed by the directory and
331# filename. filename must not contain `/'; it needs to be a file in the
332# directory named by the most recent Directory request.
333sub req_Questionable
334{
335 my ( $cmd, $data ) = @_;
336
337 $log->debug("req_Questionable : $data");
338 $state->{entries}{$state->{directory}.$data}{questionable} = 1;
3fda8c4c
ML
339}
340
341# add \n
342# Response expected: yes. Add a file or directory. This uses any previous
343# Argument, Directory, Entry, or Modified requests, if they have been sent.
344# The last Directory sent specifies the working directory at the time of
345# the operation. To add a directory, send the directory to be added using
346# Directory and Argument requests.
347sub req_add
348{
349 my ( $cmd, $data ) = @_;
350
351 argsplit("add");
352
353 my $addcount = 0;
354
355 foreach my $filename ( @{$state->{args}} )
356 {
357 $filename = filecleanup($filename);
358
359 unless ( defined ( $state->{entries}{$filename}{modified_filename} ) )
360 {
361 print "E cvs add: nothing known about `$filename'\n";
362 next;
363 }
364 # TODO : check we're not squashing an already existing file
365 if ( defined ( $state->{entries}{$filename}{revision} ) )
366 {
367 print "E cvs add: `$filename' has already been entered\n";
368 next;
369 }
370
7d90095a 371 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
3fda8c4c
ML
372
373 print "E cvs add: scheduling file `$filename' for addition\n";
374
375 print "Checked-in $dirpart\n";
376 print "$filename\n";
377 print "/$filepart/0///\n";
378
379 $addcount++;
380 }
381
382 if ( $addcount == 1 )
383 {
384 print "E cvs add: use `cvs commit' to add this file permanently\n";
385 }
386 elsif ( $addcount > 1 )
387 {
388 print "E cvs add: use `cvs commit' to add these files permanently\n";
389 }
390
391 print "ok\n";
392}
393
394# remove \n
395# Response expected: yes. Remove a file. This uses any previous Argument,
396# Directory, Entry, or Modified requests, if they have been sent. The last
397# Directory sent specifies the working directory at the time of the
398# operation. Note that this request does not actually do anything to the
399# repository; the only effect of a successful remove request is to supply
400# the client with a new entries line containing `-' to indicate a removed
401# file. In fact, the client probably could perform this operation without
402# contacting the server, although using remove may cause the server to
403# perform a few more checks. The client sends a subsequent ci request to
404# actually record the removal in the repository.
405sub req_remove
406{
407 my ( $cmd, $data ) = @_;
408
409 argsplit("remove");
410
411 # Grab a handle to the SQLite db and do any necessary updates
412 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
413 $updater->update();
414
415 #$log->debug("add state : " . Dumper($state));
416
417 my $rmcount = 0;
418
419 foreach my $filename ( @{$state->{args}} )
420 {
421 $filename = filecleanup($filename);
422
423 if ( defined ( $state->{entries}{$filename}{unchanged} ) or defined ( $state->{entries}{$filename}{modified_filename} ) )
424 {
425 print "E cvs remove: file `$filename' still in working directory\n";
426 next;
427 }
428
429 my $meta = $updater->getmeta($filename);
430 my $wrev = revparse($filename);
431
432 unless ( defined ( $wrev ) )
433 {
434 print "E cvs remove: nothing known about `$filename'\n";
435 next;
436 }
437
438 if ( defined($wrev) and $wrev < 0 )
439 {
440 print "E cvs remove: file `$filename' already scheduled for removal\n";
441 next;
442 }
443
444 unless ( $wrev == $meta->{revision} )
445 {
446 # TODO : not sure if the format of this message is quite correct.
447 print "E cvs remove: Up to date check failed for `$filename'\n";
448 next;
449 }
450
451
7d90095a 452 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
3fda8c4c
ML
453
454 print "E cvs remove: scheduling `$filename' for removal\n";
455
456 print "Checked-in $dirpart\n";
457 print "$filename\n";
458 print "/$filepart/-1.$wrev///\n";
459
460 $rmcount++;
461 }
462
463 if ( $rmcount == 1 )
464 {
465 print "E cvs remove: use `cvs commit' to remove this file permanently\n";
466 }
467 elsif ( $rmcount > 1 )
468 {
469 print "E cvs remove: use `cvs commit' to remove these files permanently\n";
470 }
471
472 print "ok\n";
473}
474
475# Modified filename \n
476# Response expected: no. Additional data: mode, \n, file transmission. Send
477# the server a copy of one locally modified file. filename is a file within
478# the most recent directory sent with Directory; it must not contain `/'.
479# If the user is operating on only some files in a directory, only those
480# files need to be included. This can also be sent without Entry, if there
481# is no entry for the file.
482sub req_Modified
483{
484 my ( $cmd, $data ) = @_;
485
486 my $mode = <STDIN>;
487 chomp $mode;
488 my $size = <STDIN>;
489 chomp $size;
490
491 # Grab config information
492 my $blocksize = 8192;
493 my $bytesleft = $size;
494 my $tmp;
495
496 # Get a filehandle/name to write it to
497 my ( $fh, $filename ) = tempfile( DIR => $TEMP_DIR );
498
499 # Loop over file data writing out to temporary file.
500 while ( $bytesleft )
501 {
502 $blocksize = $bytesleft if ( $bytesleft < $blocksize );
503 read STDIN, $tmp, $blocksize;
504 print $fh $tmp;
505 $bytesleft -= $blocksize;
506 }
507
508 close $fh;
509
510 # Ensure we have something sensible for the file mode
511 if ( $mode =~ /u=(\w+)/ )
512 {
513 $mode = $1;
514 } else {
515 $mode = "rw";
516 }
517
518 # Save the file data in $state
519 $state->{entries}{$state->{directory}.$data}{modified_filename} = $filename;
520 $state->{entries}{$state->{directory}.$data}{modified_mode} = $mode;
521 $state->{entries}{$state->{directory}.$data}{modified_hash} = `git-hash-object $filename`;
522 $state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s;
523
524 #$log->debug("req_Modified : file=$data mode=$mode size=$size");
525}
526
527# Unchanged filename \n
528# Response expected: no. Tell the server that filename has not been
529# modified in the checked out directory. The filename is a file within the
530# most recent directory sent with Directory; it must not contain `/'.
531sub req_Unchanged
532{
533 my ( $cmd, $data ) = @_;
534
535 $state->{entries}{$state->{directory}.$data}{unchanged} = 1;
536
537 #$log->debug("req_Unchanged : $data");
538}
539
540# Argument text \n
541# Response expected: no. Save argument for use in a subsequent command.
542# Arguments accumulate until an argument-using command is given, at which
543# point they are forgotten.
544# Argumentx text \n
545# Response expected: no. Append \n followed by text to the current argument
546# being saved.
547sub req_Argument
548{
549 my ( $cmd, $data ) = @_;
550
2c3cff49 551 # Argumentx means: append to last Argument (with a newline in front)
3fda8c4c
ML
552
553 $log->debug("$cmd : $data");
554
2c3cff49
JS
555 if ( $cmd eq 'Argumentx') {
556 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" . $data;
557 } else {
558 push @{$state->{arguments}}, $data;
559 }
3fda8c4c
ML
560}
561
562# expand-modules \n
563# Response expected: yes. Expand the modules which are specified in the
564# arguments. Returns the data in Module-expansion responses. Note that the
565# server can assume that this is checkout or export, not rtag or rdiff; the
566# latter do not access the working directory and thus have no need to
567# expand modules on the client side. Expand may not be the best word for
568# what this request does. It does not necessarily tell you all the files
569# contained in a module, for example. Basically it is a way of telling you
570# which working directories the server needs to know about in order to
571# handle a checkout of the specified modules. For example, suppose that the
572# server has a module defined by
573# aliasmodule -a 1dir
574# That is, one can check out aliasmodule and it will take 1dir in the
575# repository and check it out to 1dir in the working directory. Now suppose
576# the client already has this module checked out and is planning on using
577# the co request to update it. Without using expand-modules, the client
578# would have two bad choices: it could either send information about all
579# working directories under the current directory, which could be
580# unnecessarily slow, or it could be ignorant of the fact that aliasmodule
581# stands for 1dir, and neglect to send information for 1dir, which would
582# lead to incorrect operation. With expand-modules, the client would first
583# ask for the module to be expanded:
584sub req_expandmodules
585{
586 my ( $cmd, $data ) = @_;
587
588 argsplit();
589
590 $log->debug("req_expandmodules : " . ( defined($data) ? $data : "[NULL]" ) );
591
592 unless ( ref $state->{arguments} eq "ARRAY" )
593 {
594 print "ok\n";
595 return;
596 }
597
598 foreach my $module ( @{$state->{arguments}} )
599 {
600 $log->debug("SEND : Module-expansion $module");
601 print "Module-expansion $module\n";
602 }
603
604 print "ok\n";
605 statecleanup();
606}
607
608# co \n
609# Response expected: yes. Get files from the repository. This uses any
610# previous Argument, Directory, Entry, or Modified requests, if they have
611# been sent. Arguments to this command are module names; the client cannot
612# know what directories they correspond to except by (1) just sending the
613# co request, and then seeing what directory names the server sends back in
614# its responses, and (2) the expand-modules request.
615sub req_co
616{
617 my ( $cmd, $data ) = @_;
618
619 argsplit("co");
620
621 my $module = $state->{args}[0];
622 my $checkout_path = $module;
623
624 # use the user specified directory if we're given it
625 $checkout_path = $state->{opt}{d} if ( exists ( $state->{opt}{d} ) );
626
627 $log->debug("req_co : " . ( defined($data) ? $data : "[NULL]" ) );
628
629 $log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'");
630
631 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
632
633 # Grab a handle to the SQLite db and do any necessary updates
634 my $updater = GITCVS::updater->new($state->{CVSROOT}, $module, $log);
635 $updater->update();
636
c8c4f220
ML
637 $checkout_path =~ s|/$||; # get rid of trailing slashes
638
639 # Eclipse seems to need the Clear-sticky command
640 # to prepare the 'Entries' file for the new directory.
641 print "Clear-sticky $checkout_path/\n";
e74ee784 642 print $state->{CVSROOT} . "/$module/\n";
c8c4f220 643 print "Clear-static-directory $checkout_path/\n";
e74ee784 644 print $state->{CVSROOT} . "/$module/\n";
6be32d47
ML
645 print "Clear-sticky $checkout_path/\n"; # yes, twice
646 print $state->{CVSROOT} . "/$module/\n";
647 print "Template $checkout_path/\n";
648 print $state->{CVSROOT} . "/$module/\n";
649 print "0\n";
c8c4f220 650
3fda8c4c 651 # instruct the client that we're checking out to $checkout_path
c8c4f220
ML
652 print "E cvs checkout: Updating $checkout_path\n";
653
654 my %seendirs = ();
501c7372 655 my $lastdir ='';
3fda8c4c 656
6be32d47
ML
657 # recursive
658 sub prepdir {
659 my ($dir, $repodir, $remotedir, $seendirs) = @_;
660 my $parent = dirname($dir);
661 $dir =~ s|/+$||;
662 $repodir =~ s|/+$||;
663 $remotedir =~ s|/+$||;
664 $parent =~ s|/+$||;
665 $log->debug("announcedir $dir, $repodir, $remotedir" );
666
667 if ($parent eq '.' || $parent eq './') {
668 $parent = '';
669 }
670 # recurse to announce unseen parents first
671 if (length($parent) && !exists($seendirs->{$parent})) {
672 prepdir($parent, $repodir, $remotedir, $seendirs);
673 }
674 # Announce that we are going to modify at the parent level
675 if ($parent) {
676 print "E cvs checkout: Updating $remotedir/$parent\n";
677 } else {
678 print "E cvs checkout: Updating $remotedir\n";
679 }
680 print "Clear-sticky $remotedir/$parent/\n";
681 print "$repodir/$parent/\n";
682
683 print "Clear-static-directory $remotedir/$dir/\n";
684 print "$repodir/$dir/\n";
685 print "Clear-sticky $remotedir/$parent/\n"; # yes, twice
686 print "$repodir/$parent/\n";
687 print "Template $remotedir/$dir/\n";
688 print "$repodir/$dir/\n";
689 print "0\n";
690
691 $seendirs->{$dir} = 1;
692 }
693
3fda8c4c
ML
694 foreach my $git ( @{$updater->gethead} )
695 {
696 # Don't want to check out deleted files
697 next if ( $git->{filehash} eq "deleted" );
698
699 ( $git->{name}, $git->{dir} ) = filenamesplit($git->{name});
700
6be32d47
ML
701 if (length($git->{dir}) && $git->{dir} ne './'
702 && $git->{dir} ne $lastdir ) {
703 unless (exists($seendirs{$git->{dir}})) {
704 prepdir($git->{dir}, $state->{CVSROOT} . "/$module/",
705 $checkout_path, \%seendirs);
706 $lastdir = $git->{dir};
707 $seendirs{$git->{dir}} = 1;
708 }
709 print "E cvs checkout: Updating /$checkout_path/$git->{dir}\n";
710 }
711
3fda8c4c
ML
712 # modification time of this file
713 print "Mod-time $git->{modified}\n";
714
715 # print some information to the client
3fda8c4c
ML
716 if ( defined ( $git->{dir} ) and $git->{dir} ne "./" )
717 {
c8c4f220 718 print "M U $checkout_path/$git->{dir}$git->{name}\n";
3fda8c4c 719 } else {
c8c4f220 720 print "M U $checkout_path/$git->{name}\n";
3fda8c4c 721 }
c8c4f220 722
6be32d47
ML
723 # instruct client we're sending a file to put in this path
724 print "Created $checkout_path/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "\n";
3fda8c4c 725
6be32d47 726 print $state->{CVSROOT} . "/$module/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "$git->{name}\n";
3fda8c4c
ML
727
728 # this is an "entries" line
729 print "/$git->{name}/1.$git->{revision}///\n";
730 # permissions
731 print "u=$git->{mode},g=$git->{mode},o=$git->{mode}\n";
732
733 # transmit file
734 transmitfile($git->{filehash});
735 }
736
737 print "ok\n";
738
739 statecleanup();
740}
741
742# update \n
743# Response expected: yes. Actually do a cvs update command. This uses any
744# previous Argument, Directory, Entry, or Modified requests, if they have
745# been sent. The last Directory sent specifies the working directory at the
746# time of the operation. The -I option is not used--files which the client
747# can decide whether to ignore are not mentioned and the client sends the
748# Questionable request for others.
749sub req_update
750{
751 my ( $cmd, $data ) = @_;
752
753 $log->debug("req_update : " . ( defined($data) ? $data : "[NULL]" ));
754
755 argsplit("update");
756
858cbfba 757 #
5348b6e7 758 # It may just be a client exploring the available heads/modules
858cbfba
ML
759 # in that case, list them as top level directories and leave it
760 # at that. Eclipse uses this technique to offer you a list of
761 # projects (heads in this case) to checkout.
762 #
763 if ($state->{module} eq '') {
764 print "E cvs update: Updating .\n";
765 opendir HEADS, $state->{CVSROOT} . '/refs/heads';
766 while (my $head = readdir(HEADS)) {
767 if (-f $state->{CVSROOT} . '/refs/heads/' . $head) {
768 print "E cvs update: New directory `$head'\n";
769 }
770 }
771 closedir HEADS;
772 print "ok\n";
773 return 1;
774 }
775
776
3fda8c4c
ML
777 # Grab a handle to the SQLite db and do any necessary updates
778 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
779
780 $updater->update();
781
7d90095a 782 argsfromdir($updater);
3fda8c4c
ML
783
784 #$log->debug("update state : " . Dumper($state));
785
addf88e4 786 # foreach file specified on the command line ...
3fda8c4c
ML
787 foreach my $filename ( @{$state->{args}} )
788 {
789 $filename = filecleanup($filename);
790
7d90095a
MS
791 $log->debug("Processing file $filename");
792
3fda8c4c
ML
793 # if we have a -C we should pretend we never saw modified stuff
794 if ( exists ( $state->{opt}{C} ) )
795 {
796 delete $state->{entries}{$filename}{modified_hash};
797 delete $state->{entries}{$filename}{modified_filename};
798 $state->{entries}{$filename}{unchanged} = 1;
799 }
800
801 my $meta;
802 if ( defined($state->{opt}{r}) and $state->{opt}{r} =~ /^1\.(\d+)/ )
803 {
804 $meta = $updater->getmeta($filename, $1);
805 } else {
806 $meta = $updater->getmeta($filename);
807 }
808
0a7a9a12
JS
809 if ( ! defined $meta )
810 {
811 $meta = {
812 name => $filename,
813 revision => 0,
814 filehash => 'added'
815 };
816 }
3fda8c4c
ML
817
818 my $oldmeta = $meta;
819
820 my $wrev = revparse($filename);
821
822 # If the working copy is an old revision, lets get that version too for comparison.
823 if ( defined($wrev) and $wrev != $meta->{revision} )
824 {
825 $oldmeta = $updater->getmeta($filename, $wrev);
826 }
827
828 #$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");
829
ec58db15
ML
830 # Files are up to date if the working copy and repo copy have the same revision,
831 # and the working copy is unmodified _and_ the user hasn't specified -C
832 next if ( defined ( $wrev )
833 and defined($meta->{revision})
834 and $wrev == $meta->{revision}
835 and $state->{entries}{$filename}{unchanged}
836 and not exists ( $state->{opt}{C} ) );
837
838 # If the working copy and repo copy have the same revision,
839 # but the working copy is modified, tell the client it's modified
840 if ( defined ( $wrev )
841 and defined($meta->{revision})
842 and $wrev == $meta->{revision}
843 and not exists ( $state->{opt}{C} ) )
844 {
845 $log->info("Tell the client the file is modified");
0a7a9a12 846 print "MT text M \n";
ec58db15
ML
847 print "MT fname $filename\n";
848 print "MT newline\n";
849 next;
850 }
3fda8c4c
ML
851
852 if ( $meta->{filehash} eq "deleted" )
853 {
7d90095a 854 my ( $filepart, $dirpart ) = filenamesplit($filename,1);
3fda8c4c
ML
855
856 $log->info("Removing '$filename' from working copy (no longer in the repo)");
857
858 print "E cvs update: `$filename' is no longer in the repository\n";
7d90095a
MS
859 # Don't want to actually _DO_ the update if -n specified
860 unless ( $state->{globaloptions}{-n} ) {
861 print "Removed $dirpart\n";
862 print "$filepart\n";
863 }
3fda8c4c 864 }
ec58db15 865 elsif ( not defined ( $state->{entries}{$filename}{modified_hash} )
0a7a9a12
JS
866 or $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash}
867 or $meta->{filehash} eq 'added' )
3fda8c4c 868 {
0a7a9a12
JS
869 # normal update, just send the new revision (either U=Update,
870 # or A=Add, or R=Remove)
871 if ( defined($wrev) && $wrev < 0 )
872 {
873 $log->info("Tell the client the file is scheduled for removal");
874 print "MT text R \n";
875 print "MT fname $filename\n";
876 print "MT newline\n";
877 next;
878 }
535514f1 879 elsif ( (!defined($wrev) || $wrev == 0) && (!defined($meta->{revision}) || $meta->{revision} == 0) )
0a7a9a12 880 {
535514f1 881 $log->info("Tell the client the file is scheduled for addition");
0a7a9a12
JS
882 print "MT text A \n";
883 print "MT fname $filename\n";
884 print "MT newline\n";
885 next;
886
887 }
888 else {
535514f1 889 $log->info("Updating '$filename' to ".$meta->{revision});
0a7a9a12
JS
890 print "MT +updated\n";
891 print "MT text U \n";
892 print "MT fname $filename\n";
893 print "MT newline\n";
894 print "MT -updated\n";
895 }
3fda8c4c 896
7d90095a
MS
897 my ( $filepart, $dirpart ) = filenamesplit($filename,1);
898
899 # Don't want to actually _DO_ the update if -n specified
900 unless ( $state->{globaloptions}{-n} )
901 {
902 if ( defined ( $wrev ) )
903 {
904 # instruct client we're sending a file to put in this path as a replacement
905 print "Update-existing $dirpart\n";
906 $log->debug("Updating existing file 'Update-existing $dirpart'");
907 } else {
908 # instruct client we're sending a file to put in this path as a new file
909 print "Clear-static-directory $dirpart\n";
910 print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
911 print "Clear-sticky $dirpart\n";
912 print $state->{CVSROOT} . "/$state->{module}/$dirpart\n";
913
914 $log->debug("Creating new file 'Created $dirpart'");
915 print "Created $dirpart\n";
916 }
917 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
918
919 # this is an "entries" line
920 $log->debug("/$filepart/1.$meta->{revision}///");
921 print "/$filepart/1.$meta->{revision}///\n";
922
923 # permissions
924 $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
925 print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
926
927 # transmit file
928 transmitfile($meta->{filehash});
929 }
3fda8c4c 930 } else {
ec58db15 931 $log->info("Updating '$filename'");
7d90095a 932 my ( $filepart, $dirpart ) = filenamesplit($meta->{name},1);
3fda8c4c
ML
933
934 my $dir = tempdir( DIR => $TEMP_DIR, CLEANUP => 1 ) . "/";
935
936 chdir $dir;
937 my $file_local = $filepart . ".mine";
938 system("ln","-s",$state->{entries}{$filename}{modified_filename}, $file_local);
939 my $file_old = $filepart . "." . $oldmeta->{revision};
940 transmitfile($oldmeta->{filehash}, $file_old);
941 my $file_new = $filepart . "." . $meta->{revision};
942 transmitfile($meta->{filehash}, $file_new);
943
944 # we need to merge with the local changes ( M=successful merge, C=conflict merge )
945 $log->info("Merging $file_local, $file_old, $file_new");
946
947 $log->debug("Temporary directory for merge is $dir");
948
c6b4fa96 949 my $return = system("git", "merge-file", $file_local, $file_old, $file_new);
3fda8c4c
ML
950 $return >>= 8;
951
952 if ( $return == 0 )
953 {
954 $log->info("Merged successfully");
955 print "M M $filename\n";
956 $log->debug("Update-existing $dirpart");
7d90095a
MS
957
958 # Don't want to actually _DO_ the update if -n specified
959 unless ( $state->{globaloptions}{-n} )
960 {
961 print "Update-existing $dirpart\n";
962 $log->debug($state->{CVSROOT} . "/$state->{module}/$filename");
963 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
964 $log->debug("/$filepart/1.$meta->{revision}///");
965 print "/$filepart/1.$meta->{revision}///\n";
966 }
3fda8c4c
ML
967 }
968 elsif ( $return == 1 )
969 {
970 $log->info("Merged with conflicts");
971 print "M C $filename\n";
7d90095a
MS
972
973 # Don't want to actually _DO_ the update if -n specified
974 unless ( $state->{globaloptions}{-n} )
975 {
976 print "Update-existing $dirpart\n";
977 print $state->{CVSROOT} . "/$state->{module}/$filename\n";
978 print "/$filepart/1.$meta->{revision}/+//\n";
979 }
3fda8c4c
ML
980 }
981 else
982 {
983 $log->warn("Merge failed");
984 next;
985 }
986
7d90095a
MS
987 # Don't want to actually _DO_ the update if -n specified
988 unless ( $state->{globaloptions}{-n} )
989 {
990 # permissions
991 $log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
992 print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
993
994 # transmit file, format is single integer on a line by itself (file
995 # size) followed by the file contents
996 # TODO : we should copy files in blocks
997 my $data = `cat $file_local`;
998 $log->debug("File size : " . length($data));
999 print length($data) . "\n";
1000 print $data;
1001 }
3fda8c4c
ML
1002
1003 chdir "/";
1004 }
1005
1006 }
1007
1008 print "ok\n";
1009}
1010
1011sub req_ci
1012{
1013 my ( $cmd, $data ) = @_;
1014
1015 argsplit("ci");
1016
1017 #$log->debug("State : " . Dumper($state));
1018
1019 $log->info("req_ci : " . ( defined($data) ? $data : "[NULL]" ));
1020
91a6bf46
ML
1021 if ( @ARGV && $ARGV[0] eq 'pserver')
1022 {
1023 print "error 1 pserver access cannot commit\n";
1024 exit;
1025 }
1026
3fda8c4c
ML
1027 if ( -e $state->{CVSROOT} . "/index" )
1028 {
568907f5 1029 $log->warn("file 'index' already exists in the git repository");
3fda8c4c
ML
1030 print "error 1 Index already exists in git repo\n";
1031 exit;
1032 }
1033
3fda8c4c
ML
1034 # Grab a handle to the SQLite db and do any necessary updates
1035 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1036 $updater->update();
1037
1038 my $tmpdir = tempdir ( DIR => $TEMP_DIR );
1039 my ( undef, $file_index ) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
ada5ef3b 1040 $log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");
3fda8c4c
ML
1041
1042 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
1043 $ENV{GIT_INDEX_FILE} = $file_index;
1044
ada5ef3b
JH
1045 # Remember where the head was at the beginning.
1046 my $parenthash = `git show-ref -s refs/heads/$state->{module}`;
1047 chomp $parenthash;
1048 if ($parenthash !~ /^[0-9a-f]{40}$/) {
1049 print "error 1 pserver cannot find the current HEAD of module";
1050 exit;
1051 }
1052
3fda8c4c
ML
1053 chdir $tmpdir;
1054
1055 # populate the temporary index based
ada5ef3b 1056 system("git-read-tree", $parenthash);
3fda8c4c
ML
1057 unless ($? == 0)
1058 {
1059 die "Error running git-read-tree $state->{module} $file_index $!";
1060 }
1061 $log->info("Created index '$file_index' with for head $state->{module} - exit status $?");
1062
3fda8c4c
ML
1063 my @committedfiles = ();
1064
addf88e4 1065 # foreach file specified on the command line ...
3fda8c4c
ML
1066 foreach my $filename ( @{$state->{args}} )
1067 {
7d90095a 1068 my $committedfile = $filename;
3fda8c4c
ML
1069 $filename = filecleanup($filename);
1070
1071 next unless ( exists $state->{entries}{$filename}{modified_filename} or not $state->{entries}{$filename}{unchanged} );
1072
1073 my $meta = $updater->getmeta($filename);
1074
1075 my $wrev = revparse($filename);
1076
1077 my ( $filepart, $dirpart ) = filenamesplit($filename);
1078
1079 # do a checkout of the file if it part of this tree
1080 if ($wrev) {
1081 system('git-checkout-index', '-f', '-u', $filename);
1082 unless ($? == 0) {
1083 die "Error running git-checkout-index -f -u $filename : $!";
1084 }
1085 }
1086
1087 my $addflag = 0;
1088 my $rmflag = 0;
1089 $rmflag = 1 if ( defined($wrev) and $wrev < 0 );
1090 $addflag = 1 unless ( -e $filename );
1091
1092 # Do up to date checking
1093 unless ( $addflag or $wrev == $meta->{revision} or ( $rmflag and -$wrev == $meta->{revision} ) )
1094 {
1095 # fail everything if an up to date check fails
1096 print "error 1 Up to date check failed for $filename\n";
3fda8c4c
ML
1097 chdir "/";
1098 exit;
1099 }
1100
7d90095a 1101 push @committedfiles, $committedfile;
3fda8c4c
ML
1102 $log->info("Committing $filename");
1103
1104 system("mkdir","-p",$dirpart) unless ( -d $dirpart );
1105
1106 unless ( $rmflag )
1107 {
1108 $log->debug("rename $state->{entries}{$filename}{modified_filename} $filename");
1109 rename $state->{entries}{$filename}{modified_filename},$filename;
1110
1111 # Calculate modes to remove
1112 my $invmode = "";
1113 foreach ( qw (r w x) ) { $invmode .= $_ unless ( $state->{entries}{$filename}{modified_mode} =~ /$_/ ); }
1114
1115 $log->debug("chmod u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode . " $filename");
1116 system("chmod","u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode, $filename);
1117 }
1118
1119 if ( $rmflag )
1120 {
1121 $log->info("Removing file '$filename'");
1122 unlink($filename);
1123 system("git-update-index", "--remove", $filename);
1124 }
1125 elsif ( $addflag )
1126 {
1127 $log->info("Adding file '$filename'");
1128 system("git-update-index", "--add", $filename);
1129 } else {
1130 $log->info("Updating file '$filename'");
1131 system("git-update-index", $filename);
1132 }
1133 }
1134
1135 unless ( scalar(@committedfiles) > 0 )
1136 {
1137 print "E No files to commit\n";
1138 print "ok\n";
3fda8c4c
ML
1139 chdir "/";
1140 return;
1141 }
1142
1143 my $treehash = `git-write-tree`;
3fda8c4c 1144 chomp $treehash;
3fda8c4c
ML
1145
1146 $log->debug("Treehash : $treehash, Parenthash : $parenthash");
1147
1148 # write our commit message out if we have one ...
1149 my ( $msg_fh, $msg_filename ) = tempfile( DIR => $TEMP_DIR );
1150 print $msg_fh $state->{opt}{m};# if ( exists ( $state->{opt}{m} ) );
1151 print $msg_fh "\n\nvia git-CVS emulator\n";
1152 close $msg_fh;
1153
1154 my $commithash = `git-commit-tree $treehash -p $parenthash < $msg_filename`;
1155 $log->info("Commit hash : $commithash");
1156
1157 unless ( $commithash =~ /[a-zA-Z0-9]{40}/ )
1158 {
1159 $log->warn("Commit failed (Invalid commit hash)");
1160 print "error 1 Commit failed (unknown reason)\n";
3fda8c4c
ML
1161 chdir "/";
1162 exit;
1163 }
1164
b2741f63
AP
1165 # Check that this is allowed, just as we would with a receive-pack
1166 my @cmd = ( $ENV{GIT_DIR}.'hooks/update', "refs/heads/$state->{module}",
1167 $parenthash, $commithash );
1168 if( -x $cmd[0] ) {
1169 unless( system( @cmd ) == 0 )
1170 {
1171 $log->warn("Commit failed (update hook declined to update ref)");
1172 print "error 1 Commit failed (update hook declined)\n";
b2741f63
AP
1173 chdir "/";
1174 exit;
1175 }
1176 }
1177
ada5ef3b
JH
1178 if (system(qw(git update-ref -m), "cvsserver ci",
1179 "refs/heads/$state->{module}", $commithash, $parenthash)) {
1180 $log->warn("update-ref for $state->{module} failed.");
1181 print "error 1 Cannot commit -- update first\n";
1182 exit;
1183 }
3fda8c4c
ML
1184
1185 $updater->update();
1186
addf88e4 1187 # foreach file specified on the command line ...
3fda8c4c
ML
1188 foreach my $filename ( @committedfiles )
1189 {
1190 $filename = filecleanup($filename);
1191
1192 my $meta = $updater->getmeta($filename);
3486595b
ML
1193 unless (defined $meta->{revision}) {
1194 $meta->{revision} = 1;
1195 }
3fda8c4c 1196
7d90095a 1197 my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
3fda8c4c
ML
1198
1199 $log->debug("Checked-in $dirpart : $filename");
1200
3486595b 1201 if ( defined $meta->{filehash} && $meta->{filehash} eq "deleted" )
3fda8c4c
ML
1202 {
1203 print "Remove-entry $dirpart\n";
1204 print "$filename\n";
1205 } else {
1206 print "Checked-in $dirpart\n";
1207 print "$filename\n";
1208 print "/$filepart/1.$meta->{revision}///\n";
1209 }
1210 }
1211
3fda8c4c 1212 chdir "/";
3fda8c4c
ML
1213 print "ok\n";
1214}
1215
1216sub req_status
1217{
1218 my ( $cmd, $data ) = @_;
1219
1220 argsplit("status");
1221
1222 $log->info("req_status : " . ( defined($data) ? $data : "[NULL]" ));
1223 #$log->debug("status state : " . Dumper($state));
1224
1225 # Grab a handle to the SQLite db and do any necessary updates
1226 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1227 $updater->update();
1228
1229 # if no files were specified, we need to work out what files we should be providing status on ...
7d90095a 1230 argsfromdir($updater);
3fda8c4c 1231
addf88e4 1232 # foreach file specified on the command line ...
3fda8c4c
ML
1233 foreach my $filename ( @{$state->{args}} )
1234 {
1235 $filename = filecleanup($filename);
1236
1237 my $meta = $updater->getmeta($filename);
1238 my $oldmeta = $meta;
1239
1240 my $wrev = revparse($filename);
1241
1242 # If the working copy is an old revision, lets get that version too for comparison.
1243 if ( defined($wrev) and $wrev != $meta->{revision} )
1244 {
1245 $oldmeta = $updater->getmeta($filename, $wrev);
1246 }
1247
1248 # TODO : All possible statuses aren't yet implemented
1249 my $status;
1250 # Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified
1251 $status = "Up-to-date" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision}
1252 and
1253 ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
1254 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta->{filehash} ) )
1255 );
1256
1257 # Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified
1258 $status ||= "Needs Checkout" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev
1259 and
1260 ( $state->{entries}{$filename}{unchanged}
1261 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash} ) )
1262 );
1263
1264 # Need checkout if it exists in the repo but doesn't have a working copy
1265 $status ||= "Needs Checkout" if ( not defined ( $wrev ) and defined ( $meta->{revision} ) );
1266
1267 # Locally modified if working copy and repo copy have the same revision but there are local changes
1268 $status ||= "Locally Modified" if ( defined ( $wrev ) and defined($meta->{revision}) and $wrev == $meta->{revision} and $state->{entries}{$filename}{modified_filename} );
1269
1270 # Needs Merge if working copy revision is less than repo copy and there are local changes
1271 $status ||= "Needs Merge" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and $meta->{revision} > $wrev and $state->{entries}{$filename}{modified_filename} );
1272
1273 $status ||= "Locally Added" if ( defined ( $state->{entries}{$filename}{revision} ) and not defined ( $meta->{revision} ) );
1274 $status ||= "Locally Removed" if ( defined ( $wrev ) and defined ( $meta->{revision} ) and -$wrev == $meta->{revision} );
1275 $status ||= "Unresolved Conflict" if ( defined ( $state->{entries}{$filename}{conflict} ) and $state->{entries}{$filename}{conflict} =~ /^\+=/ );
1276 $status ||= "File had conflicts on merge" if ( 0 );
1277
1278 $status ||= "Unknown";
1279
1280 print "M ===================================================================\n";
1281 print "M File: $filename\tStatus: $status\n";
1282 if ( defined($state->{entries}{$filename}{revision}) )
1283 {
1284 print "M Working revision:\t" . $state->{entries}{$filename}{revision} . "\n";
1285 } else {
1286 print "M Working revision:\tNo entry for $filename\n";
1287 }
1288 if ( defined($meta->{revision}) )
1289 {
1290 print "M Repository revision:\t1." . $meta->{revision} . "\t$state->{repository}/$filename,v\n";
1291 print "M Sticky Tag:\t\t(none)\n";
1292 print "M Sticky Date:\t\t(none)\n";
1293 print "M Sticky Options:\t\t(none)\n";
1294 } else {
1295 print "M Repository revision:\tNo revision control file\n";
1296 }
1297 print "M\n";
1298 }
1299
1300 print "ok\n";
1301}
1302
1303sub req_diff
1304{
1305 my ( $cmd, $data ) = @_;
1306
1307 argsplit("diff");
1308
1309 $log->debug("req_diff : " . ( defined($data) ? $data : "[NULL]" ));
1310 #$log->debug("status state : " . Dumper($state));
1311
1312 my ($revision1, $revision2);
1313 if ( defined ( $state->{opt}{r} ) and ref $state->{opt}{r} eq "ARRAY" )
1314 {
1315 $revision1 = $state->{opt}{r}[0];
1316 $revision2 = $state->{opt}{r}[1];
1317 } else {
1318 $revision1 = $state->{opt}{r};
1319 }
1320
1321 $revision1 =~ s/^1\.// if ( defined ( $revision1 ) );
1322 $revision2 =~ s/^1\.// if ( defined ( $revision2 ) );
1323
1324 $log->debug("Diffing revisions " . ( defined($revision1) ? $revision1 : "[NULL]" ) . " and " . ( defined($revision2) ? $revision2 : "[NULL]" ) );
1325
1326 # Grab a handle to the SQLite db and do any necessary updates
1327 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1328 $updater->update();
1329
1330 # if no files were specified, we need to work out what files we should be providing status on ...
7d90095a 1331 argsfromdir($updater);
3fda8c4c 1332
addf88e4 1333 # foreach file specified on the command line ...
3fda8c4c
ML
1334 foreach my $filename ( @{$state->{args}} )
1335 {
1336 $filename = filecleanup($filename);
1337
1338 my ( $fh, $file1, $file2, $meta1, $meta2, $filediff );
1339
1340 my $wrev = revparse($filename);
1341
1342 # We need _something_ to diff against
1343 next unless ( defined ( $wrev ) );
1344
1345 # if we have a -r switch, use it
1346 if ( defined ( $revision1 ) )
1347 {
1348 ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1349 $meta1 = $updater->getmeta($filename, $revision1);
1350 unless ( defined ( $meta1 ) and $meta1->{filehash} ne "deleted" )
1351 {
1352 print "E File $filename at revision 1.$revision1 doesn't exist\n";
1353 next;
1354 }
1355 transmitfile($meta1->{filehash}, $file1);
1356 }
1357 # otherwise we just use the working copy revision
1358 else
1359 {
1360 ( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1361 $meta1 = $updater->getmeta($filename, $wrev);
1362 transmitfile($meta1->{filehash}, $file1);
1363 }
1364
1365 # if we have a second -r switch, use it too
1366 if ( defined ( $revision2 ) )
1367 {
1368 ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1369 $meta2 = $updater->getmeta($filename, $revision2);
1370
1371 unless ( defined ( $meta2 ) and $meta2->{filehash} ne "deleted" )
1372 {
1373 print "E File $filename at revision 1.$revision2 doesn't exist\n";
1374 next;
1375 }
1376
1377 transmitfile($meta2->{filehash}, $file2);
1378 }
1379 # otherwise we just use the working copy
1380 else
1381 {
1382 $file2 = $state->{entries}{$filename}{modified_filename};
1383 }
1384
1385 # if we have been given -r, and we don't have a $file2 yet, lets get one
1386 if ( defined ( $revision1 ) and not defined ( $file2 ) )
1387 {
1388 ( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
1389 $meta2 = $updater->getmeta($filename, $wrev);
1390 transmitfile($meta2->{filehash}, $file2);
1391 }
1392
1393 # We need to have retrieved something useful
1394 next unless ( defined ( $meta1 ) );
1395
1396 # Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified
1397 next if ( not defined ( $meta2 ) and $wrev == $meta1->{revision}
1398 and
1399 ( ( $state->{entries}{$filename}{unchanged} and ( not defined ( $state->{entries}{$filename}{conflict} ) or $state->{entries}{$filename}{conflict} !~ /^\+=/ ) )
1400 or ( defined($state->{entries}{$filename}{modified_hash}) and $state->{entries}{$filename}{modified_hash} eq $meta1->{filehash} ) )
1401 );
1402
1403 # Apparently we only show diffs for locally modified files
1404 next unless ( defined($meta2) or defined ( $state->{entries}{$filename}{modified_filename} ) );
1405
1406 print "M Index: $filename\n";
1407 print "M ===================================================================\n";
1408 print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
1409 print "M retrieving revision 1.$meta1->{revision}\n" if ( defined ( $meta1 ) );
1410 print "M retrieving revision 1.$meta2->{revision}\n" if ( defined ( $meta2 ) );
1411 print "M diff ";
1412 foreach my $opt ( keys %{$state->{opt}} )
1413 {
1414 if ( ref $state->{opt}{$opt} eq "ARRAY" )
1415 {
1416 foreach my $value ( @{$state->{opt}{$opt}} )
1417 {
1418 print "-$opt $value ";
1419 }
1420 } else {
1421 print "-$opt ";
1422 print "$state->{opt}{$opt} " if ( defined ( $state->{opt}{$opt} ) );
1423 }
1424 }
1425 print "$filename\n";
1426
1427 $log->info("Diffing $filename -r $meta1->{revision} -r " . ( $meta2->{revision} or "workingcopy" ));
1428
1429 ( $fh, $filediff ) = tempfile ( DIR => $TEMP_DIR );
1430
1431 if ( exists $state->{opt}{u} )
1432 {
1433 system("diff -u -L '$filename revision 1.$meta1->{revision}' -L '$filename " . ( defined($meta2->{revision}) ? "revision 1.$meta2->{revision}" : "working copy" ) . "' $file1 $file2 > $filediff");
1434 } else {
1435 system("diff $file1 $file2 > $filediff");
1436 }
1437
1438 while ( <$fh> )
1439 {
1440 print "M $_";
1441 }
1442 close $fh;
1443 }
1444
1445 print "ok\n";
1446}
1447
1448sub req_log
1449{
1450 my ( $cmd, $data ) = @_;
1451
1452 argsplit("log");
1453
1454 $log->debug("req_log : " . ( defined($data) ? $data : "[NULL]" ));
1455 #$log->debug("log state : " . Dumper($state));
1456
1457 my ( $minrev, $maxrev );
1458 if ( defined ( $state->{opt}{r} ) and $state->{opt}{r} =~ /([\d.]+)?(::?)([\d.]+)?/ )
1459 {
1460 my $control = $2;
1461 $minrev = $1;
1462 $maxrev = $3;
1463 $minrev =~ s/^1\.// if ( defined ( $minrev ) );
1464 $maxrev =~ s/^1\.// if ( defined ( $maxrev ) );
1465 $minrev++ if ( defined($minrev) and $control eq "::" );
1466 }
1467
1468 # Grab a handle to the SQLite db and do any necessary updates
1469 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1470 $updater->update();
1471
1472 # if no files were specified, we need to work out what files we should be providing status on ...
7d90095a 1473 argsfromdir($updater);
3fda8c4c 1474
addf88e4 1475 # foreach file specified on the command line ...
3fda8c4c
ML
1476 foreach my $filename ( @{$state->{args}} )
1477 {
1478 $filename = filecleanup($filename);
1479
1480 my $headmeta = $updater->getmeta($filename);
1481
1482 my $revisions = $updater->getlog($filename);
1483 my $totalrevisions = scalar(@$revisions);
1484
1485 if ( defined ( $minrev ) )
1486 {
1487 $log->debug("Removing revisions less than $minrev");
1488 while ( scalar(@$revisions) > 0 and $revisions->[-1]{revision} < $minrev )
1489 {
1490 pop @$revisions;
1491 }
1492 }
1493 if ( defined ( $maxrev ) )
1494 {
1495 $log->debug("Removing revisions greater than $maxrev");
1496 while ( scalar(@$revisions) > 0 and $revisions->[0]{revision} > $maxrev )
1497 {
1498 shift @$revisions;
1499 }
1500 }
1501
1502 next unless ( scalar(@$revisions) );
1503
1504 print "M \n";
1505 print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
1506 print "M Working file: $filename\n";
1507 print "M head: 1.$headmeta->{revision}\n";
1508 print "M branch:\n";
1509 print "M locks: strict\n";
1510 print "M access list:\n";
1511 print "M symbolic names:\n";
1512 print "M keyword substitution: kv\n";
1513 print "M total revisions: $totalrevisions;\tselected revisions: " . scalar(@$revisions) . "\n";
1514 print "M description:\n";
1515
1516 foreach my $revision ( @$revisions )
1517 {
1518 print "M ----------------------------\n";
1519 print "M revision 1.$revision->{revision}\n";
1520 # reformat the date for log output
1521 $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}) );
1522 $revision->{author} =~ s/\s+.*//;
1523 $revision->{author} =~ s/^(.{8}).*/$1/;
1524 print "M date: $revision->{modified}; author: $revision->{author}; state: " . ( $revision->{filehash} eq "deleted" ? "dead" : "Exp" ) . "; lines: +2 -3\n";
1525 my $commitmessage = $updater->commitmessage($revision->{commithash});
1526 $commitmessage =~ s/^/M /mg;
1527 print $commitmessage . "\n";
1528 }
1529 print "M =============================================================================\n";
1530 }
1531
1532 print "ok\n";
1533}
1534
1535sub req_annotate
1536{
1537 my ( $cmd, $data ) = @_;
1538
1539 argsplit("annotate");
1540
1541 $log->info("req_annotate : " . ( defined($data) ? $data : "[NULL]" ));
1542 #$log->debug("status state : " . Dumper($state));
1543
1544 # Grab a handle to the SQLite db and do any necessary updates
1545 my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
1546 $updater->update();
1547
1548 # if no files were specified, we need to work out what files we should be providing annotate on ...
7d90095a 1549 argsfromdir($updater);
3fda8c4c
ML
1550
1551 # we'll need a temporary checkout dir
1552 my $tmpdir = tempdir ( DIR => $TEMP_DIR );
1553 my ( undef, $file_index ) = tempfile ( DIR => $TEMP_DIR, OPEN => 0 );
1554 $log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");
1555
1556 $ENV{GIT_DIR} = $state->{CVSROOT} . "/";
1557 $ENV{GIT_INDEX_FILE} = $file_index;
1558
1559 chdir $tmpdir;
1560
addf88e4 1561 # foreach file specified on the command line ...
3fda8c4c
ML
1562 foreach my $filename ( @{$state->{args}} )
1563 {
1564 $filename = filecleanup($filename);
1565
1566 my $meta = $updater->getmeta($filename);
1567
1568 next unless ( $meta->{revision} );
1569
1570 # get all the commits that this file was in
1571 # in dense format -- aka skip dead revisions
1572 my $revisions = $updater->gethistorydense($filename);
1573 my $lastseenin = $revisions->[0][2];
1574
1575 # populate the temporary index based on the latest commit were we saw
1576 # the file -- but do it cheaply without checking out any files
1577 # TODO: if we got a revision from the client, use that instead
1578 # to look up the commithash in sqlite (still good to default to
1579 # the current head as we do now)
1580 system("git-read-tree", $lastseenin);
1581 unless ($? == 0)
1582 {
1583 die "Error running git-read-tree $lastseenin $file_index $!";
1584 }
1585 $log->info("Created index '$file_index' with commit $lastseenin - exit status $?");
1586
1587 # do a checkout of the file
1588 system('git-checkout-index', '-f', '-u', $filename);
1589 unless ($? == 0) {
1590 die "Error running git-checkout-index -f -u $filename : $!";
1591 }
1592
1593 $log->info("Annotate $filename");
1594
1595 # Prepare a file with the commits from the linearized
1596 # history that annotate should know about. This prevents
1597 # git-jsannotate telling us about commits we are hiding
1598 # from the client.
1599
1600 open(ANNOTATEHINTS, ">$tmpdir/.annotate_hints") or die "Error opening > $tmpdir/.annotate_hints $!";
1601 for (my $i=0; $i < @$revisions; $i++)
1602 {
1603 print ANNOTATEHINTS $revisions->[$i][2];
1604 if ($i+1 < @$revisions) { # have we got a parent?
1605 print ANNOTATEHINTS ' ' . $revisions->[$i+1][2];
1606 }
1607 print ANNOTATEHINTS "\n";
1608 }
1609
1610 print ANNOTATEHINTS "\n";
1611 close ANNOTATEHINTS;
1612
1613 my $annotatecmd = 'git-annotate';
1614 open(ANNOTATE, "-|", $annotatecmd, '-l', '-S', "$tmpdir/.annotate_hints", $filename)
1615 or die "Error invoking $annotatecmd -l -S $tmpdir/.annotate_hints $filename : $!";
1616 my $metadata = {};
1617 print "E Annotations for $filename\n";
1618 print "E ***************\n";
1619 while ( <ANNOTATE> )
1620 {
1621 if (m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)
1622 {
1623 my $commithash = $1;
1624 my $data = $2;
1625 unless ( defined ( $metadata->{$commithash} ) )
1626 {
1627 $metadata->{$commithash} = $updater->getmeta($filename, $commithash);
1628 $metadata->{$commithash}{author} =~ s/\s+.*//;
1629 $metadata->{$commithash}{author} =~ s/^(.{8}).*/$1/;
1630 $metadata->{$commithash}{modified} = sprintf("%02d-%s-%02d", $1, $2, $3) if ( $metadata->{$commithash}{modified} =~ /^(\d+)\s(\w+)\s\d\d(\d\d)/ );
1631 }
1632 printf("M 1.%-5d (%-8s %10s): %s\n",
1633 $metadata->{$commithash}{revision},
1634 $metadata->{$commithash}{author},
1635 $metadata->{$commithash}{modified},
1636 $data
1637 );
1638 } else {
1639 $log->warn("Error in annotate output! LINE: $_");
1640 print "E Annotate error \n";
1641 next;
1642 }
1643 }
1644 close ANNOTATE;
1645 }
1646
1647 # done; get out of the tempdir
1648 chdir "/";
1649
1650 print "ok\n";
1651
1652}
1653
1654# This method takes the state->{arguments} array and produces two new arrays.
1655# The first is $state->{args} which is everything before the '--' argument, and
1656# the second is $state->{files} which is everything after it.
1657sub argsplit
1658{
1659 return unless( defined($state->{arguments}) and ref $state->{arguments} eq "ARRAY" );
1660
1661 my $type = shift;
1662
1663 $state->{args} = [];
1664 $state->{files} = [];
1665 $state->{opt} = {};
1666
1667 if ( defined($type) )
1668 {
1669 my $opt = {};
1670 $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" );
1671 $opt = { v => 0, l => 0, R => 0 } if ( $type eq "status" );
1672 $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" );
1673 $opt = { l => 0, R => 0, k => 1, D => 1, D => 1, r => 2 } if ( $type eq "diff" );
1674 $opt = { c => 0, R => 0, l => 0, f => 0, F => 1, m => 1, r => 1 } if ( $type eq "ci" );
1675 $opt = { k => 1, m => 1 } if ( $type eq "add" );
1676 $opt = { f => 0, l => 0, R => 0 } if ( $type eq "remove" );
1677 $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" );
1678
1679
1680 while ( scalar ( @{$state->{arguments}} ) > 0 )
1681 {
1682 my $arg = shift @{$state->{arguments}};
1683
1684 next if ( $arg eq "--" );
1685 next unless ( $arg =~ /\S/ );
1686
1687 # if the argument looks like a switch
1688 if ( $arg =~ /^-(\w)(.*)/ )
1689 {
1690 # if it's a switch that takes an argument
1691 if ( $opt->{$1} )
1692 {
1693 # If this switch has already been provided
1694 if ( $opt->{$1} > 1 and exists ( $state->{opt}{$1} ) )
1695 {
1696 $state->{opt}{$1} = [ $state->{opt}{$1} ];
1697 if ( length($2) > 0 )
1698 {
1699 push @{$state->{opt}{$1}},$2;
1700 } else {
1701 push @{$state->{opt}{$1}}, shift @{$state->{arguments}};
1702 }
1703 } else {
1704 # if there's extra data in the arg, use that as the argument for the switch
1705 if ( length($2) > 0 )
1706 {
1707 $state->{opt}{$1} = $2;
1708 } else {
1709 $state->{opt}{$1} = shift @{$state->{arguments}};
1710 }
1711 }
1712 } else {
1713 $state->{opt}{$1} = undef;
1714 }
1715 }
1716 else
1717 {
1718 push @{$state->{args}}, $arg;
1719 }
1720 }
1721 }
1722 else
1723 {
1724 my $mode = 0;
1725
1726 foreach my $value ( @{$state->{arguments}} )
1727 {
1728 if ( $value eq "--" )
1729 {
1730 $mode++;
1731 next;
1732 }
1733 push @{$state->{args}}, $value if ( $mode == 0 );
1734 push @{$state->{files}}, $value if ( $mode == 1 );
1735 }
1736 }
1737}
1738
1739# This method uses $state->{directory} to populate $state->{args} with a list of filenames
1740sub argsfromdir
1741{
1742 my $updater = shift;
1743
7d90095a
MS
1744 $state->{args} = [] if ( scalar(@{$state->{args}}) == 1 and $state->{args}[0] eq "." );
1745
82000d74 1746 return if ( scalar ( @{$state->{args}} ) > 1 );
7d90095a 1747
0a7a9a12
JS
1748 my @gethead = @{$updater->gethead};
1749
1750 # push added files
1751 foreach my $file (keys %{$state->{entries}}) {
1752 if ( exists $state->{entries}{$file}{revision} &&
1753 $state->{entries}{$file}{revision} == 0 )
1754 {
1755 push @gethead, { name => $file, filehash => 'added' };
1756 }
1757 }
1758
82000d74
MS
1759 if ( scalar(@{$state->{args}}) == 1 )
1760 {
1761 my $arg = $state->{args}[0];
1762 $arg .= $state->{prependdir} if ( defined ( $state->{prependdir} ) );
7d90095a 1763
82000d74 1764 $log->info("Only one arg specified, checking for directory expansion on '$arg'");
3fda8c4c 1765
0a7a9a12 1766 foreach my $file ( @gethead )
82000d74
MS
1767 {
1768 next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
1769 next unless ( $file->{name} =~ /^$arg\// or $file->{name} eq $arg );
1770 push @{$state->{args}}, $file->{name};
1771 }
1772
1773 shift @{$state->{args}} if ( scalar(@{$state->{args}}) > 1 );
1774 } else {
1775 $log->info("Only one arg specified, populating file list automatically");
1776
1777 $state->{args} = [];
1778
0a7a9a12 1779 foreach my $file ( @gethead )
82000d74
MS
1780 {
1781 next if ( $file->{filehash} eq "deleted" and not defined ( $state->{entries}{$file->{name}} ) );
1782 next unless ( $file->{name} =~ s/^$state->{prependdir}// );
1783 push @{$state->{args}}, $file->{name};
1784 }
3fda8c4c
ML
1785 }
1786}
1787
1788# This method cleans up the $state variable after a command that uses arguments has run
1789sub statecleanup
1790{
1791 $state->{files} = [];
1792 $state->{args} = [];
1793 $state->{arguments} = [];
1794 $state->{entries} = {};
1795}
1796
1797sub revparse
1798{
1799 my $filename = shift;
1800
1801 return undef unless ( defined ( $state->{entries}{$filename}{revision} ) );
1802
1803 return $1 if ( $state->{entries}{$filename}{revision} =~ /^1\.(\d+)/ );
1804 return -$1 if ( $state->{entries}{$filename}{revision} =~ /^-1\.(\d+)/ );
1805
1806 return undef;
1807}
1808
1809# This method takes a file hash and does a CVS "file transfer" which transmits the
1810# size of the file, and then the file contents.
1811# If a second argument $targetfile is given, the file is instead written out to
1812# a file by the name of $targetfile
1813sub transmitfile
1814{
1815 my $filehash = shift;
1816 my $targetfile = shift;
1817
1818 if ( defined ( $filehash ) and $filehash eq "deleted" )
1819 {
1820 $log->warn("filehash is 'deleted'");
1821 return;
1822 }
1823
1824 die "Need filehash" unless ( defined ( $filehash ) and $filehash =~ /^[a-zA-Z0-9]{40}$/ );
1825
1826 my $type = `git-cat-file -t $filehash`;
1827 chomp $type;
1828
1829 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ( $type ) and $type eq "blob" );
1830
1831 my $size = `git-cat-file -s $filehash`;
1832 chomp $size;
1833
1834 $log->debug("transmitfile($filehash) size=$size, type=$type");
1835
1836 if ( open my $fh, '-|', "git-cat-file", "blob", $filehash )
1837 {
1838 if ( defined ( $targetfile ) )
1839 {
1840 open NEWFILE, ">", $targetfile or die("Couldn't open '$targetfile' for writing : $!");
1841 print NEWFILE $_ while ( <$fh> );
1842 close NEWFILE;
1843 } else {
1844 print "$size\n";
1845 print while ( <$fh> );
1846 }
1847 close $fh or die ("Couldn't close filehandle for transmitfile()");
1848 } else {
1849 die("Couldn't execute git-cat-file");
1850 }
1851}
1852
1853# This method takes a file name, and returns ( $dirpart, $filepart ) which
5348b6e7 1854# refers to the directory portion and the file portion of the filename
3fda8c4c
ML
1855# respectively
1856sub filenamesplit
1857{
1858 my $filename = shift;
7d90095a 1859 my $fixforlocaldir = shift;
3fda8c4c
ML
1860
1861 my ( $filepart, $dirpart ) = ( $filename, "." );
1862 ( $filepart, $dirpart ) = ( $2, $1 ) if ( $filename =~ /(.*)\/(.*)/ );
1863 $dirpart .= "/";
1864
7d90095a
MS
1865 if ( $fixforlocaldir )
1866 {
1867 $dirpart =~ s/^$state->{prependdir}//;
1868 }
1869
3fda8c4c
ML
1870 return ( $filepart, $dirpart );
1871}
1872
1873sub filecleanup
1874{
1875 my $filename = shift;
1876
1877 return undef unless(defined($filename));
1878 if ( $filename =~ /^\// )
1879 {
1880 print "E absolute filenames '$filename' not supported by server\n";
1881 return undef;
1882 }
1883
1884 $filename =~ s/^\.\///g;
82000d74 1885 $filename = $state->{prependdir} . $filename;
3fda8c4c
ML
1886 return $filename;
1887}
1888
1889package GITCVS::log;
1890
1891####
1892#### Copyright The Open University UK - 2006.
1893####
1894#### Authors: Martyn Smith <martyn@catalyst.net.nz>
1895#### Martin Langhoff <martin@catalyst.net.nz>
1896####
1897####
1898
1899use strict;
1900use warnings;
1901
1902=head1 NAME
1903
1904GITCVS::log
1905
1906=head1 DESCRIPTION
1907
1908This module provides very crude logging with a similar interface to
1909Log::Log4perl
1910
1911=head1 METHODS
1912
1913=cut
1914
1915=head2 new
1916
1917Creates a new log object, optionally you can specify a filename here to
5348b6e7 1918indicate the file to log to. If no log file is specified, you can specify one
3fda8c4c
ML
1919later with method setfile, or indicate you no longer want logging with method
1920nofile.
1921
1922Until one of these methods is called, all log calls will buffer messages ready
1923to write out.
1924
1925=cut
1926sub new
1927{
1928 my $class = shift;
1929 my $filename = shift;
1930
1931 my $self = {};
1932
1933 bless $self, $class;
1934
1935 if ( defined ( $filename ) )
1936 {
1937 open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
1938 }
1939
1940 return $self;
1941}
1942
1943=head2 setfile
1944
1945This methods takes a filename, and attempts to open that file as the log file.
1946If successful, all buffered data is written out to the file, and any further
1947logging is written directly to the file.
1948
1949=cut
1950sub setfile
1951{
1952 my $self = shift;
1953 my $filename = shift;
1954
1955 if ( defined ( $filename ) )
1956 {
1957 open $self->{fh}, ">>", $filename or die("Couldn't open '$filename' for writing : $!");
1958 }
1959
1960 return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
1961
1962 while ( my $line = shift @{$self->{buffer}} )
1963 {
1964 print {$self->{fh}} $line;
1965 }
1966}
1967
1968=head2 nofile
1969
1970This method indicates no logging is going to be used. It flushes any entries in
1971the internal buffer, and sets a flag to ensure no further data is put there.
1972
1973=cut
1974sub nofile
1975{
1976 my $self = shift;
1977
1978 $self->{nolog} = 1;
1979
1980 return unless ( defined ( $self->{buffer} ) and ref $self->{buffer} eq "ARRAY" );
1981
1982 $self->{buffer} = [];
1983}
1984
1985=head2 _logopen
1986
1987Internal method. Returns true if the log file is open, false otherwise.
1988
1989=cut
1990sub _logopen
1991{
1992 my $self = shift;
1993
1994 return 1 if ( defined ( $self->{fh} ) and ref $self->{fh} eq "GLOB" );
1995 return 0;
1996}
1997
1998=head2 debug info warn fatal
1999
2000These four methods are wrappers to _log. They provide the actual interface for
2001logging data.
2002
2003=cut
2004sub debug { my $self = shift; $self->_log("debug", @_); }
2005sub info { my $self = shift; $self->_log("info" , @_); }
2006sub warn { my $self = shift; $self->_log("warn" , @_); }
2007sub fatal { my $self = shift; $self->_log("fatal", @_); }
2008
2009=head2 _log
2010
2011This is an internal method called by the logging functions. It generates a
2012timestamp and pushes the logged line either to file, or internal buffer.
2013
2014=cut
2015sub _log
2016{
2017 my $self = shift;
2018 my $level = shift;
2019
2020 return if ( $self->{nolog} );
2021
2022 my @time = localtime;
2023 my $timestring = sprintf("%4d-%02d-%02d %02d:%02d:%02d : %-5s",
2024 $time[5] + 1900,
2025 $time[4] + 1,
2026 $time[3],
2027 $time[2],
2028 $time[1],
2029 $time[0],
2030 uc $level,
2031 );
2032
2033 if ( $self->_logopen )
2034 {
2035 print {$self->{fh}} $timestring . " - " . join(" ",@_) . "\n";
2036 } else {
2037 push @{$self->{buffer}}, $timestring . " - " . join(" ",@_) . "\n";
2038 }
2039}
2040
2041=head2 DESTROY
2042
2043This method simply closes the file handle if one is open
2044
2045=cut
2046sub DESTROY
2047{
2048 my $self = shift;
2049
2050 if ( $self->_logopen )
2051 {
2052 close $self->{fh};
2053 }
2054}
2055
2056package GITCVS::updater;
2057
2058####
2059#### Copyright The Open University UK - 2006.
2060####
2061#### Authors: Martyn Smith <martyn@catalyst.net.nz>
2062#### Martin Langhoff <martin@catalyst.net.nz>
2063####
2064####
2065
2066use strict;
2067use warnings;
2068use DBI;
2069
2070=head1 METHODS
2071
2072=cut
2073
2074=head2 new
2075
2076=cut
2077sub new
2078{
2079 my $class = shift;
2080 my $config = shift;
2081 my $module = shift;
2082 my $log = shift;
2083
2084 die "Need to specify a git repository" unless ( defined($config) and -d $config );
2085 die "Need to specify a module" unless ( defined($module) );
2086
2087 $class = ref($class) || $class;
2088
2089 my $self = {};
2090
2091 bless $self, $class;
2092
2093 $self->{dbdir} = $config . "/";
2094 die "Database dir '$self->{dbdir}' isn't a directory" unless ( defined($self->{dbdir}) and -d $self->{dbdir} );
2095
2096 $self->{module} = $module;
2097 $self->{file} = $self->{dbdir} . "/gitcvs.$module.sqlite";
2098
2099 $self->{git_path} = $config . "/";
2100
2101 $self->{log} = $log;
2102
2103 die "Git repo '$self->{git_path}' doesn't exist" unless ( -d $self->{git_path} );
2104
2105 $self->{dbh} = DBI->connect("dbi:SQLite:dbname=" . $self->{file},"","");
2106
2107 $self->{tables} = {};
2108 foreach my $table ( $self->{dbh}->tables )
2109 {
2110 $table =~ s/^"//;
2111 $table =~ s/"$//;
2112 $self->{tables}{$table} = 1;
2113 }
2114
2115 # Construct the revision table if required
2116 unless ( $self->{tables}{revision} )
2117 {
2118 $self->{dbh}->do("
2119 CREATE TABLE revision (
2120 name TEXT NOT NULL,
2121 revision INTEGER NOT NULL,
2122 filehash TEXT NOT NULL,
2123 commithash TEXT NOT NULL,
2124 author TEXT NOT NULL,
2125 modified TEXT NOT NULL,
2126 mode TEXT NOT NULL
2127 )
2128 ");
178e015c
SP
2129 $self->{dbh}->do("
2130 CREATE INDEX revision_ix1
2131 ON revision (name,revision)
2132 ");
2133 $self->{dbh}->do("
2134 CREATE INDEX revision_ix2
2135 ON revision (name,commithash)
2136 ");
3fda8c4c
ML
2137 }
2138
178e015c 2139 # Construct the head table if required
3fda8c4c
ML
2140 unless ( $self->{tables}{head} )
2141 {
2142 $self->{dbh}->do("
2143 CREATE TABLE head (
2144 name TEXT NOT NULL,
2145 revision INTEGER NOT NULL,
2146 filehash TEXT NOT NULL,
2147 commithash TEXT NOT NULL,
2148 author TEXT NOT NULL,
2149 modified TEXT NOT NULL,
2150 mode TEXT NOT NULL
2151 )
2152 ");
178e015c
SP
2153 $self->{dbh}->do("
2154 CREATE INDEX head_ix1
2155 ON head (name)
2156 ");
3fda8c4c
ML
2157 }
2158
2159 # Construct the properties table if required
2160 unless ( $self->{tables}{properties} )
2161 {
2162 $self->{dbh}->do("
2163 CREATE TABLE properties (
2164 key TEXT NOT NULL PRIMARY KEY,
2165 value TEXT
2166 )
2167 ");
2168 }
2169
2170 # Construct the commitmsgs table if required
2171 unless ( $self->{tables}{commitmsgs} )
2172 {
2173 $self->{dbh}->do("
2174 CREATE TABLE commitmsgs (
2175 key TEXT NOT NULL PRIMARY KEY,
2176 value TEXT
2177 )
2178 ");
2179 }
2180
2181 return $self;
2182}
2183
2184=head2 update
2185
2186=cut
2187sub update
2188{
2189 my $self = shift;
2190
2191 # first lets get the commit list
2192 $ENV{GIT_DIR} = $self->{git_path};
2193
49fb940e
ML
2194 my $commitsha1 = `git rev-parse $self->{module}`;
2195 chomp $commitsha1;
2196
2197 my $commitinfo = `git cat-file commit $self->{module} 2>&1`;
3fda8c4c
ML
2198 unless ( $commitinfo =~ /tree\s+[a-zA-Z0-9]{40}/ )
2199 {
2200 die("Invalid module '$self->{module}'");
2201 }
2202
2203
2204 my $git_log;
2205 my $lastcommit = $self->_get_prop("last_commit");
2206
49fb940e
ML
2207 if (defined $lastcommit && $lastcommit eq $commitsha1) { # up-to-date
2208 return 1;
2209 }
2210
3fda8c4c
ML
2211 # Start exclusive lock here...
2212 $self->{dbh}->begin_work() or die "Cannot lock database for BEGIN";
2213
2214 # TODO: log processing is memory bound
2215 # if we can parse into a 2nd file that is in reverse order
2216 # we can probably do something really efficient
a248c961 2217 my @git_log_params = ('--pretty', '--parents', '--topo-order');
3fda8c4c
ML
2218
2219 if (defined $lastcommit) {
2220 push @git_log_params, "$lastcommit..$self->{module}";
2221 } else {
2222 push @git_log_params, $self->{module};
2223 }
a248c961
ML
2224 # git-rev-list is the backend / plumbing version of git-log
2225 open(GITLOG, '-|', 'git-rev-list', @git_log_params) or die "Cannot call git-rev-list: $!";
3fda8c4c
ML
2226
2227 my @commits;
2228
2229 my %commit = ();
2230
2231 while ( <GITLOG> )
2232 {
2233 chomp;
2234 if (m/^commit\s+(.*)$/) {
2235 # on ^commit lines put the just seen commit in the stack
2236 # and prime things for the next one
2237 if (keys %commit) {
2238 my %copy = %commit;
2239 unshift @commits, \%copy;
2240 %commit = ();
2241 }
2242 my @parents = split(m/\s+/, $1);
2243 $commit{hash} = shift @parents;
2244 $commit{parents} = \@parents;
2245 } elsif (m/^(\w+?):\s+(.*)$/ && !exists($commit{message})) {
2246 # on rfc822-like lines seen before we see any message,
2247 # lowercase the entry and put it in the hash as key-value
2248 $commit{lc($1)} = $2;
2249 } else {
2250 # message lines - skip initial empty line
2251 # and trim whitespace
2252 if (!exists($commit{message}) && m/^\s*$/) {
2253 # define it to mark the end of headers
2254 $commit{message} = '';
2255 next;
2256 }
2257 s/^\s+//; s/\s+$//; # trim ws
2258 $commit{message} .= $_ . "\n";
2259 }
2260 }
2261 close GITLOG;
2262
2263 unshift @commits, \%commit if ( keys %commit );
2264
2265 # Now all the commits are in the @commits bucket
2266 # ordered by time DESC. for each commit that needs processing,
2267 # determine whether it's following the last head we've seen or if
2268 # it's on its own branch, grab a file list, and add whatever's changed
2269 # NOTE: $lastcommit refers to the last commit from previous run
2270 # $lastpicked is the last commit we picked in this run
2271 my $lastpicked;
2272 my $head = {};
2273 if (defined $lastcommit) {
2274 $lastpicked = $lastcommit;
2275 }
2276
2277 my $committotal = scalar(@commits);
2278 my $commitcount = 0;
2279
2280 # Load the head table into $head (for cached lookups during the update process)
2281 foreach my $file ( @{$self->gethead()} )
2282 {
2283 $head->{$file->{name}} = $file;
2284 }
2285
2286 foreach my $commit ( @commits )
2287 {
2288 $self->{log}->debug("GITCVS::updater - Processing commit $commit->{hash} (" . (++$commitcount) . " of $committotal)");
2289 if (defined $lastpicked)
2290 {
2291 if (!in_array($lastpicked, @{$commit->{parents}}))
2292 {
2293 # skip, we'll see this delta
2294 # as part of a merge later
2295 # warn "skipping off-track $commit->{hash}\n";
2296 next;
2297 } elsif (@{$commit->{parents}} > 1) {
2298 # it is a merge commit, for each parent that is
2299 # not $lastpicked, see if we can get a log
2300 # from the merge-base to that parent to put it
2301 # in the message as a merge summary.
2302 my @parents = @{$commit->{parents}};
2303 foreach my $parent (@parents) {
2304 # git-merge-base can potentially (but rarely) throw
2305 # several candidate merge bases. let's assume
2306 # that the first one is the best one.
2307 if ($parent eq $lastpicked) {
2308 next;
2309 }
2310 open my $p, 'git-merge-base '. $lastpicked . ' '
2311 . $parent . '|';
2312 my @output = (<$p>);
2313 close $p;
2314 my $base = join('', @output);
2315 chomp $base;
2316 if ($base) {
2317 my @merged;
2318 # print "want to log between $base $parent \n";
2319 open(GITLOG, '-|', 'git-log', "$base..$parent")
2320 or die "Cannot call git-log: $!";
2321 my $mergedhash;
2322 while (<GITLOG>) {
2323 chomp;
2324 if (!defined $mergedhash) {
2325 if (m/^commit\s+(.+)$/) {
2326 $mergedhash = $1;
2327 } else {
2328 next;
2329 }
2330 } else {
2331 # grab the first line that looks non-rfc822
2332 # aka has content after leading space
2333 if (m/^\s+(\S.*)$/) {
2334 my $title = $1;
2335 $title = substr($title,0,100); # truncate
2336 unshift @merged, "$mergedhash $title";
2337 undef $mergedhash;
2338 }
2339 }
2340 }
2341 close GITLOG;
2342 if (@merged) {
2343 $commit->{mergemsg} = $commit->{message};
2344 $commit->{mergemsg} .= "\nSummary of merged commits:\n\n";
2345 foreach my $summary (@merged) {
2346 $commit->{mergemsg} .= "\t$summary\n";
2347 }
2348 $commit->{mergemsg} .= "\n\n";
2349 # print "Message for $commit->{hash} \n$commit->{mergemsg}";
2350 }
2351 }
2352 }
2353 }
2354 }
2355
2356 # convert the date to CVS-happy format
2357 $commit->{date} = "$2 $1 $4 $3 $5" if ( $commit->{date} =~ /^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/ );
2358
2359 if ( defined ( $lastpicked ) )
2360 {
e02cd638
JH
2361 my $filepipe = open(FILELIST, '-|', 'git-diff-tree', '-z', '-r', $lastpicked, $commit->{hash}) or die("Cannot call git-diff-tree : $!");
2362 local ($/) = "\0";
3fda8c4c
ML
2363 while ( <FILELIST> )
2364 {
e02cd638
JH
2365 chomp;
2366 unless ( /^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o )
3fda8c4c
ML
2367 {
2368 die("Couldn't process git-diff-tree line : $_");
2369 }
e02cd638
JH
2370 my ($mode, $hash, $change) = ($1, $2, $3);
2371 my $name = <FILELIST>;
2372 chomp($name);
3fda8c4c 2373
e02cd638 2374 # $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");
3fda8c4c
ML
2375
2376 my $git_perms = "";
e02cd638
JH
2377 $git_perms .= "r" if ( $mode & 4 );
2378 $git_perms .= "w" if ( $mode & 2 );
2379 $git_perms .= "x" if ( $mode & 1 );
3fda8c4c
ML
2380 $git_perms = "rw" if ( $git_perms eq "" );
2381
e02cd638 2382 if ( $change eq "D" )
3fda8c4c 2383 {
e02cd638
JH
2384 #$log->debug("DELETE $name");
2385 $head->{$name} = {
2386 name => $name,
2387 revision => $head->{$name}{revision} + 1,
3fda8c4c
ML
2388 filehash => "deleted",
2389 commithash => $commit->{hash},
2390 modified => $commit->{date},
2391 author => $commit->{author},
2392 mode => $git_perms,
2393 };
e02cd638 2394 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
3fda8c4c 2395 }
e02cd638 2396 elsif ( $change eq "M" )
3fda8c4c 2397 {
e02cd638
JH
2398 #$log->debug("MODIFIED $name");
2399 $head->{$name} = {
2400 name => $name,
2401 revision => $head->{$name}{revision} + 1,
2402 filehash => $hash,
3fda8c4c
ML
2403 commithash => $commit->{hash},
2404 modified => $commit->{date},
2405 author => $commit->{author},
2406 mode => $git_perms,
2407 };
e02cd638 2408 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
3fda8c4c 2409 }
e02cd638 2410 elsif ( $change eq "A" )
3fda8c4c 2411 {
e02cd638
JH
2412 #$log->debug("ADDED $name");
2413 $head->{$name} = {
2414 name => $name,
3fda8c4c 2415 revision => 1,
e02cd638 2416 filehash => $hash,
3fda8c4c
ML
2417 commithash => $commit->{hash},
2418 modified => $commit->{date},
2419 author => $commit->{author},
2420 mode => $git_perms,
2421 };
e02cd638 2422 $self->insert_rev($name, $head->{$name}{revision}, $hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
3fda8c4c
ML
2423 }
2424 else
2425 {
e02cd638 2426 $log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");
3fda8c4c
ML
2427 die;
2428 }
2429 }
2430 close FILELIST;
2431 } else {
2432 # this is used to detect files removed from the repo
2433 my $seen_files = {};
2434
e02cd638
JH
2435 my $filepipe = open(FILELIST, '-|', 'git-ls-tree', '-z', '-r', $commit->{hash}) or die("Cannot call git-ls-tree : $!");
2436 local $/ = "\0";
3fda8c4c
ML
2437 while ( <FILELIST> )
2438 {
e02cd638
JH
2439 chomp;
2440 unless ( /^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o )
3fda8c4c
ML
2441 {
2442 die("Couldn't process git-ls-tree line : $_");
2443 }
2444
2445 my ( $git_perms, $git_type, $git_hash, $git_filename ) = ( $1, $2, $3, $4 );
2446
2447 $seen_files->{$git_filename} = 1;
2448
2449 my ( $oldhash, $oldrevision, $oldmode ) = (
2450 $head->{$git_filename}{filehash},
2451 $head->{$git_filename}{revision},
2452 $head->{$git_filename}{mode}
2453 );
2454
2455 if ( $git_perms =~ /^\d\d\d(\d)\d\d/o )
2456 {
2457 $git_perms = "";
2458 $git_perms .= "r" if ( $1 & 4 );
2459 $git_perms .= "w" if ( $1 & 2 );
2460 $git_perms .= "x" if ( $1 & 1 );
2461 } else {
2462 $git_perms = "rw";
2463 }
2464
2465 # unless the file exists with the same hash, we need to update it ...
2466 unless ( defined($oldhash) and $oldhash eq $git_hash and defined($oldmode) and $oldmode eq $git_perms )
2467 {
2468 my $newrevision = ( $oldrevision or 0 ) + 1;
2469
2470 $head->{$git_filename} = {
2471 name => $git_filename,
2472 revision => $newrevision,
2473 filehash => $git_hash,
2474 commithash => $commit->{hash},
2475 modified => $commit->{date},
2476 author => $commit->{author},
2477 mode => $git_perms,
2478 };
2479
2480
96256bba 2481 $self->insert_rev($git_filename, $newrevision, $git_hash, $commit->{hash}, $commit->{date}, $commit->{author}, $git_perms);
3fda8c4c
ML
2482 }
2483 }
2484 close FILELIST;
2485
2486 # Detect deleted files
2487 foreach my $file ( keys %$head )
2488 {
2489 unless ( exists $seen_files->{$file} or $head->{$file}{filehash} eq "deleted" )
2490 {
2491 $head->{$file}{revision}++;
2492 $head->{$file}{filehash} = "deleted";
2493 $head->{$file}{commithash} = $commit->{hash};
2494 $head->{$file}{modified} = $commit->{date};
2495 $head->{$file}{author} = $commit->{author};
2496
96256bba 2497 $self->insert_rev($file, $head->{$file}{revision}, $head->{$file}{filehash}, $commit->{hash}, $commit->{date}, $commit->{author}, $head->{$file}{mode});
3fda8c4c
ML
2498 }
2499 }
2500 # END : "Detect deleted files"
2501 }
2502
2503
2504 if (exists $commit->{mergemsg})
2505 {
96256bba 2506 $self->insert_mergelog($commit->{hash}, $commit->{mergemsg});
3fda8c4c
ML
2507 }
2508
2509 $lastpicked = $commit->{hash};
2510
2511 $self->_set_prop("last_commit", $commit->{hash});
2512 }
2513
96256bba 2514 $self->delete_head();
3fda8c4c
ML
2515 foreach my $file ( keys %$head )
2516 {
96256bba 2517 $self->insert_head(
3fda8c4c
ML
2518 $file,
2519 $head->{$file}{revision},
2520 $head->{$file}{filehash},
2521 $head->{$file}{commithash},
2522 $head->{$file}{modified},
2523 $head->{$file}{author},
2524 $head->{$file}{mode},
2525 );
2526 }
2527 # invalidate the gethead cache
2528 $self->{gethead_cache} = undef;
2529
2530
2531 # Ending exclusive lock here
2532 $self->{dbh}->commit() or die "Failed to commit changes to SQLite";
2533}
2534
96256bba
JS
2535sub insert_rev
2536{
2537 my $self = shift;
2538 my $name = shift;
2539 my $revision = shift;
2540 my $filehash = shift;
2541 my $commithash = shift;
2542 my $modified = shift;
2543 my $author = shift;
2544 my $mode = shift;
2545
2546 my $insert_rev = $self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
2547 $insert_rev->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
2548}
2549
2550sub insert_mergelog
2551{
2552 my $self = shift;
2553 my $key = shift;
2554 my $value = shift;
2555
2556 my $insert_mergelog = $self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);
2557 $insert_mergelog->execute($key, $value);
2558}
2559
2560sub delete_head
2561{
2562 my $self = shift;
2563
2564 my $delete_head = $self->{dbh}->prepare_cached("DELETE FROM head",{},1);
2565 $delete_head->execute();
2566}
2567
2568sub insert_head
2569{
2570 my $self = shift;
2571 my $name = shift;
2572 my $revision = shift;
2573 my $filehash = shift;
2574 my $commithash = shift;
2575 my $modified = shift;
2576 my $author = shift;
2577 my $mode = shift;
2578
2579 my $insert_head = $self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);
2580 $insert_head->execute($name, $revision, $filehash, $commithash, $modified, $author, $mode);
2581}
2582
3fda8c4c
ML
2583sub _headrev
2584{
2585 my $self = shift;
2586 my $filename = shift;
2587
2588 my $db_query = $self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);
2589 $db_query->execute($filename);
2590 my ( $hash, $revision, $mode ) = $db_query->fetchrow_array;
2591
2592 return ( $hash, $revision, $mode );
2593}
2594
2595sub _get_prop
2596{
2597 my $self = shift;
2598 my $key = shift;
2599
2600 my $db_query = $self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);
2601 $db_query->execute($key);
2602 my ( $value ) = $db_query->fetchrow_array;
2603
2604 return $value;
2605}
2606
2607sub _set_prop
2608{
2609 my $self = shift;
2610 my $key = shift;
2611 my $value = shift;
2612
2613 my $db_query = $self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);
2614 $db_query->execute($value, $key);
2615
2616 unless ( $db_query->rows )
2617 {
2618 $db_query = $self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);
2619 $db_query->execute($key, $value);
2620 }
2621
2622 return $value;
2623}
2624
2625=head2 gethead
2626
2627=cut
2628
2629sub gethead
2630{
2631 my $self = shift;
2632
2633 return $self->{gethead_cache} if ( defined ( $self->{gethead_cache} ) );
2634
501c7372 2635 my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);
3fda8c4c
ML
2636 $db_query->execute();
2637
2638 my $tree = [];
2639 while ( my $file = $db_query->fetchrow_hashref )
2640 {
2641 push @$tree, $file;
2642 }
2643
2644 $self->{gethead_cache} = $tree;
2645
2646 return $tree;
2647}
2648
2649=head2 getlog
2650
2651=cut
2652
2653sub getlog
2654{
2655 my $self = shift;
2656 my $filename = shift;
2657
2658 my $db_query = $self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);
2659 $db_query->execute($filename);
2660
2661 my $tree = [];
2662 while ( my $file = $db_query->fetchrow_hashref )
2663 {
2664 push @$tree, $file;
2665 }
2666
2667 return $tree;
2668}
2669
2670=head2 getmeta
2671
2672This function takes a filename (with path) argument and returns a hashref of
2673metadata for that file.
2674
2675=cut
2676
2677sub getmeta
2678{
2679 my $self = shift;
2680 my $filename = shift;
2681 my $revision = shift;
2682
2683 my $db_query;
2684 if ( defined($revision) and $revision =~ /^\d+$/ )
2685 {
2686 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);
2687 $db_query->execute($filename, $revision);
2688 }
2689 elsif ( defined($revision) and $revision =~ /^[a-zA-Z0-9]{40}$/ )
2690 {
2691 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);
2692 $db_query->execute($filename, $revision);
2693 } else {
2694 $db_query = $self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);
2695 $db_query->execute($filename);
2696 }
2697
2698 return $db_query->fetchrow_hashref;
2699}
2700
2701=head2 commitmessage
2702
2703this function takes a commithash and returns the commit message for that commit
2704
2705=cut
2706sub commitmessage
2707{
2708 my $self = shift;
2709 my $commithash = shift;
2710
2711 die("Need commithash") unless ( defined($commithash) and $commithash =~ /^[a-zA-Z0-9]{40}$/ );
2712
2713 my $db_query;
2714 $db_query = $self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);
2715 $db_query->execute($commithash);
2716
2717 my ( $message ) = $db_query->fetchrow_array;
2718
2719 if ( defined ( $message ) )
2720 {
2721 $message .= " " if ( $message =~ /\n$/ );
2722 return $message;
2723 }
2724
2725 my @lines = safe_pipe_capture("git-cat-file", "commit", $commithash);
2726 shift @lines while ( $lines[0] =~ /\S/ );
2727 $message = join("",@lines);
2728 $message .= " " if ( $message =~ /\n$/ );
2729 return $message;
2730}
2731
2732=head2 gethistory
2733
2734This function takes a filename (with path) argument and returns an arrayofarrays
2735containing revision,filehash,commithash ordered by revision descending
2736
2737=cut
2738sub gethistory
2739{
2740 my $self = shift;
2741 my $filename = shift;
2742
2743 my $db_query;
2744 $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);
2745 $db_query->execute($filename);
2746
2747 return $db_query->fetchall_arrayref;
2748}
2749
2750=head2 gethistorydense
2751
2752This function takes a filename (with path) argument and returns an arrayofarrays
2753containing revision,filehash,commithash ordered by revision descending.
2754
2755This version of gethistory skips deleted entries -- so it is useful for annotate.
2756The 'dense' part is a reference to a '--dense' option available for git-rev-list
2757and other git tools that depend on it.
2758
2759=cut
2760sub gethistorydense
2761{
2762 my $self = shift;
2763 my $filename = shift;
2764
2765 my $db_query;
2766 $db_query = $self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);
2767 $db_query->execute($filename);
2768
2769 return $db_query->fetchall_arrayref;
2770}
2771
2772=head2 in_array()
2773
2774from Array::PAT - mimics the in_array() function
2775found in PHP. Yuck but works for small arrays.
2776
2777=cut
2778sub in_array
2779{
2780 my ($check, @array) = @_;
2781 my $retval = 0;
2782 foreach my $test (@array){
2783 if($check eq $test){
2784 $retval = 1;
2785 }
2786 }
2787 return $retval;
2788}
2789
2790=head2 safe_pipe_capture
2791
5348b6e7 2792an alternative to `command` that allows input to be passed as an array
3fda8c4c
ML
2793to work around shell problems with weird characters in arguments
2794
2795=cut
2796sub safe_pipe_capture {
2797
2798 my @output;
2799
2800 if (my $pid = open my $child, '-|') {
2801 @output = (<$child>);
2802 close $child or die join(' ',@_).": $! $?";
2803 } else {
2804 exec(@_) or die "$! $?"; # exec() can fail the executable can't be found
2805 }
2806 return wantarray ? @output : join('',@output);
2807}
2808
2809
28101;