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::Path qw/rmtree/; 25use File::Basename; 26use Getopt::Long qw(:config require_order no_ignore_case); 27 28my$VERSION='@@GIT_VERSION@@'; 29 30my$log= GITCVS::log->new(); 31my$cfg; 32 33my$DATE_LIST= { 34 Jan =>"01", 35 Feb =>"02", 36 Mar =>"03", 37 Apr =>"04", 38 May =>"05", 39 Jun =>"06", 40 Jul =>"07", 41 Aug =>"08", 42 Sep =>"09", 43 Oct =>"10", 44 Nov =>"11", 45 Dec =>"12", 46}; 47 48# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 49$| =1; 50 51#### Definition and mappings of functions #### 52 53my$methods= { 54'Root'=> \&req_Root, 55'Valid-responses'=> \&req_Validresponses, 56'valid-requests'=> \&req_validrequests, 57'Directory'=> \&req_Directory, 58'Entry'=> \&req_Entry, 59'Modified'=> \&req_Modified, 60'Unchanged'=> \&req_Unchanged, 61'Questionable'=> \&req_Questionable, 62'Argument'=> \&req_Argument, 63'Argumentx'=> \&req_Argument, 64'expand-modules'=> \&req_expandmodules, 65'add'=> \&req_add, 66'remove'=> \&req_remove, 67'co'=> \&req_co, 68'update'=> \&req_update, 69'ci'=> \&req_ci, 70'diff'=> \&req_diff, 71'log'=> \&req_log, 72'rlog'=> \&req_log, 73'tag'=> \&req_CATCHALL, 74'status'=> \&req_status, 75'admin'=> \&req_CATCHALL, 76'history'=> \&req_CATCHALL, 77'watchers'=> \&req_EMPTY, 78'editors'=> \&req_EMPTY, 79'annotate'=> \&req_annotate, 80'Global_option'=> \&req_Globaloption, 81#'annotate' => \&req_CATCHALL, 82}; 83 84############################################## 85 86 87# $state holds all the bits of information the clients sends us that could 88# potentially be useful when it comes to actually _doing_ something. 89my$state= { prependdir =>''}; 90 91# Work is for managing temporary working directory 92my$work= 93{ 94state=>undef,# undef, 1 (empty), 2 (with stuff) 95 workDir =>undef, 96index=>undef, 97 emptyDir =>undef, 98 tmpDir =>undef 99}; 100 101$log->info("--------------- STARTING -----------------"); 102 103my$usage= 104"Usage: git cvsserver [options] [pserver|server] [<directory> ...]\n". 105" --base-path <path> : Prepend to requested CVSROOT\n". 106" --strict-paths : Don't allow recursing into subdirectories\n". 107" --export-all : Don't check for gitcvs.enabled in config\n". 108" --version, -V : Print version information and exit\n". 109" --help, -h, -H : Print usage information and exit\n". 110"\n". 111"<directory> ... is a list of allowed directories. If no directories\n". 112"are given, all are allowed. This is an additional restriction, gitcvs\n". 113"access still needs to be enabled by the gitcvs.enabled config option.\n"; 114 115my@opts= ('help|h|H','version|V', 116'base-path=s','strict-paths','export-all'); 117GetOptions($state,@opts) 118or die$usage; 119 120if($state->{version}) { 121print"git-cvsserver version$VERSION\n"; 122exit; 123} 124if($state->{help}) { 125print$usage; 126exit; 127} 128 129my$TEMP_DIR= tempdir( CLEANUP =>1); 130$log->debug("Temporary directory is '$TEMP_DIR'"); 131 132$state->{method} ='ext'; 133if(@ARGV) { 134if($ARGV[0]eq'pserver') { 135$state->{method} ='pserver'; 136shift@ARGV; 137}elsif($ARGV[0]eq'server') { 138shift@ARGV; 139} 140} 141 142# everything else is a directory 143$state->{allowed_roots} = [@ARGV]; 144 145# don't export the whole system unless the users requests it 146if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 147die"--export-all can only be used together with an explicit whitelist\n"; 148} 149 150# if we are called with a pserver argument, 151# deal with the authentication cat before entering the 152# main loop 153if($state->{method}eq'pserver') { 154my$line= <STDIN>;chomp$line; 155unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 156die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 157} 158my$request=$1; 159$line= <STDIN>;chomp$line; 160unless(req_Root('root',$line)) {# reuse Root 161print"E Invalid root$line\n"; 162exit1; 163} 164$line= <STDIN>;chomp$line; 165unless($lineeq'anonymous') { 166print"E Only anonymous user allowed via pserver\n"; 167print"I HATE YOU\n"; 168exit1; 169} 170$line= <STDIN>;chomp$line;# validate the password? 171$line= <STDIN>;chomp$line; 172unless($lineeq"END$requestREQUEST") { 173die"E Do not understand$line-- expecting END$requestREQUEST\n"; 174} 175print"I LOVE YOU\n"; 176exit if$requesteq'VERIFICATION';# cvs login 177# and now back to our regular programme... 178} 179 180# Keep going until the client closes the connection 181while(<STDIN>) 182{ 183chomp; 184 185# Check to see if we've seen this method, and call appropriate function. 186if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 187{ 188# use the $methods hash to call the appropriate sub for this command 189#$log->info("Method : $1"); 190&{$methods->{$1}}($1,$2); 191}else{ 192# log fatal because we don't understand this function. If this happens 193# we're fairly screwed because we don't know if the client is expecting 194# a response. If it is, the client will hang, we'll hang, and the whole 195# thing will be custard. 196$log->fatal("Don't understand command$_\n"); 197die("Unknown command$_"); 198} 199} 200 201$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 202$log->info("--------------- FINISH -----------------"); 203 204chdir'/'; 205exit0; 206 207# Magic catchall method. 208# This is the method that will handle all commands we haven't yet 209# implemented. It simply sends a warning to the log file indicating a 210# command that hasn't been implemented has been invoked. 211sub req_CATCHALL 212{ 213my($cmd,$data) =@_; 214$log->warn("Unhandled command : req_$cmd:$data"); 215} 216 217# This method invariably succeeds with an empty response. 218sub req_EMPTY 219{ 220print"ok\n"; 221} 222 223# Root pathname \n 224# Response expected: no. Tell the server which CVSROOT to use. Note that 225# pathname is a local directory and not a fully qualified CVSROOT variable. 226# pathname must already exist; if creating a new root, use the init 227# request, not Root. pathname does not include the hostname of the server, 228# how to access the server, etc.; by the time the CVS protocol is in use, 229# connection, authentication, etc., are already taken care of. The Root 230# request must be sent only once, and it must be sent before any requests 231# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 232sub req_Root 233{ 234my($cmd,$data) =@_; 235$log->debug("req_Root :$data"); 236 237unless($data=~ m#^/#) { 238print"error 1 Root must be an absolute pathname\n"; 239return0; 240} 241 242my$cvsroot=$state->{'base-path'} ||''; 243$cvsroot=~ s#/+$##; 244$cvsroot.=$data; 245 246if($state->{CVSROOT} 247&& ($state->{CVSROOT}ne$cvsroot)) { 248print"error 1 Conflicting roots specified\n"; 249return0; 250} 251 252$state->{CVSROOT} =$cvsroot; 253 254$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 255 256if(@{$state->{allowed_roots}}) { 257my$allowed=0; 258foreachmy$dir(@{$state->{allowed_roots}}) { 259next unless$dir=~ m#^/#; 260$dir=~ s#/+$##; 261if($state->{'strict-paths'}) { 262if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 263$allowed=1; 264last; 265} 266}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 267$allowed=1; 268last; 269} 270} 271 272unless($allowed) { 273print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 274print"E\n"; 275print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 276return0; 277} 278} 279 280unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 281print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 282print"E\n"; 283print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 284return0; 285} 286 287my@gitvars=`git-config -l`; 288if($?) { 289print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 290print"E\n"; 291print"error 1 - problem executing git-config\n"; 292return0; 293} 294foreachmy$line(@gitvars) 295{ 296next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 297unless($2) { 298$cfg->{$1}{$3} =$4; 299}else{ 300$cfg->{$1}{$2}{$3} =$4; 301} 302} 303 304my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 305||$cfg->{gitcvs}{enabled}); 306unless($state->{'export-all'} || 307($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 308print"E GITCVS emulation needs to be enabled on this repo\n"; 309print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 310print"E\n"; 311print"error 1 GITCVS emulation disabled\n"; 312return0; 313} 314 315my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 316if($logfile) 317{ 318$log->setfile($logfile); 319}else{ 320$log->nofile(); 321} 322 323return1; 324} 325 326# Global_option option \n 327# Response expected: no. Transmit one of the global options `-q', `-Q', 328# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 329# variations (such as combining of options) are allowed. For graceful 330# handling of valid-requests, it is probably better to make new global 331# options separate requests, rather than trying to add them to this 332# request. 333sub req_Globaloption 334{ 335my($cmd,$data) =@_; 336$log->debug("req_Globaloption :$data"); 337$state->{globaloptions}{$data} =1; 338} 339 340# Valid-responses request-list \n 341# Response expected: no. Tell the server what responses the client will 342# accept. request-list is a space separated list of tokens. 343sub req_Validresponses 344{ 345my($cmd,$data) =@_; 346$log->debug("req_Validresponses :$data"); 347 348# TODO : re-enable this, currently it's not particularly useful 349#$state->{validresponses} = [ split /\s+/, $data ]; 350} 351 352# valid-requests \n 353# Response expected: yes. Ask the server to send back a Valid-requests 354# response. 355sub req_validrequests 356{ 357my($cmd,$data) =@_; 358 359$log->debug("req_validrequests"); 360 361$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 362$log->debug("SEND : ok"); 363 364print"Valid-requests ".join(" ",keys%$methods) ."\n"; 365print"ok\n"; 366} 367 368# Directory local-directory \n 369# Additional data: repository \n. Response expected: no. Tell the server 370# what directory to use. The repository should be a directory name from a 371# previous server response. Note that this both gives a default for Entry 372# and Modified and also for ci and the other commands; normal usage is to 373# send Directory for each directory in which there will be an Entry or 374# Modified, and then a final Directory for the original directory, then the 375# command. The local-directory is relative to the top level at which the 376# command is occurring (i.e. the last Directory which is sent before the 377# command); to indicate that top level, `.' should be sent for 378# local-directory. 379sub req_Directory 380{ 381my($cmd,$data) =@_; 382 383my$repository= <STDIN>; 384chomp$repository; 385 386 387$state->{localdir} =$data; 388$state->{repository} =$repository; 389$state->{path} =$repository; 390$state->{path} =~s/^$state->{CVSROOT}\///; 391$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 392$state->{path} .="/"if($state->{path} =~ /\S/ ); 393 394$state->{directory} =$state->{localdir}; 395$state->{directory} =""if($state->{directory}eq"."); 396$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 397 398if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 399{ 400$log->info("Setting prepend to '$state->{path}'"); 401$state->{prependdir} =$state->{path}; 402foreachmy$entry(keys%{$state->{entries}} ) 403{ 404$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 405delete$state->{entries}{$entry}; 406} 407} 408 409if(defined($state->{prependdir} ) ) 410{ 411$log->debug("Prepending '$state->{prependdir}' to state|directory"); 412$state->{directory} =$state->{prependdir} .$state->{directory} 413} 414$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 415} 416 417# Entry entry-line \n 418# Response expected: no. Tell the server what version of a file is on the 419# local machine. The name in entry-line is a name relative to the directory 420# most recently specified with Directory. If the user is operating on only 421# some files in a directory, Entry requests for only those files need be 422# included. If an Entry request is sent without Modified, Is-modified, or 423# Unchanged, it means the file is lost (does not exist in the working 424# directory). If both Entry and one of Modified, Is-modified, or Unchanged 425# are sent for the same file, Entry must be sent first. For a given file, 426# one can send Modified, Is-modified, or Unchanged, but not more than one 427# of these three. 428sub req_Entry 429{ 430my($cmd,$data) =@_; 431 432#$log->debug("req_Entry : $data"); 433 434my@data=split(/\//,$data); 435 436$state->{entries}{$state->{directory}.$data[1]} = { 437 revision =>$data[2], 438 conflict =>$data[3], 439 options =>$data[4], 440 tag_or_date =>$data[5], 441}; 442 443$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 444} 445 446# Questionable filename \n 447# Response expected: no. Additional data: no. Tell the server to check 448# whether filename should be ignored, and if not, next time the server 449# sends responses, send (in a M response) `?' followed by the directory and 450# filename. filename must not contain `/'; it needs to be a file in the 451# directory named by the most recent Directory request. 452sub req_Questionable 453{ 454my($cmd,$data) =@_; 455 456$log->debug("req_Questionable :$data"); 457$state->{entries}{$state->{directory}.$data}{questionable} =1; 458} 459 460# add \n 461# Response expected: yes. Add a file or directory. This uses any previous 462# Argument, Directory, Entry, or Modified requests, if they have been sent. 463# The last Directory sent specifies the working directory at the time of 464# the operation. To add a directory, send the directory to be added using 465# Directory and Argument requests. 466sub req_add 467{ 468my($cmd,$data) =@_; 469 470 argsplit("add"); 471 472my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 473$updater->update(); 474 475 argsfromdir($updater); 476 477my$addcount=0; 478 479foreachmy$filename( @{$state->{args}} ) 480{ 481$filename= filecleanup($filename); 482 483my$meta=$updater->getmeta($filename); 484my$wrev= revparse($filename); 485 486if($wrev&&$meta&& ($wrev<0)) 487{ 488# previously removed file, add back 489$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 490 491print"MT +updated\n"; 492print"MT text U\n"; 493print"MT fname$filename\n"; 494print"MT newline\n"; 495print"MT -updated\n"; 496 497unless($state->{globaloptions}{-n} ) 498{ 499my($filepart,$dirpart) = filenamesplit($filename,1); 500 501print"Created$dirpart\n"; 502print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 503 504# this is an "entries" line 505my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 506$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 507print"/$filepart/1.$meta->{revision}//$kopts/\n"; 508# permissions 509$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 510print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 511# transmit file 512 transmitfile($meta->{filehash}); 513} 514 515next; 516} 517 518unless(defined($state->{entries}{$filename}{modified_filename} ) ) 519{ 520print"E cvs add: nothing known about `$filename'\n"; 521next; 522} 523# TODO : check we're not squashing an already existing file 524if(defined($state->{entries}{$filename}{revision} ) ) 525{ 526print"E cvs add: `$filename' has already been entered\n"; 527next; 528} 529 530my($filepart,$dirpart) = filenamesplit($filename,1); 531 532print"E cvs add: scheduling file `$filename' for addition\n"; 533 534print"Checked-in$dirpart\n"; 535print"$filename\n"; 536my$kopts= kopts_from_path($filename,"file", 537$state->{entries}{$filename}{modified_filename}); 538print"/$filepart/0//$kopts/\n"; 539 540my$requestedKopts=$state->{opt}{k}; 541if(defined($requestedKopts)) 542{ 543$requestedKopts="-k$requestedKopts"; 544} 545else 546{ 547$requestedKopts=""; 548} 549if($koptsne$requestedKopts) 550{ 551$log->warn("Ignoring requested -k='$requestedKopts'" 552." for '$filename'; detected -k='$kopts' instead"); 553#TODO: Also have option to send warning to user? 554} 555 556$addcount++; 557} 558 559if($addcount==1) 560{ 561print"E cvs add: use `cvs commit' to add this file permanently\n"; 562} 563elsif($addcount>1) 564{ 565print"E cvs add: use `cvs commit' to add these files permanently\n"; 566} 567 568print"ok\n"; 569} 570 571# remove \n 572# Response expected: yes. Remove a file. This uses any previous Argument, 573# Directory, Entry, or Modified requests, if they have been sent. The last 574# Directory sent specifies the working directory at the time of the 575# operation. Note that this request does not actually do anything to the 576# repository; the only effect of a successful remove request is to supply 577# the client with a new entries line containing `-' to indicate a removed 578# file. In fact, the client probably could perform this operation without 579# contacting the server, although using remove may cause the server to 580# perform a few more checks. The client sends a subsequent ci request to 581# actually record the removal in the repository. 582sub req_remove 583{ 584my($cmd,$data) =@_; 585 586 argsplit("remove"); 587 588# Grab a handle to the SQLite db and do any necessary updates 589my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 590$updater->update(); 591 592#$log->debug("add state : " . Dumper($state)); 593 594my$rmcount=0; 595 596foreachmy$filename( @{$state->{args}} ) 597{ 598$filename= filecleanup($filename); 599 600if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 601{ 602print"E cvs remove: file `$filename' still in working directory\n"; 603next; 604} 605 606my$meta=$updater->getmeta($filename); 607my$wrev= revparse($filename); 608 609unless(defined($wrev) ) 610{ 611print"E cvs remove: nothing known about `$filename'\n"; 612next; 613} 614 615if(defined($wrev)and$wrev<0) 616{ 617print"E cvs remove: file `$filename' already scheduled for removal\n"; 618next; 619} 620 621unless($wrev==$meta->{revision} ) 622{ 623# TODO : not sure if the format of this message is quite correct. 624print"E cvs remove: Up to date check failed for `$filename'\n"; 625next; 626} 627 628 629my($filepart,$dirpart) = filenamesplit($filename,1); 630 631print"E cvs remove: scheduling `$filename' for removal\n"; 632 633print"Checked-in$dirpart\n"; 634print"$filename\n"; 635my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 636print"/$filepart/-1.$wrev//$kopts/\n"; 637 638$rmcount++; 639} 640 641if($rmcount==1) 642{ 643print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 644} 645elsif($rmcount>1) 646{ 647print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 648} 649 650print"ok\n"; 651} 652 653# Modified filename \n 654# Response expected: no. Additional data: mode, \n, file transmission. Send 655# the server a copy of one locally modified file. filename is a file within 656# the most recent directory sent with Directory; it must not contain `/'. 657# If the user is operating on only some files in a directory, only those 658# files need to be included. This can also be sent without Entry, if there 659# is no entry for the file. 660sub req_Modified 661{ 662my($cmd,$data) =@_; 663 664my$mode= <STDIN>; 665defined$mode 666or(print"E end of file reading mode for$data\n"),return; 667chomp$mode; 668my$size= <STDIN>; 669defined$size 670or(print"E end of file reading size of$data\n"),return; 671chomp$size; 672 673# Grab config information 674my$blocksize=8192; 675my$bytesleft=$size; 676my$tmp; 677 678# Get a filehandle/name to write it to 679my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 680 681# Loop over file data writing out to temporary file. 682while($bytesleft) 683{ 684$blocksize=$bytesleftif($bytesleft<$blocksize); 685read STDIN,$tmp,$blocksize; 686print$fh $tmp; 687$bytesleft-=$blocksize; 688} 689 690close$fh 691or(print"E failed to write temporary,$filename:$!\n"),return; 692 693# Ensure we have something sensible for the file mode 694if($mode=~/u=(\w+)/) 695{ 696$mode=$1; 697}else{ 698$mode="rw"; 699} 700 701# Save the file data in $state 702$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 703$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 704$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 705$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 706 707 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 708} 709 710# Unchanged filename\n 711# Response expected: no. Tell the server that filename has not been 712# modified in the checked out directory. The filename is a file within the 713# most recent directory sent with Directory; it must not contain `/'. 714sub req_Unchanged 715{ 716 my ($cmd,$data) =@_; 717 718$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 719 720 #$log->debug("req_Unchanged :$data"); 721} 722 723# Argument text\n 724# Response expected: no. Save argument for use in a subsequent command. 725# Arguments accumulate until an argument-using command is given, at which 726# point they are forgotten. 727# Argumentx text\n 728# Response expected: no. Append\nfollowed by text to the current argument 729# being saved. 730sub req_Argument 731{ 732 my ($cmd,$data) =@_; 733 734 # Argumentx means: append to last Argument (with a newline in front) 735 736$log->debug("$cmd:$data"); 737 738 if ($cmdeq 'Argumentx') { 739 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 740 } else { 741 push @{$state->{arguments}},$data; 742 } 743} 744 745# expand-modules\n 746# Response expected: yes. Expand the modules which are specified in the 747# arguments. Returns the data in Module-expansion responses. Note that the 748# server can assume that this is checkout or export, not rtag or rdiff; the 749# latter do not access the working directory and thus have no need to 750# expand modules on the client side. Expand may not be the best word for 751# what this request does. It does not necessarily tell you all the files 752# contained in a module, for example. Basically it is a way of telling you 753# which working directories the server needs to know about in order to 754# handle a checkout of the specified modules. For example, suppose that the 755# server has a module defined by 756# aliasmodule -a 1dir 757# That is, one can check out aliasmodule and it will take 1dir in the 758# repository and check it out to 1dir in the working directory. Now suppose 759# the client already has this module checked out and is planning on using 760# the co request to update it. Without using expand-modules, the client 761# would have two bad choices: it could either send information about all 762# working directories under the current directory, which could be 763# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 764# stands for 1dir, and neglect to send information for 1dir, which would 765# lead to incorrect operation. With expand-modules, the client would first 766# ask for the module to be expanded: 767sub req_expandmodules 768{ 769 my ($cmd,$data) =@_; 770 771 argsplit(); 772 773$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 774 775 unless ( ref$state->{arguments} eq "ARRAY" ) 776 { 777 print "ok\n"; 778 return; 779 } 780 781 foreach my$module( @{$state->{arguments}} ) 782 { 783$log->debug("SEND : Module-expansion$module"); 784 print "Module-expansion$module\n"; 785 } 786 787 print "ok\n"; 788 statecleanup(); 789} 790 791# co\n 792# Response expected: yes. Get files from the repository. This uses any 793# previous Argument, Directory, Entry, or Modified requests, if they have 794# been sent. Arguments to this command are module names; the client cannot 795# know what directories they correspond to except by (1) just sending the 796# co request, and then seeing what directory names the server sends back in 797# its responses, and (2) the expand-modules request. 798sub req_co 799{ 800 my ($cmd,$data) =@_; 801 802 argsplit("co"); 803 804 # Provide list of modules, if -c was used. 805 if (exists$state->{opt}{c}) { 806 my$showref= `git show-ref --heads`; 807 for my$line(split '\n',$showref) { 808 if ($line=~ m% refs/heads/(.*)$%) { 809 print "M$1\t$1\n"; 810 } 811 } 812 print "ok\n"; 813 return 1; 814 } 815 816 my$module=$state->{args}[0]; 817$state->{module} =$module; 818 my$checkout_path=$module; 819 820 # use the user specified directory if we're given it 821$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 822 823$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 824 825$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 826 827$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 828 829# Grab a handle to the SQLite db and do any necessary updates 830my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 831$updater->update(); 832 833$checkout_path=~ s|/$||;# get rid of trailing slashes 834 835# Eclipse seems to need the Clear-sticky command 836# to prepare the 'Entries' file for the new directory. 837print"Clear-sticky$checkout_path/\n"; 838print$state->{CVSROOT} ."/$module/\n"; 839print"Clear-static-directory$checkout_path/\n"; 840print$state->{CVSROOT} ."/$module/\n"; 841print"Clear-sticky$checkout_path/\n";# yes, twice 842print$state->{CVSROOT} ."/$module/\n"; 843print"Template$checkout_path/\n"; 844print$state->{CVSROOT} ."/$module/\n"; 845print"0\n"; 846 847# instruct the client that we're checking out to $checkout_path 848print"E cvs checkout: Updating$checkout_path\n"; 849 850my%seendirs= (); 851my$lastdir=''; 852 853# recursive 854sub prepdir { 855my($dir,$repodir,$remotedir,$seendirs) =@_; 856my$parent= dirname($dir); 857$dir=~ s|/+$||; 858$repodir=~ s|/+$||; 859$remotedir=~ s|/+$||; 860$parent=~ s|/+$||; 861$log->debug("announcedir$dir,$repodir,$remotedir"); 862 863if($parenteq'.'||$parenteq'./') { 864$parent=''; 865} 866# recurse to announce unseen parents first 867if(length($parent) && !exists($seendirs->{$parent})) { 868 prepdir($parent,$repodir,$remotedir,$seendirs); 869} 870# Announce that we are going to modify at the parent level 871if($parent) { 872print"E cvs checkout: Updating$remotedir/$parent\n"; 873}else{ 874print"E cvs checkout: Updating$remotedir\n"; 875} 876print"Clear-sticky$remotedir/$parent/\n"; 877print"$repodir/$parent/\n"; 878 879print"Clear-static-directory$remotedir/$dir/\n"; 880print"$repodir/$dir/\n"; 881print"Clear-sticky$remotedir/$parent/\n";# yes, twice 882print"$repodir/$parent/\n"; 883print"Template$remotedir/$dir/\n"; 884print"$repodir/$dir/\n"; 885print"0\n"; 886 887$seendirs->{$dir} =1; 888} 889 890foreachmy$git( @{$updater->gethead} ) 891{ 892# Don't want to check out deleted files 893next if($git->{filehash}eq"deleted"); 894 895my$fullName=$git->{name}; 896($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 897 898if(length($git->{dir}) &&$git->{dir}ne'./' 899&&$git->{dir}ne$lastdir) { 900unless(exists($seendirs{$git->{dir}})) { 901 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 902$checkout_path, \%seendirs); 903$lastdir=$git->{dir}; 904$seendirs{$git->{dir}} =1; 905} 906print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 907} 908 909# modification time of this file 910print"Mod-time$git->{modified}\n"; 911 912# print some information to the client 913if(defined($git->{dir} )and$git->{dir}ne"./") 914{ 915print"M U$checkout_path/$git->{dir}$git->{name}\n"; 916}else{ 917print"M U$checkout_path/$git->{name}\n"; 918} 919 920# instruct client we're sending a file to put in this path 921print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 922 923print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 924 925# this is an "entries" line 926my$kopts= kopts_from_path($fullName,"sha1",$git->{filehash}); 927print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 928# permissions 929print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 930 931# transmit file 932 transmitfile($git->{filehash}); 933} 934 935print"ok\n"; 936 937 statecleanup(); 938} 939 940# update \n 941# Response expected: yes. Actually do a cvs update command. This uses any 942# previous Argument, Directory, Entry, or Modified requests, if they have 943# been sent. The last Directory sent specifies the working directory at the 944# time of the operation. The -I option is not used--files which the client 945# can decide whether to ignore are not mentioned and the client sends the 946# Questionable request for others. 947sub req_update 948{ 949my($cmd,$data) =@_; 950 951$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 952 953 argsplit("update"); 954 955# 956# It may just be a client exploring the available heads/modules 957# in that case, list them as top level directories and leave it 958# at that. Eclipse uses this technique to offer you a list of 959# projects (heads in this case) to checkout. 960# 961if($state->{module}eq'') { 962my$showref=`git show-ref --heads`; 963print"E cvs update: Updating .\n"; 964formy$line(split'\n',$showref) { 965if($line=~ m% refs/heads/(.*)$%) { 966print"E cvs update: New directory `$1'\n"; 967} 968} 969print"ok\n"; 970return1; 971} 972 973 974# Grab a handle to the SQLite db and do any necessary updates 975my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 976 977$updater->update(); 978 979 argsfromdir($updater); 980 981#$log->debug("update state : " . Dumper($state)); 982 983# foreach file specified on the command line ... 984foreachmy$filename( @{$state->{args}} ) 985{ 986$filename= filecleanup($filename); 987 988$log->debug("Processing file$filename"); 989 990# if we have a -C we should pretend we never saw modified stuff 991if(exists($state->{opt}{C} ) ) 992{ 993delete$state->{entries}{$filename}{modified_hash}; 994delete$state->{entries}{$filename}{modified_filename}; 995$state->{entries}{$filename}{unchanged} =1; 996} 997 998my$meta; 999if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/)1000{1001$meta=$updater->getmeta($filename,$1);1002}else{1003$meta=$updater->getmeta($filename);1004}10051006# If -p was given, "print" the contents of the requested revision.1007if(exists($state->{opt}{p} ) ) {1008if(defined($meta->{revision} ) ) {1009$log->info("Printing '$filename' revision ".$meta->{revision});10101011 transmitfile($meta->{filehash}, {print=>1});1012}10131014next;1015}10161017if( !defined$meta)1018{1019$meta= {1020 name =>$filename,1021 revision =>0,1022 filehash =>'added'1023};1024}10251026my$oldmeta=$meta;10271028my$wrev= revparse($filename);10291030# If the working copy is an old revision, lets get that version too for comparison.1031if(defined($wrev)and$wrev!=$meta->{revision} )1032{1033$oldmeta=$updater->getmeta($filename,$wrev);1034}10351036#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");10371038# Files are up to date if the working copy and repo copy have the same revision,1039# and the working copy is unmodified _and_ the user hasn't specified -C1040next if(defined($wrev)1041and defined($meta->{revision})1042and$wrev==$meta->{revision}1043and$state->{entries}{$filename}{unchanged}1044and not exists($state->{opt}{C} ) );10451046# If the working copy and repo copy have the same revision,1047# but the working copy is modified, tell the client it's modified1048if(defined($wrev)1049and defined($meta->{revision})1050and$wrev==$meta->{revision}1051and defined($state->{entries}{$filename}{modified_hash})1052and not exists($state->{opt}{C} ) )1053{1054$log->info("Tell the client the file is modified");1055print"MT text M\n";1056print"MT fname$filename\n";1057print"MT newline\n";1058next;1059}10601061if($meta->{filehash}eq"deleted")1062{1063my($filepart,$dirpart) = filenamesplit($filename,1);10641065$log->info("Removing '$filename' from working copy (no longer in the repo)");10661067print"E cvs update: `$filename' is no longer in the repository\n";1068# Don't want to actually _DO_ the update if -n specified1069unless($state->{globaloptions}{-n} ) {1070print"Removed$dirpart\n";1071print"$filepart\n";1072}1073}1074elsif(not defined($state->{entries}{$filename}{modified_hash} )1075or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1076or$meta->{filehash}eq'added')1077{1078# normal update, just send the new revision (either U=Update,1079# or A=Add, or R=Remove)1080if(defined($wrev) &&$wrev<0)1081{1082$log->info("Tell the client the file is scheduled for removal");1083print"MT text R\n";1084print"MT fname$filename\n";1085print"MT newline\n";1086next;1087}1088elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1089{1090$log->info("Tell the client the file is scheduled for addition");1091print"MT text A\n";1092print"MT fname$filename\n";1093print"MT newline\n";1094next;10951096}1097else{1098$log->info("Updating '$filename' to ".$meta->{revision});1099print"MT +updated\n";1100print"MT text U\n";1101print"MT fname$filename\n";1102print"MT newline\n";1103print"MT -updated\n";1104}11051106my($filepart,$dirpart) = filenamesplit($filename,1);11071108# Don't want to actually _DO_ the update if -n specified1109unless($state->{globaloptions}{-n} )1110{1111if(defined($wrev) )1112{1113# instruct client we're sending a file to put in this path as a replacement1114print"Update-existing$dirpart\n";1115$log->debug("Updating existing file 'Update-existing$dirpart'");1116}else{1117# instruct client we're sending a file to put in this path as a new file1118print"Clear-static-directory$dirpart\n";1119print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1120print"Clear-sticky$dirpart\n";1121print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";11221123$log->debug("Creating new file 'Created$dirpart'");1124print"Created$dirpart\n";1125}1126print$state->{CVSROOT} ."/$state->{module}/$filename\n";11271128# this is an "entries" line1129my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1130$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1131print"/$filepart/1.$meta->{revision}//$kopts/\n";11321133# permissions1134$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1135print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11361137# transmit file1138 transmitfile($meta->{filehash});1139}1140}else{1141$log->info("Updating '$filename'");1142my($filepart,$dirpart) = filenamesplit($meta->{name},1);11431144my$mergeDir= setupTmpDir();11451146my$file_local=$filepart.".mine";1147my$mergedFile="$mergeDir/$file_local";1148system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1149my$file_old=$filepart.".".$oldmeta->{revision};1150 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1151my$file_new=$filepart.".".$meta->{revision};1152 transmitfile($meta->{filehash}, { targetfile =>$file_new});11531154# we need to merge with the local changes ( M=successful merge, C=conflict merge )1155$log->info("Merging$file_local,$file_old,$file_new");1156print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11571158$log->debug("Temporary directory for merge is$mergeDir");11591160my$return=system("git","merge-file",$file_local,$file_old,$file_new);1161$return>>=8;11621163 cleanupTmpDir();11641165if($return==0)1166{1167$log->info("Merged successfully");1168print"M M$filename\n";1169$log->debug("Merged$dirpart");11701171# Don't want to actually _DO_ the update if -n specified1172unless($state->{globaloptions}{-n} )1173{1174print"Merged$dirpart\n";1175$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1176print$state->{CVSROOT} ."/$state->{module}/$filename\n";1177my$kopts= kopts_from_path("$dirpart/$filepart",1178"file",$mergedFile);1179$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1180print"/$filepart/1.$meta->{revision}//$kopts/\n";1181}1182}1183elsif($return==1)1184{1185$log->info("Merged with conflicts");1186print"E cvs update: conflicts found in$filename\n";1187print"M C$filename\n";11881189# Don't want to actually _DO_ the update if -n specified1190unless($state->{globaloptions}{-n} )1191{1192print"Merged$dirpart\n";1193print$state->{CVSROOT} ."/$state->{module}/$filename\n";1194my$kopts= kopts_from_path("$dirpart/$filepart",1195"file",$mergedFile);1196print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1197}1198}1199else1200{1201$log->warn("Merge failed");1202next;1203}12041205# Don't want to actually _DO_ the update if -n specified1206unless($state->{globaloptions}{-n} )1207{1208# permissions1209$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1210print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12111212# transmit file, format is single integer on a line by itself (file1213# size) followed by the file contents1214# TODO : we should copy files in blocks1215my$data=`cat$mergedFile`;1216$log->debug("File size : " . length($data));1217 print length($data) . "\n";1218 print$data;1219 }1220 }12211222 }12231224 print "ok\n";1225}12261227sub req_ci1228{1229 my ($cmd,$data) =@_;12301231 argsplit("ci");12321233 #$log->debug("State : " . Dumper($state));12341235$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));12361237 if ($state->{method} eq 'pserver')1238 {1239 print "error 1 pserver access cannot commit\n";1240 cleanupWorkTree();1241 exit;1242 }12431244 if ( -e$state->{CVSROOT} . "/index" )1245 {1246$log->warn("file 'index' already exists in the git repository");1247 print "error 1 Index already exists in git repo\n";1248 cleanupWorkTree();1249 exit;1250 }12511252 # Grab a handle to the SQLite db and do any necessary updates1253 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1254$updater->update();12551256 # Remember where the head was at the beginning.1257 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1258 chomp$parenthash;1259 if ($parenthash!~ /^[0-9a-f]{40}$/) {1260 print "error 1 pserver cannot find the current HEAD of module";1261 cleanupWorkTree();1262 exit;1263 }12641265 setupWorkTree($parenthash);12661267$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");12681269$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");12701271 my@committedfiles= ();1272 my%oldmeta;12731274 # foreach file specified on the command line ...1275 foreach my$filename( @{$state->{args}} )1276 {1277 my$committedfile=$filename;1278$filename= filecleanup($filename);12791280 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12811282 my$meta=$updater->getmeta($filename);1283$oldmeta{$filename} =$meta;12841285 my$wrev= revparse($filename);12861287 my ($filepart,$dirpart) = filenamesplit($filename);12881289 # do a checkout of the file if it is part of this tree1290 if ($wrev) {1291 system('git-checkout-index', '-f', '-u',$filename);1292 unless ($?== 0) {1293 die "Error running git-checkout-index -f -u$filename:$!";1294 }1295 }12961297 my$addflag= 0;1298 my$rmflag= 0;1299$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1300$addflag= 1 unless ( -e$filename);13011302 # Do up to date checking1303 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1304 {1305 # fail everything if an up to date check fails1306 print "error 1 Up to date check failed for$filename\n";1307 cleanupWorkTree();1308 exit;1309 }13101311 push@committedfiles,$committedfile;1312$log->info("Committing$filename");13131314 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13151316 unless ($rmflag)1317 {1318$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1319 rename$state->{entries}{$filename}{modified_filename},$filename;13201321 # Calculate modes to remove1322 my$invmode= "";1323 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }13241325$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1326 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1327 }13281329 if ($rmflag)1330 {1331$log->info("Removing file '$filename'");1332 unlink($filename);1333 system("git-update-index", "--remove",$filename);1334 }1335 elsif ($addflag)1336 {1337$log->info("Adding file '$filename'");1338 system("git-update-index", "--add",$filename);1339 } else {1340$log->info("Updating file '$filename'");1341 system("git-update-index",$filename);1342 }1343 }13441345 unless ( scalar(@committedfiles) > 0 )1346 {1347 print "E No files to commit\n";1348 print "ok\n";1349 cleanupWorkTree();1350 return;1351 }13521353 my$treehash= `git-write-tree`;1354 chomp$treehash;13551356$log->debug("Treehash :$treehash, Parenthash :$parenthash");13571358 # write our commit message out if we have one ...1359 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1360 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1361 print$msg_fh"\n\nvia git-CVS emulator\n";1362 close$msg_fh;13631364 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1365chomp($commithash);1366$log->info("Commit hash :$commithash");13671368unless($commithash=~/[a-zA-Z0-9]{40}/)1369{1370$log->warn("Commit failed (Invalid commit hash)");1371print"error 1 Commit failed (unknown reason)\n";1372 cleanupWorkTree();1373exit;1374}13751376### Emulate git-receive-pack by running hooks/update1377my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1378$parenthash,$commithash);1379if( -x $hook[0] ) {1380unless(system(@hook) ==0)1381{1382$log->warn("Commit failed (update hook declined to update ref)");1383print"error 1 Commit failed (update hook declined)\n";1384 cleanupWorkTree();1385exit;1386}1387}13881389### Update the ref1390if(system(qw(git update-ref -m),"cvsserver ci",1391"refs/heads/$state->{module}",$commithash,$parenthash)) {1392$log->warn("update-ref for$state->{module} failed.");1393print"error 1 Cannot commit -- update first\n";1394 cleanupWorkTree();1395exit;1396}13971398### Emulate git-receive-pack by running hooks/post-receive1399my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1400if( -x $hook) {1401open(my$pipe,"|$hook") ||die"can't fork$!";14021403local$SIG{PIPE} =sub{die'pipe broke'};14041405print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";14061407close$pipe||die"bad pipe:$!$?";1408}14091410### Then hooks/post-update1411$hook=$ENV{GIT_DIR}.'hooks/post-update';1412if(-x $hook) {1413system($hook,"refs/heads/$state->{module}");1414}14151416$updater->update();14171418# foreach file specified on the command line ...1419foreachmy$filename(@committedfiles)1420{1421$filename= filecleanup($filename);14221423my$meta=$updater->getmeta($filename);1424unless(defined$meta->{revision}) {1425$meta->{revision} =1;1426}14271428my($filepart,$dirpart) = filenamesplit($filename,1);14291430$log->debug("Checked-in$dirpart:$filename");14311432print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1433if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1434{1435print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1436print"Remove-entry$dirpart\n";1437print"$filename\n";1438}else{1439if($meta->{revision} ==1) {1440print"M initial revision: 1.1\n";1441}else{1442print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1443}1444print"Checked-in$dirpart\n";1445print"$filename\n";1446my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1447print"/$filepart/1.$meta->{revision}//$kopts/\n";1448}1449}14501451 cleanupWorkTree();1452print"ok\n";1453}14541455sub req_status1456{1457my($cmd,$data) =@_;14581459 argsplit("status");14601461$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1462#$log->debug("status state : " . Dumper($state));14631464# Grab a handle to the SQLite db and do any necessary updates1465my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1466$updater->update();14671468# if no files were specified, we need to work out what files we should be providing status on ...1469 argsfromdir($updater);14701471# foreach file specified on the command line ...1472foreachmy$filename( @{$state->{args}} )1473{1474$filename= filecleanup($filename);14751476next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;14771478my$meta=$updater->getmeta($filename);1479my$oldmeta=$meta;14801481my$wrev= revparse($filename);14821483# If the working copy is an old revision, lets get that version too for comparison.1484if(defined($wrev)and$wrev!=$meta->{revision} )1485{1486$oldmeta=$updater->getmeta($filename,$wrev);1487}14881489# TODO : All possible statuses aren't yet implemented1490my$status;1491# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1492$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1493and1494( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1495or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1496);14971498# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1499$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1500and1501($state->{entries}{$filename}{unchanged}1502or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1503);15041505# Need checkout if it exists in the repo but doesn't have a working copy1506$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );15071508# Locally modified if working copy and repo copy have the same revision but there are local changes1509$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );15101511# Needs Merge if working copy revision is less than repo copy and there are local changes1512$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );15131514$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1515$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1516$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1517$status||="File had conflicts on merge"if(0);15181519$status||="Unknown";15201521my($filepart) = filenamesplit($filename);15221523print"M ===================================================================\n";1524print"M File:$filepart\tStatus:$status\n";1525if(defined($state->{entries}{$filename}{revision}) )1526{1527print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1528}else{1529print"M Working revision:\tNo entry for$filename\n";1530}1531if(defined($meta->{revision}) )1532{1533print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1534print"M Sticky Tag:\t\t(none)\n";1535print"M Sticky Date:\t\t(none)\n";1536print"M Sticky Options:\t\t(none)\n";1537}else{1538print"M Repository revision:\tNo revision control file\n";1539}1540print"M\n";1541}15421543print"ok\n";1544}15451546sub req_diff1547{1548my($cmd,$data) =@_;15491550 argsplit("diff");15511552$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1553#$log->debug("status state : " . Dumper($state));15541555my($revision1,$revision2);1556if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1557{1558$revision1=$state->{opt}{r}[0];1559$revision2=$state->{opt}{r}[1];1560}else{1561$revision1=$state->{opt}{r};1562}15631564$revision1=~s/^1\.//if(defined($revision1) );1565$revision2=~s/^1\.//if(defined($revision2) );15661567$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15681569# Grab a handle to the SQLite db and do any necessary updates1570my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1571$updater->update();15721573# if no files were specified, we need to work out what files we should be providing status on ...1574 argsfromdir($updater);15751576# foreach file specified on the command line ...1577foreachmy$filename( @{$state->{args}} )1578{1579$filename= filecleanup($filename);15801581my($fh,$file1,$file2,$meta1,$meta2,$filediff);15821583my$wrev= revparse($filename);15841585# We need _something_ to diff against1586next unless(defined($wrev) );15871588# if we have a -r switch, use it1589if(defined($revision1) )1590{1591(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1592$meta1=$updater->getmeta($filename,$revision1);1593unless(defined($meta1)and$meta1->{filehash}ne"deleted")1594{1595print"E File$filenameat revision 1.$revision1doesn't exist\n";1596next;1597}1598 transmitfile($meta1->{filehash}, { targetfile =>$file1});1599}1600# otherwise we just use the working copy revision1601else1602{1603(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1604$meta1=$updater->getmeta($filename,$wrev);1605 transmitfile($meta1->{filehash}, { targetfile =>$file1});1606}16071608# if we have a second -r switch, use it too1609if(defined($revision2) )1610{1611(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1612$meta2=$updater->getmeta($filename,$revision2);16131614unless(defined($meta2)and$meta2->{filehash}ne"deleted")1615{1616print"E File$filenameat revision 1.$revision2doesn't exist\n";1617next;1618}16191620 transmitfile($meta2->{filehash}, { targetfile =>$file2});1621}1622# otherwise we just use the working copy1623else1624{1625$file2=$state->{entries}{$filename}{modified_filename};1626}16271628# if we have been given -r, and we don't have a $file2 yet, lets get one1629if(defined($revision1)and not defined($file2) )1630{1631(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1632$meta2=$updater->getmeta($filename,$wrev);1633 transmitfile($meta2->{filehash}, { targetfile =>$file2});1634}16351636# We need to have retrieved something useful1637next unless(defined($meta1) );16381639# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1640next if(not defined($meta2)and$wrev==$meta1->{revision}1641and1642( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1643or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1644);16451646# Apparently we only show diffs for locally modified files1647next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16481649print"M Index:$filename\n";1650print"M ===================================================================\n";1651print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1652print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1653print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1654print"M diff ";1655foreachmy$opt(keys%{$state->{opt}} )1656{1657if(ref$state->{opt}{$opt}eq"ARRAY")1658{1659foreachmy$value( @{$state->{opt}{$opt}} )1660{1661print"-$opt$value";1662}1663}else{1664print"-$opt";1665print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1666}1667}1668print"$filename\n";16691670$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16711672($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16731674if(exists$state->{opt}{u} )1675{1676system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1677}else{1678system("diff$file1$file2>$filediff");1679}16801681while( <$fh> )1682{1683print"M$_";1684}1685close$fh;1686}16871688print"ok\n";1689}16901691sub req_log1692{1693my($cmd,$data) =@_;16941695 argsplit("log");16961697$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1698#$log->debug("log state : " . Dumper($state));16991700my($minrev,$maxrev);1701if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1702{1703my$control=$2;1704$minrev=$1;1705$maxrev=$3;1706$minrev=~s/^1\.//if(defined($minrev) );1707$maxrev=~s/^1\.//if(defined($maxrev) );1708$minrev++if(defined($minrev)and$controleq"::");1709}17101711# Grab a handle to the SQLite db and do any necessary updates1712my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1713$updater->update();17141715# if no files were specified, we need to work out what files we should be providing status on ...1716 argsfromdir($updater);17171718# foreach file specified on the command line ...1719foreachmy$filename( @{$state->{args}} )1720{1721$filename= filecleanup($filename);17221723my$headmeta=$updater->getmeta($filename);17241725my$revisions=$updater->getlog($filename);1726my$totalrevisions=scalar(@$revisions);17271728if(defined($minrev) )1729{1730$log->debug("Removing revisions less than$minrev");1731while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1732{1733pop@$revisions;1734}1735}1736if(defined($maxrev) )1737{1738$log->debug("Removing revisions greater than$maxrev");1739while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1740{1741shift@$revisions;1742}1743}17441745next unless(scalar(@$revisions) );17461747print"M\n";1748print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1749print"M Working file:$filename\n";1750print"M head: 1.$headmeta->{revision}\n";1751print"M branch:\n";1752print"M locks: strict\n";1753print"M access list:\n";1754print"M symbolic names:\n";1755print"M keyword substitution: kv\n";1756print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1757print"M description:\n";17581759foreachmy$revision(@$revisions)1760{1761print"M ----------------------------\n";1762print"M revision 1.$revision->{revision}\n";1763# reformat the date for log output1764$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}) );1765$revision->{author} = cvs_author($revision->{author});1766print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1767my$commitmessage=$updater->commitmessage($revision->{commithash});1768$commitmessage=~s/^/M /mg;1769print$commitmessage."\n";1770}1771print"M =============================================================================\n";1772}17731774print"ok\n";1775}17761777sub req_annotate1778{1779my($cmd,$data) =@_;17801781 argsplit("annotate");17821783$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1784#$log->debug("status state : " . Dumper($state));17851786# Grab a handle to the SQLite db and do any necessary updates1787my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1788$updater->update();17891790# if no files were specified, we need to work out what files we should be providing annotate on ...1791 argsfromdir($updater);17921793# we'll need a temporary checkout dir1794 setupWorkTree();17951796$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");17971798# foreach file specified on the command line ...1799foreachmy$filename( @{$state->{args}} )1800{1801$filename= filecleanup($filename);18021803my$meta=$updater->getmeta($filename);18041805next unless($meta->{revision} );18061807# get all the commits that this file was in1808# in dense format -- aka skip dead revisions1809my$revisions=$updater->gethistorydense($filename);1810my$lastseenin=$revisions->[0][2];18111812# populate the temporary index based on the latest commit were we saw1813# the file -- but do it cheaply without checking out any files1814# TODO: if we got a revision from the client, use that instead1815# to look up the commithash in sqlite (still good to default to1816# the current head as we do now)1817system("git-read-tree",$lastseenin);1818unless($?==0)1819{1820print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1821return;1822}1823$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");18241825# do a checkout of the file1826system('git-checkout-index','-f','-u',$filename);1827unless($?==0) {1828print"E error running git-checkout-index -f -u$filename:$!\n";1829return;1830}18311832$log->info("Annotate$filename");18331834# Prepare a file with the commits from the linearized1835# history that annotate should know about. This prevents1836# git-jsannotate telling us about commits we are hiding1837# from the client.18381839my$a_hints="$work->{workDir}/.annotate_hints";1840if(!open(ANNOTATEHINTS,'>',$a_hints)) {1841print"E failed to open '$a_hints' for writing:$!\n";1842return;1843}1844for(my$i=0;$i<@$revisions;$i++)1845{1846print ANNOTATEHINTS $revisions->[$i][2];1847if($i+1<@$revisions) {# have we got a parent?1848print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1849}1850print ANNOTATEHINTS "\n";1851}18521853print ANNOTATEHINTS "\n";1854close ANNOTATEHINTS1855or(print"E failed to write$a_hints:$!\n"),return;18561857my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1858if(!open(ANNOTATE,"-|",@cmd)) {1859print"E error invoking ".join(' ',@cmd) .":$!\n";1860return;1861}1862my$metadata= {};1863print"E Annotations for$filename\n";1864print"E ***************\n";1865while( <ANNOTATE> )1866{1867if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1868{1869my$commithash=$1;1870my$data=$2;1871unless(defined($metadata->{$commithash} ) )1872{1873$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1874$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1875$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1876}1877printf("M 1.%-5d (%-8s%10s):%s\n",1878$metadata->{$commithash}{revision},1879$metadata->{$commithash}{author},1880$metadata->{$commithash}{modified},1881$data1882);1883}else{1884$log->warn("Error in annotate output! LINE:$_");1885print"E Annotate error\n";1886next;1887}1888}1889close ANNOTATE;1890}18911892# done; get out of the tempdir1893 cleanupWorkTree();18941895print"ok\n";18961897}18981899# This method takes the state->{arguments} array and produces two new arrays.1900# The first is $state->{args} which is everything before the '--' argument, and1901# the second is $state->{files} which is everything after it.1902sub argsplit1903{1904$state->{args} = [];1905$state->{files} = [];1906$state->{opt} = {};19071908return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19091910my$type=shift;19111912if(defined($type) )1913{1914my$opt= {};1915$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");1916$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1917$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");1918$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1919$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1920$opt= { k =>1, m =>1}if($typeeq"add");1921$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1922$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");192319241925while(scalar( @{$state->{arguments}} ) >0)1926{1927my$arg=shift@{$state->{arguments}};19281929next if($argeq"--");1930next unless($arg=~/\S/);19311932# if the argument looks like a switch1933if($arg=~/^-(\w)(.*)/)1934{1935# if it's a switch that takes an argument1936if($opt->{$1} )1937{1938# If this switch has already been provided1939if($opt->{$1} >1and exists($state->{opt}{$1} ) )1940{1941$state->{opt}{$1} = [$state->{opt}{$1} ];1942if(length($2) >0)1943{1944push@{$state->{opt}{$1}},$2;1945}else{1946push@{$state->{opt}{$1}},shift@{$state->{arguments}};1947}1948}else{1949# if there's extra data in the arg, use that as the argument for the switch1950if(length($2) >0)1951{1952$state->{opt}{$1} =$2;1953}else{1954$state->{opt}{$1} =shift@{$state->{arguments}};1955}1956}1957}else{1958$state->{opt}{$1} =undef;1959}1960}1961else1962{1963push@{$state->{args}},$arg;1964}1965}1966}1967else1968{1969my$mode=0;19701971foreachmy$value( @{$state->{arguments}} )1972{1973if($valueeq"--")1974{1975$mode++;1976next;1977}1978push@{$state->{args}},$valueif($mode==0);1979push@{$state->{files}},$valueif($mode==1);1980}1981}1982}19831984# This method uses $state->{directory} to populate $state->{args} with a list of filenames1985sub argsfromdir1986{1987my$updater=shift;19881989$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19901991return if(scalar( @{$state->{args}} ) >1);19921993my@gethead= @{$updater->gethead};19941995# push added files1996foreachmy$file(keys%{$state->{entries}}) {1997if(exists$state->{entries}{$file}{revision} &&1998$state->{entries}{$file}{revision} ==0)1999{2000push@gethead, { name =>$file, filehash =>'added'};2001}2002}20032004if(scalar(@{$state->{args}}) ==1)2005{2006my$arg=$state->{args}[0];2007$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );20082009$log->info("Only one arg specified, checking for directory expansion on '$arg'");20102011foreachmy$file(@gethead)2012{2013next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2014next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2015push@{$state->{args}},$file->{name};2016}20172018shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2019}else{2020$log->info("Only one arg specified, populating file list automatically");20212022$state->{args} = [];20232024foreachmy$file(@gethead)2025{2026next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2027next unless($file->{name} =~s/^$state->{prependdir}//);2028push@{$state->{args}},$file->{name};2029}2030}2031}20322033# This method cleans up the $state variable after a command that uses arguments has run2034sub statecleanup2035{2036$state->{files} = [];2037$state->{args} = [];2038$state->{arguments} = [];2039$state->{entries} = {};2040}20412042sub revparse2043{2044my$filename=shift;20452046returnundefunless(defined($state->{entries}{$filename}{revision} ) );20472048return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2049return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20502051returnundef;2052}20532054# This method takes a file hash and does a CVS "file transfer". Its2055# exact behaviour depends on a second, optional hash table argument:2056# - If $options->{targetfile}, dump the contents to that file;2057# - If $options->{print}, use M/MT to transmit the contents one line2058# at a time;2059# - Otherwise, transmit the size of the file, followed by the file2060# contents.2061sub transmitfile2062{2063my$filehash=shift;2064my$options=shift;20652066if(defined($filehash)and$filehasheq"deleted")2067{2068$log->warn("filehash is 'deleted'");2069return;2070}20712072die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20732074my$type=`git-cat-file -t$filehash`;2075 chomp$type;20762077 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20782079 my$size= `git-cat-file -s $filehash`;2080chomp$size;20812082$log->debug("transmitfile($filehash) size=$size, type=$type");20832084if(open my$fh,'-|',"git-cat-file","blob",$filehash)2085{2086if(defined($options->{targetfile} ) )2087{2088my$targetfile=$options->{targetfile};2089open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2090print NEWFILE $_while( <$fh> );2091close NEWFILE or die("Failed to write '$targetfile':$!");2092}elsif(defined($options->{print} ) &&$options->{print} ) {2093while( <$fh> ) {2094if(/\n\z/) {2095print'M ',$_;2096}else{2097print'MT text ',$_,"\n";2098}2099}2100}else{2101print"$size\n";2102printwhile( <$fh> );2103}2104close$fhor die("Couldn't close filehandle for transmitfile():$!");2105}else{2106die("Couldn't execute git-cat-file");2107}2108}21092110# This method takes a file name, and returns ( $dirpart, $filepart ) which2111# refers to the directory portion and the file portion of the filename2112# respectively2113sub filenamesplit2114{2115my$filename=shift;2116my$fixforlocaldir=shift;21172118my($filepart,$dirpart) = ($filename,".");2119($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2120$dirpart.="/";21212122if($fixforlocaldir)2123{2124$dirpart=~s/^$state->{prependdir}//;2125}21262127return($filepart,$dirpart);2128}21292130sub filecleanup2131{2132my$filename=shift;21332134returnundefunless(defined($filename));2135if($filename=~/^\// )2136{2137print"E absolute filenames '$filename' not supported by server\n";2138returnundef;2139}21402141$filename=~s/^\.\///g;2142$filename=$state->{prependdir} .$filename;2143return$filename;2144}21452146sub validateGitDir2147{2148if( !defined($state->{CVSROOT}) )2149{2150print"error 1 CVSROOT not specified\n";2151 cleanupWorkTree();2152exit;2153}2154if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2155{2156print"error 1 Internally inconsistent CVSROOT\n";2157 cleanupWorkTree();2158exit;2159}2160}21612162# Setup working directory in a work tree with the requested version2163# loaded in the index.2164sub setupWorkTree2165{2166my($ver) =@_;21672168 validateGitDir();21692170if( (defined($work->{state}) &&$work->{state} !=1) ||2171defined($work->{tmpDir}) )2172{2173$log->warn("Bad work tree state management");2174print"error 1 Internal setup multiple work trees without cleanup\n";2175 cleanupWorkTree();2176exit;2177}21782179$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);21802181if( !defined($work->{index}) )2182{2183(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2184}21852186chdir$work->{workDir}or2187die"Unable to chdir to$work->{workDir}\n";21882189$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");21902191$ENV{GIT_WORK_TREE} =".";2192$ENV{GIT_INDEX_FILE} =$work->{index};2193$work->{state} =2;21942195if($ver)2196{2197system("git","read-tree",$ver);2198unless($?==0)2199{2200$log->warn("Error running git-read-tree");2201die"Error running git-read-tree$verin$work->{workDir}$!\n";2202}2203}2204# else # req_annotate reads tree for each file2205}22062207# Ensure current directory is in some kind of working directory,2208# with a recent version loaded in the index.2209sub ensureWorkTree2210{2211if(defined($work->{tmpDir}) )2212{2213$log->warn("Bad work tree state management [ensureWorkTree()]");2214print"error 1 Internal setup multiple dirs without cleanup\n";2215 cleanupWorkTree();2216exit;2217}2218if($work->{state} )2219{2220return;2221}22222223 validateGitDir();22242225if( !defined($work->{emptyDir}) )2226{2227$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2228}2229chdir$work->{emptyDir}or2230die"Unable to chdir to$work->{emptyDir}\n";22312232my$ver=`git show-ref -s refs/heads/$state->{module}`;2233chomp$ver;2234if($ver!~/^[0-9a-f]{40}$/)2235{2236$log->warn("Error from git show-ref -s refs/head$state->{module}");2237print"error 1 cannot find the current HEAD of module";2238 cleanupWorkTree();2239exit;2240}22412242if( !defined($work->{index}) )2243{2244(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2245}22462247$ENV{GIT_WORK_TREE} =".";2248$ENV{GIT_INDEX_FILE} =$work->{index};2249$work->{state} =1;22502251system("git","read-tree",$ver);2252unless($?==0)2253{2254die"Error running git-read-tree$ver$!\n";2255}2256}22572258# Cleanup working directory that is not needed any longer.2259sub cleanupWorkTree2260{2261if( !$work->{state} )2262{2263return;2264}22652266chdir"/"or die"Unable to chdir '/'\n";22672268if(defined($work->{workDir}) )2269{2270 rmtree($work->{workDir} );2271undef$work->{workDir};2272}2273undef$work->{state};2274}22752276# Setup a temporary directory (not a working tree), typically for2277# merging dirty state as in req_update.2278sub setupTmpDir2279{2280$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2281chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";22822283return$work->{tmpDir};2284}22852286# Clean up a previously setupTmpDir. Restore previous work tree if2287# appropriate.2288sub cleanupTmpDir2289{2290if( !defined($work->{tmpDir}) )2291{2292$log->warn("cleanup tmpdir that has not been setup");2293die"Cleanup tmpDir that has not been setup\n";2294}2295if(defined($work->{state}) )2296{2297if($work->{state} ==1)2298{2299chdir$work->{emptyDir}or2300die"Unable to chdir to$work->{emptyDir}\n";2301}2302elsif($work->{state} ==2)2303{2304chdir$work->{workDir}or2305die"Unable to chdir to$work->{emptyDir}\n";2306}2307else2308{2309$log->warn("Inconsistent work dir state");2310die"Inconsistent work dir state\n";2311}2312}2313else2314{2315chdir"/"or die"Unable to chdir '/'\n";2316}2317}23182319# Given a path, this function returns a string containing the kopts2320# that should go into that path's Entries line. For example, a binary2321# file should get -kb.2322sub kopts_from_path2323{2324my($path,$srcType,$name) =@_;23252326if(defined($cfg->{gitcvs}{usecrlfattr} )and2327$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2328{2329my($val) = check_attr("crlf",$path);2330if($valeq"set")2331{2332return"";2333}2334elsif($valeq"unset")2335{2336return"-kb"2337}2338else2339{2340$log->info("Unrecognized check_attr crlf$path:$val");2341}2342}23432344if(defined($cfg->{gitcvs}{allbinary} ) )2345{2346if( ($cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i) )2347{2348return"-kb";2349}2350elsif( ($cfg->{gitcvs}{allbinary} =~/^\s*guess\s*$/i) )2351{2352if($srcTypeeq"sha1Or-k"&&2353!defined($name) )2354{2355my($ret)=$state->{entries}{$path}{options};2356if( !defined($ret) )2357{2358$ret=$state->{opt}{k};2359if(defined($ret))2360{2361$ret="-k$ret";2362}2363else2364{2365$ret="";2366}2367}2368if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )2369{2370print"E Bad -k option\n";2371$log->warn("Bad -k option:$ret");2372die"Error: Bad -k option:$ret\n";2373}23742375return$ret;2376}2377else2378{2379if( is_binary($srcType,$name) )2380{2381$log->debug("... as binary");2382return"-kb";2383}2384else2385{2386$log->debug("... as text");2387}2388}2389}2390}2391# Return "" to give no special treatment to any path2392return"";2393}23942395sub check_attr2396{2397my($attr,$path) =@_;2398 ensureWorkTree();2399if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2400{2401my$val= <$fh>;2402close$fh;2403$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2404return$val;2405}2406else2407{2408returnundef;2409}2410}24112412# This should have the same heuristics as convert.c:is_binary() and related.2413# Note that the bare CR test is done by callers in convert.c.2414sub is_binary2415{2416my($srcType,$name) =@_;2417$log->debug("is_binary($srcType,$name)");24182419# Minimize amount of interpreted code run in the inner per-character2420# loop for large files, by totalling each character value and2421# then analyzing the totals.2422my@counts;2423my$i;2424for($i=0;$i<256;$i++)2425{2426$counts[$i]=0;2427}24282429my$fh= open_blob_or_die($srcType,$name);2430my$line;2431while(defined($line=<$fh>) )2432{2433# Any '\0' and bare CR are considered binary.2434if($line=~/\0|(\r[^\n])/)2435{2436close($fh);2437return1;2438}24392440# Count up each character in the line:2441my$len=length($line);2442for($i=0;$i<$len;$i++)2443{2444$counts[ord(substr($line,$i,1))]++;2445}2446}2447close$fh;24482449# Don't count CR and LF as either printable/nonprintable2450$counts[ord("\n")]=0;2451$counts[ord("\r")]=0;24522453# Categorize individual character count into printable and nonprintable:2454my$printable=0;2455my$nonprintable=0;2456for($i=0;$i<256;$i++)2457{2458if($i<32&&2459$i!=ord("\b") &&2460$i!=ord("\t") &&2461$i!=033&&# ESC2462$i!=014)# FF2463{2464$nonprintable+=$counts[$i];2465}2466elsif($i==127)# DEL2467{2468$nonprintable+=$counts[$i];2469}2470else2471{2472$printable+=$counts[$i];2473}2474}24752476return($printable>>7) <$nonprintable;2477}24782479# Returns open file handle. Possible invocations:2480# - open_blob_or_die("file",$filename);2481# - open_blob_or_die("sha1",$filehash);2482sub open_blob_or_die2483{2484my($srcType,$name) =@_;2485my($fh);2486if($srcTypeeq"file")2487{2488if( !open$fh,"<",$name)2489{2490$log->warn("Unable to open file$name:$!");2491die"Unable to open file$name:$!\n";2492}2493}2494elsif($srcTypeeq"sha1"||$srcTypeeq"sha1Or-k")2495{2496unless(defined($name)and$name=~/^[a-zA-Z0-9]{40}$/)2497{2498$log->warn("Need filehash");2499die"Need filehash\n";2500}25012502my$type=`git cat-file -t$name`;2503 chomp$type;25042505 unless ( defined ($type) and$typeeq "blob" )2506 {2507$log->warn("Invalid type '$type' for '$name'");2508 die ( "Invalid type '$type' (expected 'blob')" )2509 }25102511 my$size= `git cat-file -s $name`;2512chomp$size;25132514$log->debug("open_blob_or_die($name) size=$size, type=$type");25152516unless(open$fh,'-|',"git","cat-file","blob",$name)2517{2518$log->warn("Unable to open sha1$name");2519die"Unable to open sha1$name\n";2520}2521}2522else2523{2524$log->warn("Unknown type of blob source:$srcType");2525die"Unknown type of blob source:$srcType\n";2526}2527return$fh;2528}25292530# Generate a CVS author name from Git author information, by taking2531# the first eight characters of the user part of the email address.2532sub cvs_author2533{2534my$author_line=shift;2535(my$author) =$author_line=~/<([^>@]{1,8})/;25362537$author;2538}25392540package GITCVS::log;25412542####2543#### Copyright The Open University UK - 2006.2544####2545#### Authors: Martyn Smith <martyn@catalyst.net.nz>2546#### Martin Langhoff <martin@catalyst.net.nz>2547####2548####25492550use strict;2551use warnings;25522553=head1 NAME25542555GITCVS::log25562557=head1 DESCRIPTION25582559This module provides very crude logging with a similar interface to2560Log::Log4perl25612562=head1 METHODS25632564=cut25652566=head2 new25672568Creates a new log object, optionally you can specify a filename here to2569indicate the file to log to. If no log file is specified, you can specify one2570later with method setfile, or indicate you no longer want logging with method2571nofile.25722573Until one of these methods is called, all log calls will buffer messages ready2574to write out.25752576=cut2577sub new2578{2579my$class=shift;2580my$filename=shift;25812582my$self= {};25832584bless$self,$class;25852586if(defined($filename) )2587{2588open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2589}25902591return$self;2592}25932594=head2 setfile25952596This methods takes a filename, and attempts to open that file as the log file.2597If successful, all buffered data is written out to the file, and any further2598logging is written directly to the file.25992600=cut2601sub setfile2602{2603my$self=shift;2604my$filename=shift;26052606if(defined($filename) )2607{2608open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2609}26102611return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26122613while(my$line=shift@{$self->{buffer}} )2614{2615print{$self->{fh}}$line;2616}2617}26182619=head2 nofile26202621This method indicates no logging is going to be used. It flushes any entries in2622the internal buffer, and sets a flag to ensure no further data is put there.26232624=cut2625sub nofile2626{2627my$self=shift;26282629$self->{nolog} =1;26302631return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26322633$self->{buffer} = [];2634}26352636=head2 _logopen26372638Internal method. Returns true if the log file is open, false otherwise.26392640=cut2641sub _logopen2642{2643my$self=shift;26442645return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2646return0;2647}26482649=head2 debug info warn fatal26502651These four methods are wrappers to _log. They provide the actual interface for2652logging data.26532654=cut2655sub debug {my$self=shift;$self->_log("debug",@_); }2656sub info {my$self=shift;$self->_log("info",@_); }2657subwarn{my$self=shift;$self->_log("warn",@_); }2658sub fatal {my$self=shift;$self->_log("fatal",@_); }26592660=head2 _log26612662This is an internal method called by the logging functions. It generates a2663timestamp and pushes the logged line either to file, or internal buffer.26642665=cut2666sub _log2667{2668my$self=shift;2669my$level=shift;26702671return if($self->{nolog} );26722673my@time=localtime;2674my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2675$time[5] +1900,2676$time[4] +1,2677$time[3],2678$time[2],2679$time[1],2680$time[0],2681uc$level,2682);26832684if($self->_logopen)2685{2686print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2687}else{2688push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2689}2690}26912692=head2 DESTROY26932694This method simply closes the file handle if one is open26952696=cut2697sub DESTROY2698{2699my$self=shift;27002701if($self->_logopen)2702{2703close$self->{fh};2704}2705}27062707package GITCVS::updater;27082709####2710#### Copyright The Open University UK - 2006.2711####2712#### Authors: Martyn Smith <martyn@catalyst.net.nz>2713#### Martin Langhoff <martin@catalyst.net.nz>2714####2715####27162717use strict;2718use warnings;2719use DBI;27202721=head1 METHODS27222723=cut27242725=head2 new27262727=cut2728sub new2729{2730my$class=shift;2731my$config=shift;2732my$module=shift;2733my$log=shift;27342735die"Need to specify a git repository"unless(defined($config)and-d $config);2736die"Need to specify a module"unless(defined($module) );27372738$class=ref($class) ||$class;27392740my$self= {};27412742bless$self,$class;27432744$self->{valid_tables} = {'revision'=>1,2745'revision_ix1'=>1,2746'revision_ix2'=>1,2747'head'=>1,2748'head_ix1'=>1,2749'properties'=>1,2750'commitmsgs'=>1};27512752$self->{module} =$module;2753$self->{git_path} =$config."/";27542755$self->{log} =$log;27562757die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );27582759$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2760$cfg->{gitcvs}{dbdriver} ||"SQLite";2761$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2762$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2763$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2764$cfg->{gitcvs}{dbuser} ||"";2765$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2766$cfg->{gitcvs}{dbpass} ||"";2767$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2768$cfg->{gitcvs}{dbtablenameprefix} ||"";2769my%mapping= ( m =>$module,2770 a =>$state->{method},2771 u =>getlogin||getpwuid($<) || $<,2772 G =>$self->{git_path},2773 g => mangle_dirname($self->{git_path}),2774);2775$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2776$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2777$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2778$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});27792780die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2781die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2782$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2783$self->{dbuser},2784$self->{dbpass});2785die"Error connecting to database\n"unlessdefined$self->{dbh};27862787$self->{tables} = {};2788foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2789{2790$self->{tables}{$table} =1;2791}27922793# Construct the revision table if required2794unless($self->{tables}{$self->tablename("revision")} )2795{2796my$tablename=$self->tablename("revision");2797my$ix1name=$self->tablename("revision_ix1");2798my$ix2name=$self->tablename("revision_ix2");2799$self->{dbh}->do("2800 CREATE TABLE$tablename(2801 name TEXT NOT NULL,2802 revision INTEGER NOT NULL,2803 filehash TEXT NOT NULL,2804 commithash TEXT NOT NULL,2805 author TEXT NOT NULL,2806 modified TEXT NOT NULL,2807 mode TEXT NOT NULL2808 )2809 ");2810$self->{dbh}->do("2811 CREATE INDEX$ix1name2812 ON$tablename(name,revision)2813 ");2814$self->{dbh}->do("2815 CREATE INDEX$ix2name2816 ON$tablename(name,commithash)2817 ");2818}28192820# Construct the head table if required2821unless($self->{tables}{$self->tablename("head")} )2822{2823my$tablename=$self->tablename("head");2824my$ix1name=$self->tablename("head_ix1");2825$self->{dbh}->do("2826 CREATE TABLE$tablename(2827 name TEXT NOT NULL,2828 revision INTEGER NOT NULL,2829 filehash TEXT NOT NULL,2830 commithash TEXT NOT NULL,2831 author TEXT NOT NULL,2832 modified TEXT NOT NULL,2833 mode TEXT NOT NULL2834 )2835 ");2836$self->{dbh}->do("2837 CREATE INDEX$ix1name2838 ON$tablename(name)2839 ");2840}28412842# Construct the properties table if required2843unless($self->{tables}{$self->tablename("properties")} )2844{2845my$tablename=$self->tablename("properties");2846$self->{dbh}->do("2847 CREATE TABLE$tablename(2848 key TEXT NOT NULL PRIMARY KEY,2849 value TEXT2850 )2851 ");2852}28532854# Construct the commitmsgs table if required2855unless($self->{tables}{$self->tablename("commitmsgs")} )2856{2857my$tablename=$self->tablename("commitmsgs");2858$self->{dbh}->do("2859 CREATE TABLE$tablename(2860 key TEXT NOT NULL PRIMARY KEY,2861 value TEXT2862 )2863 ");2864}28652866return$self;2867}28682869=head2 tablename28702871=cut2872sub tablename2873{2874my$self=shift;2875my$name=shift;28762877if(exists$self->{valid_tables}{$name}) {2878return$self->{dbtablenameprefix} .$name;2879}else{2880returnundef;2881}2882}28832884=head2 update28852886=cut2887sub update2888{2889my$self=shift;28902891# first lets get the commit list2892$ENV{GIT_DIR} =$self->{git_path};28932894my$commitsha1=`git rev-parse$self->{module}`;2895chomp$commitsha1;28962897my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2898unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2899{2900die("Invalid module '$self->{module}'");2901}290229032904my$git_log;2905my$lastcommit=$self->_get_prop("last_commit");29062907if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2908return1;2909}29102911# Start exclusive lock here...2912$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";29132914# TODO: log processing is memory bound2915# if we can parse into a 2nd file that is in reverse order2916# we can probably do something really efficient2917my@git_log_params= ('--pretty','--parents','--topo-order');29182919if(defined$lastcommit) {2920push@git_log_params,"$lastcommit..$self->{module}";2921}else{2922push@git_log_params,$self->{module};2923}2924# git-rev-list is the backend / plumbing version of git-log2925open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";29262927my@commits;29282929my%commit= ();29302931while( <GITLOG> )2932{2933chomp;2934if(m/^commit\s+(.*)$/) {2935# on ^commit lines put the just seen commit in the stack2936# and prime things for the next one2937if(keys%commit) {2938my%copy=%commit;2939unshift@commits, \%copy;2940%commit= ();2941}2942my@parents=split(m/\s+/,$1);2943$commit{hash} =shift@parents;2944$commit{parents} = \@parents;2945}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2946# on rfc822-like lines seen before we see any message,2947# lowercase the entry and put it in the hash as key-value2948$commit{lc($1)} =$2;2949}else{2950# message lines - skip initial empty line2951# and trim whitespace2952if(!exists($commit{message}) &&m/^\s*$/) {2953# define it to mark the end of headers2954$commit{message} ='';2955next;2956}2957s/^\s+//;s/\s+$//;# trim ws2958$commit{message} .=$_."\n";2959}2960}2961close GITLOG;29622963unshift@commits, \%commitif(keys%commit);29642965# Now all the commits are in the @commits bucket2966# ordered by time DESC. for each commit that needs processing,2967# determine whether it's following the last head we've seen or if2968# it's on its own branch, grab a file list, and add whatever's changed2969# NOTE: $lastcommit refers to the last commit from previous run2970# $lastpicked is the last commit we picked in this run2971my$lastpicked;2972my$head= {};2973if(defined$lastcommit) {2974$lastpicked=$lastcommit;2975}29762977my$committotal=scalar(@commits);2978my$commitcount=0;29792980# Load the head table into $head (for cached lookups during the update process)2981foreachmy$file( @{$self->gethead()} )2982{2983$head->{$file->{name}} =$file;2984}29852986foreachmy$commit(@commits)2987{2988$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2989if(defined$lastpicked)2990{2991if(!in_array($lastpicked, @{$commit->{parents}}))2992{2993# skip, we'll see this delta2994# as part of a merge later2995# warn "skipping off-track $commit->{hash}\n";2996next;2997}elsif(@{$commit->{parents}} >1) {2998# it is a merge commit, for each parent that is2999# not $lastpicked, see if we can get a log3000# from the merge-base to that parent to put it3001# in the message as a merge summary.3002my@parents= @{$commit->{parents}};3003foreachmy$parent(@parents) {3004# git-merge-base can potentially (but rarely) throw3005# several candidate merge bases. let's assume3006# that the first one is the best one.3007if($parenteq$lastpicked) {3008next;3009}3010my$base=eval{3011 safe_pipe_capture('git-merge-base',3012$lastpicked,$parent);3013};3014# The two branches may not be related at all,3015# in which case merge base simply fails to find3016# any, but that's Ok.3017next if($@);30183019chomp$base;3020if($base) {3021my@merged;3022# print "want to log between $base $parent \n";3023open(GITLOG,'-|','git-log','--pretty=medium',"$base..$parent")3024or die"Cannot call git-log:$!";3025my$mergedhash;3026while(<GITLOG>) {3027chomp;3028if(!defined$mergedhash) {3029if(m/^commit\s+(.+)$/) {3030$mergedhash=$1;3031}else{3032next;3033}3034}else{3035# grab the first line that looks non-rfc8223036# aka has content after leading space3037if(m/^\s+(\S.*)$/) {3038my$title=$1;3039$title=substr($title,0,100);# truncate3040unshift@merged,"$mergedhash$title";3041undef$mergedhash;3042}3043}3044}3045close GITLOG;3046if(@merged) {3047$commit->{mergemsg} =$commit->{message};3048$commit->{mergemsg} .="\nSummary of merged commits:\n\n";3049foreachmy$summary(@merged) {3050$commit->{mergemsg} .="\t$summary\n";3051}3052$commit->{mergemsg} .="\n\n";3053# print "Message for $commit->{hash} \n$commit->{mergemsg}";3054}3055}3056}3057}3058}30593060# convert the date to CVS-happy format3061$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);30623063if(defined($lastpicked) )3064{3065my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");3066local($/) ="\0";3067while( <FILELIST> )3068{3069chomp;3070unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)3071{3072die("Couldn't process git-diff-tree line :$_");3073}3074my($mode,$hash,$change) = ($1,$2,$3);3075my$name= <FILELIST>;3076chomp($name);30773078# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");30793080my$git_perms="";3081$git_perms.="r"if($mode&4);3082$git_perms.="w"if($mode&2);3083$git_perms.="x"if($mode&1);3084$git_perms="rw"if($git_permseq"");30853086if($changeeq"D")3087{3088#$log->debug("DELETE $name");3089$head->{$name} = {3090 name =>$name,3091 revision =>$head->{$name}{revision} +1,3092 filehash =>"deleted",3093 commithash =>$commit->{hash},3094 modified =>$commit->{date},3095 author =>$commit->{author},3096 mode =>$git_perms,3097};3098$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3099}3100elsif($changeeq"M"||$changeeq"T")3101{3102#$log->debug("MODIFIED $name");3103$head->{$name} = {3104 name =>$name,3105 revision =>$head->{$name}{revision} +1,3106 filehash =>$hash,3107 commithash =>$commit->{hash},3108 modified =>$commit->{date},3109 author =>$commit->{author},3110 mode =>$git_perms,3111};3112$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3113}3114elsif($changeeq"A")3115{3116#$log->debug("ADDED $name");3117$head->{$name} = {3118 name =>$name,3119 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,3120 filehash =>$hash,3121 commithash =>$commit->{hash},3122 modified =>$commit->{date},3123 author =>$commit->{author},3124 mode =>$git_perms,3125};3126$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3127}3128else3129{3130$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");3131die;3132}3133}3134close FILELIST;3135}else{3136# this is used to detect files removed from the repo3137my$seen_files= {};31383139my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");3140local$/="\0";3141while( <FILELIST> )3142{3143chomp;3144unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)3145{3146die("Couldn't process git-ls-tree line :$_");3147}31483149my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);31503151$seen_files->{$git_filename} =1;31523153my($oldhash,$oldrevision,$oldmode) = (3154$head->{$git_filename}{filehash},3155$head->{$git_filename}{revision},3156$head->{$git_filename}{mode}3157);31583159if($git_perms=~/^\d\d\d(\d)\d\d/o)3160{3161$git_perms="";3162$git_perms.="r"if($1&4);3163$git_perms.="w"if($1&2);3164$git_perms.="x"if($1&1);3165}else{3166$git_perms="rw";3167}31683169# unless the file exists with the same hash, we need to update it ...3170unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3171{3172my$newrevision= ($oldrevisionor0) +1;31733174$head->{$git_filename} = {3175 name =>$git_filename,3176 revision =>$newrevision,3177 filehash =>$git_hash,3178 commithash =>$commit->{hash},3179 modified =>$commit->{date},3180 author =>$commit->{author},3181 mode =>$git_perms,3182};318331843185$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3186}3187}3188close FILELIST;31893190# Detect deleted files3191foreachmy$file(keys%$head)3192{3193unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3194{3195$head->{$file}{revision}++;3196$head->{$file}{filehash} ="deleted";3197$head->{$file}{commithash} =$commit->{hash};3198$head->{$file}{modified} =$commit->{date};3199$head->{$file}{author} =$commit->{author};32003201$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3202}3203}3204# END : "Detect deleted files"3205}320632073208if(exists$commit->{mergemsg})3209{3210$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3211}32123213$lastpicked=$commit->{hash};32143215$self->_set_prop("last_commit",$commit->{hash});3216}32173218$self->delete_head();3219foreachmy$file(keys%$head)3220{3221$self->insert_head(3222$file,3223$head->{$file}{revision},3224$head->{$file}{filehash},3225$head->{$file}{commithash},3226$head->{$file}{modified},3227$head->{$file}{author},3228$head->{$file}{mode},3229);3230}3231# invalidate the gethead cache3232$self->{gethead_cache} =undef;323332343235# Ending exclusive lock here3236$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3237}32383239sub insert_rev3240{3241my$self=shift;3242my$name=shift;3243my$revision=shift;3244my$filehash=shift;3245my$commithash=shift;3246my$modified=shift;3247my$author=shift;3248my$mode=shift;3249my$tablename=$self->tablename("revision");32503251my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3252$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3253}32543255sub insert_mergelog3256{3257my$self=shift;3258my$key=shift;3259my$value=shift;3260my$tablename=$self->tablename("commitmsgs");32613262my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3263$insert_mergelog->execute($key,$value);3264}32653266sub delete_head3267{3268my$self=shift;3269my$tablename=$self->tablename("head");32703271my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3272$delete_head->execute();3273}32743275sub insert_head3276{3277my$self=shift;3278my$name=shift;3279my$revision=shift;3280my$filehash=shift;3281my$commithash=shift;3282my$modified=shift;3283my$author=shift;3284my$mode=shift;3285my$tablename=$self->tablename("head");32863287my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3288$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3289}32903291sub _headrev3292{3293my$self=shift;3294my$filename=shift;3295my$tablename=$self->tablename("head");32963297my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3298$db_query->execute($filename);3299my($hash,$revision,$mode) =$db_query->fetchrow_array;33003301return($hash,$revision,$mode);3302}33033304sub _get_prop3305{3306my$self=shift;3307my$key=shift;3308my$tablename=$self->tablename("properties");33093310my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3311$db_query->execute($key);3312my($value) =$db_query->fetchrow_array;33133314return$value;3315}33163317sub _set_prop3318{3319my$self=shift;3320my$key=shift;3321my$value=shift;3322my$tablename=$self->tablename("properties");33233324my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3325$db_query->execute($value,$key);33263327unless($db_query->rows)3328{3329$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3330$db_query->execute($key,$value);3331}33323333return$value;3334}33353336=head2 gethead33373338=cut33393340sub gethead3341{3342my$self=shift;3343my$tablename=$self->tablename("head");33443345return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );33463347my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3348$db_query->execute();33493350my$tree= [];3351while(my$file=$db_query->fetchrow_hashref)3352{3353push@$tree,$file;3354}33553356$self->{gethead_cache} =$tree;33573358return$tree;3359}33603361=head2 getlog33623363=cut33643365sub getlog3366{3367my$self=shift;3368my$filename=shift;3369my$tablename=$self->tablename("revision");33703371my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3372$db_query->execute($filename);33733374my$tree= [];3375while(my$file=$db_query->fetchrow_hashref)3376{3377push@$tree,$file;3378}33793380return$tree;3381}33823383=head2 getmeta33843385This function takes a filename (with path) argument and returns a hashref of3386metadata for that file.33873388=cut33893390sub getmeta3391{3392my$self=shift;3393my$filename=shift;3394my$revision=shift;3395my$tablename_rev=$self->tablename("revision");3396my$tablename_head=$self->tablename("head");33973398my$db_query;3399if(defined($revision)and$revision=~/^\d+$/)3400{3401$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3402$db_query->execute($filename,$revision);3403}3404elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3405{3406$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3407$db_query->execute($filename,$revision);3408}else{3409$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3410$db_query->execute($filename);3411}34123413return$db_query->fetchrow_hashref;3414}34153416=head2 commitmessage34173418this function takes a commithash and returns the commit message for that commit34193420=cut3421sub commitmessage3422{3423my$self=shift;3424my$commithash=shift;3425my$tablename=$self->tablename("commitmsgs");34263427die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);34283429my$db_query;3430$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3431$db_query->execute($commithash);34323433my($message) =$db_query->fetchrow_array;34343435if(defined($message) )3436{3437$message.=" "if($message=~/\n$/);3438return$message;3439}34403441my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);3442shift@lineswhile($lines[0] =~/\S/);3443$message=join("",@lines);3444$message.=" "if($message=~/\n$/);3445return$message;3446}34473448=head2 gethistory34493450This function takes a filename (with path) argument and returns an arrayofarrays3451containing revision,filehash,commithash ordered by revision descending34523453=cut3454sub gethistory3455{3456my$self=shift;3457my$filename=shift;3458my$tablename=$self->tablename("revision");34593460my$db_query;3461$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3462$db_query->execute($filename);34633464return$db_query->fetchall_arrayref;3465}34663467=head2 gethistorydense34683469This function takes a filename (with path) argument and returns an arrayofarrays3470containing revision,filehash,commithash ordered by revision descending.34713472This version of gethistory skips deleted entries -- so it is useful for annotate.3473The 'dense' part is a reference to a '--dense' option available for git-rev-list3474and other git tools that depend on it.34753476=cut3477sub gethistorydense3478{3479my$self=shift;3480my$filename=shift;3481my$tablename=$self->tablename("revision");34823483my$db_query;3484$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3485$db_query->execute($filename);34863487return$db_query->fetchall_arrayref;3488}34893490=head2 in_array()34913492from Array::PAT - mimics the in_array() function3493found in PHP. Yuck but works for small arrays.34943495=cut3496sub in_array3497{3498my($check,@array) =@_;3499my$retval=0;3500foreachmy$test(@array){3501if($checkeq$test){3502$retval=1;3503}3504}3505return$retval;3506}35073508=head2 safe_pipe_capture35093510an alternative to `command` that allows input to be passed as an array3511to work around shell problems with weird characters in arguments35123513=cut3514sub safe_pipe_capture {35153516my@output;35173518if(my$pid=open my$child,'-|') {3519@output= (<$child>);3520close$childor die join(' ',@_).":$!$?";3521}else{3522exec(@_)or die"$!$?";# exec() can fail the executable can't be found3523}3524returnwantarray?@output:join('',@output);3525}35263527=head2 mangle_dirname35283529create a string from a directory name that is suitable to use as3530part of a filename, mainly by converting all chars except \w.- to _35313532=cut3533sub mangle_dirname {3534my$dirname=shift;3535return unlessdefined$dirname;35363537$dirname=~s/[^\w.-]/_/g;35383539return$dirname;3540}35413542=head2 mangle_tablename35433544create a string from a that is suitable to use as part of an SQL table3545name, mainly by converting all chars except \w to _35463547=cut3548sub mangle_tablename {3549my$tablename=shift;3550return unlessdefined$tablename;35513552$tablename=~s/[^\w_]/_/g;35533554return$tablename;3555}355635571;