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_EMPTY, 77'editors'=> \&req_EMPTY, 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# This method invariably succeeds with an empty response. 203sub req_EMPTY 204{ 205print"ok\n"; 206} 207 208# Root pathname \n 209# Response expected: no. Tell the server which CVSROOT to use. Note that 210# pathname is a local directory and not a fully qualified CVSROOT variable. 211# pathname must already exist; if creating a new root, use the init 212# request, not Root. pathname does not include the hostname of the server, 213# how to access the server, etc.; by the time the CVS protocol is in use, 214# connection, authentication, etc., are already taken care of. The Root 215# request must be sent only once, and it must be sent before any requests 216# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 217sub req_Root 218{ 219my($cmd,$data) =@_; 220$log->debug("req_Root :$data"); 221 222unless($data=~ m#^/#) { 223print"error 1 Root must be an absolute pathname\n"; 224return0; 225} 226 227my$cvsroot=$state->{'base-path'} ||''; 228$cvsroot=~ s#/+$##; 229$cvsroot.=$data; 230 231if($state->{CVSROOT} 232&& ($state->{CVSROOT}ne$cvsroot)) { 233print"error 1 Conflicting roots specified\n"; 234return0; 235} 236 237$state->{CVSROOT} =$cvsroot; 238 239$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 240 241if(@{$state->{allowed_roots}}) { 242my$allowed=0; 243foreachmy$dir(@{$state->{allowed_roots}}) { 244next unless$dir=~ m#^/#; 245$dir=~ s#/+$##; 246if($state->{'strict-paths'}) { 247if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 248$allowed=1; 249last; 250} 251}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 252$allowed=1; 253last; 254} 255} 256 257unless($allowed) { 258print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 259print"E\n"; 260print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 261return0; 262} 263} 264 265unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 266print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 267print"E\n"; 268print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 269return0; 270} 271 272my@gitvars=`git-config -l`; 273if($?) { 274print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 275print"E\n"; 276print"error 1 - problem executing git-config\n"; 277return0; 278} 279foreachmy$line(@gitvars) 280{ 281next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 282unless($2) { 283$cfg->{$1}{$3} =$4; 284}else{ 285$cfg->{$1}{$2}{$3} =$4; 286} 287} 288 289my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 290||$cfg->{gitcvs}{enabled}); 291unless($state->{'export-all'} || 292($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 293print"E GITCVS emulation needs to be enabled on this repo\n"; 294print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 295print"E\n"; 296print"error 1 GITCVS emulation disabled\n"; 297return0; 298} 299 300my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 301if($logfile) 302{ 303$log->setfile($logfile); 304}else{ 305$log->nofile(); 306} 307 308return1; 309} 310 311# Global_option option \n 312# Response expected: no. Transmit one of the global options `-q', `-Q', 313# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 314# variations (such as combining of options) are allowed. For graceful 315# handling of valid-requests, it is probably better to make new global 316# options separate requests, rather than trying to add them to this 317# request. 318sub req_Globaloption 319{ 320my($cmd,$data) =@_; 321$log->debug("req_Globaloption :$data"); 322$state->{globaloptions}{$data} =1; 323} 324 325# Valid-responses request-list \n 326# Response expected: no. Tell the server what responses the client will 327# accept. request-list is a space separated list of tokens. 328sub req_Validresponses 329{ 330my($cmd,$data) =@_; 331$log->debug("req_Validresponses :$data"); 332 333# TODO : re-enable this, currently it's not particularly useful 334#$state->{validresponses} = [ split /\s+/, $data ]; 335} 336 337# valid-requests \n 338# Response expected: yes. Ask the server to send back a Valid-requests 339# response. 340sub req_validrequests 341{ 342my($cmd,$data) =@_; 343 344$log->debug("req_validrequests"); 345 346$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 347$log->debug("SEND : ok"); 348 349print"Valid-requests ".join(" ",keys%$methods) ."\n"; 350print"ok\n"; 351} 352 353# Directory local-directory \n 354# Additional data: repository \n. Response expected: no. Tell the server 355# what directory to use. The repository should be a directory name from a 356# previous server response. Note that this both gives a default for Entry 357# and Modified and also for ci and the other commands; normal usage is to 358# send Directory for each directory in which there will be an Entry or 359# Modified, and then a final Directory for the original directory, then the 360# command. The local-directory is relative to the top level at which the 361# command is occurring (i.e. the last Directory which is sent before the 362# command); to indicate that top level, `.' should be sent for 363# local-directory. 364sub req_Directory 365{ 366my($cmd,$data) =@_; 367 368my$repository= <STDIN>; 369chomp$repository; 370 371 372$state->{localdir} =$data; 373$state->{repository} =$repository; 374$state->{path} =$repository; 375$state->{path} =~s/^$state->{CVSROOT}\///; 376$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 377$state->{path} .="/"if($state->{path} =~ /\S/ ); 378 379$state->{directory} =$state->{localdir}; 380$state->{directory} =""if($state->{directory}eq"."); 381$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 382 383if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 384{ 385$log->info("Setting prepend to '$state->{path}'"); 386$state->{prependdir} =$state->{path}; 387foreachmy$entry(keys%{$state->{entries}} ) 388{ 389$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 390delete$state->{entries}{$entry}; 391} 392} 393 394if(defined($state->{prependdir} ) ) 395{ 396$log->debug("Prepending '$state->{prependdir}' to state|directory"); 397$state->{directory} =$state->{prependdir} .$state->{directory} 398} 399$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 400} 401 402# Entry entry-line \n 403# Response expected: no. Tell the server what version of a file is on the 404# local machine. The name in entry-line is a name relative to the directory 405# most recently specified with Directory. If the user is operating on only 406# some files in a directory, Entry requests for only those files need be 407# included. If an Entry request is sent without Modified, Is-modified, or 408# Unchanged, it means the file is lost (does not exist in the working 409# directory). If both Entry and one of Modified, Is-modified, or Unchanged 410# are sent for the same file, Entry must be sent first. For a given file, 411# one can send Modified, Is-modified, or Unchanged, but not more than one 412# of these three. 413sub req_Entry 414{ 415my($cmd,$data) =@_; 416 417#$log->debug("req_Entry : $data"); 418 419my@data=split(/\//,$data); 420 421$state->{entries}{$state->{directory}.$data[1]} = { 422 revision =>$data[2], 423 conflict =>$data[3], 424 options =>$data[4], 425 tag_or_date =>$data[5], 426}; 427 428$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 429} 430 431# Questionable filename \n 432# Response expected: no. Additional data: no. Tell the server to check 433# whether filename should be ignored, and if not, next time the server 434# sends responses, send (in a M response) `?' followed by the directory and 435# filename. filename must not contain `/'; it needs to be a file in the 436# directory named by the most recent Directory request. 437sub req_Questionable 438{ 439my($cmd,$data) =@_; 440 441$log->debug("req_Questionable :$data"); 442$state->{entries}{$state->{directory}.$data}{questionable} =1; 443} 444 445# add \n 446# Response expected: yes. Add a file or directory. This uses any previous 447# Argument, Directory, Entry, or Modified requests, if they have been sent. 448# The last Directory sent specifies the working directory at the time of 449# the operation. To add a directory, send the directory to be added using 450# Directory and Argument requests. 451sub req_add 452{ 453my($cmd,$data) =@_; 454 455 argsplit("add"); 456 457my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 458$updater->update(); 459 460 argsfromdir($updater); 461 462my$addcount=0; 463 464foreachmy$filename( @{$state->{args}} ) 465{ 466$filename= filecleanup($filename); 467 468my$meta=$updater->getmeta($filename); 469my$wrev= revparse($filename); 470 471if($wrev&&$meta&& ($wrev<0)) 472{ 473# previously removed file, add back 474$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 475 476print"MT +updated\n"; 477print"MT text U\n"; 478print"MT fname$filename\n"; 479print"MT newline\n"; 480print"MT -updated\n"; 481 482unless($state->{globaloptions}{-n} ) 483{ 484my($filepart,$dirpart) = filenamesplit($filename,1); 485 486print"Created$dirpart\n"; 487print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 488 489# this is an "entries" line 490my$kopts= kopts_from_path($filepart); 491$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 492print"/$filepart/1.$meta->{revision}//$kopts/\n"; 493# permissions 494$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 495print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 496# transmit file 497 transmitfile($meta->{filehash}); 498} 499 500next; 501} 502 503unless(defined($state->{entries}{$filename}{modified_filename} ) ) 504{ 505print"E cvs add: nothing known about `$filename'\n"; 506next; 507} 508# TODO : check we're not squashing an already existing file 509if(defined($state->{entries}{$filename}{revision} ) ) 510{ 511print"E cvs add: `$filename' has already been entered\n"; 512next; 513} 514 515my($filepart,$dirpart) = filenamesplit($filename,1); 516 517print"E cvs add: scheduling file `$filename' for addition\n"; 518 519print"Checked-in$dirpart\n"; 520print"$filename\n"; 521my$kopts= kopts_from_path($filepart); 522print"/$filepart/0//$kopts/\n"; 523 524$addcount++; 525} 526 527if($addcount==1) 528{ 529print"E cvs add: use `cvs commit' to add this file permanently\n"; 530} 531elsif($addcount>1) 532{ 533print"E cvs add: use `cvs commit' to add these files permanently\n"; 534} 535 536print"ok\n"; 537} 538 539# remove \n 540# Response expected: yes. Remove a file. This uses any previous Argument, 541# Directory, Entry, or Modified requests, if they have been sent. The last 542# Directory sent specifies the working directory at the time of the 543# operation. Note that this request does not actually do anything to the 544# repository; the only effect of a successful remove request is to supply 545# the client with a new entries line containing `-' to indicate a removed 546# file. In fact, the client probably could perform this operation without 547# contacting the server, although using remove may cause the server to 548# perform a few more checks. The client sends a subsequent ci request to 549# actually record the removal in the repository. 550sub req_remove 551{ 552my($cmd,$data) =@_; 553 554 argsplit("remove"); 555 556# Grab a handle to the SQLite db and do any necessary updates 557my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 558$updater->update(); 559 560#$log->debug("add state : " . Dumper($state)); 561 562my$rmcount=0; 563 564foreachmy$filename( @{$state->{args}} ) 565{ 566$filename= filecleanup($filename); 567 568if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 569{ 570print"E cvs remove: file `$filename' still in working directory\n"; 571next; 572} 573 574my$meta=$updater->getmeta($filename); 575my$wrev= revparse($filename); 576 577unless(defined($wrev) ) 578{ 579print"E cvs remove: nothing known about `$filename'\n"; 580next; 581} 582 583if(defined($wrev)and$wrev<0) 584{ 585print"E cvs remove: file `$filename' already scheduled for removal\n"; 586next; 587} 588 589unless($wrev==$meta->{revision} ) 590{ 591# TODO : not sure if the format of this message is quite correct. 592print"E cvs remove: Up to date check failed for `$filename'\n"; 593next; 594} 595 596 597my($filepart,$dirpart) = filenamesplit($filename,1); 598 599print"E cvs remove: scheduling `$filename' for removal\n"; 600 601print"Checked-in$dirpart\n"; 602print"$filename\n"; 603my$kopts= kopts_from_path($filepart); 604print"/$filepart/-1.$wrev//$kopts/\n"; 605 606$rmcount++; 607} 608 609if($rmcount==1) 610{ 611print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 612} 613elsif($rmcount>1) 614{ 615print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 616} 617 618print"ok\n"; 619} 620 621# Modified filename \n 622# Response expected: no. Additional data: mode, \n, file transmission. Send 623# the server a copy of one locally modified file. filename is a file within 624# the most recent directory sent with Directory; it must not contain `/'. 625# If the user is operating on only some files in a directory, only those 626# files need to be included. This can also be sent without Entry, if there 627# is no entry for the file. 628sub req_Modified 629{ 630my($cmd,$data) =@_; 631 632my$mode= <STDIN>; 633defined$mode 634or(print"E end of file reading mode for$data\n"),return; 635chomp$mode; 636my$size= <STDIN>; 637defined$size 638or(print"E end of file reading size of$data\n"),return; 639chomp$size; 640 641# Grab config information 642my$blocksize=8192; 643my$bytesleft=$size; 644my$tmp; 645 646# Get a filehandle/name to write it to 647my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 648 649# Loop over file data writing out to temporary file. 650while($bytesleft) 651{ 652$blocksize=$bytesleftif($bytesleft<$blocksize); 653read STDIN,$tmp,$blocksize; 654print$fh $tmp; 655$bytesleft-=$blocksize; 656} 657 658close$fh 659or(print"E failed to write temporary,$filename:$!\n"),return; 660 661# Ensure we have something sensible for the file mode 662if($mode=~/u=(\w+)/) 663{ 664$mode=$1; 665}else{ 666$mode="rw"; 667} 668 669# Save the file data in $state 670$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 671$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 672$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 673$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 674 675 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 676} 677 678# Unchanged filename\n 679# Response expected: no. Tell the server that filename has not been 680# modified in the checked out directory. The filename is a file within the 681# most recent directory sent with Directory; it must not contain `/'. 682sub req_Unchanged 683{ 684 my ($cmd,$data) =@_; 685 686$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 687 688 #$log->debug("req_Unchanged :$data"); 689} 690 691# Argument text\n 692# Response expected: no. Save argument for use in a subsequent command. 693# Arguments accumulate until an argument-using command is given, at which 694# point they are forgotten. 695# Argumentx text\n 696# Response expected: no. Append\nfollowed by text to the current argument 697# being saved. 698sub req_Argument 699{ 700 my ($cmd,$data) =@_; 701 702 # Argumentx means: append to last Argument (with a newline in front) 703 704$log->debug("$cmd:$data"); 705 706 if ($cmdeq 'Argumentx') { 707 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 708 } else { 709 push @{$state->{arguments}},$data; 710 } 711} 712 713# expand-modules\n 714# Response expected: yes. Expand the modules which are specified in the 715# arguments. Returns the data in Module-expansion responses. Note that the 716# server can assume that this is checkout or export, not rtag or rdiff; the 717# latter do not access the working directory and thus have no need to 718# expand modules on the client side. Expand may not be the best word for 719# what this request does. It does not necessarily tell you all the files 720# contained in a module, for example. Basically it is a way of telling you 721# which working directories the server needs to know about in order to 722# handle a checkout of the specified modules. For example, suppose that the 723# server has a module defined by 724# aliasmodule -a 1dir 725# That is, one can check out aliasmodule and it will take 1dir in the 726# repository and check it out to 1dir in the working directory. Now suppose 727# the client already has this module checked out and is planning on using 728# the co request to update it. Without using expand-modules, the client 729# would have two bad choices: it could either send information about all 730# working directories under the current directory, which could be 731# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 732# stands for 1dir, and neglect to send information for 1dir, which would 733# lead to incorrect operation. With expand-modules, the client would first 734# ask for the module to be expanded: 735sub req_expandmodules 736{ 737 my ($cmd,$data) =@_; 738 739 argsplit(); 740 741$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 742 743 unless ( ref$state->{arguments} eq "ARRAY" ) 744 { 745 print "ok\n"; 746 return; 747 } 748 749 foreach my$module( @{$state->{arguments}} ) 750 { 751$log->debug("SEND : Module-expansion$module"); 752 print "Module-expansion$module\n"; 753 } 754 755 print "ok\n"; 756 statecleanup(); 757} 758 759# co\n 760# Response expected: yes. Get files from the repository. This uses any 761# previous Argument, Directory, Entry, or Modified requests, if they have 762# been sent. Arguments to this command are module names; the client cannot 763# know what directories they correspond to except by (1) just sending the 764# co request, and then seeing what directory names the server sends back in 765# its responses, and (2) the expand-modules request. 766sub req_co 767{ 768 my ($cmd,$data) =@_; 769 770 argsplit("co"); 771 772 my$module=$state->{args}[0]; 773 my$checkout_path=$module; 774 775 # use the user specified directory if we're given it 776$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 777 778$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 779 780$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 781 782$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 783 784# Grab a handle to the SQLite db and do any necessary updates 785my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 786$updater->update(); 787 788$checkout_path=~ s|/$||;# get rid of trailing slashes 789 790# Eclipse seems to need the Clear-sticky command 791# to prepare the 'Entries' file for the new directory. 792print"Clear-sticky$checkout_path/\n"; 793print$state->{CVSROOT} ."/$module/\n"; 794print"Clear-static-directory$checkout_path/\n"; 795print$state->{CVSROOT} ."/$module/\n"; 796print"Clear-sticky$checkout_path/\n";# yes, twice 797print$state->{CVSROOT} ."/$module/\n"; 798print"Template$checkout_path/\n"; 799print$state->{CVSROOT} ."/$module/\n"; 800print"0\n"; 801 802# instruct the client that we're checking out to $checkout_path 803print"E cvs checkout: Updating$checkout_path\n"; 804 805my%seendirs= (); 806my$lastdir=''; 807 808# recursive 809sub prepdir { 810my($dir,$repodir,$remotedir,$seendirs) =@_; 811my$parent= dirname($dir); 812$dir=~ s|/+$||; 813$repodir=~ s|/+$||; 814$remotedir=~ s|/+$||; 815$parent=~ s|/+$||; 816$log->debug("announcedir$dir,$repodir,$remotedir"); 817 818if($parenteq'.'||$parenteq'./') { 819$parent=''; 820} 821# recurse to announce unseen parents first 822if(length($parent) && !exists($seendirs->{$parent})) { 823 prepdir($parent,$repodir,$remotedir,$seendirs); 824} 825# Announce that we are going to modify at the parent level 826if($parent) { 827print"E cvs checkout: Updating$remotedir/$parent\n"; 828}else{ 829print"E cvs checkout: Updating$remotedir\n"; 830} 831print"Clear-sticky$remotedir/$parent/\n"; 832print"$repodir/$parent/\n"; 833 834print"Clear-static-directory$remotedir/$dir/\n"; 835print"$repodir/$dir/\n"; 836print"Clear-sticky$remotedir/$parent/\n";# yes, twice 837print"$repodir/$parent/\n"; 838print"Template$remotedir/$dir/\n"; 839print"$repodir/$dir/\n"; 840print"0\n"; 841 842$seendirs->{$dir} =1; 843} 844 845foreachmy$git( @{$updater->gethead} ) 846{ 847# Don't want to check out deleted files 848next if($git->{filehash}eq"deleted"); 849 850($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 851 852if(length($git->{dir}) &&$git->{dir}ne'./' 853&&$git->{dir}ne$lastdir) { 854unless(exists($seendirs{$git->{dir}})) { 855 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 856$checkout_path, \%seendirs); 857$lastdir=$git->{dir}; 858$seendirs{$git->{dir}} =1; 859} 860print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 861} 862 863# modification time of this file 864print"Mod-time$git->{modified}\n"; 865 866# print some information to the client 867if(defined($git->{dir} )and$git->{dir}ne"./") 868{ 869print"M U$checkout_path/$git->{dir}$git->{name}\n"; 870}else{ 871print"M U$checkout_path/$git->{name}\n"; 872} 873 874# instruct client we're sending a file to put in this path 875print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 876 877print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 878 879# this is an "entries" line 880my$kopts= kopts_from_path($git->{name}); 881print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 882# permissions 883print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 884 885# transmit file 886 transmitfile($git->{filehash}); 887} 888 889print"ok\n"; 890 891 statecleanup(); 892} 893 894# update \n 895# Response expected: yes. Actually do a cvs update command. This uses any 896# previous Argument, Directory, Entry, or Modified requests, if they have 897# been sent. The last Directory sent specifies the working directory at the 898# time of the operation. The -I option is not used--files which the client 899# can decide whether to ignore are not mentioned and the client sends the 900# Questionable request for others. 901sub req_update 902{ 903my($cmd,$data) =@_; 904 905$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 906 907 argsplit("update"); 908 909# 910# It may just be a client exploring the available heads/modules 911# in that case, list them as top level directories and leave it 912# at that. Eclipse uses this technique to offer you a list of 913# projects (heads in this case) to checkout. 914# 915if($state->{module}eq'') { 916my$heads_dir=$state->{CVSROOT} .'/refs/heads'; 917if(!opendir HEADS,$heads_dir) { 918print"E [server aborted]: Failed to open directory, " 919."$heads_dir:$!\nerror\n"; 920return0; 921} 922print"E cvs update: Updating .\n"; 923while(my$head=readdir(HEADS)) { 924if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 925print"E cvs update: New directory `$head'\n"; 926} 927} 928closedir HEADS; 929print"ok\n"; 930return1; 931} 932 933 934# Grab a handle to the SQLite db and do any necessary updates 935my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 936 937$updater->update(); 938 939 argsfromdir($updater); 940 941#$log->debug("update state : " . Dumper($state)); 942 943# foreach file specified on the command line ... 944foreachmy$filename( @{$state->{args}} ) 945{ 946$filename= filecleanup($filename); 947 948$log->debug("Processing file$filename"); 949 950# if we have a -C we should pretend we never saw modified stuff 951if(exists($state->{opt}{C} ) ) 952{ 953delete$state->{entries}{$filename}{modified_hash}; 954delete$state->{entries}{$filename}{modified_filename}; 955$state->{entries}{$filename}{unchanged} =1; 956} 957 958my$meta; 959if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 960{ 961$meta=$updater->getmeta($filename,$1); 962}else{ 963$meta=$updater->getmeta($filename); 964} 965 966if( !defined$meta) 967{ 968$meta= { 969 name =>$filename, 970 revision =>0, 971 filehash =>'added' 972}; 973} 974 975my$oldmeta=$meta; 976 977my$wrev= revparse($filename); 978 979# If the working copy is an old revision, lets get that version too for comparison. 980if(defined($wrev)and$wrev!=$meta->{revision} ) 981{ 982$oldmeta=$updater->getmeta($filename,$wrev); 983} 984 985#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 986 987# Files are up to date if the working copy and repo copy have the same revision, 988# and the working copy is unmodified _and_ the user hasn't specified -C 989next if(defined($wrev) 990and defined($meta->{revision}) 991and$wrev==$meta->{revision} 992and$state->{entries}{$filename}{unchanged} 993and not exists($state->{opt}{C} ) ); 994 995# If the working copy and repo copy have the same revision, 996# but the working copy is modified, tell the client it's modified 997if(defined($wrev) 998and defined($meta->{revision}) 999and$wrev==$meta->{revision}1000and defined($state->{entries}{$filename}{modified_hash})1001and not exists($state->{opt}{C} ) )1002{1003$log->info("Tell the client the file is modified");1004print"MT text M\n";1005print"MT fname$filename\n";1006print"MT newline\n";1007next;1008}10091010if($meta->{filehash}eq"deleted")1011{1012my($filepart,$dirpart) = filenamesplit($filename,1);10131014$log->info("Removing '$filename' from working copy (no longer in the repo)");10151016print"E cvs update: `$filename' is no longer in the repository\n";1017# Don't want to actually _DO_ the update if -n specified1018unless($state->{globaloptions}{-n} ) {1019print"Removed$dirpart\n";1020print"$filepart\n";1021}1022}1023elsif(not defined($state->{entries}{$filename}{modified_hash} )1024or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1025or$meta->{filehash}eq'added')1026{1027# normal update, just send the new revision (either U=Update,1028# or A=Add, or R=Remove)1029if(defined($wrev) &&$wrev<0)1030{1031$log->info("Tell the client the file is scheduled for removal");1032print"MT text R\n";1033print"MT fname$filename\n";1034print"MT newline\n";1035next;1036}1037elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1038{1039$log->info("Tell the client the file is scheduled for addition");1040print"MT text A\n";1041print"MT fname$filename\n";1042print"MT newline\n";1043next;10441045}1046else{1047$log->info("Updating '$filename' to ".$meta->{revision});1048print"MT +updated\n";1049print"MT text U\n";1050print"MT fname$filename\n";1051print"MT newline\n";1052print"MT -updated\n";1053}10541055my($filepart,$dirpart) = filenamesplit($filename,1);10561057# Don't want to actually _DO_ the update if -n specified1058unless($state->{globaloptions}{-n} )1059{1060if(defined($wrev) )1061{1062# instruct client we're sending a file to put in this path as a replacement1063print"Update-existing$dirpart\n";1064$log->debug("Updating existing file 'Update-existing$dirpart'");1065}else{1066# instruct client we're sending a file to put in this path as a new file1067print"Clear-static-directory$dirpart\n";1068print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1069print"Clear-sticky$dirpart\n";1070print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";10711072$log->debug("Creating new file 'Created$dirpart'");1073print"Created$dirpart\n";1074}1075print$state->{CVSROOT} ."/$state->{module}/$filename\n";10761077# this is an "entries" line1078my$kopts= kopts_from_path($filepart);1079$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1080print"/$filepart/1.$meta->{revision}//$kopts/\n";10811082# permissions1083$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1084print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10851086# transmit file1087 transmitfile($meta->{filehash});1088}1089}else{1090$log->info("Updating '$filename'");1091my($filepart,$dirpart) = filenamesplit($meta->{name},1);10921093my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/";10941095chdir$dir;1096my$file_local=$filepart.".mine";1097system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1098my$file_old=$filepart.".".$oldmeta->{revision};1099 transmitfile($oldmeta->{filehash},$file_old);1100my$file_new=$filepart.".".$meta->{revision};1101 transmitfile($meta->{filehash},$file_new);11021103# we need to merge with the local changes ( M=successful merge, C=conflict merge )1104$log->info("Merging$file_local,$file_old,$file_new");1105print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11061107$log->debug("Temporary directory for merge is$dir");11081109my$return=system("git","merge-file",$file_local,$file_old,$file_new);1110$return>>=8;11111112if($return==0)1113{1114$log->info("Merged successfully");1115print"M M$filename\n";1116$log->debug("Merged$dirpart");11171118# Don't want to actually _DO_ the update if -n specified1119unless($state->{globaloptions}{-n} )1120{1121print"Merged$dirpart\n";1122$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1123print$state->{CVSROOT} ."/$state->{module}/$filename\n";1124my$kopts= kopts_from_path($filepart);1125$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1126print"/$filepart/1.$meta->{revision}//$kopts/\n";1127}1128}1129elsif($return==1)1130{1131$log->info("Merged with conflicts");1132print"E cvs update: conflicts found in$filename\n";1133print"M C$filename\n";11341135# Don't want to actually _DO_ the update if -n specified1136unless($state->{globaloptions}{-n} )1137{1138print"Merged$dirpart\n";1139print$state->{CVSROOT} ."/$state->{module}/$filename\n";1140my$kopts= kopts_from_path($filepart);1141print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1142}1143}1144else1145{1146$log->warn("Merge failed");1147next;1148}11491150# Don't want to actually _DO_ the update if -n specified1151unless($state->{globaloptions}{-n} )1152{1153# permissions1154$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1155print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11561157# transmit file, format is single integer on a line by itself (file1158# size) followed by the file contents1159# TODO : we should copy files in blocks1160my$data=`cat$file_local`;1161$log->debug("File size : " . length($data));1162 print length($data) . "\n";1163 print$data;1164 }11651166 chdir "/";1167 }11681169 }11701171 print "ok\n";1172}11731174sub req_ci1175{1176 my ($cmd,$data) =@_;11771178 argsplit("ci");11791180 #$log->debug("State : " . Dumper($state));11811182$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));11831184 if ($state->{method} eq 'pserver')1185 {1186 print "error 1 pserver access cannot commit\n";1187 exit;1188 }11891190 if ( -e$state->{CVSROOT} . "/index" )1191 {1192$log->warn("file 'index' already exists in the git repository");1193 print "error 1 Index already exists in git repo\n";1194 exit;1195 }11961197 # Grab a handle to the SQLite db and do any necessary updates1198 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1199$updater->update();12001201 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1202 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1203$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");12041205$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1206$ENV{GIT_WORK_TREE} = ".";1207$ENV{GIT_INDEX_FILE} =$file_index;12081209 # Remember where the head was at the beginning.1210 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1211 chomp$parenthash;1212 if ($parenthash!~ /^[0-9a-f]{40}$/) {1213 print "error 1 pserver cannot find the current HEAD of module";1214 exit;1215 }12161217 chdir$tmpdir;12181219 # populate the temporary index1220 system("git-read-tree",$parenthash);1221 unless ($?== 0)1222 {1223 die "Error running git-read-tree$state->{module}$file_index$!";1224 }1225$log->info("Created index '$file_index' for head$state->{module} - exit status$?");12261227 my@committedfiles= ();1228 my%oldmeta;12291230 # foreach file specified on the command line ...1231 foreach my$filename( @{$state->{args}} )1232 {1233 my$committedfile=$filename;1234$filename= filecleanup($filename);12351236 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12371238 my$meta=$updater->getmeta($filename);1239$oldmeta{$filename} =$meta;12401241 my$wrev= revparse($filename);12421243 my ($filepart,$dirpart) = filenamesplit($filename);12441245 # do a checkout of the file if it is part of this tree1246 if ($wrev) {1247 system('git-checkout-index', '-f', '-u',$filename);1248 unless ($?== 0) {1249 die "Error running git-checkout-index -f -u$filename:$!";1250 }1251 }12521253 my$addflag= 0;1254 my$rmflag= 0;1255$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1256$addflag= 1 unless ( -e$filename);12571258 # Do up to date checking1259 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1260 {1261 # fail everything if an up to date check fails1262 print "error 1 Up to date check failed for$filename\n";1263 chdir "/";1264 exit;1265 }12661267 push@committedfiles,$committedfile;1268$log->info("Committing$filename");12691270 system("mkdir","-p",$dirpart) unless ( -d$dirpart);12711272 unless ($rmflag)1273 {1274$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1275 rename$state->{entries}{$filename}{modified_filename},$filename;12761277 # Calculate modes to remove1278 my$invmode= "";1279 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }12801281$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1282 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1283 }12841285 if ($rmflag)1286 {1287$log->info("Removing file '$filename'");1288 unlink($filename);1289 system("git-update-index", "--remove",$filename);1290 }1291 elsif ($addflag)1292 {1293$log->info("Adding file '$filename'");1294 system("git-update-index", "--add",$filename);1295 } else {1296$log->info("Updating file '$filename'");1297 system("git-update-index",$filename);1298 }1299 }13001301 unless ( scalar(@committedfiles) > 0 )1302 {1303 print "E No files to commit\n";1304 print "ok\n";1305 chdir "/";1306 return;1307 }13081309 my$treehash= `git-write-tree`;1310 chomp$treehash;13111312$log->debug("Treehash :$treehash, Parenthash :$parenthash");13131314 # write our commit message out if we have one ...1315 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1316 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1317 print$msg_fh"\n\nvia git-CVS emulator\n";1318 close$msg_fh;13191320 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1321chomp($commithash);1322$log->info("Commit hash :$commithash");13231324unless($commithash=~/[a-zA-Z0-9]{40}/)1325{1326$log->warn("Commit failed (Invalid commit hash)");1327print"error 1 Commit failed (unknown reason)\n";1328chdir"/";1329exit;1330}13311332### Emulate git-receive-pack by running hooks/update1333my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1334$parenthash,$commithash);1335if( -x $hook[0] ) {1336unless(system(@hook) ==0)1337{1338$log->warn("Commit failed (update hook declined to update ref)");1339print"error 1 Commit failed (update hook declined)\n";1340chdir"/";1341exit;1342}1343}13441345### Update the ref1346if(system(qw(git update-ref -m),"cvsserver ci",1347"refs/heads/$state->{module}",$commithash,$parenthash)) {1348$log->warn("update-ref for$state->{module} failed.");1349print"error 1 Cannot commit -- update first\n";1350exit;1351}13521353### Emulate git-receive-pack by running hooks/post-receive1354my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1355if( -x $hook) {1356open(my$pipe,"|$hook") ||die"can't fork$!";13571358local$SIG{PIPE} =sub{die'pipe broke'};13591360print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";13611362close$pipe||die"bad pipe:$!$?";1363}13641365### Then hooks/post-update1366$hook=$ENV{GIT_DIR}.'hooks/post-update';1367if(-x $hook) {1368system($hook,"refs/heads/$state->{module}");1369}13701371$updater->update();13721373# foreach file specified on the command line ...1374foreachmy$filename(@committedfiles)1375{1376$filename= filecleanup($filename);13771378my$meta=$updater->getmeta($filename);1379unless(defined$meta->{revision}) {1380$meta->{revision} =1;1381}13821383my($filepart,$dirpart) = filenamesplit($filename,1);13841385$log->debug("Checked-in$dirpart:$filename");13861387print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1388if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1389{1390print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1391print"Remove-entry$dirpart\n";1392print"$filename\n";1393}else{1394if($meta->{revision} ==1) {1395print"M initial revision: 1.1\n";1396}else{1397print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1398}1399print"Checked-in$dirpart\n";1400print"$filename\n";1401my$kopts= kopts_from_path($filepart);1402print"/$filepart/1.$meta->{revision}//$kopts/\n";1403}1404}14051406chdir"/";1407print"ok\n";1408}14091410sub req_status1411{1412my($cmd,$data) =@_;14131414 argsplit("status");14151416$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1417#$log->debug("status state : " . Dumper($state));14181419# Grab a handle to the SQLite db and do any necessary updates1420my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1421$updater->update();14221423# if no files were specified, we need to work out what files we should be providing status on ...1424 argsfromdir($updater);14251426# foreach file specified on the command line ...1427foreachmy$filename( @{$state->{args}} )1428{1429$filename= filecleanup($filename);14301431my$meta=$updater->getmeta($filename);1432my$oldmeta=$meta;14331434my$wrev= revparse($filename);14351436# If the working copy is an old revision, lets get that version too for comparison.1437if(defined($wrev)and$wrev!=$meta->{revision} )1438{1439$oldmeta=$updater->getmeta($filename,$wrev);1440}14411442# TODO : All possible statuses aren't yet implemented1443my$status;1444# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1445$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1446and1447( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1448or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1449);14501451# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1452$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1453and1454($state->{entries}{$filename}{unchanged}1455or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1456);14571458# Need checkout if it exists in the repo but doesn't have a working copy1459$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );14601461# Locally modified if working copy and repo copy have the same revision but there are local changes1462$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );14631464# Needs Merge if working copy revision is less than repo copy and there are local changes1465$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );14661467$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1468$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1469$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1470$status||="File had conflicts on merge"if(0);14711472$status||="Unknown";14731474my($filepart) = filenamesplit($filename);14751476print"M ===================================================================\n";1477print"M File:$filepart\tStatus:$status\n";1478if(defined($state->{entries}{$filename}{revision}) )1479{1480print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1481}else{1482print"M Working revision:\tNo entry for$filename\n";1483}1484if(defined($meta->{revision}) )1485{1486print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1487print"M Sticky Tag:\t\t(none)\n";1488print"M Sticky Date:\t\t(none)\n";1489print"M Sticky Options:\t\t(none)\n";1490}else{1491print"M Repository revision:\tNo revision control file\n";1492}1493print"M\n";1494}14951496print"ok\n";1497}14981499sub req_diff1500{1501my($cmd,$data) =@_;15021503 argsplit("diff");15041505$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1506#$log->debug("status state : " . Dumper($state));15071508my($revision1,$revision2);1509if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1510{1511$revision1=$state->{opt}{r}[0];1512$revision2=$state->{opt}{r}[1];1513}else{1514$revision1=$state->{opt}{r};1515}15161517$revision1=~s/^1\.//if(defined($revision1) );1518$revision2=~s/^1\.//if(defined($revision2) );15191520$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15211522# Grab a handle to the SQLite db and do any necessary updates1523my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1524$updater->update();15251526# if no files were specified, we need to work out what files we should be providing status on ...1527 argsfromdir($updater);15281529# foreach file specified on the command line ...1530foreachmy$filename( @{$state->{args}} )1531{1532$filename= filecleanup($filename);15331534my($fh,$file1,$file2,$meta1,$meta2,$filediff);15351536my$wrev= revparse($filename);15371538# We need _something_ to diff against1539next unless(defined($wrev) );15401541# if we have a -r switch, use it1542if(defined($revision1) )1543{1544(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1545$meta1=$updater->getmeta($filename,$revision1);1546unless(defined($meta1)and$meta1->{filehash}ne"deleted")1547{1548print"E File$filenameat revision 1.$revision1doesn't exist\n";1549next;1550}1551 transmitfile($meta1->{filehash},$file1);1552}1553# otherwise we just use the working copy revision1554else1555{1556(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1557$meta1=$updater->getmeta($filename,$wrev);1558 transmitfile($meta1->{filehash},$file1);1559}15601561# if we have a second -r switch, use it too1562if(defined($revision2) )1563{1564(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1565$meta2=$updater->getmeta($filename,$revision2);15661567unless(defined($meta2)and$meta2->{filehash}ne"deleted")1568{1569print"E File$filenameat revision 1.$revision2doesn't exist\n";1570next;1571}15721573 transmitfile($meta2->{filehash},$file2);1574}1575# otherwise we just use the working copy1576else1577{1578$file2=$state->{entries}{$filename}{modified_filename};1579}15801581# if we have been given -r, and we don't have a $file2 yet, lets get one1582if(defined($revision1)and not defined($file2) )1583{1584(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1585$meta2=$updater->getmeta($filename,$wrev);1586 transmitfile($meta2->{filehash},$file2);1587}15881589# We need to have retrieved something useful1590next unless(defined($meta1) );15911592# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1593next if(not defined($meta2)and$wrev==$meta1->{revision}1594and1595( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1596or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1597);15981599# Apparently we only show diffs for locally modified files1600next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16011602print"M Index:$filename\n";1603print"M ===================================================================\n";1604print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1605print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1606print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1607print"M diff ";1608foreachmy$opt(keys%{$state->{opt}} )1609{1610if(ref$state->{opt}{$opt}eq"ARRAY")1611{1612foreachmy$value( @{$state->{opt}{$opt}} )1613{1614print"-$opt$value";1615}1616}else{1617print"-$opt";1618print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1619}1620}1621print"$filename\n";16221623$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16241625($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16261627if(exists$state->{opt}{u} )1628{1629system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1630}else{1631system("diff$file1$file2>$filediff");1632}16331634while( <$fh> )1635{1636print"M$_";1637}1638close$fh;1639}16401641print"ok\n";1642}16431644sub req_log1645{1646my($cmd,$data) =@_;16471648 argsplit("log");16491650$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1651#$log->debug("log state : " . Dumper($state));16521653my($minrev,$maxrev);1654if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1655{1656my$control=$2;1657$minrev=$1;1658$maxrev=$3;1659$minrev=~s/^1\.//if(defined($minrev) );1660$maxrev=~s/^1\.//if(defined($maxrev) );1661$minrev++if(defined($minrev)and$controleq"::");1662}16631664# Grab a handle to the SQLite db and do any necessary updates1665my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1666$updater->update();16671668# if no files were specified, we need to work out what files we should be providing status on ...1669 argsfromdir($updater);16701671# foreach file specified on the command line ...1672foreachmy$filename( @{$state->{args}} )1673{1674$filename= filecleanup($filename);16751676my$headmeta=$updater->getmeta($filename);16771678my$revisions=$updater->getlog($filename);1679my$totalrevisions=scalar(@$revisions);16801681if(defined($minrev) )1682{1683$log->debug("Removing revisions less than$minrev");1684while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1685{1686pop@$revisions;1687}1688}1689if(defined($maxrev) )1690{1691$log->debug("Removing revisions greater than$maxrev");1692while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1693{1694shift@$revisions;1695}1696}16971698next unless(scalar(@$revisions) );16991700print"M\n";1701print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1702print"M Working file:$filename\n";1703print"M head: 1.$headmeta->{revision}\n";1704print"M branch:\n";1705print"M locks: strict\n";1706print"M access list:\n";1707print"M symbolic names:\n";1708print"M keyword substitution: kv\n";1709print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1710print"M description:\n";17111712foreachmy$revision(@$revisions)1713{1714print"M ----------------------------\n";1715print"M revision 1.$revision->{revision}\n";1716# reformat the date for log output1717$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}) );1718$revision->{author} =~s/\s+.*//;1719$revision->{author} =~s/^(.{8}).*/$1/;1720print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1721my$commitmessage=$updater->commitmessage($revision->{commithash});1722$commitmessage=~s/^/M /mg;1723print$commitmessage."\n";1724}1725print"M =============================================================================\n";1726}17271728print"ok\n";1729}17301731sub req_annotate1732{1733my($cmd,$data) =@_;17341735 argsplit("annotate");17361737$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1738#$log->debug("status state : " . Dumper($state));17391740# Grab a handle to the SQLite db and do any necessary updates1741my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1742$updater->update();17431744# if no files were specified, we need to work out what files we should be providing annotate on ...1745 argsfromdir($updater);17461747# we'll need a temporary checkout dir1748my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1749my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1750$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");17511752$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1753$ENV{GIT_WORK_TREE} =".";1754$ENV{GIT_INDEX_FILE} =$file_index;17551756chdir$tmpdir;17571758# foreach file specified on the command line ...1759foreachmy$filename( @{$state->{args}} )1760{1761$filename= filecleanup($filename);17621763my$meta=$updater->getmeta($filename);17641765next unless($meta->{revision} );17661767# get all the commits that this file was in1768# in dense format -- aka skip dead revisions1769my$revisions=$updater->gethistorydense($filename);1770my$lastseenin=$revisions->[0][2];17711772# populate the temporary index based on the latest commit were we saw1773# the file -- but do it cheaply without checking out any files1774# TODO: if we got a revision from the client, use that instead1775# to look up the commithash in sqlite (still good to default to1776# the current head as we do now)1777system("git-read-tree",$lastseenin);1778unless($?==0)1779{1780print"E error running git-read-tree$lastseenin$file_index$!\n";1781return;1782}1783$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");17841785# do a checkout of the file1786system('git-checkout-index','-f','-u',$filename);1787unless($?==0) {1788print"E error running git-checkout-index -f -u$filename:$!\n";1789return;1790}17911792$log->info("Annotate$filename");17931794# Prepare a file with the commits from the linearized1795# history that annotate should know about. This prevents1796# git-jsannotate telling us about commits we are hiding1797# from the client.17981799my$a_hints="$tmpdir/.annotate_hints";1800if(!open(ANNOTATEHINTS,'>',$a_hints)) {1801print"E failed to open '$a_hints' for writing:$!\n";1802return;1803}1804for(my$i=0;$i<@$revisions;$i++)1805{1806print ANNOTATEHINTS $revisions->[$i][2];1807if($i+1<@$revisions) {# have we got a parent?1808print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1809}1810print ANNOTATEHINTS "\n";1811}18121813print ANNOTATEHINTS "\n";1814close ANNOTATEHINTS1815or(print"E failed to write$a_hints:$!\n"),return;18161817my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1818if(!open(ANNOTATE,"-|",@cmd)) {1819print"E error invoking ".join(' ',@cmd) .":$!\n";1820return;1821}1822my$metadata= {};1823print"E Annotations for$filename\n";1824print"E ***************\n";1825while( <ANNOTATE> )1826{1827if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1828{1829my$commithash=$1;1830my$data=$2;1831unless(defined($metadata->{$commithash} ) )1832{1833$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1834$metadata->{$commithash}{author} =~s/\s+.*//;1835$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1836$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1837}1838printf("M 1.%-5d (%-8s%10s):%s\n",1839$metadata->{$commithash}{revision},1840$metadata->{$commithash}{author},1841$metadata->{$commithash}{modified},1842$data1843);1844}else{1845$log->warn("Error in annotate output! LINE:$_");1846print"E Annotate error\n";1847next;1848}1849}1850close ANNOTATE;1851}18521853# done; get out of the tempdir1854chdir"/";18551856print"ok\n";18571858}18591860# This method takes the state->{arguments} array and produces two new arrays.1861# The first is $state->{args} which is everything before the '--' argument, and1862# the second is $state->{files} which is everything after it.1863sub argsplit1864{1865$state->{args} = [];1866$state->{files} = [];1867$state->{opt} = {};18681869return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");18701871my$type=shift;18721873if(defined($type) )1874{1875my$opt= {};1876$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");1877$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1878$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");1879$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1880$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1881$opt= { k =>1, m =>1}if($typeeq"add");1882$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1883$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");188418851886while(scalar( @{$state->{arguments}} ) >0)1887{1888my$arg=shift@{$state->{arguments}};18891890next if($argeq"--");1891next unless($arg=~/\S/);18921893# if the argument looks like a switch1894if($arg=~/^-(\w)(.*)/)1895{1896# if it's a switch that takes an argument1897if($opt->{$1} )1898{1899# If this switch has already been provided1900if($opt->{$1} >1and exists($state->{opt}{$1} ) )1901{1902$state->{opt}{$1} = [$state->{opt}{$1} ];1903if(length($2) >0)1904{1905push@{$state->{opt}{$1}},$2;1906}else{1907push@{$state->{opt}{$1}},shift@{$state->{arguments}};1908}1909}else{1910# if there's extra data in the arg, use that as the argument for the switch1911if(length($2) >0)1912{1913$state->{opt}{$1} =$2;1914}else{1915$state->{opt}{$1} =shift@{$state->{arguments}};1916}1917}1918}else{1919$state->{opt}{$1} =undef;1920}1921}1922else1923{1924push@{$state->{args}},$arg;1925}1926}1927}1928else1929{1930my$mode=0;19311932foreachmy$value( @{$state->{arguments}} )1933{1934if($valueeq"--")1935{1936$mode++;1937next;1938}1939push@{$state->{args}},$valueif($mode==0);1940push@{$state->{files}},$valueif($mode==1);1941}1942}1943}19441945# This method uses $state->{directory} to populate $state->{args} with a list of filenames1946sub argsfromdir1947{1948my$updater=shift;19491950$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19511952return if(scalar( @{$state->{args}} ) >1);19531954my@gethead= @{$updater->gethead};19551956# push added files1957foreachmy$file(keys%{$state->{entries}}) {1958if(exists$state->{entries}{$file}{revision} &&1959$state->{entries}{$file}{revision} ==0)1960{1961push@gethead, { name =>$file, filehash =>'added'};1962}1963}19641965if(scalar(@{$state->{args}}) ==1)1966{1967my$arg=$state->{args}[0];1968$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );19691970$log->info("Only one arg specified, checking for directory expansion on '$arg'");19711972foreachmy$file(@gethead)1973{1974next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1975next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1976push@{$state->{args}},$file->{name};1977}19781979shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1980}else{1981$log->info("Only one arg specified, populating file list automatically");19821983$state->{args} = [];19841985foreachmy$file(@gethead)1986{1987next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1988next unless($file->{name} =~s/^$state->{prependdir}//);1989push@{$state->{args}},$file->{name};1990}1991}1992}19931994# This method cleans up the $state variable after a command that uses arguments has run1995sub statecleanup1996{1997$state->{files} = [];1998$state->{args} = [];1999$state->{arguments} = [];2000$state->{entries} = {};2001}20022003sub revparse2004{2005my$filename=shift;20062007returnundefunless(defined($state->{entries}{$filename}{revision} ) );20082009return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2010return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20112012returnundef;2013}20142015# This method takes a file hash and does a CVS "file transfer" which transmits the2016# size of the file, and then the file contents.2017# If a second argument $targetfile is given, the file is instead written out to2018# a file by the name of $targetfile2019sub transmitfile2020{2021my$filehash=shift;2022my$targetfile=shift;20232024if(defined($filehash)and$filehasheq"deleted")2025{2026$log->warn("filehash is 'deleted'");2027return;2028}20292030die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20312032my$type=`git-cat-file -t$filehash`;2033 chomp$type;20342035 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20362037 my$size= `git-cat-file -s $filehash`;2038chomp$size;20392040$log->debug("transmitfile($filehash) size=$size, type=$type");20412042if(open my$fh,'-|',"git-cat-file","blob",$filehash)2043{2044if(defined($targetfile) )2045{2046open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2047print NEWFILE $_while( <$fh> );2048close NEWFILE or die("Failed to write '$targetfile':$!");2049}else{2050print"$size\n";2051printwhile( <$fh> );2052}2053close$fhor die("Couldn't close filehandle for transmitfile():$!");2054}else{2055die("Couldn't execute git-cat-file");2056}2057}20582059# This method takes a file name, and returns ( $dirpart, $filepart ) which2060# refers to the directory portion and the file portion of the filename2061# respectively2062sub filenamesplit2063{2064my$filename=shift;2065my$fixforlocaldir=shift;20662067my($filepart,$dirpart) = ($filename,".");2068($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2069$dirpart.="/";20702071if($fixforlocaldir)2072{2073$dirpart=~s/^$state->{prependdir}//;2074}20752076return($filepart,$dirpart);2077}20782079sub filecleanup2080{2081my$filename=shift;20822083returnundefunless(defined($filename));2084if($filename=~/^\// )2085{2086print"E absolute filenames '$filename' not supported by server\n";2087returnundef;2088}20892090$filename=~s/^\.\///g;2091$filename=$state->{prependdir} .$filename;2092return$filename;2093}20942095# Given a path, this function returns a string containing the kopts2096# that should go into that path's Entries line. For example, a binary2097# file should get -kb.2098sub kopts_from_path2099{2100my($path) =@_;21012102# Once it exists, the git attributes system should be used to look up2103# what attributes apply to this path.21042105# Until then, take the setting from the config file2106unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)2107{2108# Return "" to give no special treatment to any path2109return"";2110}else{2111# Alternatively, to have all files treated as if they are binary (which2112# is more like git itself), always return the "-kb" option2113return"-kb";2114}2115}21162117package GITCVS::log;21182119####2120#### Copyright The Open University UK - 2006.2121####2122#### Authors: Martyn Smith <martyn@catalyst.net.nz>2123#### Martin Langhoff <martin@catalyst.net.nz>2124####2125####21262127use strict;2128use warnings;21292130=head1 NAME21312132GITCVS::log21332134=head1 DESCRIPTION21352136This module provides very crude logging with a similar interface to2137Log::Log4perl21382139=head1 METHODS21402141=cut21422143=head2 new21442145Creates a new log object, optionally you can specify a filename here to2146indicate the file to log to. If no log file is specified, you can specify one2147later with method setfile, or indicate you no longer want logging with method2148nofile.21492150Until one of these methods is called, all log calls will buffer messages ready2151to write out.21522153=cut2154sub new2155{2156my$class=shift;2157my$filename=shift;21582159my$self= {};21602161bless$self,$class;21622163if(defined($filename) )2164{2165open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2166}21672168return$self;2169}21702171=head2 setfile21722173This methods takes a filename, and attempts to open that file as the log file.2174If successful, all buffered data is written out to the file, and any further2175logging is written directly to the file.21762177=cut2178sub setfile2179{2180my$self=shift;2181my$filename=shift;21822183if(defined($filename) )2184{2185open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2186}21872188return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");21892190while(my$line=shift@{$self->{buffer}} )2191{2192print{$self->{fh}}$line;2193}2194}21952196=head2 nofile21972198This method indicates no logging is going to be used. It flushes any entries in2199the internal buffer, and sets a flag to ensure no further data is put there.22002201=cut2202sub nofile2203{2204my$self=shift;22052206$self->{nolog} =1;22072208return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");22092210$self->{buffer} = [];2211}22122213=head2 _logopen22142215Internal method. Returns true if the log file is open, false otherwise.22162217=cut2218sub _logopen2219{2220my$self=shift;22212222return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2223return0;2224}22252226=head2 debug info warn fatal22272228These four methods are wrappers to _log. They provide the actual interface for2229logging data.22302231=cut2232sub debug {my$self=shift;$self->_log("debug",@_); }2233sub info {my$self=shift;$self->_log("info",@_); }2234subwarn{my$self=shift;$self->_log("warn",@_); }2235sub fatal {my$self=shift;$self->_log("fatal",@_); }22362237=head2 _log22382239This is an internal method called by the logging functions. It generates a2240timestamp and pushes the logged line either to file, or internal buffer.22412242=cut2243sub _log2244{2245my$self=shift;2246my$level=shift;22472248return if($self->{nolog} );22492250my@time=localtime;2251my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2252$time[5] +1900,2253$time[4] +1,2254$time[3],2255$time[2],2256$time[1],2257$time[0],2258uc$level,2259);22602261if($self->_logopen)2262{2263print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2264}else{2265push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2266}2267}22682269=head2 DESTROY22702271This method simply closes the file handle if one is open22722273=cut2274sub DESTROY2275{2276my$self=shift;22772278if($self->_logopen)2279{2280close$self->{fh};2281}2282}22832284package GITCVS::updater;22852286####2287#### Copyright The Open University UK - 2006.2288####2289#### Authors: Martyn Smith <martyn@catalyst.net.nz>2290#### Martin Langhoff <martin@catalyst.net.nz>2291####2292####22932294use strict;2295use warnings;2296use DBI;22972298=head1 METHODS22992300=cut23012302=head2 new23032304=cut2305sub new2306{2307my$class=shift;2308my$config=shift;2309my$module=shift;2310my$log=shift;23112312die"Need to specify a git repository"unless(defined($config)and-d $config);2313die"Need to specify a module"unless(defined($module) );23142315$class=ref($class) ||$class;23162317my$self= {};23182319bless$self,$class;23202321$self->{module} =$module;2322$self->{git_path} =$config."/";23232324$self->{log} =$log;23252326die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );23272328$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2329$cfg->{gitcvs}{dbdriver} ||"SQLite";2330$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2331$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2332$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2333$cfg->{gitcvs}{dbuser} ||"";2334$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2335$cfg->{gitcvs}{dbpass} ||"";2336my%mapping= ( m =>$module,2337 a =>$state->{method},2338 u =>getlogin||getpwuid($<) || $<,2339 G =>$self->{git_path},2340 g => mangle_dirname($self->{git_path}),2341);2342$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2343$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;23442345die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2346die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2347$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2348$self->{dbuser},2349$self->{dbpass});2350die"Error connecting to database\n"unlessdefined$self->{dbh};23512352$self->{tables} = {};2353foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2354{2355$self->{tables}{$table} =1;2356}23572358# Construct the revision table if required2359unless($self->{tables}{revision} )2360{2361$self->{dbh}->do("2362 CREATE TABLE revision (2363 name TEXT NOT NULL,2364 revision INTEGER NOT NULL,2365 filehash TEXT NOT NULL,2366 commithash TEXT NOT NULL,2367 author TEXT NOT NULL,2368 modified TEXT NOT NULL,2369 mode TEXT NOT NULL2370 )2371 ");2372$self->{dbh}->do("2373 CREATE INDEX revision_ix12374 ON revision (name,revision)2375 ");2376$self->{dbh}->do("2377 CREATE INDEX revision_ix22378 ON revision (name,commithash)2379 ");2380}23812382# Construct the head table if required2383unless($self->{tables}{head} )2384{2385$self->{dbh}->do("2386 CREATE TABLE head (2387 name TEXT NOT NULL,2388 revision INTEGER NOT NULL,2389 filehash TEXT NOT NULL,2390 commithash TEXT NOT NULL,2391 author TEXT NOT NULL,2392 modified TEXT NOT NULL,2393 mode TEXT NOT NULL2394 )2395 ");2396$self->{dbh}->do("2397 CREATE INDEX head_ix12398 ON head (name)2399 ");2400}24012402# Construct the properties table if required2403unless($self->{tables}{properties} )2404{2405$self->{dbh}->do("2406 CREATE TABLE properties (2407 key TEXT NOT NULL PRIMARY KEY,2408 value TEXT2409 )2410 ");2411}24122413# Construct the commitmsgs table if required2414unless($self->{tables}{commitmsgs} )2415{2416$self->{dbh}->do("2417 CREATE TABLE commitmsgs (2418 key TEXT NOT NULL PRIMARY KEY,2419 value TEXT2420 )2421 ");2422}24232424return$self;2425}24262427=head2 update24282429=cut2430sub update2431{2432my$self=shift;24332434# first lets get the commit list2435$ENV{GIT_DIR} =$self->{git_path};24362437my$commitsha1=`git rev-parse$self->{module}`;2438chomp$commitsha1;24392440my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2441unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2442{2443die("Invalid module '$self->{module}'");2444}244524462447my$git_log;2448my$lastcommit=$self->_get_prop("last_commit");24492450if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2451return1;2452}24532454# Start exclusive lock here...2455$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";24562457# TODO: log processing is memory bound2458# if we can parse into a 2nd file that is in reverse order2459# we can probably do something really efficient2460my@git_log_params= ('--pretty','--parents','--topo-order');24612462if(defined$lastcommit) {2463push@git_log_params,"$lastcommit..$self->{module}";2464}else{2465push@git_log_params,$self->{module};2466}2467# git-rev-list is the backend / plumbing version of git-log2468open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";24692470my@commits;24712472my%commit= ();24732474while( <GITLOG> )2475{2476chomp;2477if(m/^commit\s+(.*)$/) {2478# on ^commit lines put the just seen commit in the stack2479# and prime things for the next one2480if(keys%commit) {2481my%copy=%commit;2482unshift@commits, \%copy;2483%commit= ();2484}2485my@parents=split(m/\s+/,$1);2486$commit{hash} =shift@parents;2487$commit{parents} = \@parents;2488}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2489# on rfc822-like lines seen before we see any message,2490# lowercase the entry and put it in the hash as key-value2491$commit{lc($1)} =$2;2492}else{2493# message lines - skip initial empty line2494# and trim whitespace2495if(!exists($commit{message}) &&m/^\s*$/) {2496# define it to mark the end of headers2497$commit{message} ='';2498next;2499}2500s/^\s+//;s/\s+$//;# trim ws2501$commit{message} .=$_."\n";2502}2503}2504close GITLOG;25052506unshift@commits, \%commitif(keys%commit);25072508# Now all the commits are in the @commits bucket2509# ordered by time DESC. for each commit that needs processing,2510# determine whether it's following the last head we've seen or if2511# it's on its own branch, grab a file list, and add whatever's changed2512# NOTE: $lastcommit refers to the last commit from previous run2513# $lastpicked is the last commit we picked in this run2514my$lastpicked;2515my$head= {};2516if(defined$lastcommit) {2517$lastpicked=$lastcommit;2518}25192520my$committotal=scalar(@commits);2521my$commitcount=0;25222523# Load the head table into $head (for cached lookups during the update process)2524foreachmy$file( @{$self->gethead()} )2525{2526$head->{$file->{name}} =$file;2527}25282529foreachmy$commit(@commits)2530{2531$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2532if(defined$lastpicked)2533{2534if(!in_array($lastpicked, @{$commit->{parents}}))2535{2536# skip, we'll see this delta2537# as part of a merge later2538# warn "skipping off-track $commit->{hash}\n";2539next;2540}elsif(@{$commit->{parents}} >1) {2541# it is a merge commit, for each parent that is2542# not $lastpicked, see if we can get a log2543# from the merge-base to that parent to put it2544# in the message as a merge summary.2545my@parents= @{$commit->{parents}};2546foreachmy$parent(@parents) {2547# git-merge-base can potentially (but rarely) throw2548# several candidate merge bases. let's assume2549# that the first one is the best one.2550if($parenteq$lastpicked) {2551next;2552}2553my$base=eval{2554 safe_pipe_capture('git-merge-base',2555$lastpicked,$parent);2556};2557# The two branches may not be related at all,2558# in which case merge base simply fails to find2559# any, but that's Ok.2560next if($@);25612562chomp$base;2563if($base) {2564my@merged;2565# print "want to log between $base $parent \n";2566open(GITLOG,'-|','git-log','--pretty=medium',"$base..$parent")2567or die"Cannot call git-log:$!";2568my$mergedhash;2569while(<GITLOG>) {2570chomp;2571if(!defined$mergedhash) {2572if(m/^commit\s+(.+)$/) {2573$mergedhash=$1;2574}else{2575next;2576}2577}else{2578# grab the first line that looks non-rfc8222579# aka has content after leading space2580if(m/^\s+(\S.*)$/) {2581my$title=$1;2582$title=substr($title,0,100);# truncate2583unshift@merged,"$mergedhash$title";2584undef$mergedhash;2585}2586}2587}2588close GITLOG;2589if(@merged) {2590$commit->{mergemsg} =$commit->{message};2591$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2592foreachmy$summary(@merged) {2593$commit->{mergemsg} .="\t$summary\n";2594}2595$commit->{mergemsg} .="\n\n";2596# print "Message for $commit->{hash} \n$commit->{mergemsg}";2597}2598}2599}2600}2601}26022603# convert the date to CVS-happy format2604$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);26052606if(defined($lastpicked) )2607{2608my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2609local($/) ="\0";2610while( <FILELIST> )2611{2612chomp;2613unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2614{2615die("Couldn't process git-diff-tree line :$_");2616}2617my($mode,$hash,$change) = ($1,$2,$3);2618my$name= <FILELIST>;2619chomp($name);26202621# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");26222623my$git_perms="";2624$git_perms.="r"if($mode&4);2625$git_perms.="w"if($mode&2);2626$git_perms.="x"if($mode&1);2627$git_perms="rw"if($git_permseq"");26282629if($changeeq"D")2630{2631#$log->debug("DELETE $name");2632$head->{$name} = {2633 name =>$name,2634 revision =>$head->{$name}{revision} +1,2635 filehash =>"deleted",2636 commithash =>$commit->{hash},2637 modified =>$commit->{date},2638 author =>$commit->{author},2639 mode =>$git_perms,2640};2641$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2642}2643elsif($changeeq"M")2644{2645#$log->debug("MODIFIED $name");2646$head->{$name} = {2647 name =>$name,2648 revision =>$head->{$name}{revision} +1,2649 filehash =>$hash,2650 commithash =>$commit->{hash},2651 modified =>$commit->{date},2652 author =>$commit->{author},2653 mode =>$git_perms,2654};2655$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2656}2657elsif($changeeq"A")2658{2659#$log->debug("ADDED $name");2660$head->{$name} = {2661 name =>$name,2662 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,2663 filehash =>$hash,2664 commithash =>$commit->{hash},2665 modified =>$commit->{date},2666 author =>$commit->{author},2667 mode =>$git_perms,2668};2669$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2670}2671else2672{2673$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2674die;2675}2676}2677close FILELIST;2678}else{2679# this is used to detect files removed from the repo2680my$seen_files= {};26812682my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2683local$/="\0";2684while( <FILELIST> )2685{2686chomp;2687unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2688{2689die("Couldn't process git-ls-tree line :$_");2690}26912692my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);26932694$seen_files->{$git_filename} =1;26952696my($oldhash,$oldrevision,$oldmode) = (2697$head->{$git_filename}{filehash},2698$head->{$git_filename}{revision},2699$head->{$git_filename}{mode}2700);27012702if($git_perms=~/^\d\d\d(\d)\d\d/o)2703{2704$git_perms="";2705$git_perms.="r"if($1&4);2706$git_perms.="w"if($1&2);2707$git_perms.="x"if($1&1);2708}else{2709$git_perms="rw";2710}27112712# unless the file exists with the same hash, we need to update it ...2713unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2714{2715my$newrevision= ($oldrevisionor0) +1;27162717$head->{$git_filename} = {2718 name =>$git_filename,2719 revision =>$newrevision,2720 filehash =>$git_hash,2721 commithash =>$commit->{hash},2722 modified =>$commit->{date},2723 author =>$commit->{author},2724 mode =>$git_perms,2725};272627272728$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2729}2730}2731close FILELIST;27322733# Detect deleted files2734foreachmy$file(keys%$head)2735{2736unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2737{2738$head->{$file}{revision}++;2739$head->{$file}{filehash} ="deleted";2740$head->{$file}{commithash} =$commit->{hash};2741$head->{$file}{modified} =$commit->{date};2742$head->{$file}{author} =$commit->{author};27432744$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2745}2746}2747# END : "Detect deleted files"2748}274927502751if(exists$commit->{mergemsg})2752{2753$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2754}27552756$lastpicked=$commit->{hash};27572758$self->_set_prop("last_commit",$commit->{hash});2759}27602761$self->delete_head();2762foreachmy$file(keys%$head)2763{2764$self->insert_head(2765$file,2766$head->{$file}{revision},2767$head->{$file}{filehash},2768$head->{$file}{commithash},2769$head->{$file}{modified},2770$head->{$file}{author},2771$head->{$file}{mode},2772);2773}2774# invalidate the gethead cache2775$self->{gethead_cache} =undef;277627772778# Ending exclusive lock here2779$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2780}27812782sub insert_rev2783{2784my$self=shift;2785my$name=shift;2786my$revision=shift;2787my$filehash=shift;2788my$commithash=shift;2789my$modified=shift;2790my$author=shift;2791my$mode=shift;27922793my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2794$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2795}27962797sub insert_mergelog2798{2799my$self=shift;2800my$key=shift;2801my$value=shift;28022803my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2804$insert_mergelog->execute($key,$value);2805}28062807sub delete_head2808{2809my$self=shift;28102811my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2812$delete_head->execute();2813}28142815sub insert_head2816{2817my$self=shift;2818my$name=shift;2819my$revision=shift;2820my$filehash=shift;2821my$commithash=shift;2822my$modified=shift;2823my$author=shift;2824my$mode=shift;28252826my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2827$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2828}28292830sub _headrev2831{2832my$self=shift;2833my$filename=shift;28342835my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2836$db_query->execute($filename);2837my($hash,$revision,$mode) =$db_query->fetchrow_array;28382839return($hash,$revision,$mode);2840}28412842sub _get_prop2843{2844my$self=shift;2845my$key=shift;28462847my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2848$db_query->execute($key);2849my($value) =$db_query->fetchrow_array;28502851return$value;2852}28532854sub _set_prop2855{2856my$self=shift;2857my$key=shift;2858my$value=shift;28592860my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2861$db_query->execute($value,$key);28622863unless($db_query->rows)2864{2865$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2866$db_query->execute($key,$value);2867}28682869return$value;2870}28712872=head2 gethead28732874=cut28752876sub gethead2877{2878my$self=shift;28792880return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );28812882my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2883$db_query->execute();28842885my$tree= [];2886while(my$file=$db_query->fetchrow_hashref)2887{2888push@$tree,$file;2889}28902891$self->{gethead_cache} =$tree;28922893return$tree;2894}28952896=head2 getlog28972898=cut28992900sub getlog2901{2902my$self=shift;2903my$filename=shift;29042905my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2906$db_query->execute($filename);29072908my$tree= [];2909while(my$file=$db_query->fetchrow_hashref)2910{2911push@$tree,$file;2912}29132914return$tree;2915}29162917=head2 getmeta29182919This function takes a filename (with path) argument and returns a hashref of2920metadata for that file.29212922=cut29232924sub getmeta2925{2926my$self=shift;2927my$filename=shift;2928my$revision=shift;29292930my$db_query;2931if(defined($revision)and$revision=~/^\d+$/)2932{2933$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2934$db_query->execute($filename,$revision);2935}2936elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2937{2938$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2939$db_query->execute($filename,$revision);2940}else{2941$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2942$db_query->execute($filename);2943}29442945return$db_query->fetchrow_hashref;2946}29472948=head2 commitmessage29492950this function takes a commithash and returns the commit message for that commit29512952=cut2953sub commitmessage2954{2955my$self=shift;2956my$commithash=shift;29572958die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);29592960my$db_query;2961$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2962$db_query->execute($commithash);29632964my($message) =$db_query->fetchrow_array;29652966if(defined($message) )2967{2968$message.=" "if($message=~/\n$/);2969return$message;2970}29712972my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2973shift@lineswhile($lines[0] =~/\S/);2974$message=join("",@lines);2975$message.=" "if($message=~/\n$/);2976return$message;2977}29782979=head2 gethistory29802981This function takes a filename (with path) argument and returns an arrayofarrays2982containing revision,filehash,commithash ordered by revision descending29832984=cut2985sub gethistory2986{2987my$self=shift;2988my$filename=shift;29892990my$db_query;2991$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2992$db_query->execute($filename);29932994return$db_query->fetchall_arrayref;2995}29962997=head2 gethistorydense29982999This function takes a filename (with path) argument and returns an arrayofarrays3000containing revision,filehash,commithash ordered by revision descending.30013002This version of gethistory skips deleted entries -- so it is useful for annotate.3003The 'dense' part is a reference to a '--dense' option available for git-rev-list3004and other git tools that depend on it.30053006=cut3007sub gethistorydense3008{3009my$self=shift;3010my$filename=shift;30113012my$db_query;3013$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3014$db_query->execute($filename);30153016return$db_query->fetchall_arrayref;3017}30183019=head2 in_array()30203021from Array::PAT - mimics the in_array() function3022found in PHP. Yuck but works for small arrays.30233024=cut3025sub in_array3026{3027my($check,@array) =@_;3028my$retval=0;3029foreachmy$test(@array){3030if($checkeq$test){3031$retval=1;3032}3033}3034return$retval;3035}30363037=head2 safe_pipe_capture30383039an alternative to `command` that allows input to be passed as an array3040to work around shell problems with weird characters in arguments30413042=cut3043sub safe_pipe_capture {30443045my@output;30463047if(my$pid=open my$child,'-|') {3048@output= (<$child>);3049close$childor die join(' ',@_).":$!$?";3050}else{3051exec(@_)or die"$!$?";# exec() can fail the executable can't be found3052}3053returnwantarray?@output:join('',@output);3054}30553056=head2 mangle_dirname30573058create a string from a directory name that is suitable to use as3059part of a filename, mainly by converting all chars except \w.- to _30603061=cut3062sub mangle_dirname {3063my$dirname=shift;3064return unlessdefined$dirname;30653066$dirname=~s/[^\w.-]/_/g;30673068return$dirname;3069}307030711;