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# if we are called with a pserver argument, 134# deal with the authentication cat before entering the 135# main loop 136if($state->{method}eq'pserver') { 137my$line= <STDIN>;chomp$line; 138unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 139die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 140} 141my$request=$1; 142$line= <STDIN>;chomp$line; 143 req_Root('root',$line)# reuse Root 144or die"E Invalid root$line\n"; 145$line= <STDIN>;chomp$line; 146unless($lineeq'anonymous') { 147print"E Only anonymous user allowed via pserver\n"; 148print"I HATE YOU\n"; 149exit1; 150} 151$line= <STDIN>;chomp$line;# validate the password? 152$line= <STDIN>;chomp$line; 153unless($lineeq"END$requestREQUEST") { 154die"E Do not understand$line-- expecting END$requestREQUEST\n"; 155} 156print"I LOVE YOU\n"; 157exit if$requesteq'VERIFICATION';# cvs login 158# and now back to our regular programme... 159} 160 161# Keep going until the client closes the connection 162while(<STDIN>) 163{ 164chomp; 165 166# Check to see if we've seen this method, and call appropriate function. 167if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 168{ 169# use the $methods hash to call the appropriate sub for this command 170#$log->info("Method : $1"); 171&{$methods->{$1}}($1,$2); 172}else{ 173# log fatal because we don't understand this function. If this happens 174# we're fairly screwed because we don't know if the client is expecting 175# a response. If it is, the client will hang, we'll hang, and the whole 176# thing will be custard. 177$log->fatal("Don't understand command$_\n"); 178die("Unknown command$_"); 179} 180} 181 182$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 183$log->info("--------------- FINISH -----------------"); 184 185# Magic catchall method. 186# This is the method that will handle all commands we haven't yet 187# implemented. It simply sends a warning to the log file indicating a 188# command that hasn't been implemented has been invoked. 189sub req_CATCHALL 190{ 191my($cmd,$data) =@_; 192$log->warn("Unhandled command : req_$cmd:$data"); 193} 194 195 196# Root pathname \n 197# Response expected: no. Tell the server which CVSROOT to use. Note that 198# pathname is a local directory and not a fully qualified CVSROOT variable. 199# pathname must already exist; if creating a new root, use the init 200# request, not Root. pathname does not include the hostname of the server, 201# how to access the server, etc.; by the time the CVS protocol is in use, 202# connection, authentication, etc., are already taken care of. The Root 203# request must be sent only once, and it must be sent before any requests 204# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 205sub req_Root 206{ 207my($cmd,$data) =@_; 208$log->debug("req_Root :$data"); 209 210unless($data=~ m#^/#) { 211print"error 1 Root must be an absolute pathname\n"; 212return0; 213} 214 215my$cvsroot=$state->{'base-path'} ||''; 216$cvsroot=~ s#/+$##; 217$cvsroot.=$data; 218 219if($state->{CVSROOT} 220&& ($state->{CVSROOT}ne$cvsroot)) { 221print"error 1 Conflicting roots specified\n"; 222return0; 223} 224 225$state->{CVSROOT} =$cvsroot; 226 227$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 228 229if(@{$state->{allowed_roots}}) { 230my$allowed=0; 231foreachmy$dir(@{$state->{allowed_roots}}) { 232next unless$dir=~ m#^/#; 233$dir=~ s#/+$##; 234if($state->{'strict-paths'}) { 235if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 236$allowed=1; 237last; 238} 239}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 240$allowed=1; 241last; 242} 243} 244 245unless($allowed) { 246print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 247print"E\n"; 248print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 249return0; 250} 251} 252 253unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 254print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 255print"E\n"; 256print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 257return0; 258} 259 260my@gitvars=`git-config -l`; 261if($?) { 262print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 263print"E\n"; 264print"error 1 - problem executing git-config\n"; 265return0; 266} 267foreachmy$line(@gitvars) 268{ 269next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 270unless($2) { 271$cfg->{$1}{$3} =$4; 272}else{ 273$cfg->{$1}{$2}{$3} =$4; 274} 275} 276 277my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 278||$cfg->{gitcvs}{enabled}); 279unless($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i) { 280print"E GITCVS emulation needs to be enabled on this repo\n"; 281print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 282print"E\n"; 283print"error 1 GITCVS emulation disabled\n"; 284return0; 285} 286 287my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 288if($logfile) 289{ 290$log->setfile($logfile); 291}else{ 292$log->nofile(); 293} 294 295return1; 296} 297 298# Global_option option \n 299# Response expected: no. Transmit one of the global options `-q', `-Q', 300# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 301# variations (such as combining of options) are allowed. For graceful 302# handling of valid-requests, it is probably better to make new global 303# options separate requests, rather than trying to add them to this 304# request. 305sub req_Globaloption 306{ 307my($cmd,$data) =@_; 308$log->debug("req_Globaloption :$data"); 309$state->{globaloptions}{$data} =1; 310} 311 312# Valid-responses request-list \n 313# Response expected: no. Tell the server what responses the client will 314# accept. request-list is a space separated list of tokens. 315sub req_Validresponses 316{ 317my($cmd,$data) =@_; 318$log->debug("req_Validresponses :$data"); 319 320# TODO : re-enable this, currently it's not particularly useful 321#$state->{validresponses} = [ split /\s+/, $data ]; 322} 323 324# valid-requests \n 325# Response expected: yes. Ask the server to send back a Valid-requests 326# response. 327sub req_validrequests 328{ 329my($cmd,$data) =@_; 330 331$log->debug("req_validrequests"); 332 333$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 334$log->debug("SEND : ok"); 335 336print"Valid-requests ".join(" ",keys%$methods) ."\n"; 337print"ok\n"; 338} 339 340# Directory local-directory \n 341# Additional data: repository \n. Response expected: no. Tell the server 342# what directory to use. The repository should be a directory name from a 343# previous server response. Note that this both gives a default for Entry 344# and Modified and also for ci and the other commands; normal usage is to 345# send Directory for each directory in which there will be an Entry or 346# Modified, and then a final Directory for the original directory, then the 347# command. The local-directory is relative to the top level at which the 348# command is occurring (i.e. the last Directory which is sent before the 349# command); to indicate that top level, `.' should be sent for 350# local-directory. 351sub req_Directory 352{ 353my($cmd,$data) =@_; 354 355my$repository= <STDIN>; 356chomp$repository; 357 358 359$state->{localdir} =$data; 360$state->{repository} =$repository; 361$state->{path} =$repository; 362$state->{path} =~s/^$state->{CVSROOT}\///; 363$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 364$state->{path} .="/"if($state->{path} =~ /\S/ ); 365 366$state->{directory} =$state->{localdir}; 367$state->{directory} =""if($state->{directory}eq"."); 368$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 369 370if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 371{ 372$log->info("Setting prepend to '$state->{path}'"); 373$state->{prependdir} =$state->{path}; 374foreachmy$entry(keys%{$state->{entries}} ) 375{ 376$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 377delete$state->{entries}{$entry}; 378} 379} 380 381if(defined($state->{prependdir} ) ) 382{ 383$log->debug("Prepending '$state->{prependdir}' to state|directory"); 384$state->{directory} =$state->{prependdir} .$state->{directory} 385} 386$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 387} 388 389# Entry entry-line \n 390# Response expected: no. Tell the server what version of a file is on the 391# local machine. The name in entry-line is a name relative to the directory 392# most recently specified with Directory. If the user is operating on only 393# some files in a directory, Entry requests for only those files need be 394# included. If an Entry request is sent without Modified, Is-modified, or 395# Unchanged, it means the file is lost (does not exist in the working 396# directory). If both Entry and one of Modified, Is-modified, or Unchanged 397# are sent for the same file, Entry must be sent first. For a given file, 398# one can send Modified, Is-modified, or Unchanged, but not more than one 399# of these three. 400sub req_Entry 401{ 402my($cmd,$data) =@_; 403 404#$log->debug("req_Entry : $data"); 405 406my@data=split(/\//,$data); 407 408$state->{entries}{$state->{directory}.$data[1]} = { 409 revision =>$data[2], 410 conflict =>$data[3], 411 options =>$data[4], 412 tag_or_date =>$data[5], 413}; 414 415$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 416} 417 418# Questionable filename \n 419# Response expected: no. Additional data: no. Tell the server to check 420# whether filename should be ignored, and if not, next time the server 421# sends responses, send (in a M response) `?' followed by the directory and 422# filename. filename must not contain `/'; it needs to be a file in the 423# directory named by the most recent Directory request. 424sub req_Questionable 425{ 426my($cmd,$data) =@_; 427 428$log->debug("req_Questionable :$data"); 429$state->{entries}{$state->{directory}.$data}{questionable} =1; 430} 431 432# add \n 433# Response expected: yes. Add a file or directory. This uses any previous 434# Argument, Directory, Entry, or Modified requests, if they have been sent. 435# The last Directory sent specifies the working directory at the time of 436# the operation. To add a directory, send the directory to be added using 437# Directory and Argument requests. 438sub req_add 439{ 440my($cmd,$data) =@_; 441 442 argsplit("add"); 443 444my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 445$updater->update(); 446 447 argsfromdir($updater); 448 449my$addcount=0; 450 451foreachmy$filename( @{$state->{args}} ) 452{ 453$filename= filecleanup($filename); 454 455my$meta=$updater->getmeta($filename); 456my$wrev= revparse($filename); 457 458if($wrev&&$meta&& ($wrev<0)) 459{ 460# previously removed file, add back 461$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 462 463print"MT +updated\n"; 464print"MT text U\n"; 465print"MT fname$filename\n"; 466print"MT newline\n"; 467print"MT -updated\n"; 468 469unless($state->{globaloptions}{-n} ) 470{ 471my($filepart,$dirpart) = filenamesplit($filename,1); 472 473print"Created$dirpart\n"; 474print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 475 476# this is an "entries" line 477my$kopts= kopts_from_path($filepart); 478$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 479print"/$filepart/1.$meta->{revision}//$kopts/\n"; 480# permissions 481$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 482print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 483# transmit file 484 transmitfile($meta->{filehash}); 485} 486 487next; 488} 489 490unless(defined($state->{entries}{$filename}{modified_filename} ) ) 491{ 492print"E cvs add: nothing known about `$filename'\n"; 493next; 494} 495# TODO : check we're not squashing an already existing file 496if(defined($state->{entries}{$filename}{revision} ) ) 497{ 498print"E cvs add: `$filename' has already been entered\n"; 499next; 500} 501 502my($filepart,$dirpart) = filenamesplit($filename,1); 503 504print"E cvs add: scheduling file `$filename' for addition\n"; 505 506print"Checked-in$dirpart\n"; 507print"$filename\n"; 508my$kopts= kopts_from_path($filepart); 509print"/$filepart/0//$kopts/\n"; 510 511$addcount++; 512} 513 514if($addcount==1) 515{ 516print"E cvs add: use `cvs commit' to add this file permanently\n"; 517} 518elsif($addcount>1) 519{ 520print"E cvs add: use `cvs commit' to add these files permanently\n"; 521} 522 523print"ok\n"; 524} 525 526# remove \n 527# Response expected: yes. Remove a file. This uses any previous Argument, 528# Directory, Entry, or Modified requests, if they have been sent. The last 529# Directory sent specifies the working directory at the time of the 530# operation. Note that this request does not actually do anything to the 531# repository; the only effect of a successful remove request is to supply 532# the client with a new entries line containing `-' to indicate a removed 533# file. In fact, the client probably could perform this operation without 534# contacting the server, although using remove may cause the server to 535# perform a few more checks. The client sends a subsequent ci request to 536# actually record the removal in the repository. 537sub req_remove 538{ 539my($cmd,$data) =@_; 540 541 argsplit("remove"); 542 543# Grab a handle to the SQLite db and do any necessary updates 544my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 545$updater->update(); 546 547#$log->debug("add state : " . Dumper($state)); 548 549my$rmcount=0; 550 551foreachmy$filename( @{$state->{args}} ) 552{ 553$filename= filecleanup($filename); 554 555if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 556{ 557print"E cvs remove: file `$filename' still in working directory\n"; 558next; 559} 560 561my$meta=$updater->getmeta($filename); 562my$wrev= revparse($filename); 563 564unless(defined($wrev) ) 565{ 566print"E cvs remove: nothing known about `$filename'\n"; 567next; 568} 569 570if(defined($wrev)and$wrev<0) 571{ 572print"E cvs remove: file `$filename' already scheduled for removal\n"; 573next; 574} 575 576unless($wrev==$meta->{revision} ) 577{ 578# TODO : not sure if the format of this message is quite correct. 579print"E cvs remove: Up to date check failed for `$filename'\n"; 580next; 581} 582 583 584my($filepart,$dirpart) = filenamesplit($filename,1); 585 586print"E cvs remove: scheduling `$filename' for removal\n"; 587 588print"Checked-in$dirpart\n"; 589print"$filename\n"; 590my$kopts= kopts_from_path($filepart); 591print"/$filepart/-1.$wrev//$kopts/\n"; 592 593$rmcount++; 594} 595 596if($rmcount==1) 597{ 598print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 599} 600elsif($rmcount>1) 601{ 602print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 603} 604 605print"ok\n"; 606} 607 608# Modified filename \n 609# Response expected: no. Additional data: mode, \n, file transmission. Send 610# the server a copy of one locally modified file. filename is a file within 611# the most recent directory sent with Directory; it must not contain `/'. 612# If the user is operating on only some files in a directory, only those 613# files need to be included. This can also be sent without Entry, if there 614# is no entry for the file. 615sub req_Modified 616{ 617my($cmd,$data) =@_; 618 619my$mode= <STDIN>; 620chomp$mode; 621my$size= <STDIN>; 622chomp$size; 623 624# Grab config information 625my$blocksize=8192; 626my$bytesleft=$size; 627my$tmp; 628 629# Get a filehandle/name to write it to 630my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 631 632# Loop over file data writing out to temporary file. 633while($bytesleft) 634{ 635$blocksize=$bytesleftif($bytesleft<$blocksize); 636read STDIN,$tmp,$blocksize; 637print$fh $tmp; 638$bytesleft-=$blocksize; 639} 640 641close$fh; 642 643# Ensure we have something sensible for the file mode 644if($mode=~/u=(\w+)/) 645{ 646$mode=$1; 647}else{ 648$mode="rw"; 649} 650 651# Save the file data in $state 652$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 653$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 654$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 655$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 656 657 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 658} 659 660# Unchanged filename\n 661# Response expected: no. Tell the server that filename has not been 662# modified in the checked out directory. The filename is a file within the 663# most recent directory sent with Directory; it must not contain `/'. 664sub req_Unchanged 665{ 666 my ($cmd,$data) =@_; 667 668$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 669 670 #$log->debug("req_Unchanged :$data"); 671} 672 673# Argument text\n 674# Response expected: no. Save argument for use in a subsequent command. 675# Arguments accumulate until an argument-using command is given, at which 676# point they are forgotten. 677# Argumentx text\n 678# Response expected: no. Append\nfollowed by text to the current argument 679# being saved. 680sub req_Argument 681{ 682 my ($cmd,$data) =@_; 683 684 # Argumentx means: append to last Argument (with a newline in front) 685 686$log->debug("$cmd:$data"); 687 688 if ($cmdeq 'Argumentx') { 689 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 690 } else { 691 push @{$state->{arguments}},$data; 692 } 693} 694 695# expand-modules\n 696# Response expected: yes. Expand the modules which are specified in the 697# arguments. Returns the data in Module-expansion responses. Note that the 698# server can assume that this is checkout or export, not rtag or rdiff; the 699# latter do not access the working directory and thus have no need to 700# expand modules on the client side. Expand may not be the best word for 701# what this request does. It does not necessarily tell you all the files 702# contained in a module, for example. Basically it is a way of telling you 703# which working directories the server needs to know about in order to 704# handle a checkout of the specified modules. For example, suppose that the 705# server has a module defined by 706# aliasmodule -a 1dir 707# That is, one can check out aliasmodule and it will take 1dir in the 708# repository and check it out to 1dir in the working directory. Now suppose 709# the client already has this module checked out and is planning on using 710# the co request to update it. Without using expand-modules, the client 711# would have two bad choices: it could either send information about all 712# working directories under the current directory, which could be 713# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 714# stands for 1dir, and neglect to send information for 1dir, which would 715# lead to incorrect operation. With expand-modules, the client would first 716# ask for the module to be expanded: 717sub req_expandmodules 718{ 719 my ($cmd,$data) =@_; 720 721 argsplit(); 722 723$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 724 725 unless ( ref$state->{arguments} eq "ARRAY" ) 726 { 727 print "ok\n"; 728 return; 729 } 730 731 foreach my$module( @{$state->{arguments}} ) 732 { 733$log->debug("SEND : Module-expansion$module"); 734 print "Module-expansion$module\n"; 735 } 736 737 print "ok\n"; 738 statecleanup(); 739} 740 741# co\n 742# Response expected: yes. Get files from the repository. This uses any 743# previous Argument, Directory, Entry, or Modified requests, if they have 744# been sent. Arguments to this command are module names; the client cannot 745# know what directories they correspond to except by (1) just sending the 746# co request, and then seeing what directory names the server sends back in 747# its responses, and (2) the expand-modules request. 748sub req_co 749{ 750 my ($cmd,$data) =@_; 751 752 argsplit("co"); 753 754 my$module=$state->{args}[0]; 755 my$checkout_path=$module; 756 757 # use the user specified directory if we're given it 758$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 759 760$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 761 762$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 763 764$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 765 766# Grab a handle to the SQLite db and do any necessary updates 767my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 768$updater->update(); 769 770$checkout_path=~ s|/$||;# get rid of trailing slashes 771 772# Eclipse seems to need the Clear-sticky command 773# to prepare the 'Entries' file for the new directory. 774print"Clear-sticky$checkout_path/\n"; 775print$state->{CVSROOT} ."/$module/\n"; 776print"Clear-static-directory$checkout_path/\n"; 777print$state->{CVSROOT} ."/$module/\n"; 778print"Clear-sticky$checkout_path/\n";# yes, twice 779print$state->{CVSROOT} ."/$module/\n"; 780print"Template$checkout_path/\n"; 781print$state->{CVSROOT} ."/$module/\n"; 782print"0\n"; 783 784# instruct the client that we're checking out to $checkout_path 785print"E cvs checkout: Updating$checkout_path\n"; 786 787my%seendirs= (); 788my$lastdir=''; 789 790# recursive 791sub prepdir { 792my($dir,$repodir,$remotedir,$seendirs) =@_; 793my$parent= dirname($dir); 794$dir=~ s|/+$||; 795$repodir=~ s|/+$||; 796$remotedir=~ s|/+$||; 797$parent=~ s|/+$||; 798$log->debug("announcedir$dir,$repodir,$remotedir"); 799 800if($parenteq'.'||$parenteq'./') { 801$parent=''; 802} 803# recurse to announce unseen parents first 804if(length($parent) && !exists($seendirs->{$parent})) { 805 prepdir($parent,$repodir,$remotedir,$seendirs); 806} 807# Announce that we are going to modify at the parent level 808if($parent) { 809print"E cvs checkout: Updating$remotedir/$parent\n"; 810}else{ 811print"E cvs checkout: Updating$remotedir\n"; 812} 813print"Clear-sticky$remotedir/$parent/\n"; 814print"$repodir/$parent/\n"; 815 816print"Clear-static-directory$remotedir/$dir/\n"; 817print"$repodir/$dir/\n"; 818print"Clear-sticky$remotedir/$parent/\n";# yes, twice 819print"$repodir/$parent/\n"; 820print"Template$remotedir/$dir/\n"; 821print"$repodir/$dir/\n"; 822print"0\n"; 823 824$seendirs->{$dir} =1; 825} 826 827foreachmy$git( @{$updater->gethead} ) 828{ 829# Don't want to check out deleted files 830next if($git->{filehash}eq"deleted"); 831 832($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 833 834if(length($git->{dir}) &&$git->{dir}ne'./' 835&&$git->{dir}ne$lastdir) { 836unless(exists($seendirs{$git->{dir}})) { 837 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 838$checkout_path, \%seendirs); 839$lastdir=$git->{dir}; 840$seendirs{$git->{dir}} =1; 841} 842print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 843} 844 845# modification time of this file 846print"Mod-time$git->{modified}\n"; 847 848# print some information to the client 849if(defined($git->{dir} )and$git->{dir}ne"./") 850{ 851print"M U$checkout_path/$git->{dir}$git->{name}\n"; 852}else{ 853print"M U$checkout_path/$git->{name}\n"; 854} 855 856# instruct client we're sending a file to put in this path 857print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 858 859print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 860 861# this is an "entries" line 862my$kopts= kopts_from_path($git->{name}); 863print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 864# permissions 865print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 866 867# transmit file 868 transmitfile($git->{filehash}); 869} 870 871print"ok\n"; 872 873 statecleanup(); 874} 875 876# update \n 877# Response expected: yes. Actually do a cvs update command. This uses any 878# previous Argument, Directory, Entry, or Modified requests, if they have 879# been sent. The last Directory sent specifies the working directory at the 880# time of the operation. The -I option is not used--files which the client 881# can decide whether to ignore are not mentioned and the client sends the 882# Questionable request for others. 883sub req_update 884{ 885my($cmd,$data) =@_; 886 887$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 888 889 argsplit("update"); 890 891# 892# It may just be a client exploring the available heads/modules 893# in that case, list them as top level directories and leave it 894# at that. Eclipse uses this technique to offer you a list of 895# projects (heads in this case) to checkout. 896# 897if($state->{module}eq'') { 898print"E cvs update: Updating .\n"; 899opendir HEADS,$state->{CVSROOT} .'/refs/heads'; 900while(my$head=readdir(HEADS)) { 901if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 902print"E cvs update: New directory `$head'\n"; 903} 904} 905closedir HEADS; 906print"ok\n"; 907return1; 908} 909 910 911# Grab a handle to the SQLite db and do any necessary updates 912my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 913 914$updater->update(); 915 916 argsfromdir($updater); 917 918#$log->debug("update state : " . Dumper($state)); 919 920# foreach file specified on the command line ... 921foreachmy$filename( @{$state->{args}} ) 922{ 923$filename= filecleanup($filename); 924 925$log->debug("Processing file$filename"); 926 927# if we have a -C we should pretend we never saw modified stuff 928if(exists($state->{opt}{C} ) ) 929{ 930delete$state->{entries}{$filename}{modified_hash}; 931delete$state->{entries}{$filename}{modified_filename}; 932$state->{entries}{$filename}{unchanged} =1; 933} 934 935my$meta; 936if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 937{ 938$meta=$updater->getmeta($filename,$1); 939}else{ 940$meta=$updater->getmeta($filename); 941} 942 943if( !defined$meta) 944{ 945$meta= { 946 name =>$filename, 947 revision =>0, 948 filehash =>'added' 949}; 950} 951 952my$oldmeta=$meta; 953 954my$wrev= revparse($filename); 955 956# If the working copy is an old revision, lets get that version too for comparison. 957if(defined($wrev)and$wrev!=$meta->{revision} ) 958{ 959$oldmeta=$updater->getmeta($filename,$wrev); 960} 961 962#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 963 964# Files are up to date if the working copy and repo copy have the same revision, 965# and the working copy is unmodified _and_ the user hasn't specified -C 966next if(defined($wrev) 967and defined($meta->{revision}) 968and$wrev==$meta->{revision} 969and$state->{entries}{$filename}{unchanged} 970and not exists($state->{opt}{C} ) ); 971 972# If the working copy and repo copy have the same revision, 973# but the working copy is modified, tell the client it's modified 974if(defined($wrev) 975and defined($meta->{revision}) 976and$wrev==$meta->{revision} 977and defined($state->{entries}{$filename}{modified_hash}) 978and not exists($state->{opt}{C} ) ) 979{ 980$log->info("Tell the client the file is modified"); 981print"MT text M\n"; 982print"MT fname$filename\n"; 983print"MT newline\n"; 984next; 985} 986 987if($meta->{filehash}eq"deleted") 988{ 989my($filepart,$dirpart) = filenamesplit($filename,1); 990 991$log->info("Removing '$filename' from working copy (no longer in the repo)"); 992 993print"E cvs update: `$filename' is no longer in the repository\n"; 994# Don't want to actually _DO_ the update if -n specified 995unless($state->{globaloptions}{-n} ) { 996print"Removed$dirpart\n"; 997print"$filepart\n"; 998} 999}1000elsif(not defined($state->{entries}{$filename}{modified_hash} )1001or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1002or$meta->{filehash}eq'added')1003{1004# normal update, just send the new revision (either U=Update,1005# or A=Add, or R=Remove)1006if(defined($wrev) &&$wrev<0)1007{1008$log->info("Tell the client the file is scheduled for removal");1009print"MT text R\n";1010print"MT fname$filename\n";1011print"MT newline\n";1012next;1013}1014elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1015{1016$log->info("Tell the client the file is scheduled for addition");1017print"MT text A\n";1018print"MT fname$filename\n";1019print"MT newline\n";1020next;10211022}1023else{1024$log->info("Updating '$filename' to ".$meta->{revision});1025print"MT +updated\n";1026print"MT text U\n";1027print"MT fname$filename\n";1028print"MT newline\n";1029print"MT -updated\n";1030}10311032my($filepart,$dirpart) = filenamesplit($filename,1);10331034# Don't want to actually _DO_ the update if -n specified1035unless($state->{globaloptions}{-n} )1036{1037if(defined($wrev) )1038{1039# instruct client we're sending a file to put in this path as a replacement1040print"Update-existing$dirpart\n";1041$log->debug("Updating existing file 'Update-existing$dirpart'");1042}else{1043# instruct client we're sending a file to put in this path as a new file1044print"Clear-static-directory$dirpart\n";1045print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1046print"Clear-sticky$dirpart\n";1047print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";10481049$log->debug("Creating new file 'Created$dirpart'");1050print"Created$dirpart\n";1051}1052print$state->{CVSROOT} ."/$state->{module}/$filename\n";10531054# this is an "entries" line1055my$kopts= kopts_from_path($filepart);1056$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1057print"/$filepart/1.$meta->{revision}//$kopts/\n";10581059# permissions1060$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1061print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10621063# transmit file1064 transmitfile($meta->{filehash});1065}1066}else{1067$log->info("Updating '$filename'");1068my($filepart,$dirpart) = filenamesplit($meta->{name},1);10691070my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/";10711072chdir$dir;1073my$file_local=$filepart.".mine";1074system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1075my$file_old=$filepart.".".$oldmeta->{revision};1076 transmitfile($oldmeta->{filehash},$file_old);1077my$file_new=$filepart.".".$meta->{revision};1078 transmitfile($meta->{filehash},$file_new);10791080# we need to merge with the local changes ( M=successful merge, C=conflict merge )1081$log->info("Merging$file_local,$file_old,$file_new");1082print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";10831084$log->debug("Temporary directory for merge is$dir");10851086my$return=system("git","merge-file",$file_local,$file_old,$file_new);1087$return>>=8;10881089if($return==0)1090{1091$log->info("Merged successfully");1092print"M M$filename\n";1093$log->debug("Merged$dirpart");10941095# Don't want to actually _DO_ the update if -n specified1096unless($state->{globaloptions}{-n} )1097{1098print"Merged$dirpart\n";1099$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1100print$state->{CVSROOT} ."/$state->{module}/$filename\n";1101my$kopts= kopts_from_path($filepart);1102$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1103print"/$filepart/1.$meta->{revision}//$kopts/\n";1104}1105}1106elsif($return==1)1107{1108$log->info("Merged with conflicts");1109print"E cvs update: conflicts found in$filename\n";1110print"M C$filename\n";11111112# Don't want to actually _DO_ the update if -n specified1113unless($state->{globaloptions}{-n} )1114{1115print"Merged$dirpart\n";1116print$state->{CVSROOT} ."/$state->{module}/$filename\n";1117my$kopts= kopts_from_path($filepart);1118print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1119}1120}1121else1122{1123$log->warn("Merge failed");1124next;1125}11261127# Don't want to actually _DO_ the update if -n specified1128unless($state->{globaloptions}{-n} )1129{1130# permissions1131$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1132print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11331134# transmit file, format is single integer on a line by itself (file1135# size) followed by the file contents1136# TODO : we should copy files in blocks1137my$data=`cat$file_local`;1138$log->debug("File size : " . length($data));1139 print length($data) . "\n";1140 print$data;1141 }11421143 chdir "/";1144 }11451146 }11471148 print "ok\n";1149}11501151sub req_ci1152{1153 my ($cmd,$data) =@_;11541155 argsplit("ci");11561157 #$log->debug("State : " . Dumper($state));11581159$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));11601161 if ($state->{method} eq 'pserver')1162 {1163 print "error 1 pserver access cannot commit\n";1164 exit;1165 }11661167 if ( -e$state->{CVSROOT} . "/index" )1168 {1169$log->warn("file 'index' already exists in the git repository");1170 print "error 1 Index already exists in git repo\n";1171 exit;1172 }11731174 # Grab a handle to the SQLite db and do any necessary updates1175 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1176$updater->update();11771178 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1179 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1180$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");11811182$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1183$ENV{GIT_INDEX_FILE} =$file_index;11841185 # Remember where the head was at the beginning.1186 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1187 chomp$parenthash;1188 if ($parenthash!~ /^[0-9a-f]{40}$/) {1189 print "error 1 pserver cannot find the current HEAD of module";1190 exit;1191 }11921193 chdir$tmpdir;11941195 # populate the temporary index based1196 system("git-read-tree",$parenthash);1197 unless ($?== 0)1198 {1199 die "Error running git-read-tree$state->{module}$file_index$!";1200 }1201$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");12021203 my@committedfiles= ();1204 my%oldmeta;12051206 # foreach file specified on the command line ...1207 foreach my$filename( @{$state->{args}} )1208 {1209 my$committedfile=$filename;1210$filename= filecleanup($filename);12111212 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12131214 my$meta=$updater->getmeta($filename);1215$oldmeta{$filename} =$meta;12161217 my$wrev= revparse($filename);12181219 my ($filepart,$dirpart) = filenamesplit($filename);12201221 # do a checkout of the file if it part of this tree1222 if ($wrev) {1223 system('git-checkout-index', '-f', '-u',$filename);1224 unless ($?== 0) {1225 die "Error running git-checkout-index -f -u$filename:$!";1226 }1227 }12281229 my$addflag= 0;1230 my$rmflag= 0;1231$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1232$addflag= 1 unless ( -e$filename);12331234 # Do up to date checking1235 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1236 {1237 # fail everything if an up to date check fails1238 print "error 1 Up to date check failed for$filename\n";1239 chdir "/";1240 exit;1241 }12421243 push@committedfiles,$committedfile;1244$log->info("Committing$filename");12451246 system("mkdir","-p",$dirpart) unless ( -d$dirpart);12471248 unless ($rmflag)1249 {1250$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1251 rename$state->{entries}{$filename}{modified_filename},$filename;12521253 # Calculate modes to remove1254 my$invmode= "";1255 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }12561257$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1258 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1259 }12601261 if ($rmflag)1262 {1263$log->info("Removing file '$filename'");1264 unlink($filename);1265 system("git-update-index", "--remove",$filename);1266 }1267 elsif ($addflag)1268 {1269$log->info("Adding file '$filename'");1270 system("git-update-index", "--add",$filename);1271 } else {1272$log->info("Updating file '$filename'");1273 system("git-update-index",$filename);1274 }1275 }12761277 unless ( scalar(@committedfiles) > 0 )1278 {1279 print "E No files to commit\n";1280 print "ok\n";1281 chdir "/";1282 return;1283 }12841285 my$treehash= `git-write-tree`;1286 chomp$treehash;12871288$log->debug("Treehash :$treehash, Parenthash :$parenthash");12891290 # write our commit message out if we have one ...1291 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1292 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1293 print$msg_fh"\n\nvia git-CVS emulator\n";1294 close$msg_fh;12951296 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1297chomp($commithash);1298$log->info("Commit hash :$commithash");12991300unless($commithash=~/[a-zA-Z0-9]{40}/)1301{1302$log->warn("Commit failed (Invalid commit hash)");1303print"error 1 Commit failed (unknown reason)\n";1304chdir"/";1305exit;1306}13071308# Check that this is allowed, just as we would with a receive-pack1309my@cmd= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1310$parenthash,$commithash);1311if( -x $cmd[0] ) {1312unless(system(@cmd) ==0)1313{1314$log->warn("Commit failed (update hook declined to update ref)");1315print"error 1 Commit failed (update hook declined)\n";1316chdir"/";1317exit;1318}1319}13201321if(system(qw(git update-ref -m),"cvsserver ci",1322"refs/heads/$state->{module}",$commithash,$parenthash)) {1323$log->warn("update-ref for$state->{module} failed.");1324print"error 1 Cannot commit -- update first\n";1325exit;1326}13271328$updater->update();13291330# foreach file specified on the command line ...1331foreachmy$filename(@committedfiles)1332{1333$filename= filecleanup($filename);13341335my$meta=$updater->getmeta($filename);1336unless(defined$meta->{revision}) {1337$meta->{revision} =1;1338}13391340my($filepart,$dirpart) = filenamesplit($filename,1);13411342$log->debug("Checked-in$dirpart:$filename");13431344print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1345if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1346{1347print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1348print"Remove-entry$dirpart\n";1349print"$filename\n";1350}else{1351if($meta->{revision} ==1) {1352print"M initial revision: 1.1\n";1353}else{1354print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1355}1356print"Checked-in$dirpart\n";1357print"$filename\n";1358my$kopts= kopts_from_path($filepart);1359print"/$filepart/1.$meta->{revision}//$kopts/\n";1360}1361}13621363chdir"/";1364print"ok\n";1365}13661367sub req_status1368{1369my($cmd,$data) =@_;13701371 argsplit("status");13721373$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1374#$log->debug("status state : " . Dumper($state));13751376# Grab a handle to the SQLite db and do any necessary updates1377my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1378$updater->update();13791380# if no files were specified, we need to work out what files we should be providing status on ...1381 argsfromdir($updater);13821383# foreach file specified on the command line ...1384foreachmy$filename( @{$state->{args}} )1385{1386$filename= filecleanup($filename);13871388my$meta=$updater->getmeta($filename);1389my$oldmeta=$meta;13901391my$wrev= revparse($filename);13921393# If the working copy is an old revision, lets get that version too for comparison.1394if(defined($wrev)and$wrev!=$meta->{revision} )1395{1396$oldmeta=$updater->getmeta($filename,$wrev);1397}13981399# TODO : All possible statuses aren't yet implemented1400my$status;1401# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1402$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1403and1404( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1405or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1406);14071408# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1409$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1410and1411($state->{entries}{$filename}{unchanged}1412or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1413);14141415# Need checkout if it exists in the repo but doesn't have a working copy1416$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );14171418# Locally modified if working copy and repo copy have the same revision but there are local changes1419$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );14201421# Needs Merge if working copy revision is less than repo copy and there are local changes1422$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );14231424$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1425$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1426$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1427$status||="File had conflicts on merge"if(0);14281429$status||="Unknown";14301431print"M ===================================================================\n";1432print"M File:$filename\tStatus:$status\n";1433if(defined($state->{entries}{$filename}{revision}) )1434{1435print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1436}else{1437print"M Working revision:\tNo entry for$filename\n";1438}1439if(defined($meta->{revision}) )1440{1441print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1442print"M Sticky Tag:\t\t(none)\n";1443print"M Sticky Date:\t\t(none)\n";1444print"M Sticky Options:\t\t(none)\n";1445}else{1446print"M Repository revision:\tNo revision control file\n";1447}1448print"M\n";1449}14501451print"ok\n";1452}14531454sub req_diff1455{1456my($cmd,$data) =@_;14571458 argsplit("diff");14591460$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1461#$log->debug("status state : " . Dumper($state));14621463my($revision1,$revision2);1464if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1465{1466$revision1=$state->{opt}{r}[0];1467$revision2=$state->{opt}{r}[1];1468}else{1469$revision1=$state->{opt}{r};1470}14711472$revision1=~s/^1\.//if(defined($revision1) );1473$revision2=~s/^1\.//if(defined($revision2) );14741475$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );14761477# Grab a handle to the SQLite db and do any necessary updates1478my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1479$updater->update();14801481# if no files were specified, we need to work out what files we should be providing status on ...1482 argsfromdir($updater);14831484# foreach file specified on the command line ...1485foreachmy$filename( @{$state->{args}} )1486{1487$filename= filecleanup($filename);14881489my($fh,$file1,$file2,$meta1,$meta2,$filediff);14901491my$wrev= revparse($filename);14921493# We need _something_ to diff against1494next unless(defined($wrev) );14951496# if we have a -r switch, use it1497if(defined($revision1) )1498{1499(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1500$meta1=$updater->getmeta($filename,$revision1);1501unless(defined($meta1)and$meta1->{filehash}ne"deleted")1502{1503print"E File$filenameat revision 1.$revision1doesn't exist\n";1504next;1505}1506 transmitfile($meta1->{filehash},$file1);1507}1508# otherwise we just use the working copy revision1509else1510{1511(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1512$meta1=$updater->getmeta($filename,$wrev);1513 transmitfile($meta1->{filehash},$file1);1514}15151516# if we have a second -r switch, use it too1517if(defined($revision2) )1518{1519(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1520$meta2=$updater->getmeta($filename,$revision2);15211522unless(defined($meta2)and$meta2->{filehash}ne"deleted")1523{1524print"E File$filenameat revision 1.$revision2doesn't exist\n";1525next;1526}15271528 transmitfile($meta2->{filehash},$file2);1529}1530# otherwise we just use the working copy1531else1532{1533$file2=$state->{entries}{$filename}{modified_filename};1534}15351536# if we have been given -r, and we don't have a $file2 yet, lets get one1537if(defined($revision1)and not defined($file2) )1538{1539(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1540$meta2=$updater->getmeta($filename,$wrev);1541 transmitfile($meta2->{filehash},$file2);1542}15431544# We need to have retrieved something useful1545next unless(defined($meta1) );15461547# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1548next if(not defined($meta2)and$wrev==$meta1->{revision}1549and1550( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1551or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1552);15531554# Apparently we only show diffs for locally modified files1555next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );15561557print"M Index:$filename\n";1558print"M ===================================================================\n";1559print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1560print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1561print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1562print"M diff ";1563foreachmy$opt(keys%{$state->{opt}} )1564{1565if(ref$state->{opt}{$opt}eq"ARRAY")1566{1567foreachmy$value( @{$state->{opt}{$opt}} )1568{1569print"-$opt$value";1570}1571}else{1572print"-$opt";1573print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1574}1575}1576print"$filename\n";15771578$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));15791580($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);15811582if(exists$state->{opt}{u} )1583{1584system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1585}else{1586system("diff$file1$file2>$filediff");1587}15881589while( <$fh> )1590{1591print"M$_";1592}1593close$fh;1594}15951596print"ok\n";1597}15981599sub req_log1600{1601my($cmd,$data) =@_;16021603 argsplit("log");16041605$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1606#$log->debug("log state : " . Dumper($state));16071608my($minrev,$maxrev);1609if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1610{1611my$control=$2;1612$minrev=$1;1613$maxrev=$3;1614$minrev=~s/^1\.//if(defined($minrev) );1615$maxrev=~s/^1\.//if(defined($maxrev) );1616$minrev++if(defined($minrev)and$controleq"::");1617}16181619# Grab a handle to the SQLite db and do any necessary updates1620my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1621$updater->update();16221623# if no files were specified, we need to work out what files we should be providing status on ...1624 argsfromdir($updater);16251626# foreach file specified on the command line ...1627foreachmy$filename( @{$state->{args}} )1628{1629$filename= filecleanup($filename);16301631my$headmeta=$updater->getmeta($filename);16321633my$revisions=$updater->getlog($filename);1634my$totalrevisions=scalar(@$revisions);16351636if(defined($minrev) )1637{1638$log->debug("Removing revisions less than$minrev");1639while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1640{1641pop@$revisions;1642}1643}1644if(defined($maxrev) )1645{1646$log->debug("Removing revisions greater than$maxrev");1647while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1648{1649shift@$revisions;1650}1651}16521653next unless(scalar(@$revisions) );16541655print"M\n";1656print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1657print"M Working file:$filename\n";1658print"M head: 1.$headmeta->{revision}\n";1659print"M branch:\n";1660print"M locks: strict\n";1661print"M access list:\n";1662print"M symbolic names:\n";1663print"M keyword substitution: kv\n";1664print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1665print"M description:\n";16661667foreachmy$revision(@$revisions)1668{1669print"M ----------------------------\n";1670print"M revision 1.$revision->{revision}\n";1671# reformat the date for log output1672$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}) );1673$revision->{author} =~s/\s+.*//;1674$revision->{author} =~s/^(.{8}).*/$1/;1675print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1676my$commitmessage=$updater->commitmessage($revision->{commithash});1677$commitmessage=~s/^/M /mg;1678print$commitmessage."\n";1679}1680print"M =============================================================================\n";1681}16821683print"ok\n";1684}16851686sub req_annotate1687{1688my($cmd,$data) =@_;16891690 argsplit("annotate");16911692$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1693#$log->debug("status state : " . Dumper($state));16941695# Grab a handle to the SQLite db and do any necessary updates1696my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1697$updater->update();16981699# if no files were specified, we need to work out what files we should be providing annotate on ...1700 argsfromdir($updater);17011702# we'll need a temporary checkout dir1703my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1704my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1705$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");17061707$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1708$ENV{GIT_INDEX_FILE} =$file_index;17091710chdir$tmpdir;17111712# foreach file specified on the command line ...1713foreachmy$filename( @{$state->{args}} )1714{1715$filename= filecleanup($filename);17161717my$meta=$updater->getmeta($filename);17181719next unless($meta->{revision} );17201721# get all the commits that this file was in1722# in dense format -- aka skip dead revisions1723my$revisions=$updater->gethistorydense($filename);1724my$lastseenin=$revisions->[0][2];17251726# populate the temporary index based on the latest commit were we saw1727# the file -- but do it cheaply without checking out any files1728# TODO: if we got a revision from the client, use that instead1729# to look up the commithash in sqlite (still good to default to1730# the current head as we do now)1731system("git-read-tree",$lastseenin);1732unless($?==0)1733{1734die"Error running git-read-tree$lastseenin$file_index$!";1735}1736$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");17371738# do a checkout of the file1739system('git-checkout-index','-f','-u',$filename);1740unless($?==0) {1741die"Error running git-checkout-index -f -u$filename:$!";1742}17431744$log->info("Annotate$filename");17451746# Prepare a file with the commits from the linearized1747# history that annotate should know about. This prevents1748# git-jsannotate telling us about commits we are hiding1749# from the client.17501751open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1752for(my$i=0;$i<@$revisions;$i++)1753{1754print ANNOTATEHINTS $revisions->[$i][2];1755if($i+1<@$revisions) {# have we got a parent?1756print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1757}1758print ANNOTATEHINTS "\n";1759}17601761print ANNOTATEHINTS "\n";1762close ANNOTATEHINTS;17631764my$annotatecmd='git-annotate';1765open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1766or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1767my$metadata= {};1768print"E Annotations for$filename\n";1769print"E ***************\n";1770while( <ANNOTATE> )1771{1772if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1773{1774my$commithash=$1;1775my$data=$2;1776unless(defined($metadata->{$commithash} ) )1777{1778$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1779$metadata->{$commithash}{author} =~s/\s+.*//;1780$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1781$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1782}1783printf("M 1.%-5d (%-8s%10s):%s\n",1784$metadata->{$commithash}{revision},1785$metadata->{$commithash}{author},1786$metadata->{$commithash}{modified},1787$data1788);1789}else{1790$log->warn("Error in annotate output! LINE:$_");1791print"E Annotate error\n";1792next;1793}1794}1795close ANNOTATE;1796}17971798# done; get out of the tempdir1799chdir"/";18001801print"ok\n";18021803}18041805# This method takes the state->{arguments} array and produces two new arrays.1806# The first is $state->{args} which is everything before the '--' argument, and1807# the second is $state->{files} which is everything after it.1808sub argsplit1809{1810return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");18111812my$type=shift;18131814$state->{args} = [];1815$state->{files} = [];1816$state->{opt} = {};18171818if(defined($type) )1819{1820my$opt= {};1821$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");1822$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1823$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");1824$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1825$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1826$opt= { k =>1, m =>1}if($typeeq"add");1827$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1828$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");182918301831while(scalar( @{$state->{arguments}} ) >0)1832{1833my$arg=shift@{$state->{arguments}};18341835next if($argeq"--");1836next unless($arg=~/\S/);18371838# if the argument looks like a switch1839if($arg=~/^-(\w)(.*)/)1840{1841# if it's a switch that takes an argument1842if($opt->{$1} )1843{1844# If this switch has already been provided1845if($opt->{$1} >1and exists($state->{opt}{$1} ) )1846{1847$state->{opt}{$1} = [$state->{opt}{$1} ];1848if(length($2) >0)1849{1850push@{$state->{opt}{$1}},$2;1851}else{1852push@{$state->{opt}{$1}},shift@{$state->{arguments}};1853}1854}else{1855# if there's extra data in the arg, use that as the argument for the switch1856if(length($2) >0)1857{1858$state->{opt}{$1} =$2;1859}else{1860$state->{opt}{$1} =shift@{$state->{arguments}};1861}1862}1863}else{1864$state->{opt}{$1} =undef;1865}1866}1867else1868{1869push@{$state->{args}},$arg;1870}1871}1872}1873else1874{1875my$mode=0;18761877foreachmy$value( @{$state->{arguments}} )1878{1879if($valueeq"--")1880{1881$mode++;1882next;1883}1884push@{$state->{args}},$valueif($mode==0);1885push@{$state->{files}},$valueif($mode==1);1886}1887}1888}18891890# This method uses $state->{directory} to populate $state->{args} with a list of filenames1891sub argsfromdir1892{1893my$updater=shift;18941895$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");18961897return if(scalar( @{$state->{args}} ) >1);18981899my@gethead= @{$updater->gethead};19001901# push added files1902foreachmy$file(keys%{$state->{entries}}) {1903if(exists$state->{entries}{$file}{revision} &&1904$state->{entries}{$file}{revision} ==0)1905{1906push@gethead, { name =>$file, filehash =>'added'};1907}1908}19091910if(scalar(@{$state->{args}}) ==1)1911{1912my$arg=$state->{args}[0];1913$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );19141915$log->info("Only one arg specified, checking for directory expansion on '$arg'");19161917foreachmy$file(@gethead)1918{1919next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1920next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1921push@{$state->{args}},$file->{name};1922}19231924shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1925}else{1926$log->info("Only one arg specified, populating file list automatically");19271928$state->{args} = [];19291930foreachmy$file(@gethead)1931{1932next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1933next unless($file->{name} =~s/^$state->{prependdir}//);1934push@{$state->{args}},$file->{name};1935}1936}1937}19381939# This method cleans up the $state variable after a command that uses arguments has run1940sub statecleanup1941{1942$state->{files} = [];1943$state->{args} = [];1944$state->{arguments} = [];1945$state->{entries} = {};1946}19471948sub revparse1949{1950my$filename=shift;19511952returnundefunless(defined($state->{entries}{$filename}{revision} ) );19531954return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1955return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);19561957returnundef;1958}19591960# This method takes a file hash and does a CVS "file transfer" which transmits the1961# size of the file, and then the file contents.1962# If a second argument $targetfile is given, the file is instead written out to1963# a file by the name of $targetfile1964sub transmitfile1965{1966my$filehash=shift;1967my$targetfile=shift;19681969if(defined($filehash)and$filehasheq"deleted")1970{1971$log->warn("filehash is 'deleted'");1972return;1973}19741975die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);19761977my$type=`git-cat-file -t$filehash`;1978 chomp$type;19791980 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );19811982 my$size= `git-cat-file -s $filehash`;1983chomp$size;19841985$log->debug("transmitfile($filehash) size=$size, type=$type");19861987if(open my$fh,'-|',"git-cat-file","blob",$filehash)1988{1989if(defined($targetfile) )1990{1991open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1992print NEWFILE $_while( <$fh> );1993close NEWFILE;1994}else{1995print"$size\n";1996printwhile( <$fh> );1997}1998close$fhor die("Couldn't close filehandle for transmitfile()");1999}else{2000die("Couldn't execute git-cat-file");2001}2002}20032004# This method takes a file name, and returns ( $dirpart, $filepart ) which2005# refers to the directory portion and the file portion of the filename2006# respectively2007sub filenamesplit2008{2009my$filename=shift;2010my$fixforlocaldir=shift;20112012my($filepart,$dirpart) = ($filename,".");2013($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2014$dirpart.="/";20152016if($fixforlocaldir)2017{2018$dirpart=~s/^$state->{prependdir}//;2019}20202021return($filepart,$dirpart);2022}20232024sub filecleanup2025{2026my$filename=shift;20272028returnundefunless(defined($filename));2029if($filename=~/^\// )2030{2031print"E absolute filenames '$filename' not supported by server\n";2032returnundef;2033}20342035$filename=~s/^\.\///g;2036$filename=$state->{prependdir} .$filename;2037return$filename;2038}20392040# Given a path, this function returns a string containing the kopts2041# that should go into that path's Entries line. For example, a binary2042# file should get -kb.2043sub kopts_from_path2044{2045my($path) =@_;20462047# Once it exists, the git attributes system should be used to look up2048# what attributes apply to this path.20492050# Until then, take the setting from the config file2051unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)2052{2053# Return "" to give no special treatment to any path2054return"";2055}else{2056# Alternatively, to have all files treated as if they are binary (which2057# is more like git itself), always return the "-kb" option2058return"-kb";2059}2060}20612062package GITCVS::log;20632064####2065#### Copyright The Open University UK - 2006.2066####2067#### Authors: Martyn Smith <martyn@catalyst.net.nz>2068#### Martin Langhoff <martin@catalyst.net.nz>2069####2070####20712072use strict;2073use warnings;20742075=head1 NAME20762077GITCVS::log20782079=head1 DESCRIPTION20802081This module provides very crude logging with a similar interface to2082Log::Log4perl20832084=head1 METHODS20852086=cut20872088=head2 new20892090Creates a new log object, optionally you can specify a filename here to2091indicate the file to log to. If no log file is specified, you can specify one2092later with method setfile, or indicate you no longer want logging with method2093nofile.20942095Until one of these methods is called, all log calls will buffer messages ready2096to write out.20972098=cut2099sub new2100{2101my$class=shift;2102my$filename=shift;21032104my$self= {};21052106bless$self,$class;21072108if(defined($filename) )2109{2110open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2111}21122113return$self;2114}21152116=head2 setfile21172118This methods takes a filename, and attempts to open that file as the log file.2119If successful, all buffered data is written out to the file, and any further2120logging is written directly to the file.21212122=cut2123sub setfile2124{2125my$self=shift;2126my$filename=shift;21272128if(defined($filename) )2129{2130open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2131}21322133return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");21342135while(my$line=shift@{$self->{buffer}} )2136{2137print{$self->{fh}}$line;2138}2139}21402141=head2 nofile21422143This method indicates no logging is going to be used. It flushes any entries in2144the internal buffer, and sets a flag to ensure no further data is put there.21452146=cut2147sub nofile2148{2149my$self=shift;21502151$self->{nolog} =1;21522153return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");21542155$self->{buffer} = [];2156}21572158=head2 _logopen21592160Internal method. Returns true if the log file is open, false otherwise.21612162=cut2163sub _logopen2164{2165my$self=shift;21662167return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2168return0;2169}21702171=head2 debug info warn fatal21722173These four methods are wrappers to _log. They provide the actual interface for2174logging data.21752176=cut2177sub debug {my$self=shift;$self->_log("debug",@_); }2178sub info {my$self=shift;$self->_log("info",@_); }2179subwarn{my$self=shift;$self->_log("warn",@_); }2180sub fatal {my$self=shift;$self->_log("fatal",@_); }21812182=head2 _log21832184This is an internal method called by the logging functions. It generates a2185timestamp and pushes the logged line either to file, or internal buffer.21862187=cut2188sub _log2189{2190my$self=shift;2191my$level=shift;21922193return if($self->{nolog} );21942195my@time=localtime;2196my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2197$time[5] +1900,2198$time[4] +1,2199$time[3],2200$time[2],2201$time[1],2202$time[0],2203uc$level,2204);22052206if($self->_logopen)2207{2208print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2209}else{2210push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2211}2212}22132214=head2 DESTROY22152216This method simply closes the file handle if one is open22172218=cut2219sub DESTROY2220{2221my$self=shift;22222223if($self->_logopen)2224{2225close$self->{fh};2226}2227}22282229package GITCVS::updater;22302231####2232#### Copyright The Open University UK - 2006.2233####2234#### Authors: Martyn Smith <martyn@catalyst.net.nz>2235#### Martin Langhoff <martin@catalyst.net.nz>2236####2237####22382239use strict;2240use warnings;2241use DBI;22422243=head1 METHODS22442245=cut22462247=head2 new22482249=cut2250sub new2251{2252my$class=shift;2253my$config=shift;2254my$module=shift;2255my$log=shift;22562257die"Need to specify a git repository"unless(defined($config)and-d $config);2258die"Need to specify a module"unless(defined($module) );22592260$class=ref($class) ||$class;22612262my$self= {};22632264bless$self,$class;22652266$self->{module} =$module;2267$self->{git_path} =$config."/";22682269$self->{log} =$log;22702271die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );22722273$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2274$cfg->{gitcvs}{dbdriver} ||"SQLite";2275$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2276$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2277$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2278$cfg->{gitcvs}{dbuser} ||"";2279$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2280$cfg->{gitcvs}{dbpass} ||"";2281my%mapping= ( m =>$module,2282 a =>$state->{method},2283 u =>getlogin||getpwuid($<) || $<,2284 G =>$self->{git_path},2285 g => mangle_dirname($self->{git_path}),2286);2287$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2288$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;22892290die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2291die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2292$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2293$self->{dbuser},2294$self->{dbpass});2295die"Error connecting to database\n"unlessdefined$self->{dbh};22962297$self->{tables} = {};2298foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2299{2300$self->{tables}{$table} =1;2301}23022303# Construct the revision table if required2304unless($self->{tables}{revision} )2305{2306$self->{dbh}->do("2307 CREATE TABLE revision (2308 name TEXT NOT NULL,2309 revision INTEGER NOT NULL,2310 filehash TEXT NOT NULL,2311 commithash TEXT NOT NULL,2312 author TEXT NOT NULL,2313 modified TEXT NOT NULL,2314 mode TEXT NOT NULL2315 )2316 ");2317$self->{dbh}->do("2318 CREATE INDEX revision_ix12319 ON revision (name,revision)2320 ");2321$self->{dbh}->do("2322 CREATE INDEX revision_ix22323 ON revision (name,commithash)2324 ");2325}23262327# Construct the head table if required2328unless($self->{tables}{head} )2329{2330$self->{dbh}->do("2331 CREATE TABLE head (2332 name TEXT NOT NULL,2333 revision INTEGER NOT NULL,2334 filehash TEXT NOT NULL,2335 commithash TEXT NOT NULL,2336 author TEXT NOT NULL,2337 modified TEXT NOT NULL,2338 mode TEXT NOT NULL2339 )2340 ");2341$self->{dbh}->do("2342 CREATE INDEX head_ix12343 ON head (name)2344 ");2345}23462347# Construct the properties table if required2348unless($self->{tables}{properties} )2349{2350$self->{dbh}->do("2351 CREATE TABLE properties (2352 key TEXT NOT NULL PRIMARY KEY,2353 value TEXT2354 )2355 ");2356}23572358# Construct the commitmsgs table if required2359unless($self->{tables}{commitmsgs} )2360{2361$self->{dbh}->do("2362 CREATE TABLE commitmsgs (2363 key TEXT NOT NULL PRIMARY KEY,2364 value TEXT2365 )2366 ");2367}23682369return$self;2370}23712372=head2 update23732374=cut2375sub update2376{2377my$self=shift;23782379# first lets get the commit list2380$ENV{GIT_DIR} =$self->{git_path};23812382my$commitsha1=`git rev-parse$self->{module}`;2383chomp$commitsha1;23842385my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2386unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2387{2388die("Invalid module '$self->{module}'");2389}239023912392my$git_log;2393my$lastcommit=$self->_get_prop("last_commit");23942395if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2396return1;2397}23982399# Start exclusive lock here...2400$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";24012402# TODO: log processing is memory bound2403# if we can parse into a 2nd file that is in reverse order2404# we can probably do something really efficient2405my@git_log_params= ('--pretty','--parents','--topo-order');24062407if(defined$lastcommit) {2408push@git_log_params,"$lastcommit..$self->{module}";2409}else{2410push@git_log_params,$self->{module};2411}2412# git-rev-list is the backend / plumbing version of git-log2413open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";24142415my@commits;24162417my%commit= ();24182419while( <GITLOG> )2420{2421chomp;2422if(m/^commit\s+(.*)$/) {2423# on ^commit lines put the just seen commit in the stack2424# and prime things for the next one2425if(keys%commit) {2426my%copy=%commit;2427unshift@commits, \%copy;2428%commit= ();2429}2430my@parents=split(m/\s+/,$1);2431$commit{hash} =shift@parents;2432$commit{parents} = \@parents;2433}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2434# on rfc822-like lines seen before we see any message,2435# lowercase the entry and put it in the hash as key-value2436$commit{lc($1)} =$2;2437}else{2438# message lines - skip initial empty line2439# and trim whitespace2440if(!exists($commit{message}) &&m/^\s*$/) {2441# define it to mark the end of headers2442$commit{message} ='';2443next;2444}2445s/^\s+//;s/\s+$//;# trim ws2446$commit{message} .=$_."\n";2447}2448}2449close GITLOG;24502451unshift@commits, \%commitif(keys%commit);24522453# Now all the commits are in the @commits bucket2454# ordered by time DESC. for each commit that needs processing,2455# determine whether it's following the last head we've seen or if2456# it's on its own branch, grab a file list, and add whatever's changed2457# NOTE: $lastcommit refers to the last commit from previous run2458# $lastpicked is the last commit we picked in this run2459my$lastpicked;2460my$head= {};2461if(defined$lastcommit) {2462$lastpicked=$lastcommit;2463}24642465my$committotal=scalar(@commits);2466my$commitcount=0;24672468# Load the head table into $head (for cached lookups during the update process)2469foreachmy$file( @{$self->gethead()} )2470{2471$head->{$file->{name}} =$file;2472}24732474foreachmy$commit(@commits)2475{2476$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2477if(defined$lastpicked)2478{2479if(!in_array($lastpicked, @{$commit->{parents}}))2480{2481# skip, we'll see this delta2482# as part of a merge later2483# warn "skipping off-track $commit->{hash}\n";2484next;2485}elsif(@{$commit->{parents}} >1) {2486# it is a merge commit, for each parent that is2487# not $lastpicked, see if we can get a log2488# from the merge-base to that parent to put it2489# in the message as a merge summary.2490my@parents= @{$commit->{parents}};2491foreachmy$parent(@parents) {2492# git-merge-base can potentially (but rarely) throw2493# several candidate merge bases. let's assume2494# that the first one is the best one.2495if($parenteq$lastpicked) {2496next;2497}2498open my$p,'git-merge-base '.$lastpicked.' '2499.$parent.'|';2500my@output= (<$p>);2501close$p;2502my$base=join('',@output);2503chomp$base;2504if($base) {2505my@merged;2506# print "want to log between $base $parent \n";2507open(GITLOG,'-|','git-log',"$base..$parent")2508or die"Cannot call git-log:$!";2509my$mergedhash;2510while(<GITLOG>) {2511chomp;2512if(!defined$mergedhash) {2513if(m/^commit\s+(.+)$/) {2514$mergedhash=$1;2515}else{2516next;2517}2518}else{2519# grab the first line that looks non-rfc8222520# aka has content after leading space2521if(m/^\s+(\S.*)$/) {2522my$title=$1;2523$title=substr($title,0,100);# truncate2524unshift@merged,"$mergedhash$title";2525undef$mergedhash;2526}2527}2528}2529close GITLOG;2530if(@merged) {2531$commit->{mergemsg} =$commit->{message};2532$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2533foreachmy$summary(@merged) {2534$commit->{mergemsg} .="\t$summary\n";2535}2536$commit->{mergemsg} .="\n\n";2537# print "Message for $commit->{hash} \n$commit->{mergemsg}";2538}2539}2540}2541}2542}25432544# convert the date to CVS-happy format2545$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);25462547if(defined($lastpicked) )2548{2549my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2550local($/) ="\0";2551while( <FILELIST> )2552{2553chomp;2554unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2555{2556die("Couldn't process git-diff-tree line :$_");2557}2558my($mode,$hash,$change) = ($1,$2,$3);2559my$name= <FILELIST>;2560chomp($name);25612562# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");25632564my$git_perms="";2565$git_perms.="r"if($mode&4);2566$git_perms.="w"if($mode&2);2567$git_perms.="x"if($mode&1);2568$git_perms="rw"if($git_permseq"");25692570if($changeeq"D")2571{2572#$log->debug("DELETE $name");2573$head->{$name} = {2574 name =>$name,2575 revision =>$head->{$name}{revision} +1,2576 filehash =>"deleted",2577 commithash =>$commit->{hash},2578 modified =>$commit->{date},2579 author =>$commit->{author},2580 mode =>$git_perms,2581};2582$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2583}2584elsif($changeeq"M")2585{2586#$log->debug("MODIFIED $name");2587$head->{$name} = {2588 name =>$name,2589 revision =>$head->{$name}{revision} +1,2590 filehash =>$hash,2591 commithash =>$commit->{hash},2592 modified =>$commit->{date},2593 author =>$commit->{author},2594 mode =>$git_perms,2595};2596$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2597}2598elsif($changeeq"A")2599{2600#$log->debug("ADDED $name");2601$head->{$name} = {2602 name =>$name,2603 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,2604 filehash =>$hash,2605 commithash =>$commit->{hash},2606 modified =>$commit->{date},2607 author =>$commit->{author},2608 mode =>$git_perms,2609};2610$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2611}2612else2613{2614$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2615die;2616}2617}2618close FILELIST;2619}else{2620# this is used to detect files removed from the repo2621my$seen_files= {};26222623my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2624local$/="\0";2625while( <FILELIST> )2626{2627chomp;2628unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2629{2630die("Couldn't process git-ls-tree line :$_");2631}26322633my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);26342635$seen_files->{$git_filename} =1;26362637my($oldhash,$oldrevision,$oldmode) = (2638$head->{$git_filename}{filehash},2639$head->{$git_filename}{revision},2640$head->{$git_filename}{mode}2641);26422643if($git_perms=~/^\d\d\d(\d)\d\d/o)2644{2645$git_perms="";2646$git_perms.="r"if($1&4);2647$git_perms.="w"if($1&2);2648$git_perms.="x"if($1&1);2649}else{2650$git_perms="rw";2651}26522653# unless the file exists with the same hash, we need to update it ...2654unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2655{2656my$newrevision= ($oldrevisionor0) +1;26572658$head->{$git_filename} = {2659 name =>$git_filename,2660 revision =>$newrevision,2661 filehash =>$git_hash,2662 commithash =>$commit->{hash},2663 modified =>$commit->{date},2664 author =>$commit->{author},2665 mode =>$git_perms,2666};266726682669$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2670}2671}2672close FILELIST;26732674# Detect deleted files2675foreachmy$file(keys%$head)2676{2677unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2678{2679$head->{$file}{revision}++;2680$head->{$file}{filehash} ="deleted";2681$head->{$file}{commithash} =$commit->{hash};2682$head->{$file}{modified} =$commit->{date};2683$head->{$file}{author} =$commit->{author};26842685$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2686}2687}2688# END : "Detect deleted files"2689}269026912692if(exists$commit->{mergemsg})2693{2694$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2695}26962697$lastpicked=$commit->{hash};26982699$self->_set_prop("last_commit",$commit->{hash});2700}27012702$self->delete_head();2703foreachmy$file(keys%$head)2704{2705$self->insert_head(2706$file,2707$head->{$file}{revision},2708$head->{$file}{filehash},2709$head->{$file}{commithash},2710$head->{$file}{modified},2711$head->{$file}{author},2712$head->{$file}{mode},2713);2714}2715# invalidate the gethead cache2716$self->{gethead_cache} =undef;271727182719# Ending exclusive lock here2720$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2721}27222723sub insert_rev2724{2725my$self=shift;2726my$name=shift;2727my$revision=shift;2728my$filehash=shift;2729my$commithash=shift;2730my$modified=shift;2731my$author=shift;2732my$mode=shift;27332734my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2735$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2736}27372738sub insert_mergelog2739{2740my$self=shift;2741my$key=shift;2742my$value=shift;27432744my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2745$insert_mergelog->execute($key,$value);2746}27472748sub delete_head2749{2750my$self=shift;27512752my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2753$delete_head->execute();2754}27552756sub insert_head2757{2758my$self=shift;2759my$name=shift;2760my$revision=shift;2761my$filehash=shift;2762my$commithash=shift;2763my$modified=shift;2764my$author=shift;2765my$mode=shift;27662767my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2768$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2769}27702771sub _headrev2772{2773my$self=shift;2774my$filename=shift;27752776my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2777$db_query->execute($filename);2778my($hash,$revision,$mode) =$db_query->fetchrow_array;27792780return($hash,$revision,$mode);2781}27822783sub _get_prop2784{2785my$self=shift;2786my$key=shift;27872788my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2789$db_query->execute($key);2790my($value) =$db_query->fetchrow_array;27912792return$value;2793}27942795sub _set_prop2796{2797my$self=shift;2798my$key=shift;2799my$value=shift;28002801my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2802$db_query->execute($value,$key);28032804unless($db_query->rows)2805{2806$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2807$db_query->execute($key,$value);2808}28092810return$value;2811}28122813=head2 gethead28142815=cut28162817sub gethead2818{2819my$self=shift;28202821return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );28222823my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2824$db_query->execute();28252826my$tree= [];2827while(my$file=$db_query->fetchrow_hashref)2828{2829push@$tree,$file;2830}28312832$self->{gethead_cache} =$tree;28332834return$tree;2835}28362837=head2 getlog28382839=cut28402841sub getlog2842{2843my$self=shift;2844my$filename=shift;28452846my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2847$db_query->execute($filename);28482849my$tree= [];2850while(my$file=$db_query->fetchrow_hashref)2851{2852push@$tree,$file;2853}28542855return$tree;2856}28572858=head2 getmeta28592860This function takes a filename (with path) argument and returns a hashref of2861metadata for that file.28622863=cut28642865sub getmeta2866{2867my$self=shift;2868my$filename=shift;2869my$revision=shift;28702871my$db_query;2872if(defined($revision)and$revision=~/^\d+$/)2873{2874$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2875$db_query->execute($filename,$revision);2876}2877elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2878{2879$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2880$db_query->execute($filename,$revision);2881}else{2882$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2883$db_query->execute($filename);2884}28852886return$db_query->fetchrow_hashref;2887}28882889=head2 commitmessage28902891this function takes a commithash and returns the commit message for that commit28922893=cut2894sub commitmessage2895{2896my$self=shift;2897my$commithash=shift;28982899die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);29002901my$db_query;2902$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2903$db_query->execute($commithash);29042905my($message) =$db_query->fetchrow_array;29062907if(defined($message) )2908{2909$message.=" "if($message=~/\n$/);2910return$message;2911}29122913my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2914shift@lineswhile($lines[0] =~/\S/);2915$message=join("",@lines);2916$message.=" "if($message=~/\n$/);2917return$message;2918}29192920=head2 gethistory29212922This function takes a filename (with path) argument and returns an arrayofarrays2923containing revision,filehash,commithash ordered by revision descending29242925=cut2926sub gethistory2927{2928my$self=shift;2929my$filename=shift;29302931my$db_query;2932$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2933$db_query->execute($filename);29342935return$db_query->fetchall_arrayref;2936}29372938=head2 gethistorydense29392940This function takes a filename (with path) argument and returns an arrayofarrays2941containing revision,filehash,commithash ordered by revision descending.29422943This version of gethistory skips deleted entries -- so it is useful for annotate.2944The 'dense' part is a reference to a '--dense' option available for git-rev-list2945and other git tools that depend on it.29462947=cut2948sub gethistorydense2949{2950my$self=shift;2951my$filename=shift;29522953my$db_query;2954$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2955$db_query->execute($filename);29562957return$db_query->fetchall_arrayref;2958}29592960=head2 in_array()29612962from Array::PAT - mimics the in_array() function2963found in PHP. Yuck but works for small arrays.29642965=cut2966sub in_array2967{2968my($check,@array) =@_;2969my$retval=0;2970foreachmy$test(@array){2971if($checkeq$test){2972$retval=1;2973}2974}2975return$retval;2976}29772978=head2 safe_pipe_capture29792980an alternative to `command` that allows input to be passed as an array2981to work around shell problems with weird characters in arguments29822983=cut2984sub safe_pipe_capture {29852986my@output;29872988if(my$pid=open my$child,'-|') {2989@output= (<$child>);2990close$childor die join(' ',@_).":$!$?";2991}else{2992exec(@_)or die"$!$?";# exec() can fail the executable can't be found2993}2994returnwantarray?@output:join('',@output);2995}29962997=head2 mangle_dirname29982999create a string from a directory name that is suitable to use as3000part of a filename, mainly by converting all chars except \w.- to _30013002=cut3003sub mangle_dirname {3004my$dirname=shift;3005return unlessdefined$dirname;30063007$dirname=~s/[^\w.-]/_/g;30083009return$dirname;3010}301130121;