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 my$module=$state->{args}[0]; 805$state->{module} =$module; 806 my$checkout_path=$module; 807 808 # use the user specified directory if we're given it 809$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 810 811$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 812 813$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 814 815$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 816 817# Grab a handle to the SQLite db and do any necessary updates 818my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 819$updater->update(); 820 821$checkout_path=~ s|/$||;# get rid of trailing slashes 822 823# Eclipse seems to need the Clear-sticky command 824# to prepare the 'Entries' file for the new directory. 825print"Clear-sticky$checkout_path/\n"; 826print$state->{CVSROOT} ."/$module/\n"; 827print"Clear-static-directory$checkout_path/\n"; 828print$state->{CVSROOT} ."/$module/\n"; 829print"Clear-sticky$checkout_path/\n";# yes, twice 830print$state->{CVSROOT} ."/$module/\n"; 831print"Template$checkout_path/\n"; 832print$state->{CVSROOT} ."/$module/\n"; 833print"0\n"; 834 835# instruct the client that we're checking out to $checkout_path 836print"E cvs checkout: Updating$checkout_path\n"; 837 838my%seendirs= (); 839my$lastdir=''; 840 841# recursive 842sub prepdir { 843my($dir,$repodir,$remotedir,$seendirs) =@_; 844my$parent= dirname($dir); 845$dir=~ s|/+$||; 846$repodir=~ s|/+$||; 847$remotedir=~ s|/+$||; 848$parent=~ s|/+$||; 849$log->debug("announcedir$dir,$repodir,$remotedir"); 850 851if($parenteq'.'||$parenteq'./') { 852$parent=''; 853} 854# recurse to announce unseen parents first 855if(length($parent) && !exists($seendirs->{$parent})) { 856 prepdir($parent,$repodir,$remotedir,$seendirs); 857} 858# Announce that we are going to modify at the parent level 859if($parent) { 860print"E cvs checkout: Updating$remotedir/$parent\n"; 861}else{ 862print"E cvs checkout: Updating$remotedir\n"; 863} 864print"Clear-sticky$remotedir/$parent/\n"; 865print"$repodir/$parent/\n"; 866 867print"Clear-static-directory$remotedir/$dir/\n"; 868print"$repodir/$dir/\n"; 869print"Clear-sticky$remotedir/$parent/\n";# yes, twice 870print"$repodir/$parent/\n"; 871print"Template$remotedir/$dir/\n"; 872print"$repodir/$dir/\n"; 873print"0\n"; 874 875$seendirs->{$dir} =1; 876} 877 878foreachmy$git( @{$updater->gethead} ) 879{ 880# Don't want to check out deleted files 881next if($git->{filehash}eq"deleted"); 882 883my$fullName=$git->{name}; 884($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 885 886if(length($git->{dir}) &&$git->{dir}ne'./' 887&&$git->{dir}ne$lastdir) { 888unless(exists($seendirs{$git->{dir}})) { 889 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 890$checkout_path, \%seendirs); 891$lastdir=$git->{dir}; 892$seendirs{$git->{dir}} =1; 893} 894print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 895} 896 897# modification time of this file 898print"Mod-time$git->{modified}\n"; 899 900# print some information to the client 901if(defined($git->{dir} )and$git->{dir}ne"./") 902{ 903print"M U$checkout_path/$git->{dir}$git->{name}\n"; 904}else{ 905print"M U$checkout_path/$git->{name}\n"; 906} 907 908# instruct client we're sending a file to put in this path 909print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 910 911print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 912 913# this is an "entries" line 914my$kopts= kopts_from_path($fullName,"sha1",$git->{filehash}); 915print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 916# permissions 917print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 918 919# transmit file 920 transmitfile($git->{filehash}); 921} 922 923print"ok\n"; 924 925 statecleanup(); 926} 927 928# update \n 929# Response expected: yes. Actually do a cvs update command. This uses any 930# previous Argument, Directory, Entry, or Modified requests, if they have 931# been sent. The last Directory sent specifies the working directory at the 932# time of the operation. The -I option is not used--files which the client 933# can decide whether to ignore are not mentioned and the client sends the 934# Questionable request for others. 935sub req_update 936{ 937my($cmd,$data) =@_; 938 939$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 940 941 argsplit("update"); 942 943# 944# It may just be a client exploring the available heads/modules 945# in that case, list them as top level directories and leave it 946# at that. Eclipse uses this technique to offer you a list of 947# projects (heads in this case) to checkout. 948# 949if($state->{module}eq'') { 950my$heads_dir=$state->{CVSROOT} .'/refs/heads'; 951if(!opendir HEADS,$heads_dir) { 952print"E [server aborted]: Failed to open directory, " 953."$heads_dir:$!\nerror\n"; 954return0; 955} 956print"E cvs update: Updating .\n"; 957while(my$head=readdir(HEADS)) { 958if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 959print"E cvs update: New directory `$head'\n"; 960} 961} 962closedir HEADS; 963print"ok\n"; 964return1; 965} 966 967 968# Grab a handle to the SQLite db and do any necessary updates 969my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 970 971$updater->update(); 972 973 argsfromdir($updater); 974 975#$log->debug("update state : " . Dumper($state)); 976 977# foreach file specified on the command line ... 978foreachmy$filename( @{$state->{args}} ) 979{ 980$filename= filecleanup($filename); 981 982$log->debug("Processing file$filename"); 983 984# if we have a -C we should pretend we never saw modified stuff 985if(exists($state->{opt}{C} ) ) 986{ 987delete$state->{entries}{$filename}{modified_hash}; 988delete$state->{entries}{$filename}{modified_filename}; 989$state->{entries}{$filename}{unchanged} =1; 990} 991 992my$meta; 993if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 994{ 995$meta=$updater->getmeta($filename,$1); 996}else{ 997$meta=$updater->getmeta($filename); 998} 9991000# If -p was given, "print" the contents of the requested revision.1001if(exists($state->{opt}{p} ) ) {1002if(defined($meta->{revision} ) ) {1003$log->info("Printing '$filename' revision ".$meta->{revision});10041005 transmitfile($meta->{filehash}, {print=>1});1006}10071008next;1009}10101011if( !defined$meta)1012{1013$meta= {1014 name =>$filename,1015 revision =>0,1016 filehash =>'added'1017};1018}10191020my$oldmeta=$meta;10211022my$wrev= revparse($filename);10231024# If the working copy is an old revision, lets get that version too for comparison.1025if(defined($wrev)and$wrev!=$meta->{revision} )1026{1027$oldmeta=$updater->getmeta($filename,$wrev);1028}10291030#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");10311032# Files are up to date if the working copy and repo copy have the same revision,1033# and the working copy is unmodified _and_ the user hasn't specified -C1034next if(defined($wrev)1035and defined($meta->{revision})1036and$wrev==$meta->{revision}1037and$state->{entries}{$filename}{unchanged}1038and not exists($state->{opt}{C} ) );10391040# If the working copy and repo copy have the same revision,1041# but the working copy is modified, tell the client it's modified1042if(defined($wrev)1043and defined($meta->{revision})1044and$wrev==$meta->{revision}1045and defined($state->{entries}{$filename}{modified_hash})1046and not exists($state->{opt}{C} ) )1047{1048$log->info("Tell the client the file is modified");1049print"MT text M\n";1050print"MT fname$filename\n";1051print"MT newline\n";1052next;1053}10541055if($meta->{filehash}eq"deleted")1056{1057my($filepart,$dirpart) = filenamesplit($filename,1);10581059$log->info("Removing '$filename' from working copy (no longer in the repo)");10601061print"E cvs update: `$filename' is no longer in the repository\n";1062# Don't want to actually _DO_ the update if -n specified1063unless($state->{globaloptions}{-n} ) {1064print"Removed$dirpart\n";1065print"$filepart\n";1066}1067}1068elsif(not defined($state->{entries}{$filename}{modified_hash} )1069or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1070or$meta->{filehash}eq'added')1071{1072# normal update, just send the new revision (either U=Update,1073# or A=Add, or R=Remove)1074if(defined($wrev) &&$wrev<0)1075{1076$log->info("Tell the client the file is scheduled for removal");1077print"MT text R\n";1078print"MT fname$filename\n";1079print"MT newline\n";1080next;1081}1082elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1083{1084$log->info("Tell the client the file is scheduled for addition");1085print"MT text A\n";1086print"MT fname$filename\n";1087print"MT newline\n";1088next;10891090}1091else{1092$log->info("Updating '$filename' to ".$meta->{revision});1093print"MT +updated\n";1094print"MT text U\n";1095print"MT fname$filename\n";1096print"MT newline\n";1097print"MT -updated\n";1098}10991100my($filepart,$dirpart) = filenamesplit($filename,1);11011102# Don't want to actually _DO_ the update if -n specified1103unless($state->{globaloptions}{-n} )1104{1105if(defined($wrev) )1106{1107# instruct client we're sending a file to put in this path as a replacement1108print"Update-existing$dirpart\n";1109$log->debug("Updating existing file 'Update-existing$dirpart'");1110}else{1111# instruct client we're sending a file to put in this path as a new file1112print"Clear-static-directory$dirpart\n";1113print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1114print"Clear-sticky$dirpart\n";1115print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";11161117$log->debug("Creating new file 'Created$dirpart'");1118print"Created$dirpart\n";1119}1120print$state->{CVSROOT} ."/$state->{module}/$filename\n";11211122# this is an "entries" line1123my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1124$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1125print"/$filepart/1.$meta->{revision}//$kopts/\n";11261127# permissions1128$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1129print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11301131# transmit file1132 transmitfile($meta->{filehash});1133}1134}else{1135$log->info("Updating '$filename'");1136my($filepart,$dirpart) = filenamesplit($meta->{name},1);11371138my$mergeDir= setupTmpDir();11391140my$file_local=$filepart.".mine";1141my$mergedFile="$mergeDir/$file_local";1142system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1143my$file_old=$filepart.".".$oldmeta->{revision};1144 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1145my$file_new=$filepart.".".$meta->{revision};1146 transmitfile($meta->{filehash}, { targetfile =>$file_new});11471148# we need to merge with the local changes ( M=successful merge, C=conflict merge )1149$log->info("Merging$file_local,$file_old,$file_new");1150print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11511152$log->debug("Temporary directory for merge is$mergeDir");11531154my$return=system("git","merge-file",$file_local,$file_old,$file_new);1155$return>>=8;11561157 cleanupTmpDir();11581159if($return==0)1160{1161$log->info("Merged successfully");1162print"M M$filename\n";1163$log->debug("Merged$dirpart");11641165# Don't want to actually _DO_ the update if -n specified1166unless($state->{globaloptions}{-n} )1167{1168print"Merged$dirpart\n";1169$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1170print$state->{CVSROOT} ."/$state->{module}/$filename\n";1171my$kopts= kopts_from_path("$dirpart/$filepart",1172"file",$mergedFile);1173$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1174print"/$filepart/1.$meta->{revision}//$kopts/\n";1175}1176}1177elsif($return==1)1178{1179$log->info("Merged with conflicts");1180print"E cvs update: conflicts found in$filename\n";1181print"M C$filename\n";11821183# Don't want to actually _DO_ the update if -n specified1184unless($state->{globaloptions}{-n} )1185{1186print"Merged$dirpart\n";1187print$state->{CVSROOT} ."/$state->{module}/$filename\n";1188my$kopts= kopts_from_path("$dirpart/$filepart",1189"file",$mergedFile);1190print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1191}1192}1193else1194{1195$log->warn("Merge failed");1196next;1197}11981199# Don't want to actually _DO_ the update if -n specified1200unless($state->{globaloptions}{-n} )1201{1202# permissions1203$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1204print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12051206# transmit file, format is single integer on a line by itself (file1207# size) followed by the file contents1208# TODO : we should copy files in blocks1209my$data=`cat$mergedFile`;1210$log->debug("File size : " . length($data));1211 print length($data) . "\n";1212 print$data;1213 }1214 }12151216 }12171218 print "ok\n";1219}12201221sub req_ci1222{1223 my ($cmd,$data) =@_;12241225 argsplit("ci");12261227 #$log->debug("State : " . Dumper($state));12281229$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));12301231 if ($state->{method} eq 'pserver')1232 {1233 print "error 1 pserver access cannot commit\n";1234 cleanupWorkTree();1235 exit;1236 }12371238 if ( -e$state->{CVSROOT} . "/index" )1239 {1240$log->warn("file 'index' already exists in the git repository");1241 print "error 1 Index already exists in git repo\n";1242 cleanupWorkTree();1243 exit;1244 }12451246 # Grab a handle to the SQLite db and do any necessary updates1247 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1248$updater->update();12491250 # Remember where the head was at the beginning.1251 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1252 chomp$parenthash;1253 if ($parenthash!~ /^[0-9a-f]{40}$/) {1254 print "error 1 pserver cannot find the current HEAD of module";1255 cleanupWorkTree();1256 exit;1257 }12581259 setupWorkTree($parenthash);12601261$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");12621263$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");12641265 my@committedfiles= ();1266 my%oldmeta;12671268 # foreach file specified on the command line ...1269 foreach my$filename( @{$state->{args}} )1270 {1271 my$committedfile=$filename;1272$filename= filecleanup($filename);12731274 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12751276 my$meta=$updater->getmeta($filename);1277$oldmeta{$filename} =$meta;12781279 my$wrev= revparse($filename);12801281 my ($filepart,$dirpart) = filenamesplit($filename);12821283 # do a checkout of the file if it is part of this tree1284 if ($wrev) {1285 system('git-checkout-index', '-f', '-u',$filename);1286 unless ($?== 0) {1287 die "Error running git-checkout-index -f -u$filename:$!";1288 }1289 }12901291 my$addflag= 0;1292 my$rmflag= 0;1293$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1294$addflag= 1 unless ( -e$filename);12951296 # Do up to date checking1297 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1298 {1299 # fail everything if an up to date check fails1300 print "error 1 Up to date check failed for$filename\n";1301 cleanupWorkTree();1302 exit;1303 }13041305 push@committedfiles,$committedfile;1306$log->info("Committing$filename");13071308 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13091310 unless ($rmflag)1311 {1312$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1313 rename$state->{entries}{$filename}{modified_filename},$filename;13141315 # Calculate modes to remove1316 my$invmode= "";1317 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }13181319$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1320 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1321 }13221323 if ($rmflag)1324 {1325$log->info("Removing file '$filename'");1326 unlink($filename);1327 system("git-update-index", "--remove",$filename);1328 }1329 elsif ($addflag)1330 {1331$log->info("Adding file '$filename'");1332 system("git-update-index", "--add",$filename);1333 } else {1334$log->info("Updating file '$filename'");1335 system("git-update-index",$filename);1336 }1337 }13381339 unless ( scalar(@committedfiles) > 0 )1340 {1341 print "E No files to commit\n";1342 print "ok\n";1343 cleanupWorkTree();1344 return;1345 }13461347 my$treehash= `git-write-tree`;1348 chomp$treehash;13491350$log->debug("Treehash :$treehash, Parenthash :$parenthash");13511352 # write our commit message out if we have one ...1353 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1354 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1355 print$msg_fh"\n\nvia git-CVS emulator\n";1356 close$msg_fh;13571358 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1359chomp($commithash);1360$log->info("Commit hash :$commithash");13611362unless($commithash=~/[a-zA-Z0-9]{40}/)1363{1364$log->warn("Commit failed (Invalid commit hash)");1365print"error 1 Commit failed (unknown reason)\n";1366 cleanupWorkTree();1367exit;1368}13691370### Emulate git-receive-pack by running hooks/update1371my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1372$parenthash,$commithash);1373if( -x $hook[0] ) {1374unless(system(@hook) ==0)1375{1376$log->warn("Commit failed (update hook declined to update ref)");1377print"error 1 Commit failed (update hook declined)\n";1378 cleanupWorkTree();1379exit;1380}1381}13821383### Update the ref1384if(system(qw(git update-ref -m),"cvsserver ci",1385"refs/heads/$state->{module}",$commithash,$parenthash)) {1386$log->warn("update-ref for$state->{module} failed.");1387print"error 1 Cannot commit -- update first\n";1388 cleanupWorkTree();1389exit;1390}13911392### Emulate git-receive-pack by running hooks/post-receive1393my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1394if( -x $hook) {1395open(my$pipe,"|$hook") ||die"can't fork$!";13961397local$SIG{PIPE} =sub{die'pipe broke'};13981399print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";14001401close$pipe||die"bad pipe:$!$?";1402}14031404### Then hooks/post-update1405$hook=$ENV{GIT_DIR}.'hooks/post-update';1406if(-x $hook) {1407system($hook,"refs/heads/$state->{module}");1408}14091410$updater->update();14111412# foreach file specified on the command line ...1413foreachmy$filename(@committedfiles)1414{1415$filename= filecleanup($filename);14161417my$meta=$updater->getmeta($filename);1418unless(defined$meta->{revision}) {1419$meta->{revision} =1;1420}14211422my($filepart,$dirpart) = filenamesplit($filename,1);14231424$log->debug("Checked-in$dirpart:$filename");14251426print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1427if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1428{1429print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1430print"Remove-entry$dirpart\n";1431print"$filename\n";1432}else{1433if($meta->{revision} ==1) {1434print"M initial revision: 1.1\n";1435}else{1436print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1437}1438print"Checked-in$dirpart\n";1439print"$filename\n";1440my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1441print"/$filepart/1.$meta->{revision}//$kopts/\n";1442}1443}14441445 cleanupWorkTree();1446print"ok\n";1447}14481449sub req_status1450{1451my($cmd,$data) =@_;14521453 argsplit("status");14541455$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1456#$log->debug("status state : " . Dumper($state));14571458# Grab a handle to the SQLite db and do any necessary updates1459my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1460$updater->update();14611462# if no files were specified, we need to work out what files we should be providing status on ...1463 argsfromdir($updater);14641465# foreach file specified on the command line ...1466foreachmy$filename( @{$state->{args}} )1467{1468$filename= filecleanup($filename);14691470next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;14711472my$meta=$updater->getmeta($filename);1473my$oldmeta=$meta;14741475my$wrev= revparse($filename);14761477# If the working copy is an old revision, lets get that version too for comparison.1478if(defined($wrev)and$wrev!=$meta->{revision} )1479{1480$oldmeta=$updater->getmeta($filename,$wrev);1481}14821483# TODO : All possible statuses aren't yet implemented1484my$status;1485# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1486$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1487and1488( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1489or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1490);14911492# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1493$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1494and1495($state->{entries}{$filename}{unchanged}1496or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1497);14981499# Need checkout if it exists in the repo but doesn't have a working copy1500$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );15011502# Locally modified if working copy and repo copy have the same revision but there are local changes1503$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );15041505# Needs Merge if working copy revision is less than repo copy and there are local changes1506$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );15071508$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1509$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1510$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1511$status||="File had conflicts on merge"if(0);15121513$status||="Unknown";15141515my($filepart) = filenamesplit($filename);15161517print"M ===================================================================\n";1518print"M File:$filepart\tStatus:$status\n";1519if(defined($state->{entries}{$filename}{revision}) )1520{1521print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1522}else{1523print"M Working revision:\tNo entry for$filename\n";1524}1525if(defined($meta->{revision}) )1526{1527print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1528print"M Sticky Tag:\t\t(none)\n";1529print"M Sticky Date:\t\t(none)\n";1530print"M Sticky Options:\t\t(none)\n";1531}else{1532print"M Repository revision:\tNo revision control file\n";1533}1534print"M\n";1535}15361537print"ok\n";1538}15391540sub req_diff1541{1542my($cmd,$data) =@_;15431544 argsplit("diff");15451546$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1547#$log->debug("status state : " . Dumper($state));15481549my($revision1,$revision2);1550if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1551{1552$revision1=$state->{opt}{r}[0];1553$revision2=$state->{opt}{r}[1];1554}else{1555$revision1=$state->{opt}{r};1556}15571558$revision1=~s/^1\.//if(defined($revision1) );1559$revision2=~s/^1\.//if(defined($revision2) );15601561$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15621563# Grab a handle to the SQLite db and do any necessary updates1564my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1565$updater->update();15661567# if no files were specified, we need to work out what files we should be providing status on ...1568 argsfromdir($updater);15691570# foreach file specified on the command line ...1571foreachmy$filename( @{$state->{args}} )1572{1573$filename= filecleanup($filename);15741575my($fh,$file1,$file2,$meta1,$meta2,$filediff);15761577my$wrev= revparse($filename);15781579# We need _something_ to diff against1580next unless(defined($wrev) );15811582# if we have a -r switch, use it1583if(defined($revision1) )1584{1585(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1586$meta1=$updater->getmeta($filename,$revision1);1587unless(defined($meta1)and$meta1->{filehash}ne"deleted")1588{1589print"E File$filenameat revision 1.$revision1doesn't exist\n";1590next;1591}1592 transmitfile($meta1->{filehash}, { targetfile =>$file1});1593}1594# otherwise we just use the working copy revision1595else1596{1597(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1598$meta1=$updater->getmeta($filename,$wrev);1599 transmitfile($meta1->{filehash}, { targetfile =>$file1});1600}16011602# if we have a second -r switch, use it too1603if(defined($revision2) )1604{1605(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1606$meta2=$updater->getmeta($filename,$revision2);16071608unless(defined($meta2)and$meta2->{filehash}ne"deleted")1609{1610print"E File$filenameat revision 1.$revision2doesn't exist\n";1611next;1612}16131614 transmitfile($meta2->{filehash}, { targetfile =>$file2});1615}1616# otherwise we just use the working copy1617else1618{1619$file2=$state->{entries}{$filename}{modified_filename};1620}16211622# if we have been given -r, and we don't have a $file2 yet, lets get one1623if(defined($revision1)and not defined($file2) )1624{1625(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1626$meta2=$updater->getmeta($filename,$wrev);1627 transmitfile($meta2->{filehash}, { targetfile =>$file2});1628}16291630# We need to have retrieved something useful1631next unless(defined($meta1) );16321633# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1634next if(not defined($meta2)and$wrev==$meta1->{revision}1635and1636( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1637or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1638);16391640# Apparently we only show diffs for locally modified files1641next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16421643print"M Index:$filename\n";1644print"M ===================================================================\n";1645print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1646print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1647print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1648print"M diff ";1649foreachmy$opt(keys%{$state->{opt}} )1650{1651if(ref$state->{opt}{$opt}eq"ARRAY")1652{1653foreachmy$value( @{$state->{opt}{$opt}} )1654{1655print"-$opt$value";1656}1657}else{1658print"-$opt";1659print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1660}1661}1662print"$filename\n";16631664$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16651666($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16671668if(exists$state->{opt}{u} )1669{1670system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1671}else{1672system("diff$file1$file2>$filediff");1673}16741675while( <$fh> )1676{1677print"M$_";1678}1679close$fh;1680}16811682print"ok\n";1683}16841685sub req_log1686{1687my($cmd,$data) =@_;16881689 argsplit("log");16901691$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1692#$log->debug("log state : " . Dumper($state));16931694my($minrev,$maxrev);1695if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1696{1697my$control=$2;1698$minrev=$1;1699$maxrev=$3;1700$minrev=~s/^1\.//if(defined($minrev) );1701$maxrev=~s/^1\.//if(defined($maxrev) );1702$minrev++if(defined($minrev)and$controleq"::");1703}17041705# Grab a handle to the SQLite db and do any necessary updates1706my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1707$updater->update();17081709# if no files were specified, we need to work out what files we should be providing status on ...1710 argsfromdir($updater);17111712# foreach file specified on the command line ...1713foreachmy$filename( @{$state->{args}} )1714{1715$filename= filecleanup($filename);17161717my$headmeta=$updater->getmeta($filename);17181719my$revisions=$updater->getlog($filename);1720my$totalrevisions=scalar(@$revisions);17211722if(defined($minrev) )1723{1724$log->debug("Removing revisions less than$minrev");1725while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1726{1727pop@$revisions;1728}1729}1730if(defined($maxrev) )1731{1732$log->debug("Removing revisions greater than$maxrev");1733while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1734{1735shift@$revisions;1736}1737}17381739next unless(scalar(@$revisions) );17401741print"M\n";1742print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1743print"M Working file:$filename\n";1744print"M head: 1.$headmeta->{revision}\n";1745print"M branch:\n";1746print"M locks: strict\n";1747print"M access list:\n";1748print"M symbolic names:\n";1749print"M keyword substitution: kv\n";1750print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1751print"M description:\n";17521753foreachmy$revision(@$revisions)1754{1755print"M ----------------------------\n";1756print"M revision 1.$revision->{revision}\n";1757# reformat the date for log output1758$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}) );1759$revision->{author} = cvs_author($revision->{author});1760print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1761my$commitmessage=$updater->commitmessage($revision->{commithash});1762$commitmessage=~s/^/M /mg;1763print$commitmessage."\n";1764}1765print"M =============================================================================\n";1766}17671768print"ok\n";1769}17701771sub req_annotate1772{1773my($cmd,$data) =@_;17741775 argsplit("annotate");17761777$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1778#$log->debug("status state : " . Dumper($state));17791780# Grab a handle to the SQLite db and do any necessary updates1781my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1782$updater->update();17831784# if no files were specified, we need to work out what files we should be providing annotate on ...1785 argsfromdir($updater);17861787# we'll need a temporary checkout dir1788 setupWorkTree();17891790$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");17911792# foreach file specified on the command line ...1793foreachmy$filename( @{$state->{args}} )1794{1795$filename= filecleanup($filename);17961797my$meta=$updater->getmeta($filename);17981799next unless($meta->{revision} );18001801# get all the commits that this file was in1802# in dense format -- aka skip dead revisions1803my$revisions=$updater->gethistorydense($filename);1804my$lastseenin=$revisions->[0][2];18051806# populate the temporary index based on the latest commit were we saw1807# the file -- but do it cheaply without checking out any files1808# TODO: if we got a revision from the client, use that instead1809# to look up the commithash in sqlite (still good to default to1810# the current head as we do now)1811system("git-read-tree",$lastseenin);1812unless($?==0)1813{1814print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1815return;1816}1817$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");18181819# do a checkout of the file1820system('git-checkout-index','-f','-u',$filename);1821unless($?==0) {1822print"E error running git-checkout-index -f -u$filename:$!\n";1823return;1824}18251826$log->info("Annotate$filename");18271828# Prepare a file with the commits from the linearized1829# history that annotate should know about. This prevents1830# git-jsannotate telling us about commits we are hiding1831# from the client.18321833my$a_hints="$work->{workDir}/.annotate_hints";1834if(!open(ANNOTATEHINTS,'>',$a_hints)) {1835print"E failed to open '$a_hints' for writing:$!\n";1836return;1837}1838for(my$i=0;$i<@$revisions;$i++)1839{1840print ANNOTATEHINTS $revisions->[$i][2];1841if($i+1<@$revisions) {# have we got a parent?1842print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1843}1844print ANNOTATEHINTS "\n";1845}18461847print ANNOTATEHINTS "\n";1848close ANNOTATEHINTS1849or(print"E failed to write$a_hints:$!\n"),return;18501851my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1852if(!open(ANNOTATE,"-|",@cmd)) {1853print"E error invoking ".join(' ',@cmd) .":$!\n";1854return;1855}1856my$metadata= {};1857print"E Annotations for$filename\n";1858print"E ***************\n";1859while( <ANNOTATE> )1860{1861if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1862{1863my$commithash=$1;1864my$data=$2;1865unless(defined($metadata->{$commithash} ) )1866{1867$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1868$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1869$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1870}1871printf("M 1.%-5d (%-8s%10s):%s\n",1872$metadata->{$commithash}{revision},1873$metadata->{$commithash}{author},1874$metadata->{$commithash}{modified},1875$data1876);1877}else{1878$log->warn("Error in annotate output! LINE:$_");1879print"E Annotate error\n";1880next;1881}1882}1883close ANNOTATE;1884}18851886# done; get out of the tempdir1887 cleanupWorkDir();18881889print"ok\n";18901891}18921893# This method takes the state->{arguments} array and produces two new arrays.1894# The first is $state->{args} which is everything before the '--' argument, and1895# the second is $state->{files} which is everything after it.1896sub argsplit1897{1898$state->{args} = [];1899$state->{files} = [];1900$state->{opt} = {};19011902return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19031904my$type=shift;19051906if(defined($type) )1907{1908my$opt= {};1909$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");1910$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1911$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");1912$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1913$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1914$opt= { k =>1, m =>1}if($typeeq"add");1915$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1916$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");191719181919while(scalar( @{$state->{arguments}} ) >0)1920{1921my$arg=shift@{$state->{arguments}};19221923next if($argeq"--");1924next unless($arg=~/\S/);19251926# if the argument looks like a switch1927if($arg=~/^-(\w)(.*)/)1928{1929# if it's a switch that takes an argument1930if($opt->{$1} )1931{1932# If this switch has already been provided1933if($opt->{$1} >1and exists($state->{opt}{$1} ) )1934{1935$state->{opt}{$1} = [$state->{opt}{$1} ];1936if(length($2) >0)1937{1938push@{$state->{opt}{$1}},$2;1939}else{1940push@{$state->{opt}{$1}},shift@{$state->{arguments}};1941}1942}else{1943# if there's extra data in the arg, use that as the argument for the switch1944if(length($2) >0)1945{1946$state->{opt}{$1} =$2;1947}else{1948$state->{opt}{$1} =shift@{$state->{arguments}};1949}1950}1951}else{1952$state->{opt}{$1} =undef;1953}1954}1955else1956{1957push@{$state->{args}},$arg;1958}1959}1960}1961else1962{1963my$mode=0;19641965foreachmy$value( @{$state->{arguments}} )1966{1967if($valueeq"--")1968{1969$mode++;1970next;1971}1972push@{$state->{args}},$valueif($mode==0);1973push@{$state->{files}},$valueif($mode==1);1974}1975}1976}19771978# This method uses $state->{directory} to populate $state->{args} with a list of filenames1979sub argsfromdir1980{1981my$updater=shift;19821983$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19841985return if(scalar( @{$state->{args}} ) >1);19861987my@gethead= @{$updater->gethead};19881989# push added files1990foreachmy$file(keys%{$state->{entries}}) {1991if(exists$state->{entries}{$file}{revision} &&1992$state->{entries}{$file}{revision} ==0)1993{1994push@gethead, { name =>$file, filehash =>'added'};1995}1996}19971998if(scalar(@{$state->{args}}) ==1)1999{2000my$arg=$state->{args}[0];2001$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );20022003$log->info("Only one arg specified, checking for directory expansion on '$arg'");20042005foreachmy$file(@gethead)2006{2007next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2008next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2009push@{$state->{args}},$file->{name};2010}20112012shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2013}else{2014$log->info("Only one arg specified, populating file list automatically");20152016$state->{args} = [];20172018foreachmy$file(@gethead)2019{2020next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2021next unless($file->{name} =~s/^$state->{prependdir}//);2022push@{$state->{args}},$file->{name};2023}2024}2025}20262027# This method cleans up the $state variable after a command that uses arguments has run2028sub statecleanup2029{2030$state->{files} = [];2031$state->{args} = [];2032$state->{arguments} = [];2033$state->{entries} = {};2034}20352036sub revparse2037{2038my$filename=shift;20392040returnundefunless(defined($state->{entries}{$filename}{revision} ) );20412042return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2043return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20442045returnundef;2046}20472048# This method takes a file hash and does a CVS "file transfer". Its2049# exact behaviour depends on a second, optional hash table argument:2050# - If $options->{targetfile}, dump the contents to that file;2051# - If $options->{print}, use M/MT to transmit the contents one line2052# at a time;2053# - Otherwise, transmit the size of the file, followed by the file2054# contents.2055sub transmitfile2056{2057my$filehash=shift;2058my$options=shift;20592060if(defined($filehash)and$filehasheq"deleted")2061{2062$log->warn("filehash is 'deleted'");2063return;2064}20652066die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20672068my$type=`git-cat-file -t$filehash`;2069 chomp$type;20702071 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20722073 my$size= `git-cat-file -s $filehash`;2074chomp$size;20752076$log->debug("transmitfile($filehash) size=$size, type=$type");20772078if(open my$fh,'-|',"git-cat-file","blob",$filehash)2079{2080if(defined($options->{targetfile} ) )2081{2082my$targetfile=$options->{targetfile};2083open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2084print NEWFILE $_while( <$fh> );2085close NEWFILE or die("Failed to write '$targetfile':$!");2086}elsif(defined($options->{print} ) &&$options->{print} ) {2087while( <$fh> ) {2088if(/\n\z/) {2089print'M ',$_;2090}else{2091print'MT text ',$_,"\n";2092}2093}2094}else{2095print"$size\n";2096printwhile( <$fh> );2097}2098close$fhor die("Couldn't close filehandle for transmitfile():$!");2099}else{2100die("Couldn't execute git-cat-file");2101}2102}21032104# This method takes a file name, and returns ( $dirpart, $filepart ) which2105# refers to the directory portion and the file portion of the filename2106# respectively2107sub filenamesplit2108{2109my$filename=shift;2110my$fixforlocaldir=shift;21112112my($filepart,$dirpart) = ($filename,".");2113($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2114$dirpart.="/";21152116if($fixforlocaldir)2117{2118$dirpart=~s/^$state->{prependdir}//;2119}21202121return($filepart,$dirpart);2122}21232124sub filecleanup2125{2126my$filename=shift;21272128returnundefunless(defined($filename));2129if($filename=~/^\// )2130{2131print"E absolute filenames '$filename' not supported by server\n";2132returnundef;2133}21342135$filename=~s/^\.\///g;2136$filename=$state->{prependdir} .$filename;2137return$filename;2138}21392140sub validateGitDir2141{2142if( !defined($state->{CVSROOT}) )2143{2144print"error 1 CVSROOT not specified\n";2145 cleanupWorkTree();2146exit;2147}2148if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2149{2150print"error 1 Internally inconsistent CVSROOT\n";2151 cleanupWorkTree();2152exit;2153}2154}21552156# Setup working directory in a work tree with the requested version2157# loaded in the index.2158sub setupWorkTree2159{2160my($ver) =@_;21612162 validateGitDir();21632164if( (defined($work->{state}) &&$work->{state} !=1) ||2165defined($work->{tmpDir}) )2166{2167$log->warn("Bad work tree state management");2168print"error 1 Internal setup multiple work trees without cleanup\n";2169 cleanupWorkTree();2170exit;2171}21722173$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);21742175if( !defined($work->{index}) )2176{2177(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2178}21792180chdir$work->{workDir}or2181die"Unable to chdir to$work->{workDir}\n";21822183$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");21842185$ENV{GIT_WORK_TREE} =".";2186$ENV{GIT_INDEX_FILE} =$work->{index};2187$work->{state} =2;21882189if($ver)2190{2191system("git","read-tree",$ver);2192unless($?==0)2193{2194$log->warn("Error running git-read-tree");2195die"Error running git-read-tree$verin$work->{workDir}$!\n";2196}2197}2198# else # req_annotate reads tree for each file2199}22002201# Ensure current directory is in some kind of working directory,2202# with a recent version loaded in the index.2203sub ensureWorkTree2204{2205if(defined($work->{tmpDir}) )2206{2207$log->warn("Bad work tree state management [ensureWorkTree()]");2208print"error 1 Internal setup multiple dirs without cleanup\n";2209 cleanupWorkTree();2210exit;2211}2212if($work->{state} )2213{2214return;2215}22162217 validateGitDir();22182219if( !defined($work->{emptyDir}) )2220{2221$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2222}2223chdir$work->{emptyDir}or2224die"Unable to chdir to$work->{emptyDir}\n";22252226my$ver=`git show-ref -s refs/heads/$state->{module}`;2227chomp$ver;2228if($ver!~/^[0-9a-f]{40}$/)2229{2230$log->warn("Error from git show-ref -s refs/head$state->{module}");2231print"error 1 cannot find the current HEAD of module";2232 cleanupWorkTree();2233exit;2234}22352236if( !defined($work->{index}) )2237{2238(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2239}22402241$ENV{GIT_WORK_TREE} =".";2242$ENV{GIT_INDEX_FILE} =$work->{index};2243$work->{state} =1;22442245system("git","read-tree",$ver);2246unless($?==0)2247{2248die"Error running git-read-tree$ver$!\n";2249}2250}22512252# Cleanup working directory that is not needed any longer.2253sub cleanupWorkTree2254{2255if( !$work->{state} )2256{2257return;2258}22592260chdir"/"or die"Unable to chdir '/'\n";22612262if(defined($work->{workDir}) )2263{2264 rmtree($work->{workDir} );2265undef$work->{workDir};2266}2267undef$work->{state};2268}22692270# Setup a temporary directory (not a working tree), typically for2271# merging dirty state as in req_update.2272sub setupTmpDir2273{2274$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2275chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";22762277return$work->{tmpDir};2278}22792280# Clean up a previously setupTmpDir. Restore previous work tree if2281# appropriate.2282sub cleanupTmpDir2283{2284if( !defined($work->{tmpDir}) )2285{2286$log->warn("cleanup tmpdir that has not been setup");2287die"Cleanup tmpDir that has not been setup\n";2288}2289if(defined($work->{state}) )2290{2291if($work->{state} ==1)2292{2293chdir$work->{emptyDir}or2294die"Unable to chdir to$work->{emptyDir}\n";2295}2296elsif($work->{state} ==2)2297{2298chdir$work->{workDir}or2299die"Unable to chdir to$work->{emptyDir}\n";2300}2301else2302{2303$log->warn("Inconsistent work dir state");2304die"Inconsistent work dir state\n";2305}2306}2307else2308{2309chdir"/"or die"Unable to chdir '/'\n";2310}2311}23122313# Given a path, this function returns a string containing the kopts2314# that should go into that path's Entries line. For example, a binary2315# file should get -kb.2316sub kopts_from_path2317{2318my($path,$srcType,$name) =@_;23192320if(defined($cfg->{gitcvs}{usecrlfattr} )and2321$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2322{2323my($val) = check_attr("crlf",$path);2324if($valeq"set")2325{2326return"";2327}2328elsif($valeq"unset")2329{2330return"-kb"2331}2332else2333{2334$log->info("Unrecognized check_attr crlf$path:$val");2335}2336}23372338if(defined($cfg->{gitcvs}{allbinary} ) )2339{2340if( ($cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i) )2341{2342return"-kb";2343}2344elsif( ($cfg->{gitcvs}{allbinary} =~/^\s*guess\s*$/i) )2345{2346if($srcTypeeq"sha1Or-k"&&2347!defined($name) )2348{2349my($ret)=$state->{entries}{$path}{options};2350if( !defined($ret) )2351{2352$ret=$state->{opt}{k};2353if(defined($ret))2354{2355$ret="-k$ret";2356}2357else2358{2359$ret="";2360}2361}2362if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )2363{2364print"E Bad -k option\n";2365$log->warn("Bad -k option:$ret");2366die"Error: Bad -k option:$ret\n";2367}23682369return$ret;2370}2371else2372{2373if( is_binary($srcType,$name) )2374{2375$log->debug("... as binary");2376return"-kb";2377}2378else2379{2380$log->debug("... as text");2381}2382}2383}2384}2385# Return "" to give no special treatment to any path2386return"";2387}23882389sub check_attr2390{2391my($attr,$path) =@_;2392 ensureWorkTree();2393if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2394{2395my$val= <$fh>;2396close$fh;2397$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2398return$val;2399}2400else2401{2402returnundef;2403}2404}24052406# This should have the same heuristics as convert.c:is_binary() and related.2407# Note that the bare CR test is done by callers in convert.c.2408sub is_binary2409{2410my($srcType,$name) =@_;2411$log->debug("is_binary($srcType,$name)");24122413# Minimize amount of interpreted code run in the inner per-character2414# loop for large files, by totalling each character value and2415# then analyzing the totals.2416my@counts;2417my$i;2418for($i=0;$i<256;$i++)2419{2420$counts[$i]=0;2421}24222423my$fh= open_blob_or_die($srcType,$name);2424my$line;2425while(defined($line=<$fh>) )2426{2427# Any '\0' and bare CR are considered binary.2428if($line=~/\0|(\r[^\n])/)2429{2430close($fh);2431return1;2432}24332434# Count up each character in the line:2435my$len=length($line);2436for($i=0;$i<$len;$i++)2437{2438$counts[ord(substr($line,$i,1))]++;2439}2440}2441close$fh;24422443# Don't count CR and LF as either printable/nonprintable2444$counts[ord("\n")]=0;2445$counts[ord("\r")]=0;24462447# Categorize individual character count into printable and nonprintable:2448my$printable=0;2449my$nonprintable=0;2450for($i=0;$i<256;$i++)2451{2452if($i<32&&2453$i!=ord("\b") &&2454$i!=ord("\t") &&2455$i!=033&&# ESC2456$i!=014)# FF2457{2458$nonprintable+=$counts[$i];2459}2460elsif($i==127)# DEL2461{2462$nonprintable+=$counts[$i];2463}2464else2465{2466$printable+=$counts[$i];2467}2468}24692470return($printable>>7) <$nonprintable;2471}24722473# Returns open file handle. Possible invocations:2474# - open_blob_or_die("file",$filename);2475# - open_blob_or_die("sha1",$filehash);2476sub open_blob_or_die2477{2478my($srcType,$name) =@_;2479my($fh);2480if($srcTypeeq"file")2481{2482if( !open$fh,"<",$name)2483{2484$log->warn("Unable to open file$name:$!");2485die"Unable to open file$name:$!\n";2486}2487}2488elsif($srcTypeeq"sha1"||$srcTypeeq"sha1Or-k")2489{2490unless(defined($name)and$name=~/^[a-zA-Z0-9]{40}$/)2491{2492$log->warn("Need filehash");2493die"Need filehash\n";2494}24952496my$type=`git cat-file -t$name`;2497 chomp$type;24982499 unless ( defined ($type) and$typeeq "blob" )2500 {2501$log->warn("Invalid type '$type' for '$name'");2502 die ( "Invalid type '$type' (expected 'blob')" )2503 }25042505 my$size= `git cat-file -s $name`;2506chomp$size;25072508$log->debug("open_blob_or_die($name) size=$size, type=$type");25092510unless(open$fh,'-|',"git","cat-file","blob",$name)2511{2512$log->warn("Unable to open sha1$name");2513die"Unable to open sha1$name\n";2514}2515}2516else2517{2518$log->warn("Unknown type of blob source:$srcType");2519die"Unknown type of blob source:$srcType\n";2520}2521return$fh;2522}25232524# Generate a CVS author name from Git author information, by taking2525# the first eight characters of the user part of the email address.2526sub cvs_author2527{2528my$author_line=shift;2529(my$author) =$author_line=~/<([^>@]{1,8})/;25302531$author;2532}25332534package GITCVS::log;25352536####2537#### Copyright The Open University UK - 2006.2538####2539#### Authors: Martyn Smith <martyn@catalyst.net.nz>2540#### Martin Langhoff <martin@catalyst.net.nz>2541####2542####25432544use strict;2545use warnings;25462547=head1 NAME25482549GITCVS::log25502551=head1 DESCRIPTION25522553This module provides very crude logging with a similar interface to2554Log::Log4perl25552556=head1 METHODS25572558=cut25592560=head2 new25612562Creates a new log object, optionally you can specify a filename here to2563indicate the file to log to. If no log file is specified, you can specify one2564later with method setfile, or indicate you no longer want logging with method2565nofile.25662567Until one of these methods is called, all log calls will buffer messages ready2568to write out.25692570=cut2571sub new2572{2573my$class=shift;2574my$filename=shift;25752576my$self= {};25772578bless$self,$class;25792580if(defined($filename) )2581{2582open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2583}25842585return$self;2586}25872588=head2 setfile25892590This methods takes a filename, and attempts to open that file as the log file.2591If successful, all buffered data is written out to the file, and any further2592logging is written directly to the file.25932594=cut2595sub setfile2596{2597my$self=shift;2598my$filename=shift;25992600if(defined($filename) )2601{2602open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2603}26042605return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26062607while(my$line=shift@{$self->{buffer}} )2608{2609print{$self->{fh}}$line;2610}2611}26122613=head2 nofile26142615This method indicates no logging is going to be used. It flushes any entries in2616the internal buffer, and sets a flag to ensure no further data is put there.26172618=cut2619sub nofile2620{2621my$self=shift;26222623$self->{nolog} =1;26242625return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26262627$self->{buffer} = [];2628}26292630=head2 _logopen26312632Internal method. Returns true if the log file is open, false otherwise.26332634=cut2635sub _logopen2636{2637my$self=shift;26382639return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2640return0;2641}26422643=head2 debug info warn fatal26442645These four methods are wrappers to _log. They provide the actual interface for2646logging data.26472648=cut2649sub debug {my$self=shift;$self->_log("debug",@_); }2650sub info {my$self=shift;$self->_log("info",@_); }2651subwarn{my$self=shift;$self->_log("warn",@_); }2652sub fatal {my$self=shift;$self->_log("fatal",@_); }26532654=head2 _log26552656This is an internal method called by the logging functions. It generates a2657timestamp and pushes the logged line either to file, or internal buffer.26582659=cut2660sub _log2661{2662my$self=shift;2663my$level=shift;26642665return if($self->{nolog} );26662667my@time=localtime;2668my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2669$time[5] +1900,2670$time[4] +1,2671$time[3],2672$time[2],2673$time[1],2674$time[0],2675uc$level,2676);26772678if($self->_logopen)2679{2680print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2681}else{2682push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2683}2684}26852686=head2 DESTROY26872688This method simply closes the file handle if one is open26892690=cut2691sub DESTROY2692{2693my$self=shift;26942695if($self->_logopen)2696{2697close$self->{fh};2698}2699}27002701package GITCVS::updater;27022703####2704#### Copyright The Open University UK - 2006.2705####2706#### Authors: Martyn Smith <martyn@catalyst.net.nz>2707#### Martin Langhoff <martin@catalyst.net.nz>2708####2709####27102711use strict;2712use warnings;2713use DBI;27142715=head1 METHODS27162717=cut27182719=head2 new27202721=cut2722sub new2723{2724my$class=shift;2725my$config=shift;2726my$module=shift;2727my$log=shift;27282729die"Need to specify a git repository"unless(defined($config)and-d $config);2730die"Need to specify a module"unless(defined($module) );27312732$class=ref($class) ||$class;27332734my$self= {};27352736bless$self,$class;27372738$self->{valid_tables} = {'revision'=>1,2739'revision_ix1'=>1,2740'revision_ix2'=>1,2741'head'=>1,2742'head_ix1'=>1,2743'properties'=>1,2744'commitmsgs'=>1};27452746$self->{module} =$module;2747$self->{git_path} =$config."/";27482749$self->{log} =$log;27502751die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );27522753$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2754$cfg->{gitcvs}{dbdriver} ||"SQLite";2755$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2756$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2757$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2758$cfg->{gitcvs}{dbuser} ||"";2759$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2760$cfg->{gitcvs}{dbpass} ||"";2761$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2762$cfg->{gitcvs}{dbtablenameprefix} ||"";2763my%mapping= ( m =>$module,2764 a =>$state->{method},2765 u =>getlogin||getpwuid($<) || $<,2766 G =>$self->{git_path},2767 g => mangle_dirname($self->{git_path}),2768);2769$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2770$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2771$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2772$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});27732774die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2775die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2776$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2777$self->{dbuser},2778$self->{dbpass});2779die"Error connecting to database\n"unlessdefined$self->{dbh};27802781$self->{tables} = {};2782foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2783{2784$self->{tables}{$table} =1;2785}27862787# Construct the revision table if required2788unless($self->{tables}{$self->tablename("revision")} )2789{2790my$tablename=$self->tablename("revision");2791my$ix1name=$self->tablename("revision_ix1");2792my$ix2name=$self->tablename("revision_ix2");2793$self->{dbh}->do("2794 CREATE TABLE$tablename(2795 name TEXT NOT NULL,2796 revision INTEGER NOT NULL,2797 filehash TEXT NOT NULL,2798 commithash TEXT NOT NULL,2799 author TEXT NOT NULL,2800 modified TEXT NOT NULL,2801 mode TEXT NOT NULL2802 )2803 ");2804$self->{dbh}->do("2805 CREATE INDEX$ix1name2806 ON$tablename(name,revision)2807 ");2808$self->{dbh}->do("2809 CREATE INDEX$ix2name2810 ON$tablename(name,commithash)2811 ");2812}28132814# Construct the head table if required2815unless($self->{tables}{$self->tablename("head")} )2816{2817my$tablename=$self->tablename("head");2818my$ix1name=$self->tablename("head_ix1");2819$self->{dbh}->do("2820 CREATE TABLE$tablename(2821 name TEXT NOT NULL,2822 revision INTEGER NOT NULL,2823 filehash TEXT NOT NULL,2824 commithash TEXT NOT NULL,2825 author TEXT NOT NULL,2826 modified TEXT NOT NULL,2827 mode TEXT NOT NULL2828 )2829 ");2830$self->{dbh}->do("2831 CREATE INDEX$ix1name2832 ON$tablename(name)2833 ");2834}28352836# Construct the properties table if required2837unless($self->{tables}{$self->tablename("properties")} )2838{2839my$tablename=$self->tablename("properties");2840$self->{dbh}->do("2841 CREATE TABLE$tablename(2842 key TEXT NOT NULL PRIMARY KEY,2843 value TEXT2844 )2845 ");2846}28472848# Construct the commitmsgs table if required2849unless($self->{tables}{$self->tablename("commitmsgs")} )2850{2851my$tablename=$self->tablename("commitmsgs");2852$self->{dbh}->do("2853 CREATE TABLE$tablename(2854 key TEXT NOT NULL PRIMARY KEY,2855 value TEXT2856 )2857 ");2858}28592860return$self;2861}28622863=head2 tablename28642865=cut2866sub tablename2867{2868my$self=shift;2869my$name=shift;28702871if(exists$self->{valid_tables}{$name}) {2872return$self->{dbtablenameprefix} .$name;2873}else{2874returnundef;2875}2876}28772878=head2 update28792880=cut2881sub update2882{2883my$self=shift;28842885# first lets get the commit list2886$ENV{GIT_DIR} =$self->{git_path};28872888my$commitsha1=`git rev-parse$self->{module}`;2889chomp$commitsha1;28902891my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2892unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2893{2894die("Invalid module '$self->{module}'");2895}289628972898my$git_log;2899my$lastcommit=$self->_get_prop("last_commit");29002901if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2902return1;2903}29042905# Start exclusive lock here...2906$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";29072908# TODO: log processing is memory bound2909# if we can parse into a 2nd file that is in reverse order2910# we can probably do something really efficient2911my@git_log_params= ('--pretty','--parents','--topo-order');29122913if(defined$lastcommit) {2914push@git_log_params,"$lastcommit..$self->{module}";2915}else{2916push@git_log_params,$self->{module};2917}2918# git-rev-list is the backend / plumbing version of git-log2919open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";29202921my@commits;29222923my%commit= ();29242925while( <GITLOG> )2926{2927chomp;2928if(m/^commit\s+(.*)$/) {2929# on ^commit lines put the just seen commit in the stack2930# and prime things for the next one2931if(keys%commit) {2932my%copy=%commit;2933unshift@commits, \%copy;2934%commit= ();2935}2936my@parents=split(m/\s+/,$1);2937$commit{hash} =shift@parents;2938$commit{parents} = \@parents;2939}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2940# on rfc822-like lines seen before we see any message,2941# lowercase the entry and put it in the hash as key-value2942$commit{lc($1)} =$2;2943}else{2944# message lines - skip initial empty line2945# and trim whitespace2946if(!exists($commit{message}) &&m/^\s*$/) {2947# define it to mark the end of headers2948$commit{message} ='';2949next;2950}2951s/^\s+//;s/\s+$//;# trim ws2952$commit{message} .=$_."\n";2953}2954}2955close GITLOG;29562957unshift@commits, \%commitif(keys%commit);29582959# Now all the commits are in the @commits bucket2960# ordered by time DESC. for each commit that needs processing,2961# determine whether it's following the last head we've seen or if2962# it's on its own branch, grab a file list, and add whatever's changed2963# NOTE: $lastcommit refers to the last commit from previous run2964# $lastpicked is the last commit we picked in this run2965my$lastpicked;2966my$head= {};2967if(defined$lastcommit) {2968$lastpicked=$lastcommit;2969}29702971my$committotal=scalar(@commits);2972my$commitcount=0;29732974# Load the head table into $head (for cached lookups during the update process)2975foreachmy$file( @{$self->gethead()} )2976{2977$head->{$file->{name}} =$file;2978}29792980foreachmy$commit(@commits)2981{2982$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2983if(defined$lastpicked)2984{2985if(!in_array($lastpicked, @{$commit->{parents}}))2986{2987# skip, we'll see this delta2988# as part of a merge later2989# warn "skipping off-track $commit->{hash}\n";2990next;2991}elsif(@{$commit->{parents}} >1) {2992# it is a merge commit, for each parent that is2993# not $lastpicked, see if we can get a log2994# from the merge-base to that parent to put it2995# in the message as a merge summary.2996my@parents= @{$commit->{parents}};2997foreachmy$parent(@parents) {2998# git-merge-base can potentially (but rarely) throw2999# several candidate merge bases. let's assume3000# that the first one is the best one.3001if($parenteq$lastpicked) {3002next;3003}3004my$base=eval{3005 safe_pipe_capture('git-merge-base',3006$lastpicked,$parent);3007};3008# The two branches may not be related at all,3009# in which case merge base simply fails to find3010# any, but that's Ok.3011next if($@);30123013chomp$base;3014if($base) {3015my@merged;3016# print "want to log between $base $parent \n";3017open(GITLOG,'-|','git-log','--pretty=medium',"$base..$parent")3018or die"Cannot call git-log:$!";3019my$mergedhash;3020while(<GITLOG>) {3021chomp;3022if(!defined$mergedhash) {3023if(m/^commit\s+(.+)$/) {3024$mergedhash=$1;3025}else{3026next;3027}3028}else{3029# grab the first line that looks non-rfc8223030# aka has content after leading space3031if(m/^\s+(\S.*)$/) {3032my$title=$1;3033$title=substr($title,0,100);# truncate3034unshift@merged,"$mergedhash$title";3035undef$mergedhash;3036}3037}3038}3039close GITLOG;3040if(@merged) {3041$commit->{mergemsg} =$commit->{message};3042$commit->{mergemsg} .="\nSummary of merged commits:\n\n";3043foreachmy$summary(@merged) {3044$commit->{mergemsg} .="\t$summary\n";3045}3046$commit->{mergemsg} .="\n\n";3047# print "Message for $commit->{hash} \n$commit->{mergemsg}";3048}3049}3050}3051}3052}30533054# convert the date to CVS-happy format3055$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);30563057if(defined($lastpicked) )3058{3059my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");3060local($/) ="\0";3061while( <FILELIST> )3062{3063chomp;3064unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)3065{3066die("Couldn't process git-diff-tree line :$_");3067}3068my($mode,$hash,$change) = ($1,$2,$3);3069my$name= <FILELIST>;3070chomp($name);30713072# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");30733074my$git_perms="";3075$git_perms.="r"if($mode&4);3076$git_perms.="w"if($mode&2);3077$git_perms.="x"if($mode&1);3078$git_perms="rw"if($git_permseq"");30793080if($changeeq"D")3081{3082#$log->debug("DELETE $name");3083$head->{$name} = {3084 name =>$name,3085 revision =>$head->{$name}{revision} +1,3086 filehash =>"deleted",3087 commithash =>$commit->{hash},3088 modified =>$commit->{date},3089 author =>$commit->{author},3090 mode =>$git_perms,3091};3092$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3093}3094elsif($changeeq"M"||$changeeq"T")3095{3096#$log->debug("MODIFIED $name");3097$head->{$name} = {3098 name =>$name,3099 revision =>$head->{$name}{revision} +1,3100 filehash =>$hash,3101 commithash =>$commit->{hash},3102 modified =>$commit->{date},3103 author =>$commit->{author},3104 mode =>$git_perms,3105};3106$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3107}3108elsif($changeeq"A")3109{3110#$log->debug("ADDED $name");3111$head->{$name} = {3112 name =>$name,3113 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,3114 filehash =>$hash,3115 commithash =>$commit->{hash},3116 modified =>$commit->{date},3117 author =>$commit->{author},3118 mode =>$git_perms,3119};3120$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3121}3122else3123{3124$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");3125die;3126}3127}3128close FILELIST;3129}else{3130# this is used to detect files removed from the repo3131my$seen_files= {};31323133my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");3134local$/="\0";3135while( <FILELIST> )3136{3137chomp;3138unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)3139{3140die("Couldn't process git-ls-tree line :$_");3141}31423143my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);31443145$seen_files->{$git_filename} =1;31463147my($oldhash,$oldrevision,$oldmode) = (3148$head->{$git_filename}{filehash},3149$head->{$git_filename}{revision},3150$head->{$git_filename}{mode}3151);31523153if($git_perms=~/^\d\d\d(\d)\d\d/o)3154{3155$git_perms="";3156$git_perms.="r"if($1&4);3157$git_perms.="w"if($1&2);3158$git_perms.="x"if($1&1);3159}else{3160$git_perms="rw";3161}31623163# unless the file exists with the same hash, we need to update it ...3164unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3165{3166my$newrevision= ($oldrevisionor0) +1;31673168$head->{$git_filename} = {3169 name =>$git_filename,3170 revision =>$newrevision,3171 filehash =>$git_hash,3172 commithash =>$commit->{hash},3173 modified =>$commit->{date},3174 author =>$commit->{author},3175 mode =>$git_perms,3176};317731783179$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3180}3181}3182close FILELIST;31833184# Detect deleted files3185foreachmy$file(keys%$head)3186{3187unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3188{3189$head->{$file}{revision}++;3190$head->{$file}{filehash} ="deleted";3191$head->{$file}{commithash} =$commit->{hash};3192$head->{$file}{modified} =$commit->{date};3193$head->{$file}{author} =$commit->{author};31943195$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3196}3197}3198# END : "Detect deleted files"3199}320032013202if(exists$commit->{mergemsg})3203{3204$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3205}32063207$lastpicked=$commit->{hash};32083209$self->_set_prop("last_commit",$commit->{hash});3210}32113212$self->delete_head();3213foreachmy$file(keys%$head)3214{3215$self->insert_head(3216$file,3217$head->{$file}{revision},3218$head->{$file}{filehash},3219$head->{$file}{commithash},3220$head->{$file}{modified},3221$head->{$file}{author},3222$head->{$file}{mode},3223);3224}3225# invalidate the gethead cache3226$self->{gethead_cache} =undef;322732283229# Ending exclusive lock here3230$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3231}32323233sub insert_rev3234{3235my$self=shift;3236my$name=shift;3237my$revision=shift;3238my$filehash=shift;3239my$commithash=shift;3240my$modified=shift;3241my$author=shift;3242my$mode=shift;3243my$tablename=$self->tablename("revision");32443245my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3246$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3247}32483249sub insert_mergelog3250{3251my$self=shift;3252my$key=shift;3253my$value=shift;3254my$tablename=$self->tablename("commitmsgs");32553256my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3257$insert_mergelog->execute($key,$value);3258}32593260sub delete_head3261{3262my$self=shift;3263my$tablename=$self->tablename("head");32643265my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3266$delete_head->execute();3267}32683269sub insert_head3270{3271my$self=shift;3272my$name=shift;3273my$revision=shift;3274my$filehash=shift;3275my$commithash=shift;3276my$modified=shift;3277my$author=shift;3278my$mode=shift;3279my$tablename=$self->tablename("head");32803281my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3282$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3283}32843285sub _headrev3286{3287my$self=shift;3288my$filename=shift;3289my$tablename=$self->tablename("head");32903291my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3292$db_query->execute($filename);3293my($hash,$revision,$mode) =$db_query->fetchrow_array;32943295return($hash,$revision,$mode);3296}32973298sub _get_prop3299{3300my$self=shift;3301my$key=shift;3302my$tablename=$self->tablename("properties");33033304my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3305$db_query->execute($key);3306my($value) =$db_query->fetchrow_array;33073308return$value;3309}33103311sub _set_prop3312{3313my$self=shift;3314my$key=shift;3315my$value=shift;3316my$tablename=$self->tablename("properties");33173318my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3319$db_query->execute($value,$key);33203321unless($db_query->rows)3322{3323$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3324$db_query->execute($key,$value);3325}33263327return$value;3328}33293330=head2 gethead33313332=cut33333334sub gethead3335{3336my$self=shift;3337my$tablename=$self->tablename("head");33383339return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );33403341my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3342$db_query->execute();33433344my$tree= [];3345while(my$file=$db_query->fetchrow_hashref)3346{3347push@$tree,$file;3348}33493350$self->{gethead_cache} =$tree;33513352return$tree;3353}33543355=head2 getlog33563357=cut33583359sub getlog3360{3361my$self=shift;3362my$filename=shift;3363my$tablename=$self->tablename("revision");33643365my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3366$db_query->execute($filename);33673368my$tree= [];3369while(my$file=$db_query->fetchrow_hashref)3370{3371push@$tree,$file;3372}33733374return$tree;3375}33763377=head2 getmeta33783379This function takes a filename (with path) argument and returns a hashref of3380metadata for that file.33813382=cut33833384sub getmeta3385{3386my$self=shift;3387my$filename=shift;3388my$revision=shift;3389my$tablename_rev=$self->tablename("revision");3390my$tablename_head=$self->tablename("head");33913392my$db_query;3393if(defined($revision)and$revision=~/^\d+$/)3394{3395$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3396$db_query->execute($filename,$revision);3397}3398elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3399{3400$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3401$db_query->execute($filename,$revision);3402}else{3403$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3404$db_query->execute($filename);3405}34063407return$db_query->fetchrow_hashref;3408}34093410=head2 commitmessage34113412this function takes a commithash and returns the commit message for that commit34133414=cut3415sub commitmessage3416{3417my$self=shift;3418my$commithash=shift;3419my$tablename=$self->tablename("commitmsgs");34203421die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);34223423my$db_query;3424$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3425$db_query->execute($commithash);34263427my($message) =$db_query->fetchrow_array;34283429if(defined($message) )3430{3431$message.=" "if($message=~/\n$/);3432return$message;3433}34343435my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);3436shift@lineswhile($lines[0] =~/\S/);3437$message=join("",@lines);3438$message.=" "if($message=~/\n$/);3439return$message;3440}34413442=head2 gethistory34433444This function takes a filename (with path) argument and returns an arrayofarrays3445containing revision,filehash,commithash ordered by revision descending34463447=cut3448sub gethistory3449{3450my$self=shift;3451my$filename=shift;3452my$tablename=$self->tablename("revision");34533454my$db_query;3455$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3456$db_query->execute($filename);34573458return$db_query->fetchall_arrayref;3459}34603461=head2 gethistorydense34623463This function takes a filename (with path) argument and returns an arrayofarrays3464containing revision,filehash,commithash ordered by revision descending.34653466This version of gethistory skips deleted entries -- so it is useful for annotate.3467The 'dense' part is a reference to a '--dense' option available for git-rev-list3468and other git tools that depend on it.34693470=cut3471sub gethistorydense3472{3473my$self=shift;3474my$filename=shift;3475my$tablename=$self->tablename("revision");34763477my$db_query;3478$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3479$db_query->execute($filename);34803481return$db_query->fetchall_arrayref;3482}34833484=head2 in_array()34853486from Array::PAT - mimics the in_array() function3487found in PHP. Yuck but works for small arrays.34883489=cut3490sub in_array3491{3492my($check,@array) =@_;3493my$retval=0;3494foreachmy$test(@array){3495if($checkeq$test){3496$retval=1;3497}3498}3499return$retval;3500}35013502=head2 safe_pipe_capture35033504an alternative to `command` that allows input to be passed as an array3505to work around shell problems with weird characters in arguments35063507=cut3508sub safe_pipe_capture {35093510my@output;35113512if(my$pid=open my$child,'-|') {3513@output= (<$child>);3514close$childor die join(' ',@_).":$!$?";3515}else{3516exec(@_)or die"$!$?";# exec() can fail the executable can't be found3517}3518returnwantarray?@output:join('',@output);3519}35203521=head2 mangle_dirname35223523create a string from a directory name that is suitable to use as3524part of a filename, mainly by converting all chars except \w.- to _35253526=cut3527sub mangle_dirname {3528my$dirname=shift;3529return unlessdefined$dirname;35303531$dirname=~s/[^\w.-]/_/g;35323533return$dirname;3534}35353536=head2 mangle_tablename35373538create a string from a that is suitable to use as part of an SQL table3539name, mainly by converting all chars except \w to _35403541=cut3542sub mangle_tablename {3543my$tablename=shift;3544return unlessdefined$tablename;35453546$tablename=~s/[^\w_]/_/g;35473548return$tablename;3549}355035511;