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; 20use bytes; 21 22use Fcntl; 23use File::Temp qw/tempdir tempfile/; 24use File::Basename; 25use Getopt::Long qw(:config require_order no_ignore_case); 26 27my$VERSION='@@GIT_VERSION@@'; 28 29my$log= GITCVS::log->new(); 30my$cfg; 31 32my$DATE_LIST= { 33 Jan =>"01", 34 Feb =>"02", 35 Mar =>"03", 36 Apr =>"04", 37 May =>"05", 38 Jun =>"06", 39 Jul =>"07", 40 Aug =>"08", 41 Sep =>"09", 42 Oct =>"10", 43 Nov =>"11", 44 Dec =>"12", 45}; 46 47# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 48$| =1; 49 50#### Definition and mappings of functions #### 51 52my$methods= { 53'Root'=> \&req_Root, 54'Valid-responses'=> \&req_Validresponses, 55'valid-requests'=> \&req_validrequests, 56'Directory'=> \&req_Directory, 57'Entry'=> \&req_Entry, 58'Modified'=> \&req_Modified, 59'Unchanged'=> \&req_Unchanged, 60'Questionable'=> \&req_Questionable, 61'Argument'=> \&req_Argument, 62'Argumentx'=> \&req_Argument, 63'expand-modules'=> \&req_expandmodules, 64'add'=> \&req_add, 65'remove'=> \&req_remove, 66'co'=> \&req_co, 67'update'=> \&req_update, 68'ci'=> \&req_ci, 69'diff'=> \&req_diff, 70'log'=> \&req_log, 71'rlog'=> \&req_log, 72'tag'=> \&req_CATCHALL, 73'status'=> \&req_status, 74'admin'=> \&req_CATCHALL, 75'history'=> \&req_CATCHALL, 76'watchers'=> \&req_CATCHALL, 77'editors'=> \&req_CATCHALL, 78'annotate'=> \&req_annotate, 79'Global_option'=> \&req_Globaloption, 80#'annotate' => \&req_CATCHALL, 81}; 82 83############################################## 84 85 86# $state holds all the bits of information the clients sends us that could 87# potentially be useful when it comes to actually _doing_ something. 88my$state= { prependdir =>''}; 89$log->info("--------------- STARTING -----------------"); 90 91my$usage= 92"Usage: git-cvsserver [options] [pserver|server] [<directory> ...]\n". 93" --base-path <path> : Prepend to requested CVSROOT\n". 94" --strict-paths : Don't allow recursing into subdirectories\n". 95" --export-all : Don't check for gitcvs.enabled in config\n". 96" --version, -V : Print version information and exit\n". 97" --help, -h, -H : Print usage information and exit\n". 98"\n". 99"<directory> ... is a list of allowed directories. If no directories\n". 100"are given, all are allowed. This is an additional restriction, gitcvs\n". 101"access still needs to be enabled by the gitcvs.enabled config option.\n"; 102 103my@opts= ('help|h|H','version|V', 104'base-path=s','strict-paths','export-all'); 105GetOptions($state,@opts) 106or die$usage; 107 108if($state->{version}) { 109print"git-cvsserver version$VERSION\n"; 110exit; 111} 112if($state->{help}) { 113print$usage; 114exit; 115} 116 117my$TEMP_DIR= tempdir( CLEANUP =>1); 118$log->debug("Temporary directory is '$TEMP_DIR'"); 119 120$state->{method} ='ext'; 121if(@ARGV) { 122if($ARGV[0]eq'pserver') { 123$state->{method} ='pserver'; 124shift@ARGV; 125}elsif($ARGV[0]eq'server') { 126shift@ARGV; 127} 128} 129 130# everything else is a directory 131$state->{allowed_roots} = [@ARGV]; 132 133# don't export the whole system unless the users requests it 134if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 135die"--export-all can only be used together with an explicit whitelist\n"; 136} 137 138# if we are called with a pserver argument, 139# deal with the authentication cat before entering the 140# main loop 141if($state->{method}eq'pserver') { 142my$line= <STDIN>;chomp$line; 143unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 144die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 145} 146my$request=$1; 147$line= <STDIN>;chomp$line; 148unless(req_Root('root',$line)) {# reuse Root 149print"E Invalid root$line\n"; 150exit1; 151} 152$line= <STDIN>;chomp$line; 153unless($lineeq'anonymous') { 154print"E Only anonymous user allowed via pserver\n"; 155print"I HATE YOU\n"; 156exit1; 157} 158$line= <STDIN>;chomp$line;# validate the password? 159$line= <STDIN>;chomp$line; 160unless($lineeq"END$requestREQUEST") { 161die"E Do not understand$line-- expecting END$requestREQUEST\n"; 162} 163print"I LOVE YOU\n"; 164exit if$requesteq'VERIFICATION';# cvs login 165# and now back to our regular programme... 166} 167 168# Keep going until the client closes the connection 169while(<STDIN>) 170{ 171chomp; 172 173# Check to see if we've seen this method, and call appropriate function. 174if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 175{ 176# use the $methods hash to call the appropriate sub for this command 177#$log->info("Method : $1"); 178&{$methods->{$1}}($1,$2); 179}else{ 180# log fatal because we don't understand this function. If this happens 181# we're fairly screwed because we don't know if the client is expecting 182# a response. If it is, the client will hang, we'll hang, and the whole 183# thing will be custard. 184$log->fatal("Don't understand command$_\n"); 185die("Unknown command$_"); 186} 187} 188 189$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 190$log->info("--------------- FINISH -----------------"); 191 192# Magic catchall method. 193# This is the method that will handle all commands we haven't yet 194# implemented. It simply sends a warning to the log file indicating a 195# command that hasn't been implemented has been invoked. 196sub req_CATCHALL 197{ 198my($cmd,$data) =@_; 199$log->warn("Unhandled command : req_$cmd:$data"); 200} 201 202 203# Root pathname \n 204# Response expected: no. Tell the server which CVSROOT to use. Note that 205# pathname is a local directory and not a fully qualified CVSROOT variable. 206# pathname must already exist; if creating a new root, use the init 207# request, not Root. pathname does not include the hostname of the server, 208# how to access the server, etc.; by the time the CVS protocol is in use, 209# connection, authentication, etc., are already taken care of. The Root 210# request must be sent only once, and it must be sent before any requests 211# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 212sub req_Root 213{ 214my($cmd,$data) =@_; 215$log->debug("req_Root :$data"); 216 217unless($data=~ m#^/#) { 218print"error 1 Root must be an absolute pathname\n"; 219return0; 220} 221 222my$cvsroot=$state->{'base-path'} ||''; 223$cvsroot=~ s#/+$##; 224$cvsroot.=$data; 225 226if($state->{CVSROOT} 227&& ($state->{CVSROOT}ne$cvsroot)) { 228print"error 1 Conflicting roots specified\n"; 229return0; 230} 231 232$state->{CVSROOT} =$cvsroot; 233 234$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 235 236if(@{$state->{allowed_roots}}) { 237my$allowed=0; 238foreachmy$dir(@{$state->{allowed_roots}}) { 239next unless$dir=~ m#^/#; 240$dir=~ s#/+$##; 241if($state->{'strict-paths'}) { 242if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 243$allowed=1; 244last; 245} 246}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 247$allowed=1; 248last; 249} 250} 251 252unless($allowed) { 253print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 254print"E\n"; 255print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 256return0; 257} 258} 259 260unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 261print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 262print"E\n"; 263print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 264return0; 265} 266 267my@gitvars=`git-config -l`; 268if($?) { 269print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 270print"E\n"; 271print"error 1 - problem executing git-config\n"; 272return0; 273} 274foreachmy$line(@gitvars) 275{ 276next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 277unless($2) { 278$cfg->{$1}{$3} =$4; 279}else{ 280$cfg->{$1}{$2}{$3} =$4; 281} 282} 283 284my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 285||$cfg->{gitcvs}{enabled}); 286unless($state->{'export-all'} || 287($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 288print"E GITCVS emulation needs to be enabled on this repo\n"; 289print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 290print"E\n"; 291print"error 1 GITCVS emulation disabled\n"; 292return0; 293} 294 295my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 296if($logfile) 297{ 298$log->setfile($logfile); 299}else{ 300$log->nofile(); 301} 302 303return1; 304} 305 306# Global_option option \n 307# Response expected: no. Transmit one of the global options `-q', `-Q', 308# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 309# variations (such as combining of options) are allowed. For graceful 310# handling of valid-requests, it is probably better to make new global 311# options separate requests, rather than trying to add them to this 312# request. 313sub req_Globaloption 314{ 315my($cmd,$data) =@_; 316$log->debug("req_Globaloption :$data"); 317$state->{globaloptions}{$data} =1; 318} 319 320# Valid-responses request-list \n 321# Response expected: no. Tell the server what responses the client will 322# accept. request-list is a space separated list of tokens. 323sub req_Validresponses 324{ 325my($cmd,$data) =@_; 326$log->debug("req_Validresponses :$data"); 327 328# TODO : re-enable this, currently it's not particularly useful 329#$state->{validresponses} = [ split /\s+/, $data ]; 330} 331 332# valid-requests \n 333# Response expected: yes. Ask the server to send back a Valid-requests 334# response. 335sub req_validrequests 336{ 337my($cmd,$data) =@_; 338 339$log->debug("req_validrequests"); 340 341$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 342$log->debug("SEND : ok"); 343 344print"Valid-requests ".join(" ",keys%$methods) ."\n"; 345print"ok\n"; 346} 347 348# Directory local-directory \n 349# Additional data: repository \n. Response expected: no. Tell the server 350# what directory to use. The repository should be a directory name from a 351# previous server response. Note that this both gives a default for Entry 352# and Modified and also for ci and the other commands; normal usage is to 353# send Directory for each directory in which there will be an Entry or 354# Modified, and then a final Directory for the original directory, then the 355# command. The local-directory is relative to the top level at which the 356# command is occurring (i.e. the last Directory which is sent before the 357# command); to indicate that top level, `.' should be sent for 358# local-directory. 359sub req_Directory 360{ 361my($cmd,$data) =@_; 362 363my$repository= <STDIN>; 364chomp$repository; 365 366 367$state->{localdir} =$data; 368$state->{repository} =$repository; 369$state->{path} =$repository; 370$state->{path} =~s/^$state->{CVSROOT}\///; 371$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 372$state->{path} .="/"if($state->{path} =~ /\S/ ); 373 374$state->{directory} =$state->{localdir}; 375$state->{directory} =""if($state->{directory}eq"."); 376$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 377 378if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 379{ 380$log->info("Setting prepend to '$state->{path}'"); 381$state->{prependdir} =$state->{path}; 382foreachmy$entry(keys%{$state->{entries}} ) 383{ 384$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 385delete$state->{entries}{$entry}; 386} 387} 388 389if(defined($state->{prependdir} ) ) 390{ 391$log->debug("Prepending '$state->{prependdir}' to state|directory"); 392$state->{directory} =$state->{prependdir} .$state->{directory} 393} 394$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 395} 396 397# Entry entry-line \n 398# Response expected: no. Tell the server what version of a file is on the 399# local machine. The name in entry-line is a name relative to the directory 400# most recently specified with Directory. If the user is operating on only 401# some files in a directory, Entry requests for only those files need be 402# included. If an Entry request is sent without Modified, Is-modified, or 403# Unchanged, it means the file is lost (does not exist in the working 404# directory). If both Entry and one of Modified, Is-modified, or Unchanged 405# are sent for the same file, Entry must be sent first. For a given file, 406# one can send Modified, Is-modified, or Unchanged, but not more than one 407# of these three. 408sub req_Entry 409{ 410my($cmd,$data) =@_; 411 412#$log->debug("req_Entry : $data"); 413 414my@data=split(/\//,$data); 415 416$state->{entries}{$state->{directory}.$data[1]} = { 417 revision =>$data[2], 418 conflict =>$data[3], 419 options =>$data[4], 420 tag_or_date =>$data[5], 421}; 422 423$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 424} 425 426# Questionable filename \n 427# Response expected: no. Additional data: no. Tell the server to check 428# whether filename should be ignored, and if not, next time the server 429# sends responses, send (in a M response) `?' followed by the directory and 430# filename. filename must not contain `/'; it needs to be a file in the 431# directory named by the most recent Directory request. 432sub req_Questionable 433{ 434my($cmd,$data) =@_; 435 436$log->debug("req_Questionable :$data"); 437$state->{entries}{$state->{directory}.$data}{questionable} =1; 438} 439 440# add \n 441# Response expected: yes. Add a file or directory. This uses any previous 442# Argument, Directory, Entry, or Modified requests, if they have been sent. 443# The last Directory sent specifies the working directory at the time of 444# the operation. To add a directory, send the directory to be added using 445# Directory and Argument requests. 446sub req_add 447{ 448my($cmd,$data) =@_; 449 450 argsplit("add"); 451 452my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 453$updater->update(); 454 455 argsfromdir($updater); 456 457my$addcount=0; 458 459foreachmy$filename( @{$state->{args}} ) 460{ 461$filename= filecleanup($filename); 462 463my$meta=$updater->getmeta($filename); 464my$wrev= revparse($filename); 465 466if($wrev&&$meta&& ($wrev<0)) 467{ 468# previously removed file, add back 469$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 470 471print"MT +updated\n"; 472print"MT text U\n"; 473print"MT fname$filename\n"; 474print"MT newline\n"; 475print"MT -updated\n"; 476 477unless($state->{globaloptions}{-n} ) 478{ 479my($filepart,$dirpart) = filenamesplit($filename,1); 480 481print"Created$dirpart\n"; 482print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 483 484# this is an "entries" line 485my$kopts= kopts_from_path($filepart); 486$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 487print"/$filepart/1.$meta->{revision}//$kopts/\n"; 488# permissions 489$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 490print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 491# transmit file 492 transmitfile($meta->{filehash}); 493} 494 495next; 496} 497 498unless(defined($state->{entries}{$filename}{modified_filename} ) ) 499{ 500print"E cvs add: nothing known about `$filename'\n"; 501next; 502} 503# TODO : check we're not squashing an already existing file 504if(defined($state->{entries}{$filename}{revision} ) ) 505{ 506print"E cvs add: `$filename' has already been entered\n"; 507next; 508} 509 510my($filepart,$dirpart) = filenamesplit($filename,1); 511 512print"E cvs add: scheduling file `$filename' for addition\n"; 513 514print"Checked-in$dirpart\n"; 515print"$filename\n"; 516my$kopts= kopts_from_path($filepart); 517print"/$filepart/0//$kopts/\n"; 518 519$addcount++; 520} 521 522if($addcount==1) 523{ 524print"E cvs add: use `cvs commit' to add this file permanently\n"; 525} 526elsif($addcount>1) 527{ 528print"E cvs add: use `cvs commit' to add these files permanently\n"; 529} 530 531print"ok\n"; 532} 533 534# remove \n 535# Response expected: yes. Remove a file. This uses any previous Argument, 536# Directory, Entry, or Modified requests, if they have been sent. The last 537# Directory sent specifies the working directory at the time of the 538# operation. Note that this request does not actually do anything to the 539# repository; the only effect of a successful remove request is to supply 540# the client with a new entries line containing `-' to indicate a removed 541# file. In fact, the client probably could perform this operation without 542# contacting the server, although using remove may cause the server to 543# perform a few more checks. The client sends a subsequent ci request to 544# actually record the removal in the repository. 545sub req_remove 546{ 547my($cmd,$data) =@_; 548 549 argsplit("remove"); 550 551# Grab a handle to the SQLite db and do any necessary updates 552my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 553$updater->update(); 554 555#$log->debug("add state : " . Dumper($state)); 556 557my$rmcount=0; 558 559foreachmy$filename( @{$state->{args}} ) 560{ 561$filename= filecleanup($filename); 562 563if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 564{ 565print"E cvs remove: file `$filename' still in working directory\n"; 566next; 567} 568 569my$meta=$updater->getmeta($filename); 570my$wrev= revparse($filename); 571 572unless(defined($wrev) ) 573{ 574print"E cvs remove: nothing known about `$filename'\n"; 575next; 576} 577 578if(defined($wrev)and$wrev<0) 579{ 580print"E cvs remove: file `$filename' already scheduled for removal\n"; 581next; 582} 583 584unless($wrev==$meta->{revision} ) 585{ 586# TODO : not sure if the format of this message is quite correct. 587print"E cvs remove: Up to date check failed for `$filename'\n"; 588next; 589} 590 591 592my($filepart,$dirpart) = filenamesplit($filename,1); 593 594print"E cvs remove: scheduling `$filename' for removal\n"; 595 596print"Checked-in$dirpart\n"; 597print"$filename\n"; 598my$kopts= kopts_from_path($filepart); 599print"/$filepart/-1.$wrev//$kopts/\n"; 600 601$rmcount++; 602} 603 604if($rmcount==1) 605{ 606print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 607} 608elsif($rmcount>1) 609{ 610print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 611} 612 613print"ok\n"; 614} 615 616# Modified filename \n 617# Response expected: no. Additional data: mode, \n, file transmission. Send 618# the server a copy of one locally modified file. filename is a file within 619# the most recent directory sent with Directory; it must not contain `/'. 620# If the user is operating on only some files in a directory, only those 621# files need to be included. This can also be sent without Entry, if there 622# is no entry for the file. 623sub req_Modified 624{ 625my($cmd,$data) =@_; 626 627my$mode= <STDIN>; 628defined$mode 629or(print"E end of file reading mode for$data\n"),return; 630chomp$mode; 631my$size= <STDIN>; 632defined$size 633or(print"E end of file reading size of$data\n"),return; 634chomp$size; 635 636# Grab config information 637my$blocksize=8192; 638my$bytesleft=$size; 639my$tmp; 640 641# Get a filehandle/name to write it to 642my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 643 644# Loop over file data writing out to temporary file. 645while($bytesleft) 646{ 647$blocksize=$bytesleftif($bytesleft<$blocksize); 648read STDIN,$tmp,$blocksize; 649print$fh $tmp; 650$bytesleft-=$blocksize; 651} 652 653close$fh 654or(print"E failed to write temporary,$filename:$!\n"),return; 655 656# Ensure we have something sensible for the file mode 657if($mode=~/u=(\w+)/) 658{ 659$mode=$1; 660}else{ 661$mode="rw"; 662} 663 664# Save the file data in $state 665$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 666$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 667$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 668$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 669 670 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 671} 672 673# Unchanged filename\n 674# Response expected: no. Tell the server that filename has not been 675# modified in the checked out directory. The filename is a file within the 676# most recent directory sent with Directory; it must not contain `/'. 677sub req_Unchanged 678{ 679 my ($cmd,$data) =@_; 680 681$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 682 683 #$log->debug("req_Unchanged :$data"); 684} 685 686# Argument text\n 687# Response expected: no. Save argument for use in a subsequent command. 688# Arguments accumulate until an argument-using command is given, at which 689# point they are forgotten. 690# Argumentx text\n 691# Response expected: no. Append\nfollowed by text to the current argument 692# being saved. 693sub req_Argument 694{ 695 my ($cmd,$data) =@_; 696 697 # Argumentx means: append to last Argument (with a newline in front) 698 699$log->debug("$cmd:$data"); 700 701 if ($cmdeq 'Argumentx') { 702 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 703 } else { 704 push @{$state->{arguments}},$data; 705 } 706} 707 708# expand-modules\n 709# Response expected: yes. Expand the modules which are specified in the 710# arguments. Returns the data in Module-expansion responses. Note that the 711# server can assume that this is checkout or export, not rtag or rdiff; the 712# latter do not access the working directory and thus have no need to 713# expand modules on the client side. Expand may not be the best word for 714# what this request does. It does not necessarily tell you all the files 715# contained in a module, for example. Basically it is a way of telling you 716# which working directories the server needs to know about in order to 717# handle a checkout of the specified modules. For example, suppose that the 718# server has a module defined by 719# aliasmodule -a 1dir 720# That is, one can check out aliasmodule and it will take 1dir in the 721# repository and check it out to 1dir in the working directory. Now suppose 722# the client already has this module checked out and is planning on using 723# the co request to update it. Without using expand-modules, the client 724# would have two bad choices: it could either send information about all 725# working directories under the current directory, which could be 726# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 727# stands for 1dir, and neglect to send information for 1dir, which would 728# lead to incorrect operation. With expand-modules, the client would first 729# ask for the module to be expanded: 730sub req_expandmodules 731{ 732 my ($cmd,$data) =@_; 733 734 argsplit(); 735 736$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 737 738 unless ( ref$state->{arguments} eq "ARRAY" ) 739 { 740 print "ok\n"; 741 return; 742 } 743 744 foreach my$module( @{$state->{arguments}} ) 745 { 746$log->debug("SEND : Module-expansion$module"); 747 print "Module-expansion$module\n"; 748 } 749 750 print "ok\n"; 751 statecleanup(); 752} 753 754# co\n 755# Response expected: yes. Get files from the repository. This uses any 756# previous Argument, Directory, Entry, or Modified requests, if they have 757# been sent. Arguments to this command are module names; the client cannot 758# know what directories they correspond to except by (1) just sending the 759# co request, and then seeing what directory names the server sends back in 760# its responses, and (2) the expand-modules request. 761sub req_co 762{ 763 my ($cmd,$data) =@_; 764 765 argsplit("co"); 766 767 my$module=$state->{args}[0]; 768 my$checkout_path=$module; 769 770 # use the user specified directory if we're given it 771$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 772 773$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 774 775$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 776 777$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 778 779# Grab a handle to the SQLite db and do any necessary updates 780my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 781$updater->update(); 782 783$checkout_path=~ s|/$||;# get rid of trailing slashes 784 785# Eclipse seems to need the Clear-sticky command 786# to prepare the 'Entries' file for the new directory. 787print"Clear-sticky$checkout_path/\n"; 788print$state->{CVSROOT} ."/$module/\n"; 789print"Clear-static-directory$checkout_path/\n"; 790print$state->{CVSROOT} ."/$module/\n"; 791print"Clear-sticky$checkout_path/\n";# yes, twice 792print$state->{CVSROOT} ."/$module/\n"; 793print"Template$checkout_path/\n"; 794print$state->{CVSROOT} ."/$module/\n"; 795print"0\n"; 796 797# instruct the client that we're checking out to $checkout_path 798print"E cvs checkout: Updating$checkout_path\n"; 799 800my%seendirs= (); 801my$lastdir=''; 802 803# recursive 804sub prepdir { 805my($dir,$repodir,$remotedir,$seendirs) =@_; 806my$parent= dirname($dir); 807$dir=~ s|/+$||; 808$repodir=~ s|/+$||; 809$remotedir=~ s|/+$||; 810$parent=~ s|/+$||; 811$log->debug("announcedir$dir,$repodir,$remotedir"); 812 813if($parenteq'.'||$parenteq'./') { 814$parent=''; 815} 816# recurse to announce unseen parents first 817if(length($parent) && !exists($seendirs->{$parent})) { 818 prepdir($parent,$repodir,$remotedir,$seendirs); 819} 820# Announce that we are going to modify at the parent level 821if($parent) { 822print"E cvs checkout: Updating$remotedir/$parent\n"; 823}else{ 824print"E cvs checkout: Updating$remotedir\n"; 825} 826print"Clear-sticky$remotedir/$parent/\n"; 827print"$repodir/$parent/\n"; 828 829print"Clear-static-directory$remotedir/$dir/\n"; 830print"$repodir/$dir/\n"; 831print"Clear-sticky$remotedir/$parent/\n";# yes, twice 832print"$repodir/$parent/\n"; 833print"Template$remotedir/$dir/\n"; 834print"$repodir/$dir/\n"; 835print"0\n"; 836 837$seendirs->{$dir} =1; 838} 839 840foreachmy$git( @{$updater->gethead} ) 841{ 842# Don't want to check out deleted files 843next if($git->{filehash}eq"deleted"); 844 845($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 846 847if(length($git->{dir}) &&$git->{dir}ne'./' 848&&$git->{dir}ne$lastdir) { 849unless(exists($seendirs{$git->{dir}})) { 850 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 851$checkout_path, \%seendirs); 852$lastdir=$git->{dir}; 853$seendirs{$git->{dir}} =1; 854} 855print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 856} 857 858# modification time of this file 859print"Mod-time$git->{modified}\n"; 860 861# print some information to the client 862if(defined($git->{dir} )and$git->{dir}ne"./") 863{ 864print"M U$checkout_path/$git->{dir}$git->{name}\n"; 865}else{ 866print"M U$checkout_path/$git->{name}\n"; 867} 868 869# instruct client we're sending a file to put in this path 870print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 871 872print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 873 874# this is an "entries" line 875my$kopts= kopts_from_path($git->{name}); 876print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 877# permissions 878print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 879 880# transmit file 881 transmitfile($git->{filehash}); 882} 883 884print"ok\n"; 885 886 statecleanup(); 887} 888 889# update \n 890# Response expected: yes. Actually do a cvs update command. This uses any 891# previous Argument, Directory, Entry, or Modified requests, if they have 892# been sent. The last Directory sent specifies the working directory at the 893# time of the operation. The -I option is not used--files which the client 894# can decide whether to ignore are not mentioned and the client sends the 895# Questionable request for others. 896sub req_update 897{ 898my($cmd,$data) =@_; 899 900$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 901 902 argsplit("update"); 903 904# 905# It may just be a client exploring the available heads/modules 906# in that case, list them as top level directories and leave it 907# at that. Eclipse uses this technique to offer you a list of 908# projects (heads in this case) to checkout. 909# 910if($state->{module}eq'') { 911my$heads_dir=$state->{CVSROOT} .'/refs/heads'; 912if(!opendir HEADS,$heads_dir) { 913print"E [server aborted]: Failed to open directory, " 914."$heads_dir:$!\nerror\n"; 915return0; 916} 917print"E cvs update: Updating .\n"; 918while(my$head=readdir(HEADS)) { 919if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 920print"E cvs update: New directory `$head'\n"; 921} 922} 923closedir HEADS; 924print"ok\n"; 925return1; 926} 927 928 929# Grab a handle to the SQLite db and do any necessary updates 930my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 931 932$updater->update(); 933 934 argsfromdir($updater); 935 936#$log->debug("update state : " . Dumper($state)); 937 938# foreach file specified on the command line ... 939foreachmy$filename( @{$state->{args}} ) 940{ 941$filename= filecleanup($filename); 942 943$log->debug("Processing file$filename"); 944 945# if we have a -C we should pretend we never saw modified stuff 946if(exists($state->{opt}{C} ) ) 947{ 948delete$state->{entries}{$filename}{modified_hash}; 949delete$state->{entries}{$filename}{modified_filename}; 950$state->{entries}{$filename}{unchanged} =1; 951} 952 953my$meta; 954if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 955{ 956$meta=$updater->getmeta($filename,$1); 957}else{ 958$meta=$updater->getmeta($filename); 959} 960 961if( !defined$meta) 962{ 963$meta= { 964 name =>$filename, 965 revision =>0, 966 filehash =>'added' 967}; 968} 969 970my$oldmeta=$meta; 971 972my$wrev= revparse($filename); 973 974# If the working copy is an old revision, lets get that version too for comparison. 975if(defined($wrev)and$wrev!=$meta->{revision} ) 976{ 977$oldmeta=$updater->getmeta($filename,$wrev); 978} 979 980#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 981 982# Files are up to date if the working copy and repo copy have the same revision, 983# and the working copy is unmodified _and_ the user hasn't specified -C 984next if(defined($wrev) 985and defined($meta->{revision}) 986and$wrev==$meta->{revision} 987and$state->{entries}{$filename}{unchanged} 988and not exists($state->{opt}{C} ) ); 989 990# If the working copy and repo copy have the same revision, 991# but the working copy is modified, tell the client it's modified 992if(defined($wrev) 993and defined($meta->{revision}) 994and$wrev==$meta->{revision} 995and defined($state->{entries}{$filename}{modified_hash}) 996and not exists($state->{opt}{C} ) ) 997{ 998$log->info("Tell the client the file is modified"); 999print"MT text M\n";1000print"MT fname$filename\n";1001print"MT newline\n";1002next;1003}10041005if($meta->{filehash}eq"deleted")1006{1007my($filepart,$dirpart) = filenamesplit($filename,1);10081009$log->info("Removing '$filename' from working copy (no longer in the repo)");10101011print"E cvs update: `$filename' is no longer in the repository\n";1012# Don't want to actually _DO_ the update if -n specified1013unless($state->{globaloptions}{-n} ) {1014print"Removed$dirpart\n";1015print"$filepart\n";1016}1017}1018elsif(not defined($state->{entries}{$filename}{modified_hash} )1019or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1020or$meta->{filehash}eq'added')1021{1022# normal update, just send the new revision (either U=Update,1023# or A=Add, or R=Remove)1024if(defined($wrev) &&$wrev<0)1025{1026$log->info("Tell the client the file is scheduled for removal");1027print"MT text R\n";1028print"MT fname$filename\n";1029print"MT newline\n";1030next;1031}1032elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1033{1034$log->info("Tell the client the file is scheduled for addition");1035print"MT text A\n";1036print"MT fname$filename\n";1037print"MT newline\n";1038next;10391040}1041else{1042$log->info("Updating '$filename' to ".$meta->{revision});1043print"MT +updated\n";1044print"MT text U\n";1045print"MT fname$filename\n";1046print"MT newline\n";1047print"MT -updated\n";1048}10491050my($filepart,$dirpart) = filenamesplit($filename,1);10511052# Don't want to actually _DO_ the update if -n specified1053unless($state->{globaloptions}{-n} )1054{1055if(defined($wrev) )1056{1057# instruct client we're sending a file to put in this path as a replacement1058print"Update-existing$dirpart\n";1059$log->debug("Updating existing file 'Update-existing$dirpart'");1060}else{1061# instruct client we're sending a file to put in this path as a new file1062print"Clear-static-directory$dirpart\n";1063print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1064print"Clear-sticky$dirpart\n";1065print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";10661067$log->debug("Creating new file 'Created$dirpart'");1068print"Created$dirpart\n";1069}1070print$state->{CVSROOT} ."/$state->{module}/$filename\n";10711072# this is an "entries" line1073my$kopts= kopts_from_path($filepart);1074$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1075print"/$filepart/1.$meta->{revision}//$kopts/\n";10761077# permissions1078$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1079print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10801081# transmit file1082 transmitfile($meta->{filehash});1083}1084}else{1085$log->info("Updating '$filename'");1086my($filepart,$dirpart) = filenamesplit($meta->{name},1);10871088my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/";10891090chdir$dir;1091my$file_local=$filepart.".mine";1092system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1093my$file_old=$filepart.".".$oldmeta->{revision};1094 transmitfile($oldmeta->{filehash},$file_old);1095my$file_new=$filepart.".".$meta->{revision};1096 transmitfile($meta->{filehash},$file_new);10971098# we need to merge with the local changes ( M=successful merge, C=conflict merge )1099$log->info("Merging$file_local,$file_old,$file_new");1100print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11011102$log->debug("Temporary directory for merge is$dir");11031104my$return=system("git","merge-file",$file_local,$file_old,$file_new);1105$return>>=8;11061107if($return==0)1108{1109$log->info("Merged successfully");1110print"M M$filename\n";1111$log->debug("Merged$dirpart");11121113# Don't want to actually _DO_ the update if -n specified1114unless($state->{globaloptions}{-n} )1115{1116print"Merged$dirpart\n";1117$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1118print$state->{CVSROOT} ."/$state->{module}/$filename\n";1119my$kopts= kopts_from_path($filepart);1120$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1121print"/$filepart/1.$meta->{revision}//$kopts/\n";1122}1123}1124elsif($return==1)1125{1126$log->info("Merged with conflicts");1127print"E cvs update: conflicts found in$filename\n";1128print"M C$filename\n";11291130# Don't want to actually _DO_ the update if -n specified1131unless($state->{globaloptions}{-n} )1132{1133print"Merged$dirpart\n";1134print$state->{CVSROOT} ."/$state->{module}/$filename\n";1135my$kopts= kopts_from_path($filepart);1136print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1137}1138}1139else1140{1141$log->warn("Merge failed");1142next;1143}11441145# Don't want to actually _DO_ the update if -n specified1146unless($state->{globaloptions}{-n} )1147{1148# permissions1149$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1150print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11511152# transmit file, format is single integer on a line by itself (file1153# size) followed by the file contents1154# TODO : we should copy files in blocks1155my$data=`cat$file_local`;1156$log->debug("File size : " . length($data));1157 print length($data) . "\n";1158 print$data;1159 }11601161 chdir "/";1162 }11631164 }11651166 print "ok\n";1167}11681169sub req_ci1170{1171 my ($cmd,$data) =@_;11721173 argsplit("ci");11741175 #$log->debug("State : " . Dumper($state));11761177$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));11781179 if ($state->{method} eq 'pserver')1180 {1181 print "error 1 pserver access cannot commit\n";1182 exit;1183 }11841185 if ( -e$state->{CVSROOT} . "/index" )1186 {1187$log->warn("file 'index' already exists in the git repository");1188 print "error 1 Index already exists in git repo\n";1189 exit;1190 }11911192 # Grab a handle to the SQLite db and do any necessary updates1193 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1194$updater->update();11951196 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1197 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1198$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");11991200$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1201$ENV{GIT_WORK_TREE} = ".";1202$ENV{GIT_INDEX_FILE} =$file_index;12031204 # Remember where the head was at the beginning.1205 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1206 chomp$parenthash;1207 if ($parenthash!~ /^[0-9a-f]{40}$/) {1208 print "error 1 pserver cannot find the current HEAD of module";1209 exit;1210 }12111212 chdir$tmpdir;12131214 # populate the temporary index1215 system("git-read-tree",$parenthash);1216 unless ($?== 0)1217 {1218 die "Error running git-read-tree$state->{module}$file_index$!";1219 }1220$log->info("Created index '$file_index' for head$state->{module} - exit status$?");12211222 my@committedfiles= ();1223 my%oldmeta;12241225 # foreach file specified on the command line ...1226 foreach my$filename( @{$state->{args}} )1227 {1228 my$committedfile=$filename;1229$filename= filecleanup($filename);12301231 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12321233 my$meta=$updater->getmeta($filename);1234$oldmeta{$filename} =$meta;12351236 my$wrev= revparse($filename);12371238 my ($filepart,$dirpart) = filenamesplit($filename);12391240 # do a checkout of the file if it is part of this tree1241 if ($wrev) {1242 system('git-checkout-index', '-f', '-u',$filename);1243 unless ($?== 0) {1244 die "Error running git-checkout-index -f -u$filename:$!";1245 }1246 }12471248 my$addflag= 0;1249 my$rmflag= 0;1250$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1251$addflag= 1 unless ( -e$filename);12521253 # Do up to date checking1254 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1255 {1256 # fail everything if an up to date check fails1257 print "error 1 Up to date check failed for$filename\n";1258 chdir "/";1259 exit;1260 }12611262 push@committedfiles,$committedfile;1263$log->info("Committing$filename");12641265 system("mkdir","-p",$dirpart) unless ( -d$dirpart);12661267 unless ($rmflag)1268 {1269$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1270 rename$state->{entries}{$filename}{modified_filename},$filename;12711272 # Calculate modes to remove1273 my$invmode= "";1274 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }12751276$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1277 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1278 }12791280 if ($rmflag)1281 {1282$log->info("Removing file '$filename'");1283 unlink($filename);1284 system("git-update-index", "--remove",$filename);1285 }1286 elsif ($addflag)1287 {1288$log->info("Adding file '$filename'");1289 system("git-update-index", "--add",$filename);1290 } else {1291$log->info("Updating file '$filename'");1292 system("git-update-index",$filename);1293 }1294 }12951296 unless ( scalar(@committedfiles) > 0 )1297 {1298 print "E No files to commit\n";1299 print "ok\n";1300 chdir "/";1301 return;1302 }13031304 my$treehash= `git-write-tree`;1305 chomp$treehash;13061307$log->debug("Treehash :$treehash, Parenthash :$parenthash");13081309 # write our commit message out if we have one ...1310 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1311 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1312 print$msg_fh"\n\nvia git-CVS emulator\n";1313 close$msg_fh;13141315 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1316chomp($commithash);1317$log->info("Commit hash :$commithash");13181319unless($commithash=~/[a-zA-Z0-9]{40}/)1320{1321$log->warn("Commit failed (Invalid commit hash)");1322print"error 1 Commit failed (unknown reason)\n";1323chdir"/";1324exit;1325}13261327### Emulate git-receive-pack by running hooks/update1328my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1329$parenthash,$commithash);1330if( -x $hook[0] ) {1331unless(system(@hook) ==0)1332{1333$log->warn("Commit failed (update hook declined to update ref)");1334print"error 1 Commit failed (update hook declined)\n";1335chdir"/";1336exit;1337}1338}13391340### Update the ref1341if(system(qw(git update-ref -m),"cvsserver ci",1342"refs/heads/$state->{module}",$commithash,$parenthash)) {1343$log->warn("update-ref for$state->{module} failed.");1344print"error 1 Cannot commit -- update first\n";1345exit;1346}13471348### Emulate git-receive-pack by running hooks/post-receive1349my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1350if( -x $hook) {1351open(my$pipe,"|$hook") ||die"can't fork$!";13521353local$SIG{PIPE} =sub{die'pipe broke'};13541355print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";13561357close$pipe||die"bad pipe:$!$?";1358}13591360$updater->update();13611362# foreach file specified on the command line ...1363foreachmy$filename(@committedfiles)1364{1365$filename= filecleanup($filename);13661367my$meta=$updater->getmeta($filename);1368unless(defined$meta->{revision}) {1369$meta->{revision} =1;1370}13711372my($filepart,$dirpart) = filenamesplit($filename,1);13731374$log->debug("Checked-in$dirpart:$filename");13751376print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1377if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1378{1379print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1380print"Remove-entry$dirpart\n";1381print"$filename\n";1382}else{1383if($meta->{revision} ==1) {1384print"M initial revision: 1.1\n";1385}else{1386print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1387}1388print"Checked-in$dirpart\n";1389print"$filename\n";1390my$kopts= kopts_from_path($filepart);1391print"/$filepart/1.$meta->{revision}//$kopts/\n";1392}1393}13941395chdir"/";1396print"ok\n";1397}13981399sub req_status1400{1401my($cmd,$data) =@_;14021403 argsplit("status");14041405$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1406#$log->debug("status state : " . Dumper($state));14071408# Grab a handle to the SQLite db and do any necessary updates1409my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1410$updater->update();14111412# if no files were specified, we need to work out what files we should be providing status on ...1413 argsfromdir($updater);14141415# foreach file specified on the command line ...1416foreachmy$filename( @{$state->{args}} )1417{1418$filename= filecleanup($filename);14191420my$meta=$updater->getmeta($filename);1421my$oldmeta=$meta;14221423my$wrev= revparse($filename);14241425# If the working copy is an old revision, lets get that version too for comparison.1426if(defined($wrev)and$wrev!=$meta->{revision} )1427{1428$oldmeta=$updater->getmeta($filename,$wrev);1429}14301431# TODO : All possible statuses aren't yet implemented1432my$status;1433# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1434$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1435and1436( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1437or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1438);14391440# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1441$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1442and1443($state->{entries}{$filename}{unchanged}1444or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1445);14461447# Need checkout if it exists in the repo but doesn't have a working copy1448$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );14491450# Locally modified if working copy and repo copy have the same revision but there are local changes1451$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );14521453# Needs Merge if working copy revision is less than repo copy and there are local changes1454$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );14551456$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1457$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1458$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1459$status||="File had conflicts on merge"if(0);14601461$status||="Unknown";14621463print"M ===================================================================\n";1464print"M File:$filename\tStatus:$status\n";1465if(defined($state->{entries}{$filename}{revision}) )1466{1467print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1468}else{1469print"M Working revision:\tNo entry for$filename\n";1470}1471if(defined($meta->{revision}) )1472{1473print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1474print"M Sticky Tag:\t\t(none)\n";1475print"M Sticky Date:\t\t(none)\n";1476print"M Sticky Options:\t\t(none)\n";1477}else{1478print"M Repository revision:\tNo revision control file\n";1479}1480print"M\n";1481}14821483print"ok\n";1484}14851486sub req_diff1487{1488my($cmd,$data) =@_;14891490 argsplit("diff");14911492$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1493#$log->debug("status state : " . Dumper($state));14941495my($revision1,$revision2);1496if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1497{1498$revision1=$state->{opt}{r}[0];1499$revision2=$state->{opt}{r}[1];1500}else{1501$revision1=$state->{opt}{r};1502}15031504$revision1=~s/^1\.//if(defined($revision1) );1505$revision2=~s/^1\.//if(defined($revision2) );15061507$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15081509# Grab a handle to the SQLite db and do any necessary updates1510my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1511$updater->update();15121513# if no files were specified, we need to work out what files we should be providing status on ...1514 argsfromdir($updater);15151516# foreach file specified on the command line ...1517foreachmy$filename( @{$state->{args}} )1518{1519$filename= filecleanup($filename);15201521my($fh,$file1,$file2,$meta1,$meta2,$filediff);15221523my$wrev= revparse($filename);15241525# We need _something_ to diff against1526next unless(defined($wrev) );15271528# if we have a -r switch, use it1529if(defined($revision1) )1530{1531(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1532$meta1=$updater->getmeta($filename,$revision1);1533unless(defined($meta1)and$meta1->{filehash}ne"deleted")1534{1535print"E File$filenameat revision 1.$revision1doesn't exist\n";1536next;1537}1538 transmitfile($meta1->{filehash},$file1);1539}1540# otherwise we just use the working copy revision1541else1542{1543(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1544$meta1=$updater->getmeta($filename,$wrev);1545 transmitfile($meta1->{filehash},$file1);1546}15471548# if we have a second -r switch, use it too1549if(defined($revision2) )1550{1551(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1552$meta2=$updater->getmeta($filename,$revision2);15531554unless(defined($meta2)and$meta2->{filehash}ne"deleted")1555{1556print"E File$filenameat revision 1.$revision2doesn't exist\n";1557next;1558}15591560 transmitfile($meta2->{filehash},$file2);1561}1562# otherwise we just use the working copy1563else1564{1565$file2=$state->{entries}{$filename}{modified_filename};1566}15671568# if we have been given -r, and we don't have a $file2 yet, lets get one1569if(defined($revision1)and not defined($file2) )1570{1571(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1572$meta2=$updater->getmeta($filename,$wrev);1573 transmitfile($meta2->{filehash},$file2);1574}15751576# We need to have retrieved something useful1577next unless(defined($meta1) );15781579# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1580next if(not defined($meta2)and$wrev==$meta1->{revision}1581and1582( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1583or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1584);15851586# Apparently we only show diffs for locally modified files1587next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );15881589print"M Index:$filename\n";1590print"M ===================================================================\n";1591print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1592print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1593print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1594print"M diff ";1595foreachmy$opt(keys%{$state->{opt}} )1596{1597if(ref$state->{opt}{$opt}eq"ARRAY")1598{1599foreachmy$value( @{$state->{opt}{$opt}} )1600{1601print"-$opt$value";1602}1603}else{1604print"-$opt";1605print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1606}1607}1608print"$filename\n";16091610$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16111612($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16131614if(exists$state->{opt}{u} )1615{1616system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1617}else{1618system("diff$file1$file2>$filediff");1619}16201621while( <$fh> )1622{1623print"M$_";1624}1625close$fh;1626}16271628print"ok\n";1629}16301631sub req_log1632{1633my($cmd,$data) =@_;16341635 argsplit("log");16361637$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1638#$log->debug("log state : " . Dumper($state));16391640my($minrev,$maxrev);1641if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1642{1643my$control=$2;1644$minrev=$1;1645$maxrev=$3;1646$minrev=~s/^1\.//if(defined($minrev) );1647$maxrev=~s/^1\.//if(defined($maxrev) );1648$minrev++if(defined($minrev)and$controleq"::");1649}16501651# Grab a handle to the SQLite db and do any necessary updates1652my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1653$updater->update();16541655# if no files were specified, we need to work out what files we should be providing status on ...1656 argsfromdir($updater);16571658# foreach file specified on the command line ...1659foreachmy$filename( @{$state->{args}} )1660{1661$filename= filecleanup($filename);16621663my$headmeta=$updater->getmeta($filename);16641665my$revisions=$updater->getlog($filename);1666my$totalrevisions=scalar(@$revisions);16671668if(defined($minrev) )1669{1670$log->debug("Removing revisions less than$minrev");1671while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1672{1673pop@$revisions;1674}1675}1676if(defined($maxrev) )1677{1678$log->debug("Removing revisions greater than$maxrev");1679while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1680{1681shift@$revisions;1682}1683}16841685next unless(scalar(@$revisions) );16861687print"M\n";1688print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1689print"M Working file:$filename\n";1690print"M head: 1.$headmeta->{revision}\n";1691print"M branch:\n";1692print"M locks: strict\n";1693print"M access list:\n";1694print"M symbolic names:\n";1695print"M keyword substitution: kv\n";1696print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1697print"M description:\n";16981699foreachmy$revision(@$revisions)1700{1701print"M ----------------------------\n";1702print"M revision 1.$revision->{revision}\n";1703# reformat the date for log output1704$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}) );1705$revision->{author} =~s/\s+.*//;1706$revision->{author} =~s/^(.{8}).*/$1/;1707print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1708my$commitmessage=$updater->commitmessage($revision->{commithash});1709$commitmessage=~s/^/M /mg;1710print$commitmessage."\n";1711}1712print"M =============================================================================\n";1713}17141715print"ok\n";1716}17171718sub req_annotate1719{1720my($cmd,$data) =@_;17211722 argsplit("annotate");17231724$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1725#$log->debug("status state : " . Dumper($state));17261727# Grab a handle to the SQLite db and do any necessary updates1728my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1729$updater->update();17301731# if no files were specified, we need to work out what files we should be providing annotate on ...1732 argsfromdir($updater);17331734# we'll need a temporary checkout dir1735my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1736my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1737$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");17381739$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1740$ENV{GIT_WORK_TREE} =".";1741$ENV{GIT_INDEX_FILE} =$file_index;17421743chdir$tmpdir;17441745# foreach file specified on the command line ...1746foreachmy$filename( @{$state->{args}} )1747{1748$filename= filecleanup($filename);17491750my$meta=$updater->getmeta($filename);17511752next unless($meta->{revision} );17531754# get all the commits that this file was in1755# in dense format -- aka skip dead revisions1756my$revisions=$updater->gethistorydense($filename);1757my$lastseenin=$revisions->[0][2];17581759# populate the temporary index based on the latest commit were we saw1760# the file -- but do it cheaply without checking out any files1761# TODO: if we got a revision from the client, use that instead1762# to look up the commithash in sqlite (still good to default to1763# the current head as we do now)1764system("git-read-tree",$lastseenin);1765unless($?==0)1766{1767print"E error running git-read-tree$lastseenin$file_index$!\n";1768return;1769}1770$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");17711772# do a checkout of the file1773system('git-checkout-index','-f','-u',$filename);1774unless($?==0) {1775print"E error running git-checkout-index -f -u$filename:$!\n";1776return;1777}17781779$log->info("Annotate$filename");17801781# Prepare a file with the commits from the linearized1782# history that annotate should know about. This prevents1783# git-jsannotate telling us about commits we are hiding1784# from the client.17851786my$a_hints="$tmpdir/.annotate_hints";1787if(!open(ANNOTATEHINTS,'>',$a_hints)) {1788print"E failed to open '$a_hints' for writing:$!\n";1789return;1790}1791for(my$i=0;$i<@$revisions;$i++)1792{1793print ANNOTATEHINTS $revisions->[$i][2];1794if($i+1<@$revisions) {# have we got a parent?1795print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1796}1797print ANNOTATEHINTS "\n";1798}17991800print ANNOTATEHINTS "\n";1801close ANNOTATEHINTS1802or(print"E failed to write$a_hints:$!\n"),return;18031804my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1805if(!open(ANNOTATE,"-|",@cmd)) {1806print"E error invoking ".join(' ',@cmd) .":$!\n";1807return;1808}1809my$metadata= {};1810print"E Annotations for$filename\n";1811print"E ***************\n";1812while( <ANNOTATE> )1813{1814if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1815{1816my$commithash=$1;1817my$data=$2;1818unless(defined($metadata->{$commithash} ) )1819{1820$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1821$metadata->{$commithash}{author} =~s/\s+.*//;1822$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1823$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1824}1825printf("M 1.%-5d (%-8s%10s):%s\n",1826$metadata->{$commithash}{revision},1827$metadata->{$commithash}{author},1828$metadata->{$commithash}{modified},1829$data1830);1831}else{1832$log->warn("Error in annotate output! LINE:$_");1833print"E Annotate error\n";1834next;1835}1836}1837close ANNOTATE;1838}18391840# done; get out of the tempdir1841chdir"/";18421843print"ok\n";18441845}18461847# This method takes the state->{arguments} array and produces two new arrays.1848# The first is $state->{args} which is everything before the '--' argument, and1849# the second is $state->{files} which is everything after it.1850sub argsplit1851{1852$state->{args} = [];1853$state->{files} = [];1854$state->{opt} = {};18551856return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");18571858my$type=shift;18591860if(defined($type) )1861{1862my$opt= {};1863$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($typeeq"co");1864$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1865$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($typeeq"update");1866$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1867$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1868$opt= { k =>1, m =>1}if($typeeq"add");1869$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1870$opt= { l =>0, b =>0, h =>0, R =>0, t =>0, N =>0, S =>0, r =>1, d =>1, s =>1, w =>1}if($typeeq"log");187118721873while(scalar( @{$state->{arguments}} ) >0)1874{1875my$arg=shift@{$state->{arguments}};18761877next if($argeq"--");1878next unless($arg=~/\S/);18791880# if the argument looks like a switch1881if($arg=~/^-(\w)(.*)/)1882{1883# if it's a switch that takes an argument1884if($opt->{$1} )1885{1886# If this switch has already been provided1887if($opt->{$1} >1and exists($state->{opt}{$1} ) )1888{1889$state->{opt}{$1} = [$state->{opt}{$1} ];1890if(length($2) >0)1891{1892push@{$state->{opt}{$1}},$2;1893}else{1894push@{$state->{opt}{$1}},shift@{$state->{arguments}};1895}1896}else{1897# if there's extra data in the arg, use that as the argument for the switch1898if(length($2) >0)1899{1900$state->{opt}{$1} =$2;1901}else{1902$state->{opt}{$1} =shift@{$state->{arguments}};1903}1904}1905}else{1906$state->{opt}{$1} =undef;1907}1908}1909else1910{1911push@{$state->{args}},$arg;1912}1913}1914}1915else1916{1917my$mode=0;19181919foreachmy$value( @{$state->{arguments}} )1920{1921if($valueeq"--")1922{1923$mode++;1924next;1925}1926push@{$state->{args}},$valueif($mode==0);1927push@{$state->{files}},$valueif($mode==1);1928}1929}1930}19311932# This method uses $state->{directory} to populate $state->{args} with a list of filenames1933sub argsfromdir1934{1935my$updater=shift;19361937$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19381939return if(scalar( @{$state->{args}} ) >1);19401941my@gethead= @{$updater->gethead};19421943# push added files1944foreachmy$file(keys%{$state->{entries}}) {1945if(exists$state->{entries}{$file}{revision} &&1946$state->{entries}{$file}{revision} ==0)1947{1948push@gethead, { name =>$file, filehash =>'added'};1949}1950}19511952if(scalar(@{$state->{args}}) ==1)1953{1954my$arg=$state->{args}[0];1955$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );19561957$log->info("Only one arg specified, checking for directory expansion on '$arg'");19581959foreachmy$file(@gethead)1960{1961next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1962next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1963push@{$state->{args}},$file->{name};1964}19651966shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1967}else{1968$log->info("Only one arg specified, populating file list automatically");19691970$state->{args} = [];19711972foreachmy$file(@gethead)1973{1974next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1975next unless($file->{name} =~s/^$state->{prependdir}//);1976push@{$state->{args}},$file->{name};1977}1978}1979}19801981# This method cleans up the $state variable after a command that uses arguments has run1982sub statecleanup1983{1984$state->{files} = [];1985$state->{args} = [];1986$state->{arguments} = [];1987$state->{entries} = {};1988}19891990sub revparse1991{1992my$filename=shift;19931994returnundefunless(defined($state->{entries}{$filename}{revision} ) );19951996return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1997return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);19981999returnundef;2000}20012002# This method takes a file hash and does a CVS "file transfer" which transmits the2003# size of the file, and then the file contents.2004# If a second argument $targetfile is given, the file is instead written out to2005# a file by the name of $targetfile2006sub transmitfile2007{2008my$filehash=shift;2009my$targetfile=shift;20102011if(defined($filehash)and$filehasheq"deleted")2012{2013$log->warn("filehash is 'deleted'");2014return;2015}20162017die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20182019my$type=`git-cat-file -t$filehash`;2020 chomp$type;20212022 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20232024 my$size= `git-cat-file -s $filehash`;2025chomp$size;20262027$log->debug("transmitfile($filehash) size=$size, type=$type");20282029if(open my$fh,'-|',"git-cat-file","blob",$filehash)2030{2031if(defined($targetfile) )2032{2033open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2034print NEWFILE $_while( <$fh> );2035close NEWFILE or die("Failed to write '$targetfile':$!");2036}else{2037print"$size\n";2038printwhile( <$fh> );2039}2040close$fhor die("Couldn't close filehandle for transmitfile():$!");2041}else{2042die("Couldn't execute git-cat-file");2043}2044}20452046# This method takes a file name, and returns ( $dirpart, $filepart ) which2047# refers to the directory portion and the file portion of the filename2048# respectively2049sub filenamesplit2050{2051my$filename=shift;2052my$fixforlocaldir=shift;20532054my($filepart,$dirpart) = ($filename,".");2055($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2056$dirpart.="/";20572058if($fixforlocaldir)2059{2060$dirpart=~s/^$state->{prependdir}//;2061}20622063return($filepart,$dirpart);2064}20652066sub filecleanup2067{2068my$filename=shift;20692070returnundefunless(defined($filename));2071if($filename=~/^\// )2072{2073print"E absolute filenames '$filename' not supported by server\n";2074returnundef;2075}20762077$filename=~s/^\.\///g;2078$filename=$state->{prependdir} .$filename;2079return$filename;2080}20812082# Given a path, this function returns a string containing the kopts2083# that should go into that path's Entries line. For example, a binary2084# file should get -kb.2085sub kopts_from_path2086{2087my($path) =@_;20882089# Once it exists, the git attributes system should be used to look up2090# what attributes apply to this path.20912092# Until then, take the setting from the config file2093unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)2094{2095# Return "" to give no special treatment to any path2096return"";2097}else{2098# Alternatively, to have all files treated as if they are binary (which2099# is more like git itself), always return the "-kb" option2100return"-kb";2101}2102}21032104package GITCVS::log;21052106####2107#### Copyright The Open University UK - 2006.2108####2109#### Authors: Martyn Smith <martyn@catalyst.net.nz>2110#### Martin Langhoff <martin@catalyst.net.nz>2111####2112####21132114use strict;2115use warnings;21162117=head1 NAME21182119GITCVS::log21202121=head1 DESCRIPTION21222123This module provides very crude logging with a similar interface to2124Log::Log4perl21252126=head1 METHODS21272128=cut21292130=head2 new21312132Creates a new log object, optionally you can specify a filename here to2133indicate the file to log to. If no log file is specified, you can specify one2134later with method setfile, or indicate you no longer want logging with method2135nofile.21362137Until one of these methods is called, all log calls will buffer messages ready2138to write out.21392140=cut2141sub new2142{2143my$class=shift;2144my$filename=shift;21452146my$self= {};21472148bless$self,$class;21492150if(defined($filename) )2151{2152open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2153}21542155return$self;2156}21572158=head2 setfile21592160This methods takes a filename, and attempts to open that file as the log file.2161If successful, all buffered data is written out to the file, and any further2162logging is written directly to the file.21632164=cut2165sub setfile2166{2167my$self=shift;2168my$filename=shift;21692170if(defined($filename) )2171{2172open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2173}21742175return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");21762177while(my$line=shift@{$self->{buffer}} )2178{2179print{$self->{fh}}$line;2180}2181}21822183=head2 nofile21842185This method indicates no logging is going to be used. It flushes any entries in2186the internal buffer, and sets a flag to ensure no further data is put there.21872188=cut2189sub nofile2190{2191my$self=shift;21922193$self->{nolog} =1;21942195return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");21962197$self->{buffer} = [];2198}21992200=head2 _logopen22012202Internal method. Returns true if the log file is open, false otherwise.22032204=cut2205sub _logopen2206{2207my$self=shift;22082209return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2210return0;2211}22122213=head2 debug info warn fatal22142215These four methods are wrappers to _log. They provide the actual interface for2216logging data.22172218=cut2219sub debug {my$self=shift;$self->_log("debug",@_); }2220sub info {my$self=shift;$self->_log("info",@_); }2221subwarn{my$self=shift;$self->_log("warn",@_); }2222sub fatal {my$self=shift;$self->_log("fatal",@_); }22232224=head2 _log22252226This is an internal method called by the logging functions. It generates a2227timestamp and pushes the logged line either to file, or internal buffer.22282229=cut2230sub _log2231{2232my$self=shift;2233my$level=shift;22342235return if($self->{nolog} );22362237my@time=localtime;2238my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2239$time[5] +1900,2240$time[4] +1,2241$time[3],2242$time[2],2243$time[1],2244$time[0],2245uc$level,2246);22472248if($self->_logopen)2249{2250print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2251}else{2252push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2253}2254}22552256=head2 DESTROY22572258This method simply closes the file handle if one is open22592260=cut2261sub DESTROY2262{2263my$self=shift;22642265if($self->_logopen)2266{2267close$self->{fh};2268}2269}22702271package GITCVS::updater;22722273####2274#### Copyright The Open University UK - 2006.2275####2276#### Authors: Martyn Smith <martyn@catalyst.net.nz>2277#### Martin Langhoff <martin@catalyst.net.nz>2278####2279####22802281use strict;2282use warnings;2283use DBI;22842285=head1 METHODS22862287=cut22882289=head2 new22902291=cut2292sub new2293{2294my$class=shift;2295my$config=shift;2296my$module=shift;2297my$log=shift;22982299die"Need to specify a git repository"unless(defined($config)and-d $config);2300die"Need to specify a module"unless(defined($module) );23012302$class=ref($class) ||$class;23032304my$self= {};23052306bless$self,$class;23072308$self->{module} =$module;2309$self->{git_path} =$config."/";23102311$self->{log} =$log;23122313die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );23142315$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2316$cfg->{gitcvs}{dbdriver} ||"SQLite";2317$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2318$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2319$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2320$cfg->{gitcvs}{dbuser} ||"";2321$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2322$cfg->{gitcvs}{dbpass} ||"";2323my%mapping= ( m =>$module,2324 a =>$state->{method},2325 u =>getlogin||getpwuid($<) || $<,2326 G =>$self->{git_path},2327 g => mangle_dirname($self->{git_path}),2328);2329$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2330$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;23312332die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2333die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2334$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2335$self->{dbuser},2336$self->{dbpass});2337die"Error connecting to database\n"unlessdefined$self->{dbh};23382339$self->{tables} = {};2340foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2341{2342$self->{tables}{$table} =1;2343}23442345# Construct the revision table if required2346unless($self->{tables}{revision} )2347{2348$self->{dbh}->do("2349 CREATE TABLE revision (2350 name TEXT NOT NULL,2351 revision INTEGER NOT NULL,2352 filehash TEXT NOT NULL,2353 commithash TEXT NOT NULL,2354 author TEXT NOT NULL,2355 modified TEXT NOT NULL,2356 mode TEXT NOT NULL2357 )2358 ");2359$self->{dbh}->do("2360 CREATE INDEX revision_ix12361 ON revision (name,revision)2362 ");2363$self->{dbh}->do("2364 CREATE INDEX revision_ix22365 ON revision (name,commithash)2366 ");2367}23682369# Construct the head table if required2370unless($self->{tables}{head} )2371{2372$self->{dbh}->do("2373 CREATE TABLE head (2374 name TEXT NOT NULL,2375 revision INTEGER NOT NULL,2376 filehash TEXT NOT NULL,2377 commithash TEXT NOT NULL,2378 author TEXT NOT NULL,2379 modified TEXT NOT NULL,2380 mode TEXT NOT NULL2381 )2382 ");2383$self->{dbh}->do("2384 CREATE INDEX head_ix12385 ON head (name)2386 ");2387}23882389# Construct the properties table if required2390unless($self->{tables}{properties} )2391{2392$self->{dbh}->do("2393 CREATE TABLE properties (2394 key TEXT NOT NULL PRIMARY KEY,2395 value TEXT2396 )2397 ");2398}23992400# Construct the commitmsgs table if required2401unless($self->{tables}{commitmsgs} )2402{2403$self->{dbh}->do("2404 CREATE TABLE commitmsgs (2405 key TEXT NOT NULL PRIMARY KEY,2406 value TEXT2407 )2408 ");2409}24102411return$self;2412}24132414=head2 update24152416=cut2417sub update2418{2419my$self=shift;24202421# first lets get the commit list2422$ENV{GIT_DIR} =$self->{git_path};24232424my$commitsha1=`git rev-parse$self->{module}`;2425chomp$commitsha1;24262427my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2428unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2429{2430die("Invalid module '$self->{module}'");2431}243224332434my$git_log;2435my$lastcommit=$self->_get_prop("last_commit");24362437if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2438return1;2439}24402441# Start exclusive lock here...2442$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";24432444# TODO: log processing is memory bound2445# if we can parse into a 2nd file that is in reverse order2446# we can probably do something really efficient2447my@git_log_params= ('--pretty','--parents','--topo-order');24482449if(defined$lastcommit) {2450push@git_log_params,"$lastcommit..$self->{module}";2451}else{2452push@git_log_params,$self->{module};2453}2454# git-rev-list is the backend / plumbing version of git-log2455open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";24562457my@commits;24582459my%commit= ();24602461while( <GITLOG> )2462{2463chomp;2464if(m/^commit\s+(.*)$/) {2465# on ^commit lines put the just seen commit in the stack2466# and prime things for the next one2467if(keys%commit) {2468my%copy=%commit;2469unshift@commits, \%copy;2470%commit= ();2471}2472my@parents=split(m/\s+/,$1);2473$commit{hash} =shift@parents;2474$commit{parents} = \@parents;2475}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2476# on rfc822-like lines seen before we see any message,2477# lowercase the entry and put it in the hash as key-value2478$commit{lc($1)} =$2;2479}else{2480# message lines - skip initial empty line2481# and trim whitespace2482if(!exists($commit{message}) &&m/^\s*$/) {2483# define it to mark the end of headers2484$commit{message} ='';2485next;2486}2487s/^\s+//;s/\s+$//;# trim ws2488$commit{message} .=$_."\n";2489}2490}2491close GITLOG;24922493unshift@commits, \%commitif(keys%commit);24942495# Now all the commits are in the @commits bucket2496# ordered by time DESC. for each commit that needs processing,2497# determine whether it's following the last head we've seen or if2498# it's on its own branch, grab a file list, and add whatever's changed2499# NOTE: $lastcommit refers to the last commit from previous run2500# $lastpicked is the last commit we picked in this run2501my$lastpicked;2502my$head= {};2503if(defined$lastcommit) {2504$lastpicked=$lastcommit;2505}25062507my$committotal=scalar(@commits);2508my$commitcount=0;25092510# Load the head table into $head (for cached lookups during the update process)2511foreachmy$file( @{$self->gethead()} )2512{2513$head->{$file->{name}} =$file;2514}25152516foreachmy$commit(@commits)2517{2518$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2519if(defined$lastpicked)2520{2521if(!in_array($lastpicked, @{$commit->{parents}}))2522{2523# skip, we'll see this delta2524# as part of a merge later2525# warn "skipping off-track $commit->{hash}\n";2526next;2527}elsif(@{$commit->{parents}} >1) {2528# it is a merge commit, for each parent that is2529# not $lastpicked, see if we can get a log2530# from the merge-base to that parent to put it2531# in the message as a merge summary.2532my@parents= @{$commit->{parents}};2533foreachmy$parent(@parents) {2534# git-merge-base can potentially (but rarely) throw2535# several candidate merge bases. let's assume2536# that the first one is the best one.2537if($parenteq$lastpicked) {2538next;2539}2540my$base= safe_pipe_capture('git-merge-base',2541$lastpicked,$parent);2542chomp$base;2543if($base) {2544my@merged;2545# print "want to log between $base $parent \n";2546open(GITLOG,'-|','git-log',"$base..$parent")2547or die"Cannot call git-log:$!";2548my$mergedhash;2549while(<GITLOG>) {2550chomp;2551if(!defined$mergedhash) {2552if(m/^commit\s+(.+)$/) {2553$mergedhash=$1;2554}else{2555next;2556}2557}else{2558# grab the first line that looks non-rfc8222559# aka has content after leading space2560if(m/^\s+(\S.*)$/) {2561my$title=$1;2562$title=substr($title,0,100);# truncate2563unshift@merged,"$mergedhash$title";2564undef$mergedhash;2565}2566}2567}2568close GITLOG;2569if(@merged) {2570$commit->{mergemsg} =$commit->{message};2571$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2572foreachmy$summary(@merged) {2573$commit->{mergemsg} .="\t$summary\n";2574}2575$commit->{mergemsg} .="\n\n";2576# print "Message for $commit->{hash} \n$commit->{mergemsg}";2577}2578}2579}2580}2581}25822583# convert the date to CVS-happy format2584$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);25852586if(defined($lastpicked) )2587{2588my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2589local($/) ="\0";2590while( <FILELIST> )2591{2592chomp;2593unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2594{2595die("Couldn't process git-diff-tree line :$_");2596}2597my($mode,$hash,$change) = ($1,$2,$3);2598my$name= <FILELIST>;2599chomp($name);26002601# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");26022603my$git_perms="";2604$git_perms.="r"if($mode&4);2605$git_perms.="w"if($mode&2);2606$git_perms.="x"if($mode&1);2607$git_perms="rw"if($git_permseq"");26082609if($changeeq"D")2610{2611#$log->debug("DELETE $name");2612$head->{$name} = {2613 name =>$name,2614 revision =>$head->{$name}{revision} +1,2615 filehash =>"deleted",2616 commithash =>$commit->{hash},2617 modified =>$commit->{date},2618 author =>$commit->{author},2619 mode =>$git_perms,2620};2621$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2622}2623elsif($changeeq"M")2624{2625#$log->debug("MODIFIED $name");2626$head->{$name} = {2627 name =>$name,2628 revision =>$head->{$name}{revision} +1,2629 filehash =>$hash,2630 commithash =>$commit->{hash},2631 modified =>$commit->{date},2632 author =>$commit->{author},2633 mode =>$git_perms,2634};2635$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2636}2637elsif($changeeq"A")2638{2639#$log->debug("ADDED $name");2640$head->{$name} = {2641 name =>$name,2642 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,2643 filehash =>$hash,2644 commithash =>$commit->{hash},2645 modified =>$commit->{date},2646 author =>$commit->{author},2647 mode =>$git_perms,2648};2649$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2650}2651else2652{2653$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2654die;2655}2656}2657close FILELIST;2658}else{2659# this is used to detect files removed from the repo2660my$seen_files= {};26612662my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2663local$/="\0";2664while( <FILELIST> )2665{2666chomp;2667unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2668{2669die("Couldn't process git-ls-tree line :$_");2670}26712672my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);26732674$seen_files->{$git_filename} =1;26752676my($oldhash,$oldrevision,$oldmode) = (2677$head->{$git_filename}{filehash},2678$head->{$git_filename}{revision},2679$head->{$git_filename}{mode}2680);26812682if($git_perms=~/^\d\d\d(\d)\d\d/o)2683{2684$git_perms="";2685$git_perms.="r"if($1&4);2686$git_perms.="w"if($1&2);2687$git_perms.="x"if($1&1);2688}else{2689$git_perms="rw";2690}26912692# unless the file exists with the same hash, we need to update it ...2693unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2694{2695my$newrevision= ($oldrevisionor0) +1;26962697$head->{$git_filename} = {2698 name =>$git_filename,2699 revision =>$newrevision,2700 filehash =>$git_hash,2701 commithash =>$commit->{hash},2702 modified =>$commit->{date},2703 author =>$commit->{author},2704 mode =>$git_perms,2705};270627072708$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2709}2710}2711close FILELIST;27122713# Detect deleted files2714foreachmy$file(keys%$head)2715{2716unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2717{2718$head->{$file}{revision}++;2719$head->{$file}{filehash} ="deleted";2720$head->{$file}{commithash} =$commit->{hash};2721$head->{$file}{modified} =$commit->{date};2722$head->{$file}{author} =$commit->{author};27232724$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2725}2726}2727# END : "Detect deleted files"2728}272927302731if(exists$commit->{mergemsg})2732{2733$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2734}27352736$lastpicked=$commit->{hash};27372738$self->_set_prop("last_commit",$commit->{hash});2739}27402741$self->delete_head();2742foreachmy$file(keys%$head)2743{2744$self->insert_head(2745$file,2746$head->{$file}{revision},2747$head->{$file}{filehash},2748$head->{$file}{commithash},2749$head->{$file}{modified},2750$head->{$file}{author},2751$head->{$file}{mode},2752);2753}2754# invalidate the gethead cache2755$self->{gethead_cache} =undef;275627572758# Ending exclusive lock here2759$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2760}27612762sub insert_rev2763{2764my$self=shift;2765my$name=shift;2766my$revision=shift;2767my$filehash=shift;2768my$commithash=shift;2769my$modified=shift;2770my$author=shift;2771my$mode=shift;27722773my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2774$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2775}27762777sub insert_mergelog2778{2779my$self=shift;2780my$key=shift;2781my$value=shift;27822783my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2784$insert_mergelog->execute($key,$value);2785}27862787sub delete_head2788{2789my$self=shift;27902791my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2792$delete_head->execute();2793}27942795sub insert_head2796{2797my$self=shift;2798my$name=shift;2799my$revision=shift;2800my$filehash=shift;2801my$commithash=shift;2802my$modified=shift;2803my$author=shift;2804my$mode=shift;28052806my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2807$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2808}28092810sub _headrev2811{2812my$self=shift;2813my$filename=shift;28142815my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2816$db_query->execute($filename);2817my($hash,$revision,$mode) =$db_query->fetchrow_array;28182819return($hash,$revision,$mode);2820}28212822sub _get_prop2823{2824my$self=shift;2825my$key=shift;28262827my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2828$db_query->execute($key);2829my($value) =$db_query->fetchrow_array;28302831return$value;2832}28332834sub _set_prop2835{2836my$self=shift;2837my$key=shift;2838my$value=shift;28392840my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2841$db_query->execute($value,$key);28422843unless($db_query->rows)2844{2845$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2846$db_query->execute($key,$value);2847}28482849return$value;2850}28512852=head2 gethead28532854=cut28552856sub gethead2857{2858my$self=shift;28592860return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );28612862my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2863$db_query->execute();28642865my$tree= [];2866while(my$file=$db_query->fetchrow_hashref)2867{2868push@$tree,$file;2869}28702871$self->{gethead_cache} =$tree;28722873return$tree;2874}28752876=head2 getlog28772878=cut28792880sub getlog2881{2882my$self=shift;2883my$filename=shift;28842885my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2886$db_query->execute($filename);28872888my$tree= [];2889while(my$file=$db_query->fetchrow_hashref)2890{2891push@$tree,$file;2892}28932894return$tree;2895}28962897=head2 getmeta28982899This function takes a filename (with path) argument and returns a hashref of2900metadata for that file.29012902=cut29032904sub getmeta2905{2906my$self=shift;2907my$filename=shift;2908my$revision=shift;29092910my$db_query;2911if(defined($revision)and$revision=~/^\d+$/)2912{2913$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2914$db_query->execute($filename,$revision);2915}2916elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2917{2918$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2919$db_query->execute($filename,$revision);2920}else{2921$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2922$db_query->execute($filename);2923}29242925return$db_query->fetchrow_hashref;2926}29272928=head2 commitmessage29292930this function takes a commithash and returns the commit message for that commit29312932=cut2933sub commitmessage2934{2935my$self=shift;2936my$commithash=shift;29372938die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);29392940my$db_query;2941$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2942$db_query->execute($commithash);29432944my($message) =$db_query->fetchrow_array;29452946if(defined($message) )2947{2948$message.=" "if($message=~/\n$/);2949return$message;2950}29512952my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2953shift@lineswhile($lines[0] =~/\S/);2954$message=join("",@lines);2955$message.=" "if($message=~/\n$/);2956return$message;2957}29582959=head2 gethistory29602961This function takes a filename (with path) argument and returns an arrayofarrays2962containing revision,filehash,commithash ordered by revision descending29632964=cut2965sub gethistory2966{2967my$self=shift;2968my$filename=shift;29692970my$db_query;2971$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2972$db_query->execute($filename);29732974return$db_query->fetchall_arrayref;2975}29762977=head2 gethistorydense29782979This function takes a filename (with path) argument and returns an arrayofarrays2980containing revision,filehash,commithash ordered by revision descending.29812982This version of gethistory skips deleted entries -- so it is useful for annotate.2983The 'dense' part is a reference to a '--dense' option available for git-rev-list2984and other git tools that depend on it.29852986=cut2987sub gethistorydense2988{2989my$self=shift;2990my$filename=shift;29912992my$db_query;2993$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2994$db_query->execute($filename);29952996return$db_query->fetchall_arrayref;2997}29982999=head2 in_array()30003001from Array::PAT - mimics the in_array() function3002found in PHP. Yuck but works for small arrays.30033004=cut3005sub in_array3006{3007my($check,@array) =@_;3008my$retval=0;3009foreachmy$test(@array){3010if($checkeq$test){3011$retval=1;3012}3013}3014return$retval;3015}30163017=head2 safe_pipe_capture30183019an alternative to `command` that allows input to be passed as an array3020to work around shell problems with weird characters in arguments30213022=cut3023sub safe_pipe_capture {30243025my@output;30263027if(my$pid=open my$child,'-|') {3028@output= (<$child>);3029close$childor die join(' ',@_).":$!$?";3030}else{3031exec(@_)or die"$!$?";# exec() can fail the executable can't be found3032}3033returnwantarray?@output:join('',@output);3034}30353036=head2 mangle_dirname30373038create a string from a directory name that is suitable to use as3039part of a filename, mainly by converting all chars except \w.- to _30403041=cut3042sub mangle_dirname {3043my$dirname=shift;3044return unlessdefined$dirname;30453046$dirname=~s/[^\w.-]/_/g;30473048return$dirname;3049}305030511;