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 966# If -p was given, "print" the contents of the requested revision. 967if(exists($state->{opt}{p} ) ) { 968if(defined($meta->{revision} ) ) { 969$log->info("Printing '$filename' revision ".$meta->{revision}); 970 971 transmitfile($meta->{filehash}, {print=>1}); 972} 973 974next; 975} 976 977if( !defined$meta) 978{ 979$meta= { 980 name =>$filename, 981 revision =>0, 982 filehash =>'added' 983}; 984} 985 986my$oldmeta=$meta; 987 988my$wrev= revparse($filename); 989 990# If the working copy is an old revision, lets get that version too for comparison. 991if(defined($wrev)and$wrev!=$meta->{revision} ) 992{ 993$oldmeta=$updater->getmeta($filename,$wrev); 994} 995 996#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 997 998# Files are up to date if the working copy and repo copy have the same revision, 999# and the working copy is unmodified _and_ the user hasn't specified -C1000next if(defined($wrev)1001and defined($meta->{revision})1002and$wrev==$meta->{revision}1003and$state->{entries}{$filename}{unchanged}1004and not exists($state->{opt}{C} ) );10051006# If the working copy and repo copy have the same revision,1007# but the working copy is modified, tell the client it's modified1008if(defined($wrev)1009and defined($meta->{revision})1010and$wrev==$meta->{revision}1011and defined($state->{entries}{$filename}{modified_hash})1012and not exists($state->{opt}{C} ) )1013{1014$log->info("Tell the client the file is modified");1015print"MT text M\n";1016print"MT fname$filename\n";1017print"MT newline\n";1018next;1019}10201021if($meta->{filehash}eq"deleted")1022{1023my($filepart,$dirpart) = filenamesplit($filename,1);10241025$log->info("Removing '$filename' from working copy (no longer in the repo)");10261027print"E cvs update: `$filename' is no longer in the repository\n";1028# Don't want to actually _DO_ the update if -n specified1029unless($state->{globaloptions}{-n} ) {1030print"Removed$dirpart\n";1031print"$filepart\n";1032}1033}1034elsif(not defined($state->{entries}{$filename}{modified_hash} )1035or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1036or$meta->{filehash}eq'added')1037{1038# normal update, just send the new revision (either U=Update,1039# or A=Add, or R=Remove)1040if(defined($wrev) &&$wrev<0)1041{1042$log->info("Tell the client the file is scheduled for removal");1043print"MT text R\n";1044print"MT fname$filename\n";1045print"MT newline\n";1046next;1047}1048elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1049{1050$log->info("Tell the client the file is scheduled for addition");1051print"MT text A\n";1052print"MT fname$filename\n";1053print"MT newline\n";1054next;10551056}1057else{1058$log->info("Updating '$filename' to ".$meta->{revision});1059print"MT +updated\n";1060print"MT text U\n";1061print"MT fname$filename\n";1062print"MT newline\n";1063print"MT -updated\n";1064}10651066my($filepart,$dirpart) = filenamesplit($filename,1);10671068# Don't want to actually _DO_ the update if -n specified1069unless($state->{globaloptions}{-n} )1070{1071if(defined($wrev) )1072{1073# instruct client we're sending a file to put in this path as a replacement1074print"Update-existing$dirpart\n";1075$log->debug("Updating existing file 'Update-existing$dirpart'");1076}else{1077# instruct client we're sending a file to put in this path as a new file1078print"Clear-static-directory$dirpart\n";1079print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1080print"Clear-sticky$dirpart\n";1081print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";10821083$log->debug("Creating new file 'Created$dirpart'");1084print"Created$dirpart\n";1085}1086print$state->{CVSROOT} ."/$state->{module}/$filename\n";10871088# this is an "entries" line1089my$kopts= kopts_from_path($filepart);1090$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1091print"/$filepart/1.$meta->{revision}//$kopts/\n";10921093# permissions1094$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1095print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10961097# transmit file1098 transmitfile($meta->{filehash});1099}1100}else{1101$log->info("Updating '$filename'");1102my($filepart,$dirpart) = filenamesplit($meta->{name},1);11031104my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/";11051106chdir$dir;1107my$file_local=$filepart.".mine";1108system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1109my$file_old=$filepart.".".$oldmeta->{revision};1110 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1111my$file_new=$filepart.".".$meta->{revision};1112 transmitfile($meta->{filehash}, { targetfile =>$file_new});11131114# we need to merge with the local changes ( M=successful merge, C=conflict merge )1115$log->info("Merging$file_local,$file_old,$file_new");1116print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11171118$log->debug("Temporary directory for merge is$dir");11191120my$return=system("git","merge-file",$file_local,$file_old,$file_new);1121$return>>=8;11221123if($return==0)1124{1125$log->info("Merged successfully");1126print"M M$filename\n";1127$log->debug("Merged$dirpart");11281129# Don't want to actually _DO_ the update if -n specified1130unless($state->{globaloptions}{-n} )1131{1132print"Merged$dirpart\n";1133$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1134print$state->{CVSROOT} ."/$state->{module}/$filename\n";1135my$kopts= kopts_from_path($filepart);1136$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1137print"/$filepart/1.$meta->{revision}//$kopts/\n";1138}1139}1140elsif($return==1)1141{1142$log->info("Merged with conflicts");1143print"E cvs update: conflicts found in$filename\n";1144print"M C$filename\n";11451146# Don't want to actually _DO_ the update if -n specified1147unless($state->{globaloptions}{-n} )1148{1149print"Merged$dirpart\n";1150print$state->{CVSROOT} ."/$state->{module}/$filename\n";1151my$kopts= kopts_from_path($filepart);1152print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1153}1154}1155else1156{1157$log->warn("Merge failed");1158next;1159}11601161# Don't want to actually _DO_ the update if -n specified1162unless($state->{globaloptions}{-n} )1163{1164# permissions1165$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1166print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11671168# transmit file, format is single integer on a line by itself (file1169# size) followed by the file contents1170# TODO : we should copy files in blocks1171my$data=`cat$file_local`;1172$log->debug("File size : " . length($data));1173 print length($data) . "\n";1174 print$data;1175 }11761177 chdir "/";1178 }11791180 }11811182 print "ok\n";1183}11841185sub req_ci1186{1187 my ($cmd,$data) =@_;11881189 argsplit("ci");11901191 #$log->debug("State : " . Dumper($state));11921193$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));11941195 if ($state->{method} eq 'pserver')1196 {1197 print "error 1 pserver access cannot commit\n";1198 exit;1199 }12001201 if ( -e$state->{CVSROOT} . "/index" )1202 {1203$log->warn("file 'index' already exists in the git repository");1204 print "error 1 Index already exists in git repo\n";1205 exit;1206 }12071208 # Grab a handle to the SQLite db and do any necessary updates1209 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1210$updater->update();12111212 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1213 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1214$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");12151216$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1217$ENV{GIT_WORK_TREE} = ".";1218$ENV{GIT_INDEX_FILE} =$file_index;12191220 # Remember where the head was at the beginning.1221 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1222 chomp$parenthash;1223 if ($parenthash!~ /^[0-9a-f]{40}$/) {1224 print "error 1 pserver cannot find the current HEAD of module";1225 exit;1226 }12271228 chdir$tmpdir;12291230 # populate the temporary index1231 system("git-read-tree",$parenthash);1232 unless ($?== 0)1233 {1234 die "Error running git-read-tree$state->{module}$file_index$!";1235 }1236$log->info("Created index '$file_index' for head$state->{module} - exit status$?");12371238 my@committedfiles= ();1239 my%oldmeta;12401241 # foreach file specified on the command line ...1242 foreach my$filename( @{$state->{args}} )1243 {1244 my$committedfile=$filename;1245$filename= filecleanup($filename);12461247 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12481249 my$meta=$updater->getmeta($filename);1250$oldmeta{$filename} =$meta;12511252 my$wrev= revparse($filename);12531254 my ($filepart,$dirpart) = filenamesplit($filename);12551256 # do a checkout of the file if it is part of this tree1257 if ($wrev) {1258 system('git-checkout-index', '-f', '-u',$filename);1259 unless ($?== 0) {1260 die "Error running git-checkout-index -f -u$filename:$!";1261 }1262 }12631264 my$addflag= 0;1265 my$rmflag= 0;1266$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1267$addflag= 1 unless ( -e$filename);12681269 # Do up to date checking1270 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1271 {1272 # fail everything if an up to date check fails1273 print "error 1 Up to date check failed for$filename\n";1274 chdir "/";1275 exit;1276 }12771278 push@committedfiles,$committedfile;1279$log->info("Committing$filename");12801281 system("mkdir","-p",$dirpart) unless ( -d$dirpart);12821283 unless ($rmflag)1284 {1285$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1286 rename$state->{entries}{$filename}{modified_filename},$filename;12871288 # Calculate modes to remove1289 my$invmode= "";1290 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }12911292$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1293 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1294 }12951296 if ($rmflag)1297 {1298$log->info("Removing file '$filename'");1299 unlink($filename);1300 system("git-update-index", "--remove",$filename);1301 }1302 elsif ($addflag)1303 {1304$log->info("Adding file '$filename'");1305 system("git-update-index", "--add",$filename);1306 } else {1307$log->info("Updating file '$filename'");1308 system("git-update-index",$filename);1309 }1310 }13111312 unless ( scalar(@committedfiles) > 0 )1313 {1314 print "E No files to commit\n";1315 print "ok\n";1316 chdir "/";1317 return;1318 }13191320 my$treehash= `git-write-tree`;1321 chomp$treehash;13221323$log->debug("Treehash :$treehash, Parenthash :$parenthash");13241325 # write our commit message out if we have one ...1326 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1327 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1328 print$msg_fh"\n\nvia git-CVS emulator\n";1329 close$msg_fh;13301331 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1332chomp($commithash);1333$log->info("Commit hash :$commithash");13341335unless($commithash=~/[a-zA-Z0-9]{40}/)1336{1337$log->warn("Commit failed (Invalid commit hash)");1338print"error 1 Commit failed (unknown reason)\n";1339chdir"/";1340exit;1341}13421343### Emulate git-receive-pack by running hooks/update1344my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1345$parenthash,$commithash);1346if( -x $hook[0] ) {1347unless(system(@hook) ==0)1348{1349$log->warn("Commit failed (update hook declined to update ref)");1350print"error 1 Commit failed (update hook declined)\n";1351chdir"/";1352exit;1353}1354}13551356### Update the ref1357if(system(qw(git update-ref -m),"cvsserver ci",1358"refs/heads/$state->{module}",$commithash,$parenthash)) {1359$log->warn("update-ref for$state->{module} failed.");1360print"error 1 Cannot commit -- update first\n";1361exit;1362}13631364### Emulate git-receive-pack by running hooks/post-receive1365my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1366if( -x $hook) {1367open(my$pipe,"|$hook") ||die"can't fork$!";13681369local$SIG{PIPE} =sub{die'pipe broke'};13701371print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";13721373close$pipe||die"bad pipe:$!$?";1374}13751376### Then hooks/post-update1377$hook=$ENV{GIT_DIR}.'hooks/post-update';1378if(-x $hook) {1379system($hook,"refs/heads/$state->{module}");1380}13811382$updater->update();13831384# foreach file specified on the command line ...1385foreachmy$filename(@committedfiles)1386{1387$filename= filecleanup($filename);13881389my$meta=$updater->getmeta($filename);1390unless(defined$meta->{revision}) {1391$meta->{revision} =1;1392}13931394my($filepart,$dirpart) = filenamesplit($filename,1);13951396$log->debug("Checked-in$dirpart:$filename");13971398print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1399if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1400{1401print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1402print"Remove-entry$dirpart\n";1403print"$filename\n";1404}else{1405if($meta->{revision} ==1) {1406print"M initial revision: 1.1\n";1407}else{1408print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1409}1410print"Checked-in$dirpart\n";1411print"$filename\n";1412my$kopts= kopts_from_path($filepart);1413print"/$filepart/1.$meta->{revision}//$kopts/\n";1414}1415}14161417chdir"/";1418print"ok\n";1419}14201421sub req_status1422{1423my($cmd,$data) =@_;14241425 argsplit("status");14261427$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1428#$log->debug("status state : " . Dumper($state));14291430# Grab a handle to the SQLite db and do any necessary updates1431my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1432$updater->update();14331434# if no files were specified, we need to work out what files we should be providing status on ...1435 argsfromdir($updater);14361437# foreach file specified on the command line ...1438foreachmy$filename( @{$state->{args}} )1439{1440$filename= filecleanup($filename);14411442next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;14431444my$meta=$updater->getmeta($filename);1445my$oldmeta=$meta;14461447my$wrev= revparse($filename);14481449# If the working copy is an old revision, lets get that version too for comparison.1450if(defined($wrev)and$wrev!=$meta->{revision} )1451{1452$oldmeta=$updater->getmeta($filename,$wrev);1453}14541455# TODO : All possible statuses aren't yet implemented1456my$status;1457# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1458$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1459and1460( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1461or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1462);14631464# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1465$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1466and1467($state->{entries}{$filename}{unchanged}1468or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1469);14701471# Need checkout if it exists in the repo but doesn't have a working copy1472$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );14731474# Locally modified if working copy and repo copy have the same revision but there are local changes1475$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );14761477# Needs Merge if working copy revision is less than repo copy and there are local changes1478$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );14791480$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1481$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1482$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1483$status||="File had conflicts on merge"if(0);14841485$status||="Unknown";14861487my($filepart) = filenamesplit($filename);14881489print"M ===================================================================\n";1490print"M File:$filepart\tStatus:$status\n";1491if(defined($state->{entries}{$filename}{revision}) )1492{1493print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1494}else{1495print"M Working revision:\tNo entry for$filename\n";1496}1497if(defined($meta->{revision}) )1498{1499print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1500print"M Sticky Tag:\t\t(none)\n";1501print"M Sticky Date:\t\t(none)\n";1502print"M Sticky Options:\t\t(none)\n";1503}else{1504print"M Repository revision:\tNo revision control file\n";1505}1506print"M\n";1507}15081509print"ok\n";1510}15111512sub req_diff1513{1514my($cmd,$data) =@_;15151516 argsplit("diff");15171518$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1519#$log->debug("status state : " . Dumper($state));15201521my($revision1,$revision2);1522if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1523{1524$revision1=$state->{opt}{r}[0];1525$revision2=$state->{opt}{r}[1];1526}else{1527$revision1=$state->{opt}{r};1528}15291530$revision1=~s/^1\.//if(defined($revision1) );1531$revision2=~s/^1\.//if(defined($revision2) );15321533$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15341535# Grab a handle to the SQLite db and do any necessary updates1536my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1537$updater->update();15381539# if no files were specified, we need to work out what files we should be providing status on ...1540 argsfromdir($updater);15411542# foreach file specified on the command line ...1543foreachmy$filename( @{$state->{args}} )1544{1545$filename= filecleanup($filename);15461547my($fh,$file1,$file2,$meta1,$meta2,$filediff);15481549my$wrev= revparse($filename);15501551# We need _something_ to diff against1552next unless(defined($wrev) );15531554# if we have a -r switch, use it1555if(defined($revision1) )1556{1557(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1558$meta1=$updater->getmeta($filename,$revision1);1559unless(defined($meta1)and$meta1->{filehash}ne"deleted")1560{1561print"E File$filenameat revision 1.$revision1doesn't exist\n";1562next;1563}1564 transmitfile($meta1->{filehash}, { targetfile =>$file1});1565}1566# otherwise we just use the working copy revision1567else1568{1569(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1570$meta1=$updater->getmeta($filename,$wrev);1571 transmitfile($meta1->{filehash}, { targetfile =>$file1});1572}15731574# if we have a second -r switch, use it too1575if(defined($revision2) )1576{1577(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1578$meta2=$updater->getmeta($filename,$revision2);15791580unless(defined($meta2)and$meta2->{filehash}ne"deleted")1581{1582print"E File$filenameat revision 1.$revision2doesn't exist\n";1583next;1584}15851586 transmitfile($meta2->{filehash}, { targetfile =>$file2});1587}1588# otherwise we just use the working copy1589else1590{1591$file2=$state->{entries}{$filename}{modified_filename};1592}15931594# if we have been given -r, and we don't have a $file2 yet, lets get one1595if(defined($revision1)and not defined($file2) )1596{1597(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1598$meta2=$updater->getmeta($filename,$wrev);1599 transmitfile($meta2->{filehash}, { targetfile =>$file2});1600}16011602# We need to have retrieved something useful1603next unless(defined($meta1) );16041605# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1606next if(not defined($meta2)and$wrev==$meta1->{revision}1607and1608( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1609or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1610);16111612# Apparently we only show diffs for locally modified files1613next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16141615print"M Index:$filename\n";1616print"M ===================================================================\n";1617print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1618print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1619print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1620print"M diff ";1621foreachmy$opt(keys%{$state->{opt}} )1622{1623if(ref$state->{opt}{$opt}eq"ARRAY")1624{1625foreachmy$value( @{$state->{opt}{$opt}} )1626{1627print"-$opt$value";1628}1629}else{1630print"-$opt";1631print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1632}1633}1634print"$filename\n";16351636$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16371638($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16391640if(exists$state->{opt}{u} )1641{1642system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1643}else{1644system("diff$file1$file2>$filediff");1645}16461647while( <$fh> )1648{1649print"M$_";1650}1651close$fh;1652}16531654print"ok\n";1655}16561657sub req_log1658{1659my($cmd,$data) =@_;16601661 argsplit("log");16621663$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1664#$log->debug("log state : " . Dumper($state));16651666my($minrev,$maxrev);1667if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1668{1669my$control=$2;1670$minrev=$1;1671$maxrev=$3;1672$minrev=~s/^1\.//if(defined($minrev) );1673$maxrev=~s/^1\.//if(defined($maxrev) );1674$minrev++if(defined($minrev)and$controleq"::");1675}16761677# Grab a handle to the SQLite db and do any necessary updates1678my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1679$updater->update();16801681# if no files were specified, we need to work out what files we should be providing status on ...1682 argsfromdir($updater);16831684# foreach file specified on the command line ...1685foreachmy$filename( @{$state->{args}} )1686{1687$filename= filecleanup($filename);16881689my$headmeta=$updater->getmeta($filename);16901691my$revisions=$updater->getlog($filename);1692my$totalrevisions=scalar(@$revisions);16931694if(defined($minrev) )1695{1696$log->debug("Removing revisions less than$minrev");1697while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1698{1699pop@$revisions;1700}1701}1702if(defined($maxrev) )1703{1704$log->debug("Removing revisions greater than$maxrev");1705while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1706{1707shift@$revisions;1708}1709}17101711next unless(scalar(@$revisions) );17121713print"M\n";1714print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1715print"M Working file:$filename\n";1716print"M head: 1.$headmeta->{revision}\n";1717print"M branch:\n";1718print"M locks: strict\n";1719print"M access list:\n";1720print"M symbolic names:\n";1721print"M keyword substitution: kv\n";1722print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1723print"M description:\n";17241725foreachmy$revision(@$revisions)1726{1727print"M ----------------------------\n";1728print"M revision 1.$revision->{revision}\n";1729# reformat the date for log output1730$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}) );1731$revision->{author} = cvs_author($revision->{author});1732print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1733my$commitmessage=$updater->commitmessage($revision->{commithash});1734$commitmessage=~s/^/M /mg;1735print$commitmessage."\n";1736}1737print"M =============================================================================\n";1738}17391740print"ok\n";1741}17421743sub req_annotate1744{1745my($cmd,$data) =@_;17461747 argsplit("annotate");17481749$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1750#$log->debug("status state : " . Dumper($state));17511752# Grab a handle to the SQLite db and do any necessary updates1753my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1754$updater->update();17551756# if no files were specified, we need to work out what files we should be providing annotate on ...1757 argsfromdir($updater);17581759# we'll need a temporary checkout dir1760my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1761my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1762$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");17631764$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1765$ENV{GIT_WORK_TREE} =".";1766$ENV{GIT_INDEX_FILE} =$file_index;17671768chdir$tmpdir;17691770# foreach file specified on the command line ...1771foreachmy$filename( @{$state->{args}} )1772{1773$filename= filecleanup($filename);17741775my$meta=$updater->getmeta($filename);17761777next unless($meta->{revision} );17781779# get all the commits that this file was in1780# in dense format -- aka skip dead revisions1781my$revisions=$updater->gethistorydense($filename);1782my$lastseenin=$revisions->[0][2];17831784# populate the temporary index based on the latest commit were we saw1785# the file -- but do it cheaply without checking out any files1786# TODO: if we got a revision from the client, use that instead1787# to look up the commithash in sqlite (still good to default to1788# the current head as we do now)1789system("git-read-tree",$lastseenin);1790unless($?==0)1791{1792print"E error running git-read-tree$lastseenin$file_index$!\n";1793return;1794}1795$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");17961797# do a checkout of the file1798system('git-checkout-index','-f','-u',$filename);1799unless($?==0) {1800print"E error running git-checkout-index -f -u$filename:$!\n";1801return;1802}18031804$log->info("Annotate$filename");18051806# Prepare a file with the commits from the linearized1807# history that annotate should know about. This prevents1808# git-jsannotate telling us about commits we are hiding1809# from the client.18101811my$a_hints="$tmpdir/.annotate_hints";1812if(!open(ANNOTATEHINTS,'>',$a_hints)) {1813print"E failed to open '$a_hints' for writing:$!\n";1814return;1815}1816for(my$i=0;$i<@$revisions;$i++)1817{1818print ANNOTATEHINTS $revisions->[$i][2];1819if($i+1<@$revisions) {# have we got a parent?1820print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1821}1822print ANNOTATEHINTS "\n";1823}18241825print ANNOTATEHINTS "\n";1826close ANNOTATEHINTS1827or(print"E failed to write$a_hints:$!\n"),return;18281829my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1830if(!open(ANNOTATE,"-|",@cmd)) {1831print"E error invoking ".join(' ',@cmd) .":$!\n";1832return;1833}1834my$metadata= {};1835print"E Annotations for$filename\n";1836print"E ***************\n";1837while( <ANNOTATE> )1838{1839if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1840{1841my$commithash=$1;1842my$data=$2;1843unless(defined($metadata->{$commithash} ) )1844{1845$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1846$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1847$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1848}1849printf("M 1.%-5d (%-8s%10s):%s\n",1850$metadata->{$commithash}{revision},1851$metadata->{$commithash}{author},1852$metadata->{$commithash}{modified},1853$data1854);1855}else{1856$log->warn("Error in annotate output! LINE:$_");1857print"E Annotate error\n";1858next;1859}1860}1861close ANNOTATE;1862}18631864# done; get out of the tempdir1865chdir"/";18661867print"ok\n";18681869}18701871# This method takes the state->{arguments} array and produces two new arrays.1872# The first is $state->{args} which is everything before the '--' argument, and1873# the second is $state->{files} which is everything after it.1874sub argsplit1875{1876$state->{args} = [];1877$state->{files} = [];1878$state->{opt} = {};18791880return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");18811882my$type=shift;18831884if(defined($type) )1885{1886my$opt= {};1887$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");1888$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1889$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");1890$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1891$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1892$opt= { k =>1, m =>1}if($typeeq"add");1893$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1894$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");189518961897while(scalar( @{$state->{arguments}} ) >0)1898{1899my$arg=shift@{$state->{arguments}};19001901next if($argeq"--");1902next unless($arg=~/\S/);19031904# if the argument looks like a switch1905if($arg=~/^-(\w)(.*)/)1906{1907# if it's a switch that takes an argument1908if($opt->{$1} )1909{1910# If this switch has already been provided1911if($opt->{$1} >1and exists($state->{opt}{$1} ) )1912{1913$state->{opt}{$1} = [$state->{opt}{$1} ];1914if(length($2) >0)1915{1916push@{$state->{opt}{$1}},$2;1917}else{1918push@{$state->{opt}{$1}},shift@{$state->{arguments}};1919}1920}else{1921# if there's extra data in the arg, use that as the argument for the switch1922if(length($2) >0)1923{1924$state->{opt}{$1} =$2;1925}else{1926$state->{opt}{$1} =shift@{$state->{arguments}};1927}1928}1929}else{1930$state->{opt}{$1} =undef;1931}1932}1933else1934{1935push@{$state->{args}},$arg;1936}1937}1938}1939else1940{1941my$mode=0;19421943foreachmy$value( @{$state->{arguments}} )1944{1945if($valueeq"--")1946{1947$mode++;1948next;1949}1950push@{$state->{args}},$valueif($mode==0);1951push@{$state->{files}},$valueif($mode==1);1952}1953}1954}19551956# This method uses $state->{directory} to populate $state->{args} with a list of filenames1957sub argsfromdir1958{1959my$updater=shift;19601961$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19621963return if(scalar( @{$state->{args}} ) >1);19641965my@gethead= @{$updater->gethead};19661967# push added files1968foreachmy$file(keys%{$state->{entries}}) {1969if(exists$state->{entries}{$file}{revision} &&1970$state->{entries}{$file}{revision} ==0)1971{1972push@gethead, { name =>$file, filehash =>'added'};1973}1974}19751976if(scalar(@{$state->{args}}) ==1)1977{1978my$arg=$state->{args}[0];1979$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );19801981$log->info("Only one arg specified, checking for directory expansion on '$arg'");19821983foreachmy$file(@gethead)1984{1985next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1986next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1987push@{$state->{args}},$file->{name};1988}19891990shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1991}else{1992$log->info("Only one arg specified, populating file list automatically");19931994$state->{args} = [];19951996foreachmy$file(@gethead)1997{1998next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1999next unless($file->{name} =~s/^$state->{prependdir}//);2000push@{$state->{args}},$file->{name};2001}2002}2003}20042005# This method cleans up the $state variable after a command that uses arguments has run2006sub statecleanup2007{2008$state->{files} = [];2009$state->{args} = [];2010$state->{arguments} = [];2011$state->{entries} = {};2012}20132014sub revparse2015{2016my$filename=shift;20172018returnundefunless(defined($state->{entries}{$filename}{revision} ) );20192020return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2021return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20222023returnundef;2024}20252026# This method takes a file hash and does a CVS "file transfer". Its2027# exact behaviour depends on a second, optional hash table argument:2028# - If $options->{targetfile}, dump the contents to that file;2029# - If $options->{print}, use M/MT to transmit the contents one line2030# at a time;2031# - Otherwise, transmit the size of the file, followed by the file2032# contents.2033sub transmitfile2034{2035my$filehash=shift;2036my$options=shift;20372038if(defined($filehash)and$filehasheq"deleted")2039{2040$log->warn("filehash is 'deleted'");2041return;2042}20432044die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20452046my$type=`git-cat-file -t$filehash`;2047 chomp$type;20482049 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20502051 my$size= `git-cat-file -s $filehash`;2052chomp$size;20532054$log->debug("transmitfile($filehash) size=$size, type=$type");20552056if(open my$fh,'-|',"git-cat-file","blob",$filehash)2057{2058if(defined($options->{targetfile} ) )2059{2060my$targetfile=$options->{targetfile};2061open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2062print NEWFILE $_while( <$fh> );2063close NEWFILE or die("Failed to write '$targetfile':$!");2064}elsif(defined($options->{print} ) &&$options->{print} ) {2065while( <$fh> ) {2066if(/\n\z/) {2067print'M ',$_;2068}else{2069print'MT text ',$_,"\n";2070}2071}2072}else{2073print"$size\n";2074printwhile( <$fh> );2075}2076close$fhor die("Couldn't close filehandle for transmitfile():$!");2077}else{2078die("Couldn't execute git-cat-file");2079}2080}20812082# This method takes a file name, and returns ( $dirpart, $filepart ) which2083# refers to the directory portion and the file portion of the filename2084# respectively2085sub filenamesplit2086{2087my$filename=shift;2088my$fixforlocaldir=shift;20892090my($filepart,$dirpart) = ($filename,".");2091($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2092$dirpart.="/";20932094if($fixforlocaldir)2095{2096$dirpart=~s/^$state->{prependdir}//;2097}20982099return($filepart,$dirpart);2100}21012102sub filecleanup2103{2104my$filename=shift;21052106returnundefunless(defined($filename));2107if($filename=~/^\// )2108{2109print"E absolute filenames '$filename' not supported by server\n";2110returnundef;2111}21122113$filename=~s/^\.\///g;2114$filename=$state->{prependdir} .$filename;2115return$filename;2116}21172118# Given a path, this function returns a string containing the kopts2119# that should go into that path's Entries line. For example, a binary2120# file should get -kb.2121sub kopts_from_path2122{2123my($path) =@_;21242125# Once it exists, the git attributes system should be used to look up2126# what attributes apply to this path.21272128# Until then, take the setting from the config file2129unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)2130{2131# Return "" to give no special treatment to any path2132return"";2133}else{2134# Alternatively, to have all files treated as if they are binary (which2135# is more like git itself), always return the "-kb" option2136return"-kb";2137}2138}21392140# Generate a CVS author name from Git author information, by taking2141# the first eight characters of the user part of the email address.2142sub cvs_author2143{2144my$author_line=shift;2145(my$author) =$author_line=~/<([^>@]{1,8})/;21462147$author;2148}21492150package GITCVS::log;21512152####2153#### Copyright The Open University UK - 2006.2154####2155#### Authors: Martyn Smith <martyn@catalyst.net.nz>2156#### Martin Langhoff <martin@catalyst.net.nz>2157####2158####21592160use strict;2161use warnings;21622163=head1 NAME21642165GITCVS::log21662167=head1 DESCRIPTION21682169This module provides very crude logging with a similar interface to2170Log::Log4perl21712172=head1 METHODS21732174=cut21752176=head2 new21772178Creates a new log object, optionally you can specify a filename here to2179indicate the file to log to. If no log file is specified, you can specify one2180later with method setfile, or indicate you no longer want logging with method2181nofile.21822183Until one of these methods is called, all log calls will buffer messages ready2184to write out.21852186=cut2187sub new2188{2189my$class=shift;2190my$filename=shift;21912192my$self= {};21932194bless$self,$class;21952196if(defined($filename) )2197{2198open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2199}22002201return$self;2202}22032204=head2 setfile22052206This methods takes a filename, and attempts to open that file as the log file.2207If successful, all buffered data is written out to the file, and any further2208logging is written directly to the file.22092210=cut2211sub setfile2212{2213my$self=shift;2214my$filename=shift;22152216if(defined($filename) )2217{2218open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2219}22202221return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");22222223while(my$line=shift@{$self->{buffer}} )2224{2225print{$self->{fh}}$line;2226}2227}22282229=head2 nofile22302231This method indicates no logging is going to be used. It flushes any entries in2232the internal buffer, and sets a flag to ensure no further data is put there.22332234=cut2235sub nofile2236{2237my$self=shift;22382239$self->{nolog} =1;22402241return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");22422243$self->{buffer} = [];2244}22452246=head2 _logopen22472248Internal method. Returns true if the log file is open, false otherwise.22492250=cut2251sub _logopen2252{2253my$self=shift;22542255return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2256return0;2257}22582259=head2 debug info warn fatal22602261These four methods are wrappers to _log. They provide the actual interface for2262logging data.22632264=cut2265sub debug {my$self=shift;$self->_log("debug",@_); }2266sub info {my$self=shift;$self->_log("info",@_); }2267subwarn{my$self=shift;$self->_log("warn",@_); }2268sub fatal {my$self=shift;$self->_log("fatal",@_); }22692270=head2 _log22712272This is an internal method called by the logging functions. It generates a2273timestamp and pushes the logged line either to file, or internal buffer.22742275=cut2276sub _log2277{2278my$self=shift;2279my$level=shift;22802281return if($self->{nolog} );22822283my@time=localtime;2284my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2285$time[5] +1900,2286$time[4] +1,2287$time[3],2288$time[2],2289$time[1],2290$time[0],2291uc$level,2292);22932294if($self->_logopen)2295{2296print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2297}else{2298push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2299}2300}23012302=head2 DESTROY23032304This method simply closes the file handle if one is open23052306=cut2307sub DESTROY2308{2309my$self=shift;23102311if($self->_logopen)2312{2313close$self->{fh};2314}2315}23162317package GITCVS::updater;23182319####2320#### Copyright The Open University UK - 2006.2321####2322#### Authors: Martyn Smith <martyn@catalyst.net.nz>2323#### Martin Langhoff <martin@catalyst.net.nz>2324####2325####23262327use strict;2328use warnings;2329use DBI;23302331=head1 METHODS23322333=cut23342335=head2 new23362337=cut2338sub new2339{2340my$class=shift;2341my$config=shift;2342my$module=shift;2343my$log=shift;23442345die"Need to specify a git repository"unless(defined($config)and-d $config);2346die"Need to specify a module"unless(defined($module) );23472348$class=ref($class) ||$class;23492350my$self= {};23512352bless$self,$class;23532354$self->{valid_tables} = {'revision'=>1,2355'revision_ix1'=>1,2356'revision_ix2'=>1,2357'head'=>1,2358'head_ix1'=>1,2359'properties'=>1,2360'commitmsgs'=>1};23612362$self->{module} =$module;2363$self->{git_path} =$config."/";23642365$self->{log} =$log;23662367die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );23682369$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2370$cfg->{gitcvs}{dbdriver} ||"SQLite";2371$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2372$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2373$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2374$cfg->{gitcvs}{dbuser} ||"";2375$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2376$cfg->{gitcvs}{dbpass} ||"";2377$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2378$cfg->{gitcvs}{dbtablenameprefix} ||"";2379my%mapping= ( m =>$module,2380 a =>$state->{method},2381 u =>getlogin||getpwuid($<) || $<,2382 G =>$self->{git_path},2383 g => mangle_dirname($self->{git_path}),2384);2385$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2386$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2387$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2388$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});23892390die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2391die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2392$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2393$self->{dbuser},2394$self->{dbpass});2395die"Error connecting to database\n"unlessdefined$self->{dbh};23962397$self->{tables} = {};2398foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2399{2400$self->{tables}{$table} =1;2401}24022403# Construct the revision table if required2404unless($self->{tables}{$self->tablename("revision")} )2405{2406my$tablename=$self->tablename("revision");2407my$ix1name=$self->tablename("revision_ix1");2408my$ix2name=$self->tablename("revision_ix2");2409$self->{dbh}->do("2410 CREATE TABLE$tablename(2411 name TEXT NOT NULL,2412 revision INTEGER NOT NULL,2413 filehash TEXT NOT NULL,2414 commithash TEXT NOT NULL,2415 author TEXT NOT NULL,2416 modified TEXT NOT NULL,2417 mode TEXT NOT NULL2418 )2419 ");2420$self->{dbh}->do("2421 CREATE INDEX$ix1name2422 ON$tablename(name,revision)2423 ");2424$self->{dbh}->do("2425 CREATE INDEX$ix2name2426 ON$tablename(name,commithash)2427 ");2428}24292430# Construct the head table if required2431unless($self->{tables}{$self->tablename("head")} )2432{2433my$tablename=$self->tablename("head");2434my$ix1name=$self->tablename("head_ix1");2435$self->{dbh}->do("2436 CREATE TABLE$tablename(2437 name TEXT NOT NULL,2438 revision INTEGER NOT NULL,2439 filehash TEXT NOT NULL,2440 commithash TEXT NOT NULL,2441 author TEXT NOT NULL,2442 modified TEXT NOT NULL,2443 mode TEXT NOT NULL2444 )2445 ");2446$self->{dbh}->do("2447 CREATE INDEX$ix1name2448 ON$tablename(name)2449 ");2450}24512452# Construct the properties table if required2453unless($self->{tables}{$self->tablename("properties")} )2454{2455my$tablename=$self->tablename("properties");2456$self->{dbh}->do("2457 CREATE TABLE$tablename(2458 key TEXT NOT NULL PRIMARY KEY,2459 value TEXT2460 )2461 ");2462}24632464# Construct the commitmsgs table if required2465unless($self->{tables}{$self->tablename("commitmsgs")} )2466{2467my$tablename=$self->tablename("commitmsgs");2468$self->{dbh}->do("2469 CREATE TABLE$tablename(2470 key TEXT NOT NULL PRIMARY KEY,2471 value TEXT2472 )2473 ");2474}24752476return$self;2477}24782479=head2 tablename24802481=cut2482sub tablename2483{2484my$self=shift;2485my$name=shift;24862487if(exists$self->{valid_tables}{$name}) {2488return$self->{dbtablenameprefix} .$name;2489}else{2490returnundef;2491}2492}24932494=head2 update24952496=cut2497sub update2498{2499my$self=shift;25002501# first lets get the commit list2502$ENV{GIT_DIR} =$self->{git_path};25032504my$commitsha1=`git rev-parse$self->{module}`;2505chomp$commitsha1;25062507my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2508unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2509{2510die("Invalid module '$self->{module}'");2511}251225132514my$git_log;2515my$lastcommit=$self->_get_prop("last_commit");25162517if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2518return1;2519}25202521# Start exclusive lock here...2522$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";25232524# TODO: log processing is memory bound2525# if we can parse into a 2nd file that is in reverse order2526# we can probably do something really efficient2527my@git_log_params= ('--pretty','--parents','--topo-order');25282529if(defined$lastcommit) {2530push@git_log_params,"$lastcommit..$self->{module}";2531}else{2532push@git_log_params,$self->{module};2533}2534# git-rev-list is the backend / plumbing version of git-log2535open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";25362537my@commits;25382539my%commit= ();25402541while( <GITLOG> )2542{2543chomp;2544if(m/^commit\s+(.*)$/) {2545# on ^commit lines put the just seen commit in the stack2546# and prime things for the next one2547if(keys%commit) {2548my%copy=%commit;2549unshift@commits, \%copy;2550%commit= ();2551}2552my@parents=split(m/\s+/,$1);2553$commit{hash} =shift@parents;2554$commit{parents} = \@parents;2555}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2556# on rfc822-like lines seen before we see any message,2557# lowercase the entry and put it in the hash as key-value2558$commit{lc($1)} =$2;2559}else{2560# message lines - skip initial empty line2561# and trim whitespace2562if(!exists($commit{message}) &&m/^\s*$/) {2563# define it to mark the end of headers2564$commit{message} ='';2565next;2566}2567s/^\s+//;s/\s+$//;# trim ws2568$commit{message} .=$_."\n";2569}2570}2571close GITLOG;25722573unshift@commits, \%commitif(keys%commit);25742575# Now all the commits are in the @commits bucket2576# ordered by time DESC. for each commit that needs processing,2577# determine whether it's following the last head we've seen or if2578# it's on its own branch, grab a file list, and add whatever's changed2579# NOTE: $lastcommit refers to the last commit from previous run2580# $lastpicked is the last commit we picked in this run2581my$lastpicked;2582my$head= {};2583if(defined$lastcommit) {2584$lastpicked=$lastcommit;2585}25862587my$committotal=scalar(@commits);2588my$commitcount=0;25892590# Load the head table into $head (for cached lookups during the update process)2591foreachmy$file( @{$self->gethead()} )2592{2593$head->{$file->{name}} =$file;2594}25952596foreachmy$commit(@commits)2597{2598$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2599if(defined$lastpicked)2600{2601if(!in_array($lastpicked, @{$commit->{parents}}))2602{2603# skip, we'll see this delta2604# as part of a merge later2605# warn "skipping off-track $commit->{hash}\n";2606next;2607}elsif(@{$commit->{parents}} >1) {2608# it is a merge commit, for each parent that is2609# not $lastpicked, see if we can get a log2610# from the merge-base to that parent to put it2611# in the message as a merge summary.2612my@parents= @{$commit->{parents}};2613foreachmy$parent(@parents) {2614# git-merge-base can potentially (but rarely) throw2615# several candidate merge bases. let's assume2616# that the first one is the best one.2617if($parenteq$lastpicked) {2618next;2619}2620my$base=eval{2621 safe_pipe_capture('git-merge-base',2622$lastpicked,$parent);2623};2624# The two branches may not be related at all,2625# in which case merge base simply fails to find2626# any, but that's Ok.2627next if($@);26282629chomp$base;2630if($base) {2631my@merged;2632# print "want to log between $base $parent \n";2633open(GITLOG,'-|','git-log','--pretty=medium',"$base..$parent")2634or die"Cannot call git-log:$!";2635my$mergedhash;2636while(<GITLOG>) {2637chomp;2638if(!defined$mergedhash) {2639if(m/^commit\s+(.+)$/) {2640$mergedhash=$1;2641}else{2642next;2643}2644}else{2645# grab the first line that looks non-rfc8222646# aka has content after leading space2647if(m/^\s+(\S.*)$/) {2648my$title=$1;2649$title=substr($title,0,100);# truncate2650unshift@merged,"$mergedhash$title";2651undef$mergedhash;2652}2653}2654}2655close GITLOG;2656if(@merged) {2657$commit->{mergemsg} =$commit->{message};2658$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2659foreachmy$summary(@merged) {2660$commit->{mergemsg} .="\t$summary\n";2661}2662$commit->{mergemsg} .="\n\n";2663# print "Message for $commit->{hash} \n$commit->{mergemsg}";2664}2665}2666}2667}2668}26692670# convert the date to CVS-happy format2671$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);26722673if(defined($lastpicked) )2674{2675my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2676local($/) ="\0";2677while( <FILELIST> )2678{2679chomp;2680unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2681{2682die("Couldn't process git-diff-tree line :$_");2683}2684my($mode,$hash,$change) = ($1,$2,$3);2685my$name= <FILELIST>;2686chomp($name);26872688# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");26892690my$git_perms="";2691$git_perms.="r"if($mode&4);2692$git_perms.="w"if($mode&2);2693$git_perms.="x"if($mode&1);2694$git_perms="rw"if($git_permseq"");26952696if($changeeq"D")2697{2698#$log->debug("DELETE $name");2699$head->{$name} = {2700 name =>$name,2701 revision =>$head->{$name}{revision} +1,2702 filehash =>"deleted",2703 commithash =>$commit->{hash},2704 modified =>$commit->{date},2705 author =>$commit->{author},2706 mode =>$git_perms,2707};2708$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2709}2710elsif($changeeq"M"||$changeeq"T")2711{2712#$log->debug("MODIFIED $name");2713$head->{$name} = {2714 name =>$name,2715 revision =>$head->{$name}{revision} +1,2716 filehash =>$hash,2717 commithash =>$commit->{hash},2718 modified =>$commit->{date},2719 author =>$commit->{author},2720 mode =>$git_perms,2721};2722$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2723}2724elsif($changeeq"A")2725{2726#$log->debug("ADDED $name");2727$head->{$name} = {2728 name =>$name,2729 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,2730 filehash =>$hash,2731 commithash =>$commit->{hash},2732 modified =>$commit->{date},2733 author =>$commit->{author},2734 mode =>$git_perms,2735};2736$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2737}2738else2739{2740$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2741die;2742}2743}2744close FILELIST;2745}else{2746# this is used to detect files removed from the repo2747my$seen_files= {};27482749my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2750local$/="\0";2751while( <FILELIST> )2752{2753chomp;2754unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2755{2756die("Couldn't process git-ls-tree line :$_");2757}27582759my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);27602761$seen_files->{$git_filename} =1;27622763my($oldhash,$oldrevision,$oldmode) = (2764$head->{$git_filename}{filehash},2765$head->{$git_filename}{revision},2766$head->{$git_filename}{mode}2767);27682769if($git_perms=~/^\d\d\d(\d)\d\d/o)2770{2771$git_perms="";2772$git_perms.="r"if($1&4);2773$git_perms.="w"if($1&2);2774$git_perms.="x"if($1&1);2775}else{2776$git_perms="rw";2777}27782779# unless the file exists with the same hash, we need to update it ...2780unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2781{2782my$newrevision= ($oldrevisionor0) +1;27832784$head->{$git_filename} = {2785 name =>$git_filename,2786 revision =>$newrevision,2787 filehash =>$git_hash,2788 commithash =>$commit->{hash},2789 modified =>$commit->{date},2790 author =>$commit->{author},2791 mode =>$git_perms,2792};279327942795$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2796}2797}2798close FILELIST;27992800# Detect deleted files2801foreachmy$file(keys%$head)2802{2803unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2804{2805$head->{$file}{revision}++;2806$head->{$file}{filehash} ="deleted";2807$head->{$file}{commithash} =$commit->{hash};2808$head->{$file}{modified} =$commit->{date};2809$head->{$file}{author} =$commit->{author};28102811$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2812}2813}2814# END : "Detect deleted files"2815}281628172818if(exists$commit->{mergemsg})2819{2820$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2821}28222823$lastpicked=$commit->{hash};28242825$self->_set_prop("last_commit",$commit->{hash});2826}28272828$self->delete_head();2829foreachmy$file(keys%$head)2830{2831$self->insert_head(2832$file,2833$head->{$file}{revision},2834$head->{$file}{filehash},2835$head->{$file}{commithash},2836$head->{$file}{modified},2837$head->{$file}{author},2838$head->{$file}{mode},2839);2840}2841# invalidate the gethead cache2842$self->{gethead_cache} =undef;284328442845# Ending exclusive lock here2846$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2847}28482849sub insert_rev2850{2851my$self=shift;2852my$name=shift;2853my$revision=shift;2854my$filehash=shift;2855my$commithash=shift;2856my$modified=shift;2857my$author=shift;2858my$mode=shift;2859my$tablename=$self->tablename("revision");28602861my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2862$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2863}28642865sub insert_mergelog2866{2867my$self=shift;2868my$key=shift;2869my$value=shift;2870my$tablename=$self->tablename("commitmsgs");28712872my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);2873$insert_mergelog->execute($key,$value);2874}28752876sub delete_head2877{2878my$self=shift;2879my$tablename=$self->tablename("head");28802881my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);2882$delete_head->execute();2883}28842885sub insert_head2886{2887my$self=shift;2888my$name=shift;2889my$revision=shift;2890my$filehash=shift;2891my$commithash=shift;2892my$modified=shift;2893my$author=shift;2894my$mode=shift;2895my$tablename=$self->tablename("head");28962897my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2898$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2899}29002901sub _headrev2902{2903my$self=shift;2904my$filename=shift;2905my$tablename=$self->tablename("head");29062907my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);2908$db_query->execute($filename);2909my($hash,$revision,$mode) =$db_query->fetchrow_array;29102911return($hash,$revision,$mode);2912}29132914sub _get_prop2915{2916my$self=shift;2917my$key=shift;2918my$tablename=$self->tablename("properties");29192920my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);2921$db_query->execute($key);2922my($value) =$db_query->fetchrow_array;29232924return$value;2925}29262927sub _set_prop2928{2929my$self=shift;2930my$key=shift;2931my$value=shift;2932my$tablename=$self->tablename("properties");29332934my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);2935$db_query->execute($value,$key);29362937unless($db_query->rows)2938{2939$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);2940$db_query->execute($key,$value);2941}29422943return$value;2944}29452946=head2 gethead29472948=cut29492950sub gethead2951{2952my$self=shift;2953my$tablename=$self->tablename("head");29542955return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );29562957my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);2958$db_query->execute();29592960my$tree= [];2961while(my$file=$db_query->fetchrow_hashref)2962{2963push@$tree,$file;2964}29652966$self->{gethead_cache} =$tree;29672968return$tree;2969}29702971=head2 getlog29722973=cut29742975sub getlog2976{2977my$self=shift;2978my$filename=shift;2979my$tablename=$self->tablename("revision");29802981my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);2982$db_query->execute($filename);29832984my$tree= [];2985while(my$file=$db_query->fetchrow_hashref)2986{2987push@$tree,$file;2988}29892990return$tree;2991}29922993=head2 getmeta29942995This function takes a filename (with path) argument and returns a hashref of2996metadata for that file.29972998=cut29993000sub getmeta3001{3002my$self=shift;3003my$filename=shift;3004my$revision=shift;3005my$tablename_rev=$self->tablename("revision");3006my$tablename_head=$self->tablename("head");30073008my$db_query;3009if(defined($revision)and$revision=~/^\d+$/)3010{3011$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3012$db_query->execute($filename,$revision);3013}3014elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3015{3016$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3017$db_query->execute($filename,$revision);3018}else{3019$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3020$db_query->execute($filename);3021}30223023return$db_query->fetchrow_hashref;3024}30253026=head2 commitmessage30273028this function takes a commithash and returns the commit message for that commit30293030=cut3031sub commitmessage3032{3033my$self=shift;3034my$commithash=shift;3035my$tablename=$self->tablename("commitmsgs");30363037die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);30383039my$db_query;3040$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3041$db_query->execute($commithash);30423043my($message) =$db_query->fetchrow_array;30443045if(defined($message) )3046{3047$message.=" "if($message=~/\n$/);3048return$message;3049}30503051my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);3052shift@lineswhile($lines[0] =~/\S/);3053$message=join("",@lines);3054$message.=" "if($message=~/\n$/);3055return$message;3056}30573058=head2 gethistory30593060This function takes a filename (with path) argument and returns an arrayofarrays3061containing revision,filehash,commithash ordered by revision descending30623063=cut3064sub gethistory3065{3066my$self=shift;3067my$filename=shift;3068my$tablename=$self->tablename("revision");30693070my$db_query;3071$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3072$db_query->execute($filename);30733074return$db_query->fetchall_arrayref;3075}30763077=head2 gethistorydense30783079This function takes a filename (with path) argument and returns an arrayofarrays3080containing revision,filehash,commithash ordered by revision descending.30813082This version of gethistory skips deleted entries -- so it is useful for annotate.3083The 'dense' part is a reference to a '--dense' option available for git-rev-list3084and other git tools that depend on it.30853086=cut3087sub gethistorydense3088{3089my$self=shift;3090my$filename=shift;3091my$tablename=$self->tablename("revision");30923093my$db_query;3094$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3095$db_query->execute($filename);30963097return$db_query->fetchall_arrayref;3098}30993100=head2 in_array()31013102from Array::PAT - mimics the in_array() function3103found in PHP. Yuck but works for small arrays.31043105=cut3106sub in_array3107{3108my($check,@array) =@_;3109my$retval=0;3110foreachmy$test(@array){3111if($checkeq$test){3112$retval=1;3113}3114}3115return$retval;3116}31173118=head2 safe_pipe_capture31193120an alternative to `command` that allows input to be passed as an array3121to work around shell problems with weird characters in arguments31223123=cut3124sub safe_pipe_capture {31253126my@output;31273128if(my$pid=open my$child,'-|') {3129@output= (<$child>);3130close$childor die join(' ',@_).":$!$?";3131}else{3132exec(@_)or die"$!$?";# exec() can fail the executable can't be found3133}3134returnwantarray?@output:join('',@output);3135}31363137=head2 mangle_dirname31383139create a string from a directory name that is suitable to use as3140part of a filename, mainly by converting all chars except \w.- to _31413142=cut3143sub mangle_dirname {3144my$dirname=shift;3145return unlessdefined$dirname;31463147$dirname=~s/[^\w.-]/_/g;31483149return$dirname;3150}31513152=head2 mangle_tablename31533154create a string from a that is suitable to use as part of an SQL table3155name, mainly by converting all chars except \w to _31563157=cut3158sub mangle_tablename {3159my$tablename=shift;3160return unlessdefined$tablename;31613162$tablename=~s/[^\w_]/_/g;31633164return$tablename;3165}316631671;