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'noop'=> \&req_EMPTY, 80'annotate'=> \&req_annotate, 81'Global_option'=> \&req_Globaloption, 82#'annotate' => \&req_CATCHALL, 83}; 84 85############################################## 86 87 88# $state holds all the bits of information the clients sends us that could 89# potentially be useful when it comes to actually _doing_ something. 90my$state= { prependdir =>''}; 91 92# Work is for managing temporary working directory 93my$work= 94{ 95state=>undef,# undef, 1 (empty), 2 (with stuff) 96 workDir =>undef, 97index=>undef, 98 emptyDir =>undef, 99 tmpDir =>undef 100}; 101 102$log->info("--------------- STARTING -----------------"); 103 104my$usage= 105"Usage: git cvsserver [options] [pserver|server] [<directory> ...]\n". 106" --base-path <path> : Prepend to requested CVSROOT\n". 107" Can be read from GIT_CVSSERVER_BASE_PATH\n". 108" --strict-paths : Don't allow recursing into subdirectories\n". 109" --export-all : Don't check for gitcvs.enabled in config\n". 110" --version, -V : Print version information and exit\n". 111" --help, -h, -H : Print usage information and exit\n". 112"\n". 113"<directory> ... is a list of allowed directories. If no directories\n". 114"are given, all are allowed. This is an additional restriction, gitcvs\n". 115"access still needs to be enabled by the gitcvs.enabled config option.\n". 116"Alternately, one directory may be specified in GIT_CVSSERVER_ROOT.\n"; 117 118my@opts= ('help|h|H','version|V', 119'base-path=s','strict-paths','export-all'); 120GetOptions($state,@opts) 121or die$usage; 122 123if($state->{version}) { 124print"git-cvsserver version$VERSION\n"; 125exit; 126} 127if($state->{help}) { 128print$usage; 129exit; 130} 131 132my$TEMP_DIR= tempdir( CLEANUP =>1); 133$log->debug("Temporary directory is '$TEMP_DIR'"); 134 135$state->{method} ='ext'; 136if(@ARGV) { 137if($ARGV[0]eq'pserver') { 138$state->{method} ='pserver'; 139shift@ARGV; 140}elsif($ARGV[0]eq'server') { 141shift@ARGV; 142} 143} 144 145# everything else is a directory 146$state->{allowed_roots} = [@ARGV]; 147 148# don't export the whole system unless the users requests it 149if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 150die"--export-all can only be used together with an explicit whitelist\n"; 151} 152 153# Environment handling for running under git-shell 154if(exists$ENV{GIT_CVSSERVER_BASE_PATH}) { 155if($state->{'base-path'}) { 156die"Cannot specify base path both ways.\n"; 157} 158my$base_path=$ENV{GIT_CVSSERVER_BASE_PATH}; 159$state->{'base-path'} =$base_path; 160$log->debug("Picked up base path '$base_path' from environment.\n"); 161} 162if(exists$ENV{GIT_CVSSERVER_ROOT}) { 163if(@{$state->{allowed_roots}}) { 164die"Cannot specify roots both ways:@ARGV\n"; 165} 166my$allowed_root=$ENV{GIT_CVSSERVER_ROOT}; 167$state->{allowed_roots} = [$allowed_root]; 168$log->debug("Picked up allowed root '$allowed_root' from environment.\n"); 169} 170 171# if we are called with a pserver argument, 172# deal with the authentication cat before entering the 173# main loop 174if($state->{method}eq'pserver') { 175my$line= <STDIN>;chomp$line; 176unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 177die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 178} 179my$request=$1; 180$line= <STDIN>;chomp$line; 181unless(req_Root('root',$line)) {# reuse Root 182print"E Invalid root$line\n"; 183exit1; 184} 185$line= <STDIN>;chomp$line; 186my$user=$line; 187$line= <STDIN>;chomp$line; 188my$password=$line; 189 190unless($usereq'anonymous') { 191# Trying to authenticate a user 192if(not exists$cfg->{gitcvs}->{authdb}) { 193print"E the repo config file needs a [gitcvs.authdb] section with a filename\n"; 194print"I HATE YOU\n"; 195exit1; 196} 197my$auth_ok; 198open PASSWD,"<$cfg->{gitcvs}->{authdb}"or die$!; 199while(<PASSWD>) { 200if(m{^\Q$user\E:(.*)}) { 201if(crypt($user,$1)eq$1) { 202$auth_ok=1; 203} 204}; 205} 206unless($auth_ok) { 207print"I HATE YOU\n"; 208exit1; 209} 210# else fall through to LOVE 211} 212 213# For checking whether the user is anonymous on commit 214$state->{user} =$user; 215 216$line= <STDIN>;chomp$line; 217unless($lineeq"END$requestREQUEST") { 218die"E Do not understand$line-- expecting END$requestREQUEST\n"; 219} 220print"I LOVE YOU\n"; 221exit if$requesteq'VERIFICATION';# cvs login 222# and now back to our regular programme... 223} 224 225# Keep going until the client closes the connection 226while(<STDIN>) 227{ 228chomp; 229 230# Check to see if we've seen this method, and call appropriate function. 231if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 232{ 233# use the $methods hash to call the appropriate sub for this command 234#$log->info("Method : $1"); 235&{$methods->{$1}}($1,$2); 236}else{ 237# log fatal because we don't understand this function. If this happens 238# we're fairly screwed because we don't know if the client is expecting 239# a response. If it is, the client will hang, we'll hang, and the whole 240# thing will be custard. 241$log->fatal("Don't understand command$_\n"); 242die("Unknown command$_"); 243} 244} 245 246$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 247$log->info("--------------- FINISH -----------------"); 248 249chdir'/'; 250exit0; 251 252# Magic catchall method. 253# This is the method that will handle all commands we haven't yet 254# implemented. It simply sends a warning to the log file indicating a 255# command that hasn't been implemented has been invoked. 256sub req_CATCHALL 257{ 258my($cmd,$data) =@_; 259$log->warn("Unhandled command : req_$cmd:$data"); 260} 261 262# This method invariably succeeds with an empty response. 263sub req_EMPTY 264{ 265print"ok\n"; 266} 267 268# Root pathname \n 269# Response expected: no. Tell the server which CVSROOT to use. Note that 270# pathname is a local directory and not a fully qualified CVSROOT variable. 271# pathname must already exist; if creating a new root, use the init 272# request, not Root. pathname does not include the hostname of the server, 273# how to access the server, etc.; by the time the CVS protocol is in use, 274# connection, authentication, etc., are already taken care of. The Root 275# request must be sent only once, and it must be sent before any requests 276# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 277sub req_Root 278{ 279my($cmd,$data) =@_; 280$log->debug("req_Root :$data"); 281 282unless($data=~ m#^/#) { 283print"error 1 Root must be an absolute pathname\n"; 284return0; 285} 286 287my$cvsroot=$state->{'base-path'} ||''; 288$cvsroot=~ s#/+$##; 289$cvsroot.=$data; 290 291if($state->{CVSROOT} 292&& ($state->{CVSROOT}ne$cvsroot)) { 293print"error 1 Conflicting roots specified\n"; 294return0; 295} 296 297$state->{CVSROOT} =$cvsroot; 298 299$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 300 301if(@{$state->{allowed_roots}}) { 302my$allowed=0; 303foreachmy$dir(@{$state->{allowed_roots}}) { 304next unless$dir=~ m#^/#; 305$dir=~ s#/+$##; 306if($state->{'strict-paths'}) { 307if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 308$allowed=1; 309last; 310} 311}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 312$allowed=1; 313last; 314} 315} 316 317unless($allowed) { 318print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 319print"E\n"; 320print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 321return0; 322} 323} 324 325unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 326print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 327print"E\n"; 328print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 329return0; 330} 331 332my@gitvars=`git config -l`; 333if($?) { 334print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 335print"E\n"; 336print"error 1 - problem executing git-config\n"; 337return0; 338} 339foreachmy$line(@gitvars) 340{ 341next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 342unless($2) { 343$cfg->{$1}{$3} =$4; 344}else{ 345$cfg->{$1}{$2}{$3} =$4; 346} 347} 348 349my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 350||$cfg->{gitcvs}{enabled}); 351unless($state->{'export-all'} || 352($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 353print"E GITCVS emulation needs to be enabled on this repo\n"; 354print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 355print"E\n"; 356print"error 1 GITCVS emulation disabled\n"; 357return0; 358} 359 360my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 361if($logfile) 362{ 363$log->setfile($logfile); 364}else{ 365$log->nofile(); 366} 367 368return1; 369} 370 371# Global_option option \n 372# Response expected: no. Transmit one of the global options `-q', `-Q', 373# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 374# variations (such as combining of options) are allowed. For graceful 375# handling of valid-requests, it is probably better to make new global 376# options separate requests, rather than trying to add them to this 377# request. 378sub req_Globaloption 379{ 380my($cmd,$data) =@_; 381$log->debug("req_Globaloption :$data"); 382$state->{globaloptions}{$data} =1; 383} 384 385# Valid-responses request-list \n 386# Response expected: no. Tell the server what responses the client will 387# accept. request-list is a space separated list of tokens. 388sub req_Validresponses 389{ 390my($cmd,$data) =@_; 391$log->debug("req_Validresponses :$data"); 392 393# TODO : re-enable this, currently it's not particularly useful 394#$state->{validresponses} = [ split /\s+/, $data ]; 395} 396 397# valid-requests \n 398# Response expected: yes. Ask the server to send back a Valid-requests 399# response. 400sub req_validrequests 401{ 402my($cmd,$data) =@_; 403 404$log->debug("req_validrequests"); 405 406$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 407$log->debug("SEND : ok"); 408 409print"Valid-requests ".join(" ",keys%$methods) ."\n"; 410print"ok\n"; 411} 412 413# Directory local-directory \n 414# Additional data: repository \n. Response expected: no. Tell the server 415# what directory to use. The repository should be a directory name from a 416# previous server response. Note that this both gives a default for Entry 417# and Modified and also for ci and the other commands; normal usage is to 418# send Directory for each directory in which there will be an Entry or 419# Modified, and then a final Directory for the original directory, then the 420# command. The local-directory is relative to the top level at which the 421# command is occurring (i.e. the last Directory which is sent before the 422# command); to indicate that top level, `.' should be sent for 423# local-directory. 424sub req_Directory 425{ 426my($cmd,$data) =@_; 427 428my$repository= <STDIN>; 429chomp$repository; 430 431 432$state->{localdir} =$data; 433$state->{repository} =$repository; 434$state->{path} =$repository; 435$state->{path} =~s/^\Q$state->{CVSROOT}\E\///; 436$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 437$state->{path} .="/"if($state->{path} =~ /\S/ ); 438 439$state->{directory} =$state->{localdir}; 440$state->{directory} =""if($state->{directory}eq"."); 441$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 442 443if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 444{ 445$log->info("Setting prepend to '$state->{path}'"); 446$state->{prependdir} =$state->{path}; 447foreachmy$entry(keys%{$state->{entries}} ) 448{ 449$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 450delete$state->{entries}{$entry}; 451} 452} 453 454if(defined($state->{prependdir} ) ) 455{ 456$log->debug("Prepending '$state->{prependdir}' to state|directory"); 457$state->{directory} =$state->{prependdir} .$state->{directory} 458} 459$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 460} 461 462# Entry entry-line \n 463# Response expected: no. Tell the server what version of a file is on the 464# local machine. The name in entry-line is a name relative to the directory 465# most recently specified with Directory. If the user is operating on only 466# some files in a directory, Entry requests for only those files need be 467# included. If an Entry request is sent without Modified, Is-modified, or 468# Unchanged, it means the file is lost (does not exist in the working 469# directory). If both Entry and one of Modified, Is-modified, or Unchanged 470# are sent for the same file, Entry must be sent first. For a given file, 471# one can send Modified, Is-modified, or Unchanged, but not more than one 472# of these three. 473sub req_Entry 474{ 475my($cmd,$data) =@_; 476 477#$log->debug("req_Entry : $data"); 478 479my@data=split(/\//,$data); 480 481$state->{entries}{$state->{directory}.$data[1]} = { 482 revision =>$data[2], 483 conflict =>$data[3], 484 options =>$data[4], 485 tag_or_date =>$data[5], 486}; 487 488$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 489} 490 491# Questionable filename \n 492# Response expected: no. Additional data: no. Tell the server to check 493# whether filename should be ignored, and if not, next time the server 494# sends responses, send (in a M response) `?' followed by the directory and 495# filename. filename must not contain `/'; it needs to be a file in the 496# directory named by the most recent Directory request. 497sub req_Questionable 498{ 499my($cmd,$data) =@_; 500 501$log->debug("req_Questionable :$data"); 502$state->{entries}{$state->{directory}.$data}{questionable} =1; 503} 504 505# add \n 506# Response expected: yes. Add a file or directory. This uses any previous 507# Argument, Directory, Entry, or Modified requests, if they have been sent. 508# The last Directory sent specifies the working directory at the time of 509# the operation. To add a directory, send the directory to be added using 510# Directory and Argument requests. 511sub req_add 512{ 513my($cmd,$data) =@_; 514 515 argsplit("add"); 516 517my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 518$updater->update(); 519 520 argsfromdir($updater); 521 522my$addcount=0; 523 524foreachmy$filename( @{$state->{args}} ) 525{ 526$filename= filecleanup($filename); 527 528my$meta=$updater->getmeta($filename); 529my$wrev= revparse($filename); 530 531if($wrev&&$meta&& ($wrev<0)) 532{ 533# previously removed file, add back 534$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 535 536print"MT +updated\n"; 537print"MT text U\n"; 538print"MT fname$filename\n"; 539print"MT newline\n"; 540print"MT -updated\n"; 541 542unless($state->{globaloptions}{-n} ) 543{ 544my($filepart,$dirpart) = filenamesplit($filename,1); 545 546print"Created$dirpart\n"; 547print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 548 549# this is an "entries" line 550my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 551$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 552print"/$filepart/1.$meta->{revision}//$kopts/\n"; 553# permissions 554$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 555print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 556# transmit file 557 transmitfile($meta->{filehash}); 558} 559 560next; 561} 562 563unless(defined($state->{entries}{$filename}{modified_filename} ) ) 564{ 565print"E cvs add: nothing known about `$filename'\n"; 566next; 567} 568# TODO : check we're not squashing an already existing file 569if(defined($state->{entries}{$filename}{revision} ) ) 570{ 571print"E cvs add: `$filename' has already been entered\n"; 572next; 573} 574 575my($filepart,$dirpart) = filenamesplit($filename,1); 576 577print"E cvs add: scheduling file `$filename' for addition\n"; 578 579print"Checked-in$dirpart\n"; 580print"$filename\n"; 581my$kopts= kopts_from_path($filename,"file", 582$state->{entries}{$filename}{modified_filename}); 583print"/$filepart/0//$kopts/\n"; 584 585my$requestedKopts=$state->{opt}{k}; 586if(defined($requestedKopts)) 587{ 588$requestedKopts="-k$requestedKopts"; 589} 590else 591{ 592$requestedKopts=""; 593} 594if($koptsne$requestedKopts) 595{ 596$log->warn("Ignoring requested -k='$requestedKopts'" 597." for '$filename'; detected -k='$kopts' instead"); 598#TODO: Also have option to send warning to user? 599} 600 601$addcount++; 602} 603 604if($addcount==1) 605{ 606print"E cvs add: use `cvs commit' to add this file permanently\n"; 607} 608elsif($addcount>1) 609{ 610print"E cvs add: use `cvs commit' to add these files permanently\n"; 611} 612 613print"ok\n"; 614} 615 616# remove \n 617# Response expected: yes. Remove a file. This uses any previous Argument, 618# Directory, Entry, or Modified requests, if they have been sent. The last 619# Directory sent specifies the working directory at the time of the 620# operation. Note that this request does not actually do anything to the 621# repository; the only effect of a successful remove request is to supply 622# the client with a new entries line containing `-' to indicate a removed 623# file. In fact, the client probably could perform this operation without 624# contacting the server, although using remove may cause the server to 625# perform a few more checks. The client sends a subsequent ci request to 626# actually record the removal in the repository. 627sub req_remove 628{ 629my($cmd,$data) =@_; 630 631 argsplit("remove"); 632 633# Grab a handle to the SQLite db and do any necessary updates 634my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 635$updater->update(); 636 637#$log->debug("add state : " . Dumper($state)); 638 639my$rmcount=0; 640 641foreachmy$filename( @{$state->{args}} ) 642{ 643$filename= filecleanup($filename); 644 645if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 646{ 647print"E cvs remove: file `$filename' still in working directory\n"; 648next; 649} 650 651my$meta=$updater->getmeta($filename); 652my$wrev= revparse($filename); 653 654unless(defined($wrev) ) 655{ 656print"E cvs remove: nothing known about `$filename'\n"; 657next; 658} 659 660if(defined($wrev)and$wrev<0) 661{ 662print"E cvs remove: file `$filename' already scheduled for removal\n"; 663next; 664} 665 666unless($wrev==$meta->{revision} ) 667{ 668# TODO : not sure if the format of this message is quite correct. 669print"E cvs remove: Up to date check failed for `$filename'\n"; 670next; 671} 672 673 674my($filepart,$dirpart) = filenamesplit($filename,1); 675 676print"E cvs remove: scheduling `$filename' for removal\n"; 677 678print"Checked-in$dirpart\n"; 679print"$filename\n"; 680my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 681print"/$filepart/-1.$wrev//$kopts/\n"; 682 683$rmcount++; 684} 685 686if($rmcount==1) 687{ 688print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 689} 690elsif($rmcount>1) 691{ 692print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 693} 694 695print"ok\n"; 696} 697 698# Modified filename \n 699# Response expected: no. Additional data: mode, \n, file transmission. Send 700# the server a copy of one locally modified file. filename is a file within 701# the most recent directory sent with Directory; it must not contain `/'. 702# If the user is operating on only some files in a directory, only those 703# files need to be included. This can also be sent without Entry, if there 704# is no entry for the file. 705sub req_Modified 706{ 707my($cmd,$data) =@_; 708 709my$mode= <STDIN>; 710defined$mode 711or(print"E end of file reading mode for$data\n"),return; 712chomp$mode; 713my$size= <STDIN>; 714defined$size 715or(print"E end of file reading size of$data\n"),return; 716chomp$size; 717 718# Grab config information 719my$blocksize=8192; 720my$bytesleft=$size; 721my$tmp; 722 723# Get a filehandle/name to write it to 724my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 725 726# Loop over file data writing out to temporary file. 727while($bytesleft) 728{ 729$blocksize=$bytesleftif($bytesleft<$blocksize); 730read STDIN,$tmp,$blocksize; 731print$fh $tmp; 732$bytesleft-=$blocksize; 733} 734 735close$fh 736or(print"E failed to write temporary,$filename:$!\n"),return; 737 738# Ensure we have something sensible for the file mode 739if($mode=~/u=(\w+)/) 740{ 741$mode=$1; 742}else{ 743$mode="rw"; 744} 745 746# Save the file data in $state 747$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 748$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 749$state->{entries}{$state->{directory}.$data}{modified_hash} =`git hash-object$filename`; 750$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 751 752 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 753} 754 755# Unchanged filename\n 756# Response expected: no. Tell the server that filename has not been 757# modified in the checked out directory. The filename is a file within the 758# most recent directory sent with Directory; it must not contain `/'. 759sub req_Unchanged 760{ 761 my ($cmd,$data) =@_; 762 763$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 764 765 #$log->debug("req_Unchanged :$data"); 766} 767 768# Argument text\n 769# Response expected: no. Save argument for use in a subsequent command. 770# Arguments accumulate until an argument-using command is given, at which 771# point they are forgotten. 772# Argumentx text\n 773# Response expected: no. Append\nfollowed by text to the current argument 774# being saved. 775sub req_Argument 776{ 777 my ($cmd,$data) =@_; 778 779 # Argumentx means: append to last Argument (with a newline in front) 780 781$log->debug("$cmd:$data"); 782 783 if ($cmdeq 'Argumentx') { 784 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 785 } else { 786 push @{$state->{arguments}},$data; 787 } 788} 789 790# expand-modules\n 791# Response expected: yes. Expand the modules which are specified in the 792# arguments. Returns the data in Module-expansion responses. Note that the 793# server can assume that this is checkout or export, not rtag or rdiff; the 794# latter do not access the working directory and thus have no need to 795# expand modules on the client side. Expand may not be the best word for 796# what this request does. It does not necessarily tell you all the files 797# contained in a module, for example. Basically it is a way of telling you 798# which working directories the server needs to know about in order to 799# handle a checkout of the specified modules. For example, suppose that the 800# server has a module defined by 801# aliasmodule -a 1dir 802# That is, one can check out aliasmodule and it will take 1dir in the 803# repository and check it out to 1dir in the working directory. Now suppose 804# the client already has this module checked out and is planning on using 805# the co request to update it. Without using expand-modules, the client 806# would have two bad choices: it could either send information about all 807# working directories under the current directory, which could be 808# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 809# stands for 1dir, and neglect to send information for 1dir, which would 810# lead to incorrect operation. With expand-modules, the client would first 811# ask for the module to be expanded: 812sub req_expandmodules 813{ 814 my ($cmd,$data) =@_; 815 816 argsplit(); 817 818$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 819 820 unless ( ref$state->{arguments} eq "ARRAY" ) 821 { 822 print "ok\n"; 823 return; 824 } 825 826 foreach my$module( @{$state->{arguments}} ) 827 { 828$log->debug("SEND : Module-expansion$module"); 829 print "Module-expansion$module\n"; 830 } 831 832 print "ok\n"; 833 statecleanup(); 834} 835 836# co\n 837# Response expected: yes. Get files from the repository. This uses any 838# previous Argument, Directory, Entry, or Modified requests, if they have 839# been sent. Arguments to this command are module names; the client cannot 840# know what directories they correspond to except by (1) just sending the 841# co request, and then seeing what directory names the server sends back in 842# its responses, and (2) the expand-modules request. 843sub req_co 844{ 845 my ($cmd,$data) =@_; 846 847 argsplit("co"); 848 849 # Provide list of modules, if -c was used. 850 if (exists$state->{opt}{c}) { 851 my$showref= `git show-ref --heads`; 852 for my$line(split '\n',$showref) { 853 if ($line=~ m% refs/heads/(.*)$%) { 854 print "M$1\t$1\n"; 855 } 856 } 857 print "ok\n"; 858 return 1; 859 } 860 861 my$module=$state->{args}[0]; 862$state->{module} =$module; 863 my$checkout_path=$module; 864 865 # use the user specified directory if we're given it 866$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 867 868$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 869 870$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 871 872$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 873 874# Grab a handle to the SQLite db and do any necessary updates 875my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 876$updater->update(); 877 878$checkout_path=~ s|/$||;# get rid of trailing slashes 879 880# Eclipse seems to need the Clear-sticky command 881# to prepare the 'Entries' file for the new directory. 882print"Clear-sticky$checkout_path/\n"; 883print$state->{CVSROOT} ."/$module/\n"; 884print"Clear-static-directory$checkout_path/\n"; 885print$state->{CVSROOT} ."/$module/\n"; 886print"Clear-sticky$checkout_path/\n";# yes, twice 887print$state->{CVSROOT} ."/$module/\n"; 888print"Template$checkout_path/\n"; 889print$state->{CVSROOT} ."/$module/\n"; 890print"0\n"; 891 892# instruct the client that we're checking out to $checkout_path 893print"E cvs checkout: Updating$checkout_path\n"; 894 895my%seendirs= (); 896my$lastdir=''; 897 898# recursive 899sub prepdir { 900my($dir,$repodir,$remotedir,$seendirs) =@_; 901my$parent= dirname($dir); 902$dir=~ s|/+$||; 903$repodir=~ s|/+$||; 904$remotedir=~ s|/+$||; 905$parent=~ s|/+$||; 906$log->debug("announcedir$dir,$repodir,$remotedir"); 907 908if($parenteq'.'||$parenteq'./') { 909$parent=''; 910} 911# recurse to announce unseen parents first 912if(length($parent) && !exists($seendirs->{$parent})) { 913 prepdir($parent,$repodir,$remotedir,$seendirs); 914} 915# Announce that we are going to modify at the parent level 916if($parent) { 917print"E cvs checkout: Updating$remotedir/$parent\n"; 918}else{ 919print"E cvs checkout: Updating$remotedir\n"; 920} 921print"Clear-sticky$remotedir/$parent/\n"; 922print"$repodir/$parent/\n"; 923 924print"Clear-static-directory$remotedir/$dir/\n"; 925print"$repodir/$dir/\n"; 926print"Clear-sticky$remotedir/$parent/\n";# yes, twice 927print"$repodir/$parent/\n"; 928print"Template$remotedir/$dir/\n"; 929print"$repodir/$dir/\n"; 930print"0\n"; 931 932$seendirs->{$dir} =1; 933} 934 935foreachmy$git( @{$updater->gethead} ) 936{ 937# Don't want to check out deleted files 938next if($git->{filehash}eq"deleted"); 939 940my$fullName=$git->{name}; 941($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 942 943if(length($git->{dir}) &&$git->{dir}ne'./' 944&&$git->{dir}ne$lastdir) { 945unless(exists($seendirs{$git->{dir}})) { 946 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 947$checkout_path, \%seendirs); 948$lastdir=$git->{dir}; 949$seendirs{$git->{dir}} =1; 950} 951print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 952} 953 954# modification time of this file 955print"Mod-time$git->{modified}\n"; 956 957# print some information to the client 958if(defined($git->{dir} )and$git->{dir}ne"./") 959{ 960print"M U$checkout_path/$git->{dir}$git->{name}\n"; 961}else{ 962print"M U$checkout_path/$git->{name}\n"; 963} 964 965# instruct client we're sending a file to put in this path 966print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 967 968print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 969 970# this is an "entries" line 971my$kopts= kopts_from_path($fullName,"sha1",$git->{filehash}); 972print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 973# permissions 974print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 975 976# transmit file 977 transmitfile($git->{filehash}); 978} 979 980print"ok\n"; 981 982 statecleanup(); 983} 984 985# update \n 986# Response expected: yes. Actually do a cvs update command. This uses any 987# previous Argument, Directory, Entry, or Modified requests, if they have 988# been sent. The last Directory sent specifies the working directory at the 989# time of the operation. The -I option is not used--files which the client 990# can decide whether to ignore are not mentioned and the client sends the 991# Questionable request for others. 992sub req_update 993{ 994my($cmd,$data) =@_; 995 996$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 997 998 argsplit("update"); 9991000#1001# It may just be a client exploring the available heads/modules1002# in that case, list them as top level directories and leave it1003# at that. Eclipse uses this technique to offer you a list of1004# projects (heads in this case) to checkout.1005#1006if($state->{module}eq'') {1007my$showref=`git show-ref --heads`;1008print"E cvs update: Updating .\n";1009formy$line(split'\n',$showref) {1010if($line=~ m% refs/heads/(.*)$%) {1011print"E cvs update: New directory `$1'\n";1012}1013}1014print"ok\n";1015return1;1016}101710181019# Grab a handle to the SQLite db and do any necessary updates1020my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);10211022$updater->update();10231024 argsfromdir($updater);10251026#$log->debug("update state : " . Dumper($state));10271028my$last_dirname="///";10291030# foreach file specified on the command line ...1031foreachmy$filename( @{$state->{args}} )1032{1033$filename= filecleanup($filename);10341035$log->debug("Processing file$filename");10361037unless($state->{globaloptions}{-Q} ||$state->{globaloptions}{-q} )1038{1039my$cur_dirname= dirname($filename);1040if($cur_dirnamene$last_dirname)1041{1042$last_dirname=$cur_dirname;1043if($cur_dirnameeq"")1044{1045$cur_dirname=".";1046}1047print"E cvs update: Updating$cur_dirname\n";1048}1049}10501051# if we have a -C we should pretend we never saw modified stuff1052if(exists($state->{opt}{C} ) )1053{1054delete$state->{entries}{$filename}{modified_hash};1055delete$state->{entries}{$filename}{modified_filename};1056$state->{entries}{$filename}{unchanged} =1;1057}10581059my$meta;1060if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/)1061{1062$meta=$updater->getmeta($filename,$1);1063}else{1064$meta=$updater->getmeta($filename);1065}10661067# If -p was given, "print" the contents of the requested revision.1068if(exists($state->{opt}{p} ) ) {1069if(defined($meta->{revision} ) ) {1070$log->info("Printing '$filename' revision ".$meta->{revision});10711072 transmitfile($meta->{filehash}, {print=>1});1073}10741075next;1076}10771078if( !defined$meta)1079{1080$meta= {1081 name =>$filename,1082 revision =>0,1083 filehash =>'added'1084};1085}10861087my$oldmeta=$meta;10881089my$wrev= revparse($filename);10901091# If the working copy is an old revision, lets get that version too for comparison.1092if(defined($wrev)and$wrev!=$meta->{revision} )1093{1094$oldmeta=$updater->getmeta($filename,$wrev);1095}10961097#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");10981099# Files are up to date if the working copy and repo copy have the same revision,1100# and the working copy is unmodified _and_ the user hasn't specified -C1101next if(defined($wrev)1102and defined($meta->{revision})1103and$wrev==$meta->{revision}1104and$state->{entries}{$filename}{unchanged}1105and not exists($state->{opt}{C} ) );11061107# If the working copy and repo copy have the same revision,1108# but the working copy is modified, tell the client it's modified1109if(defined($wrev)1110and defined($meta->{revision})1111and$wrev==$meta->{revision}1112and defined($state->{entries}{$filename}{modified_hash})1113and not exists($state->{opt}{C} ) )1114{1115$log->info("Tell the client the file is modified");1116print"MT text M\n";1117print"MT fname$filename\n";1118print"MT newline\n";1119next;1120}11211122if($meta->{filehash}eq"deleted")1123{1124my($filepart,$dirpart) = filenamesplit($filename,1);11251126$log->info("Removing '$filename' from working copy (no longer in the repo)");11271128print"E cvs update: `$filename' is no longer in the repository\n";1129# Don't want to actually _DO_ the update if -n specified1130unless($state->{globaloptions}{-n} ) {1131print"Removed$dirpart\n";1132print"$filepart\n";1133}1134}1135elsif(not defined($state->{entries}{$filename}{modified_hash} )1136or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1137or$meta->{filehash}eq'added')1138{1139# normal update, just send the new revision (either U=Update,1140# or A=Add, or R=Remove)1141if(defined($wrev) &&$wrev<0)1142{1143$log->info("Tell the client the file is scheduled for removal");1144print"MT text R\n";1145print"MT fname$filename\n";1146print"MT newline\n";1147next;1148}1149elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1150{1151$log->info("Tell the client the file is scheduled for addition");1152print"MT text A\n";1153print"MT fname$filename\n";1154print"MT newline\n";1155next;11561157}1158else{1159$log->info("Updating '$filename' to ".$meta->{revision});1160print"MT +updated\n";1161print"MT text U\n";1162print"MT fname$filename\n";1163print"MT newline\n";1164print"MT -updated\n";1165}11661167my($filepart,$dirpart) = filenamesplit($filename,1);11681169# Don't want to actually _DO_ the update if -n specified1170unless($state->{globaloptions}{-n} )1171{1172if(defined($wrev) )1173{1174# instruct client we're sending a file to put in this path as a replacement1175print"Update-existing$dirpart\n";1176$log->debug("Updating existing file 'Update-existing$dirpart'");1177}else{1178# instruct client we're sending a file to put in this path as a new file1179print"Clear-static-directory$dirpart\n";1180print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1181print"Clear-sticky$dirpart\n";1182print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";11831184$log->debug("Creating new file 'Created$dirpart'");1185print"Created$dirpart\n";1186}1187print$state->{CVSROOT} ."/$state->{module}/$filename\n";11881189# this is an "entries" line1190my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1191$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1192print"/$filepart/1.$meta->{revision}//$kopts/\n";11931194# permissions1195$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1196print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11971198# transmit file1199 transmitfile($meta->{filehash});1200}1201}else{1202$log->info("Updating '$filename'");1203my($filepart,$dirpart) = filenamesplit($meta->{name},1);12041205my$mergeDir= setupTmpDir();12061207my$file_local=$filepart.".mine";1208my$mergedFile="$mergeDir/$file_local";1209system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1210my$file_old=$filepart.".".$oldmeta->{revision};1211 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1212my$file_new=$filepart.".".$meta->{revision};1213 transmitfile($meta->{filehash}, { targetfile =>$file_new});12141215# we need to merge with the local changes ( M=successful merge, C=conflict merge )1216$log->info("Merging$file_local,$file_old,$file_new");1217print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";12181219$log->debug("Temporary directory for merge is$mergeDir");12201221my$return=system("git","merge-file",$file_local,$file_old,$file_new);1222$return>>=8;12231224 cleanupTmpDir();12251226if($return==0)1227{1228$log->info("Merged successfully");1229print"M M$filename\n";1230$log->debug("Merged$dirpart");12311232# Don't want to actually _DO_ the update if -n specified1233unless($state->{globaloptions}{-n} )1234{1235print"Merged$dirpart\n";1236$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1237print$state->{CVSROOT} ."/$state->{module}/$filename\n";1238my$kopts= kopts_from_path("$dirpart/$filepart",1239"file",$mergedFile);1240$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1241print"/$filepart/1.$meta->{revision}//$kopts/\n";1242}1243}1244elsif($return==1)1245{1246$log->info("Merged with conflicts");1247print"E cvs update: conflicts found in$filename\n";1248print"M C$filename\n";12491250# Don't want to actually _DO_ the update if -n specified1251unless($state->{globaloptions}{-n} )1252{1253print"Merged$dirpart\n";1254print$state->{CVSROOT} ."/$state->{module}/$filename\n";1255my$kopts= kopts_from_path("$dirpart/$filepart",1256"file",$mergedFile);1257print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1258}1259}1260else1261{1262$log->warn("Merge failed");1263next;1264}12651266# Don't want to actually _DO_ the update if -n specified1267unless($state->{globaloptions}{-n} )1268{1269# permissions1270$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1271print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12721273# transmit file, format is single integer on a line by itself (file1274# size) followed by the file contents1275# TODO : we should copy files in blocks1276my$data=`cat$mergedFile`;1277$log->debug("File size : " . length($data));1278 print length($data) . "\n";1279 print$data;1280 }1281 }12821283 }12841285 print "ok\n";1286}12871288sub req_ci1289{1290 my ($cmd,$data) =@_;12911292 argsplit("ci");12931294 #$log->debug("State : " . Dumper($state));12951296$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));12971298 if ($state->{method} eq 'pserver' and$state->{user} eq 'anonymous' )1299 {1300 print "error 1 anonymous user cannot commit via pserver\n";1301 cleanupWorkTree();1302 exit;1303 }13041305 if ( -e$state->{CVSROOT} . "/index" )1306 {1307$log->warn("file 'index' already exists in the git repository");1308 print "error 1 Index already exists in git repo\n";1309 cleanupWorkTree();1310 exit;1311 }13121313 # Grab a handle to the SQLite db and do any necessary updates1314 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1315$updater->update();13161317 # Remember where the head was at the beginning.1318 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1319 chomp$parenthash;1320 if ($parenthash!~ /^[0-9a-f]{40}$/) {1321 print "error 1 pserver cannot find the current HEAD of module";1322 cleanupWorkTree();1323 exit;1324 }13251326 setupWorkTree($parenthash);13271328$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");13291330$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");13311332 my@committedfiles= ();1333 my%oldmeta;13341335 # foreach file specified on the command line ...1336 foreach my$filename( @{$state->{args}} )1337 {1338 my$committedfile=$filename;1339$filename= filecleanup($filename);13401341 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );13421343 my$meta=$updater->getmeta($filename);1344$oldmeta{$filename} =$meta;13451346 my$wrev= revparse($filename);13471348 my ($filepart,$dirpart) = filenamesplit($filename);13491350 # do a checkout of the file if it is part of this tree1351 if ($wrev) {1352 system('git', 'checkout-index', '-f', '-u',$filename);1353 unless ($?== 0) {1354 die "Error running git-checkout-index -f -u$filename:$!";1355 }1356 }13571358 my$addflag= 0;1359 my$rmflag= 0;1360$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1361$addflag= 1 unless ( -e$filename);13621363 # Do up to date checking1364 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1365 {1366 # fail everything if an up to date check fails1367 print "error 1 Up to date check failed for$filename\n";1368 cleanupWorkTree();1369 exit;1370 }13711372 push@committedfiles,$committedfile;1373$log->info("Committing$filename");13741375 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13761377 unless ($rmflag)1378 {1379$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1380 rename$state->{entries}{$filename}{modified_filename},$filename;13811382 # Calculate modes to remove1383 my$invmode= "";1384 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }13851386$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1387 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1388 }13891390 if ($rmflag)1391 {1392$log->info("Removing file '$filename'");1393 unlink($filename);1394 system("git", "update-index", "--remove",$filename);1395 }1396 elsif ($addflag)1397 {1398$log->info("Adding file '$filename'");1399 system("git", "update-index", "--add",$filename);1400 } else {1401$log->info("Updating file '$filename'");1402 system("git", "update-index",$filename);1403 }1404 }14051406 unless ( scalar(@committedfiles) > 0 )1407 {1408 print "E No files to commit\n";1409 print "ok\n";1410 cleanupWorkTree();1411 return;1412 }14131414 my$treehash= `git write-tree`;1415 chomp$treehash;14161417$log->debug("Treehash :$treehash, Parenthash :$parenthash");14181419 # write our commit message out if we have one ...1420 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1421 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1422 if ( defined ($cfg->{gitcvs}{commitmsgannotation} ) ) {1423 if ($cfg->{gitcvs}{commitmsgannotation} !~ /^\s*$/) {1424 print$msg_fh"\n\n".$cfg->{gitcvs}{commitmsgannotation}."\n"1425 }1426 } else {1427 print$msg_fh"\n\nvia git-CVS emulator\n";1428 }1429 close$msg_fh;14301431 my$commithash= `git commit-tree $treehash-p $parenthash<$msg_filename`;1432chomp($commithash);1433$log->info("Commit hash :$commithash");14341435unless($commithash=~/[a-zA-Z0-9]{40}/)1436{1437$log->warn("Commit failed (Invalid commit hash)");1438print"error 1 Commit failed (unknown reason)\n";1439 cleanupWorkTree();1440exit;1441}14421443### Emulate git-receive-pack by running hooks/update1444my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1445$parenthash,$commithash);1446if( -x $hook[0] ) {1447unless(system(@hook) ==0)1448{1449$log->warn("Commit failed (update hook declined to update ref)");1450print"error 1 Commit failed (update hook declined)\n";1451 cleanupWorkTree();1452exit;1453}1454}14551456### Update the ref1457if(system(qw(git update-ref -m),"cvsserver ci",1458"refs/heads/$state->{module}",$commithash,$parenthash)) {1459$log->warn("update-ref for$state->{module} failed.");1460print"error 1 Cannot commit -- update first\n";1461 cleanupWorkTree();1462exit;1463}14641465### Emulate git-receive-pack by running hooks/post-receive1466my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1467if( -x $hook) {1468open(my$pipe,"|$hook") ||die"can't fork$!";14691470local$SIG{PIPE} =sub{die'pipe broke'};14711472print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";14731474close$pipe||die"bad pipe:$!$?";1475}14761477$updater->update();14781479### Then hooks/post-update1480$hook=$ENV{GIT_DIR}.'hooks/post-update';1481if(-x $hook) {1482system($hook,"refs/heads/$state->{module}");1483}14841485# foreach file specified on the command line ...1486foreachmy$filename(@committedfiles)1487{1488$filename= filecleanup($filename);14891490my$meta=$updater->getmeta($filename);1491unless(defined$meta->{revision}) {1492$meta->{revision} =1;1493}14941495my($filepart,$dirpart) = filenamesplit($filename,1);14961497$log->debug("Checked-in$dirpart:$filename");14981499print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1500if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1501{1502print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1503print"Remove-entry$dirpart\n";1504print"$filename\n";1505}else{1506if($meta->{revision} ==1) {1507print"M initial revision: 1.1\n";1508}else{1509print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1510}1511print"Checked-in$dirpart\n";1512print"$filename\n";1513my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1514print"/$filepart/1.$meta->{revision}//$kopts/\n";1515}1516}15171518 cleanupWorkTree();1519print"ok\n";1520}15211522sub req_status1523{1524my($cmd,$data) =@_;15251526 argsplit("status");15271528$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1529#$log->debug("status state : " . Dumper($state));15301531# Grab a handle to the SQLite db and do any necessary updates1532my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1533$updater->update();15341535# if no files were specified, we need to work out what files we should be providing status on ...1536 argsfromdir($updater);15371538# foreach file specified on the command line ...1539foreachmy$filename( @{$state->{args}} )1540{1541$filename= filecleanup($filename);15421543next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;15441545my$meta=$updater->getmeta($filename);1546my$oldmeta=$meta;15471548my$wrev= revparse($filename);15491550# If the working copy is an old revision, lets get that version too for comparison.1551if(defined($wrev)and$wrev!=$meta->{revision} )1552{1553$oldmeta=$updater->getmeta($filename,$wrev);1554}15551556# TODO : All possible statuses aren't yet implemented1557my$status;1558# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1559$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1560and1561( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1562or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1563);15641565# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1566$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1567and1568($state->{entries}{$filename}{unchanged}1569or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1570);15711572# Need checkout if it exists in the repo but doesn't have a working copy1573$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );15741575# Locally modified if working copy and repo copy have the same revision but there are local changes1576$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );15771578# Needs Merge if working copy revision is less than repo copy and there are local changes1579$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );15801581$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1582$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1583$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1584$status||="File had conflicts on merge"if(0);15851586$status||="Unknown";15871588my($filepart) = filenamesplit($filename);15891590print"M ===================================================================\n";1591print"M File:$filepart\tStatus:$status\n";1592if(defined($state->{entries}{$filename}{revision}) )1593{1594print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1595}else{1596print"M Working revision:\tNo entry for$filename\n";1597}1598if(defined($meta->{revision}) )1599{1600print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1601print"M Sticky Tag:\t\t(none)\n";1602print"M Sticky Date:\t\t(none)\n";1603print"M Sticky Options:\t\t(none)\n";1604}else{1605print"M Repository revision:\tNo revision control file\n";1606}1607print"M\n";1608}16091610print"ok\n";1611}16121613sub req_diff1614{1615my($cmd,$data) =@_;16161617 argsplit("diff");16181619$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1620#$log->debug("status state : " . Dumper($state));16211622my($revision1,$revision2);1623if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1624{1625$revision1=$state->{opt}{r}[0];1626$revision2=$state->{opt}{r}[1];1627}else{1628$revision1=$state->{opt}{r};1629}16301631$revision1=~s/^1\.//if(defined($revision1) );1632$revision2=~s/^1\.//if(defined($revision2) );16331634$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );16351636# Grab a handle to the SQLite db and do any necessary updates1637my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1638$updater->update();16391640# if no files were specified, we need to work out what files we should be providing status on ...1641 argsfromdir($updater);16421643# foreach file specified on the command line ...1644foreachmy$filename( @{$state->{args}} )1645{1646$filename= filecleanup($filename);16471648my($fh,$file1,$file2,$meta1,$meta2,$filediff);16491650my$wrev= revparse($filename);16511652# We need _something_ to diff against1653next unless(defined($wrev) );16541655# if we have a -r switch, use it1656if(defined($revision1) )1657{1658(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1659$meta1=$updater->getmeta($filename,$revision1);1660unless(defined($meta1)and$meta1->{filehash}ne"deleted")1661{1662print"E File$filenameat revision 1.$revision1doesn't exist\n";1663next;1664}1665 transmitfile($meta1->{filehash}, { targetfile =>$file1});1666}1667# otherwise we just use the working copy revision1668else1669{1670(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1671$meta1=$updater->getmeta($filename,$wrev);1672 transmitfile($meta1->{filehash}, { targetfile =>$file1});1673}16741675# if we have a second -r switch, use it too1676if(defined($revision2) )1677{1678(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1679$meta2=$updater->getmeta($filename,$revision2);16801681unless(defined($meta2)and$meta2->{filehash}ne"deleted")1682{1683print"E File$filenameat revision 1.$revision2doesn't exist\n";1684next;1685}16861687 transmitfile($meta2->{filehash}, { targetfile =>$file2});1688}1689# otherwise we just use the working copy1690else1691{1692$file2=$state->{entries}{$filename}{modified_filename};1693}16941695# if we have been given -r, and we don't have a $file2 yet, lets get one1696if(defined($revision1)and not defined($file2) )1697{1698(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1699$meta2=$updater->getmeta($filename,$wrev);1700 transmitfile($meta2->{filehash}, { targetfile =>$file2});1701}17021703# We need to have retrieved something useful1704next unless(defined($meta1) );17051706# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1707next if(not defined($meta2)and$wrev==$meta1->{revision}1708and1709( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1710or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1711);17121713# Apparently we only show diffs for locally modified files1714next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );17151716print"M Index:$filename\n";1717print"M ===================================================================\n";1718print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1719print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1720print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1721print"M diff ";1722foreachmy$opt(keys%{$state->{opt}} )1723{1724if(ref$state->{opt}{$opt}eq"ARRAY")1725{1726foreachmy$value( @{$state->{opt}{$opt}} )1727{1728print"-$opt$value";1729}1730}else{1731print"-$opt";1732print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1733}1734}1735print"$filename\n";17361737$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));17381739($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);17401741if(exists$state->{opt}{u} )1742{1743system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1744}else{1745system("diff$file1$file2>$filediff");1746}17471748while( <$fh> )1749{1750print"M$_";1751}1752close$fh;1753}17541755print"ok\n";1756}17571758sub req_log1759{1760my($cmd,$data) =@_;17611762 argsplit("log");17631764$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1765#$log->debug("log state : " . Dumper($state));17661767my($minrev,$maxrev);1768if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1769{1770my$control=$2;1771$minrev=$1;1772$maxrev=$3;1773$minrev=~s/^1\.//if(defined($minrev) );1774$maxrev=~s/^1\.//if(defined($maxrev) );1775$minrev++if(defined($minrev)and$controleq"::");1776}17771778# Grab a handle to the SQLite db and do any necessary updates1779my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1780$updater->update();17811782# if no files were specified, we need to work out what files we should be providing status on ...1783 argsfromdir($updater);17841785# foreach file specified on the command line ...1786foreachmy$filename( @{$state->{args}} )1787{1788$filename= filecleanup($filename);17891790my$headmeta=$updater->getmeta($filename);17911792my$revisions=$updater->getlog($filename);1793my$totalrevisions=scalar(@$revisions);17941795if(defined($minrev) )1796{1797$log->debug("Removing revisions less than$minrev");1798while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1799{1800pop@$revisions;1801}1802}1803if(defined($maxrev) )1804{1805$log->debug("Removing revisions greater than$maxrev");1806while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1807{1808shift@$revisions;1809}1810}18111812next unless(scalar(@$revisions) );18131814print"M\n";1815print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1816print"M Working file:$filename\n";1817print"M head: 1.$headmeta->{revision}\n";1818print"M branch:\n";1819print"M locks: strict\n";1820print"M access list:\n";1821print"M symbolic names:\n";1822print"M keyword substitution: kv\n";1823print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1824print"M description:\n";18251826foreachmy$revision(@$revisions)1827{1828print"M ----------------------------\n";1829print"M revision 1.$revision->{revision}\n";1830# reformat the date for log output1831$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}) );1832$revision->{author} = cvs_author($revision->{author});1833print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1834my$commitmessage=$updater->commitmessage($revision->{commithash});1835$commitmessage=~s/^/M /mg;1836print$commitmessage."\n";1837}1838print"M =============================================================================\n";1839}18401841print"ok\n";1842}18431844sub req_annotate1845{1846my($cmd,$data) =@_;18471848 argsplit("annotate");18491850$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1851#$log->debug("status state : " . Dumper($state));18521853# Grab a handle to the SQLite db and do any necessary updates1854my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1855$updater->update();18561857# if no files were specified, we need to work out what files we should be providing annotate on ...1858 argsfromdir($updater);18591860# we'll need a temporary checkout dir1861 setupWorkTree();18621863$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");18641865# foreach file specified on the command line ...1866foreachmy$filename( @{$state->{args}} )1867{1868$filename= filecleanup($filename);18691870my$meta=$updater->getmeta($filename);18711872next unless($meta->{revision} );18731874# get all the commits that this file was in1875# in dense format -- aka skip dead revisions1876my$revisions=$updater->gethistorydense($filename);1877my$lastseenin=$revisions->[0][2];18781879# populate the temporary index based on the latest commit were we saw1880# the file -- but do it cheaply without checking out any files1881# TODO: if we got a revision from the client, use that instead1882# to look up the commithash in sqlite (still good to default to1883# the current head as we do now)1884system("git","read-tree",$lastseenin);1885unless($?==0)1886{1887print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1888return;1889}1890$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");18911892# do a checkout of the file1893system('git','checkout-index','-f','-u',$filename);1894unless($?==0) {1895print"E error running git-checkout-index -f -u$filename:$!\n";1896return;1897}18981899$log->info("Annotate$filename");19001901# Prepare a file with the commits from the linearized1902# history that annotate should know about. This prevents1903# git-jsannotate telling us about commits we are hiding1904# from the client.19051906my$a_hints="$work->{workDir}/.annotate_hints";1907if(!open(ANNOTATEHINTS,'>',$a_hints)) {1908print"E failed to open '$a_hints' for writing:$!\n";1909return;1910}1911for(my$i=0;$i<@$revisions;$i++)1912{1913print ANNOTATEHINTS $revisions->[$i][2];1914if($i+1<@$revisions) {# have we got a parent?1915print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1916}1917print ANNOTATEHINTS "\n";1918}19191920print ANNOTATEHINTS "\n";1921close ANNOTATEHINTS1922or(print"E failed to write$a_hints:$!\n"),return;19231924my@cmd= (qw(git annotate -l -S),$a_hints,$filename);1925if(!open(ANNOTATE,"-|",@cmd)) {1926print"E error invoking ".join(' ',@cmd) .":$!\n";1927return;1928}1929my$metadata= {};1930print"E Annotations for$filename\n";1931print"E ***************\n";1932while( <ANNOTATE> )1933{1934if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1935{1936my$commithash=$1;1937my$data=$2;1938unless(defined($metadata->{$commithash} ) )1939{1940$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1941$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1942$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1943}1944printf("M 1.%-5d (%-8s%10s):%s\n",1945$metadata->{$commithash}{revision},1946$metadata->{$commithash}{author},1947$metadata->{$commithash}{modified},1948$data1949);1950}else{1951$log->warn("Error in annotate output! LINE:$_");1952print"E Annotate error\n";1953next;1954}1955}1956close ANNOTATE;1957}19581959# done; get out of the tempdir1960 cleanupWorkTree();19611962print"ok\n";19631964}19651966# This method takes the state->{arguments} array and produces two new arrays.1967# The first is $state->{args} which is everything before the '--' argument, and1968# the second is $state->{files} which is everything after it.1969sub argsplit1970{1971$state->{args} = [];1972$state->{files} = [];1973$state->{opt} = {};19741975return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19761977my$type=shift;19781979if(defined($type) )1980{1981my$opt= {};1982$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");1983$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1984$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");1985$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1986$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1987$opt= { k =>1, m =>1}if($typeeq"add");1988$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1989$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");199019911992while(scalar( @{$state->{arguments}} ) >0)1993{1994my$arg=shift@{$state->{arguments}};19951996next if($argeq"--");1997next unless($arg=~/\S/);19981999# if the argument looks like a switch2000if($arg=~/^-(\w)(.*)/)2001{2002# if it's a switch that takes an argument2003if($opt->{$1} )2004{2005# If this switch has already been provided2006if($opt->{$1} >1and exists($state->{opt}{$1} ) )2007{2008$state->{opt}{$1} = [$state->{opt}{$1} ];2009if(length($2) >0)2010{2011push@{$state->{opt}{$1}},$2;2012}else{2013push@{$state->{opt}{$1}},shift@{$state->{arguments}};2014}2015}else{2016# if there's extra data in the arg, use that as the argument for the switch2017if(length($2) >0)2018{2019$state->{opt}{$1} =$2;2020}else{2021$state->{opt}{$1} =shift@{$state->{arguments}};2022}2023}2024}else{2025$state->{opt}{$1} =undef;2026}2027}2028else2029{2030push@{$state->{args}},$arg;2031}2032}2033}2034else2035{2036my$mode=0;20372038foreachmy$value( @{$state->{arguments}} )2039{2040if($valueeq"--")2041{2042$mode++;2043next;2044}2045push@{$state->{args}},$valueif($mode==0);2046push@{$state->{files}},$valueif($mode==1);2047}2048}2049}20502051# This method uses $state->{directory} to populate $state->{args} with a list of filenames2052sub argsfromdir2053{2054my$updater=shift;20552056$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");20572058return if(scalar( @{$state->{args}} ) >1);20592060my@gethead= @{$updater->gethead};20612062# push added files2063foreachmy$file(keys%{$state->{entries}}) {2064if(exists$state->{entries}{$file}{revision} &&2065$state->{entries}{$file}{revision} ==0)2066{2067push@gethead, { name =>$file, filehash =>'added'};2068}2069}20702071if(scalar(@{$state->{args}}) ==1)2072{2073my$arg=$state->{args}[0];2074$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );20752076$log->info("Only one arg specified, checking for directory expansion on '$arg'");20772078foreachmy$file(@gethead)2079{2080next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2081next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2082push@{$state->{args}},$file->{name};2083}20842085shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2086}else{2087$log->info("Only one arg specified, populating file list automatically");20882089$state->{args} = [];20902091foreachmy$file(@gethead)2092{2093next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2094next unless($file->{name} =~s/^$state->{prependdir}//);2095push@{$state->{args}},$file->{name};2096}2097}2098}20992100# This method cleans up the $state variable after a command that uses arguments has run2101sub statecleanup2102{2103$state->{files} = [];2104$state->{args} = [];2105$state->{arguments} = [];2106$state->{entries} = {};2107}21082109sub revparse2110{2111my$filename=shift;21122113returnundefunless(defined($state->{entries}{$filename}{revision} ) );21142115return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2116return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);21172118returnundef;2119}21202121# This method takes a file hash and does a CVS "file transfer". Its2122# exact behaviour depends on a second, optional hash table argument:2123# - If $options->{targetfile}, dump the contents to that file;2124# - If $options->{print}, use M/MT to transmit the contents one line2125# at a time;2126# - Otherwise, transmit the size of the file, followed by the file2127# contents.2128sub transmitfile2129{2130my$filehash=shift;2131my$options=shift;21322133if(defined($filehash)and$filehasheq"deleted")2134{2135$log->warn("filehash is 'deleted'");2136return;2137}21382139die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);21402141my$type=`git cat-file -t$filehash`;2142 chomp$type;21432144 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );21452146 my$size= `git cat-file -s $filehash`;2147chomp$size;21482149$log->debug("transmitfile($filehash) size=$size, type=$type");21502151if(open my$fh,'-|',"git","cat-file","blob",$filehash)2152{2153if(defined($options->{targetfile} ) )2154{2155my$targetfile=$options->{targetfile};2156open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2157print NEWFILE $_while( <$fh> );2158close NEWFILE or die("Failed to write '$targetfile':$!");2159}elsif(defined($options->{print} ) &&$options->{print} ) {2160while( <$fh> ) {2161if(/\n\z/) {2162print'M ',$_;2163}else{2164print'MT text ',$_,"\n";2165}2166}2167}else{2168print"$size\n";2169printwhile( <$fh> );2170}2171close$fhor die("Couldn't close filehandle for transmitfile():$!");2172}else{2173die("Couldn't execute git-cat-file");2174}2175}21762177# This method takes a file name, and returns ( $dirpart, $filepart ) which2178# refers to the directory portion and the file portion of the filename2179# respectively2180sub filenamesplit2181{2182my$filename=shift;2183my$fixforlocaldir=shift;21842185my($filepart,$dirpart) = ($filename,".");2186($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2187$dirpart.="/";21882189if($fixforlocaldir)2190{2191$dirpart=~s/^$state->{prependdir}//;2192}21932194return($filepart,$dirpart);2195}21962197sub filecleanup2198{2199my$filename=shift;22002201returnundefunless(defined($filename));2202if($filename=~/^\// )2203{2204print"E absolute filenames '$filename' not supported by server\n";2205returnundef;2206}22072208$filename=~s/^\.\///g;2209$filename=$state->{prependdir} .$filename;2210return$filename;2211}22122213sub validateGitDir2214{2215if( !defined($state->{CVSROOT}) )2216{2217print"error 1 CVSROOT not specified\n";2218 cleanupWorkTree();2219exit;2220}2221if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2222{2223print"error 1 Internally inconsistent CVSROOT\n";2224 cleanupWorkTree();2225exit;2226}2227}22282229# Setup working directory in a work tree with the requested version2230# loaded in the index.2231sub setupWorkTree2232{2233my($ver) =@_;22342235 validateGitDir();22362237if( (defined($work->{state}) &&$work->{state} !=1) ||2238defined($work->{tmpDir}) )2239{2240$log->warn("Bad work tree state management");2241print"error 1 Internal setup multiple work trees without cleanup\n";2242 cleanupWorkTree();2243exit;2244}22452246$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);22472248if( !defined($work->{index}) )2249{2250(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2251}22522253chdir$work->{workDir}or2254die"Unable to chdir to$work->{workDir}\n";22552256$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");22572258$ENV{GIT_WORK_TREE} =".";2259$ENV{GIT_INDEX_FILE} =$work->{index};2260$work->{state} =2;22612262if($ver)2263{2264system("git","read-tree",$ver);2265unless($?==0)2266{2267$log->warn("Error running git-read-tree");2268die"Error running git-read-tree$verin$work->{workDir}$!\n";2269}2270}2271# else # req_annotate reads tree for each file2272}22732274# Ensure current directory is in some kind of working directory,2275# with a recent version loaded in the index.2276sub ensureWorkTree2277{2278if(defined($work->{tmpDir}) )2279{2280$log->warn("Bad work tree state management [ensureWorkTree()]");2281print"error 1 Internal setup multiple dirs without cleanup\n";2282 cleanupWorkTree();2283exit;2284}2285if($work->{state} )2286{2287return;2288}22892290 validateGitDir();22912292if( !defined($work->{emptyDir}) )2293{2294$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2295}2296chdir$work->{emptyDir}or2297die"Unable to chdir to$work->{emptyDir}\n";22982299my$ver=`git show-ref -s refs/heads/$state->{module}`;2300chomp$ver;2301if($ver!~/^[0-9a-f]{40}$/)2302{2303$log->warn("Error from git show-ref -s refs/head$state->{module}");2304print"error 1 cannot find the current HEAD of module";2305 cleanupWorkTree();2306exit;2307}23082309if( !defined($work->{index}) )2310{2311(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2312}23132314$ENV{GIT_WORK_TREE} =".";2315$ENV{GIT_INDEX_FILE} =$work->{index};2316$work->{state} =1;23172318system("git","read-tree",$ver);2319unless($?==0)2320{2321die"Error running git-read-tree$ver$!\n";2322}2323}23242325# Cleanup working directory that is not needed any longer.2326sub cleanupWorkTree2327{2328if( !$work->{state} )2329{2330return;2331}23322333chdir"/"or die"Unable to chdir '/'\n";23342335if(defined($work->{workDir}) )2336{2337 rmtree($work->{workDir} );2338undef$work->{workDir};2339}2340undef$work->{state};2341}23422343# Setup a temporary directory (not a working tree), typically for2344# merging dirty state as in req_update.2345sub setupTmpDir2346{2347$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2348chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";23492350return$work->{tmpDir};2351}23522353# Clean up a previously setupTmpDir. Restore previous work tree if2354# appropriate.2355sub cleanupTmpDir2356{2357if( !defined($work->{tmpDir}) )2358{2359$log->warn("cleanup tmpdir that has not been setup");2360die"Cleanup tmpDir that has not been setup\n";2361}2362if(defined($work->{state}) )2363{2364if($work->{state} ==1)2365{2366chdir$work->{emptyDir}or2367die"Unable to chdir to$work->{emptyDir}\n";2368}2369elsif($work->{state} ==2)2370{2371chdir$work->{workDir}or2372die"Unable to chdir to$work->{emptyDir}\n";2373}2374else2375{2376$log->warn("Inconsistent work dir state");2377die"Inconsistent work dir state\n";2378}2379}2380else2381{2382chdir"/"or die"Unable to chdir '/'\n";2383}2384}23852386# Given a path, this function returns a string containing the kopts2387# that should go into that path's Entries line. For example, a binary2388# file should get -kb.2389sub kopts_from_path2390{2391my($path,$srcType,$name) =@_;23922393if(defined($cfg->{gitcvs}{usecrlfattr} )and2394$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2395{2396my($val) = check_attr("crlf",$path);2397if($valeq"set")2398{2399return"";2400}2401elsif($valeq"unset")2402{2403return"-kb"2404}2405else2406{2407$log->info("Unrecognized check_attr crlf$path:$val");2408}2409}24102411if(defined($cfg->{gitcvs}{allbinary} ) )2412{2413if( ($cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i) )2414{2415return"-kb";2416}2417elsif( ($cfg->{gitcvs}{allbinary} =~/^\s*guess\s*$/i) )2418{2419if($srcTypeeq"sha1Or-k"&&2420!defined($name) )2421{2422my($ret)=$state->{entries}{$path}{options};2423if( !defined($ret) )2424{2425$ret=$state->{opt}{k};2426if(defined($ret))2427{2428$ret="-k$ret";2429}2430else2431{2432$ret="";2433}2434}2435if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )2436{2437print"E Bad -k option\n";2438$log->warn("Bad -k option:$ret");2439die"Error: Bad -k option:$ret\n";2440}24412442return$ret;2443}2444else2445{2446if( is_binary($srcType,$name) )2447{2448$log->debug("... as binary");2449return"-kb";2450}2451else2452{2453$log->debug("... as text");2454}2455}2456}2457}2458# Return "" to give no special treatment to any path2459return"";2460}24612462sub check_attr2463{2464my($attr,$path) =@_;2465 ensureWorkTree();2466if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2467{2468my$val= <$fh>;2469close$fh;2470$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2471return$val;2472}2473else2474{2475returnundef;2476}2477}24782479# This should have the same heuristics as convert.c:is_binary() and related.2480# Note that the bare CR test is done by callers in convert.c.2481sub is_binary2482{2483my($srcType,$name) =@_;2484$log->debug("is_binary($srcType,$name)");24852486# Minimize amount of interpreted code run in the inner per-character2487# loop for large files, by totalling each character value and2488# then analyzing the totals.2489my@counts;2490my$i;2491for($i=0;$i<256;$i++)2492{2493$counts[$i]=0;2494}24952496my$fh= open_blob_or_die($srcType,$name);2497my$line;2498while(defined($line=<$fh>) )2499{2500# Any '\0' and bare CR are considered binary.2501if($line=~/\0|(\r[^\n])/)2502{2503close($fh);2504return1;2505}25062507# Count up each character in the line:2508my$len=length($line);2509for($i=0;$i<$len;$i++)2510{2511$counts[ord(substr($line,$i,1))]++;2512}2513}2514close$fh;25152516# Don't count CR and LF as either printable/nonprintable2517$counts[ord("\n")]=0;2518$counts[ord("\r")]=0;25192520# Categorize individual character count into printable and nonprintable:2521my$printable=0;2522my$nonprintable=0;2523for($i=0;$i<256;$i++)2524{2525if($i<32&&2526$i!=ord("\b") &&2527$i!=ord("\t") &&2528$i!=033&&# ESC2529$i!=014)# FF2530{2531$nonprintable+=$counts[$i];2532}2533elsif($i==127)# DEL2534{2535$nonprintable+=$counts[$i];2536}2537else2538{2539$printable+=$counts[$i];2540}2541}25422543return($printable>>7) <$nonprintable;2544}25452546# Returns open file handle. Possible invocations:2547# - open_blob_or_die("file",$filename);2548# - open_blob_or_die("sha1",$filehash);2549sub open_blob_or_die2550{2551my($srcType,$name) =@_;2552my($fh);2553if($srcTypeeq"file")2554{2555if( !open$fh,"<",$name)2556{2557$log->warn("Unable to open file$name:$!");2558die"Unable to open file$name:$!\n";2559}2560}2561elsif($srcTypeeq"sha1"||$srcTypeeq"sha1Or-k")2562{2563unless(defined($name)and$name=~/^[a-zA-Z0-9]{40}$/)2564{2565$log->warn("Need filehash");2566die"Need filehash\n";2567}25682569my$type=`git cat-file -t$name`;2570 chomp$type;25712572 unless ( defined ($type) and$typeeq "blob" )2573 {2574$log->warn("Invalid type '$type' for '$name'");2575 die ( "Invalid type '$type' (expected 'blob')" )2576 }25772578 my$size= `git cat-file -s $name`;2579chomp$size;25802581$log->debug("open_blob_or_die($name) size=$size, type=$type");25822583unless(open$fh,'-|',"git","cat-file","blob",$name)2584{2585$log->warn("Unable to open sha1$name");2586die"Unable to open sha1$name\n";2587}2588}2589else2590{2591$log->warn("Unknown type of blob source:$srcType");2592die"Unknown type of blob source:$srcType\n";2593}2594return$fh;2595}25962597# Generate a CVS author name from Git author information, by taking the local2598# part of the email address and replacing characters not in the Portable2599# Filename Character Set (see IEEE Std 1003.1-2001, 3.276) by underscores. CVS2600# Login names are Unix login names, which should be restricted to this2601# character set.2602sub cvs_author2603{2604my$author_line=shift;2605(my$author) =$author_line=~/<([^@>]*)/;26062607$author=~s/[^-a-zA-Z0-9_.]/_/g;2608$author=~s/^-/_/;26092610$author;2611}261226132614sub descramble2615{2616# This table is from src/scramble.c in the CVS source2617my@SHIFTS= (26180,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,261916,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,2620114,120,53,79,96,109,72,108,70,64,76,67,116,74,68,87,2621111,52,75,119,49,34,82,81,95,65,112,86,118,110,122,105,262241,57,83,43,46,102,40,89,38,103,45,50,42,123,91,35,2623125,55,54,66,124,126,59,47,92,71,115,78,88,107,106,56,262436,121,117,104,101,100,69,73,99,63,94,93,39,37,61,48,262558,113,32,90,44,98,60,51,33,97,62,77,84,80,85,223,2626225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190,2627199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193,2628174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212,2629207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246,2630192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176,2631227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127,2632182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195,2633243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,1522634);2635my($str) =@_;26362637# This should never happen, the same password format (A) bas been2638# used by CVS since the beginning of time2639die"invalid password format$1"unlesssubstr($str,0,1)eq'A';26402641my@str=unpack"C*",substr($str,1);2642my$ret=join'',map{chr$SHIFTS[$_] }@str;2643return$ret;2644}264526462647package GITCVS::log;26482649####2650#### Copyright The Open University UK - 2006.2651####2652#### Authors: Martyn Smith <martyn@catalyst.net.nz>2653#### Martin Langhoff <martin@catalyst.net.nz>2654####2655####26562657use strict;2658use warnings;26592660=head1 NAME26612662GITCVS::log26632664=head1 DESCRIPTION26652666This module provides very crude logging with a similar interface to2667Log::Log4perl26682669=head1 METHODS26702671=cut26722673=head2 new26742675Creates a new log object, optionally you can specify a filename here to2676indicate the file to log to. If no log file is specified, you can specify one2677later with method setfile, or indicate you no longer want logging with method2678nofile.26792680Until one of these methods is called, all log calls will buffer messages ready2681to write out.26822683=cut2684sub new2685{2686my$class=shift;2687my$filename=shift;26882689my$self= {};26902691bless$self,$class;26922693if(defined($filename) )2694{2695open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2696}26972698return$self;2699}27002701=head2 setfile27022703This methods takes a filename, and attempts to open that file as the log file.2704If successful, all buffered data is written out to the file, and any further2705logging is written directly to the file.27062707=cut2708sub setfile2709{2710my$self=shift;2711my$filename=shift;27122713if(defined($filename) )2714{2715open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2716}27172718return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");27192720while(my$line=shift@{$self->{buffer}} )2721{2722print{$self->{fh}}$line;2723}2724}27252726=head2 nofile27272728This method indicates no logging is going to be used. It flushes any entries in2729the internal buffer, and sets a flag to ensure no further data is put there.27302731=cut2732sub nofile2733{2734my$self=shift;27352736$self->{nolog} =1;27372738return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");27392740$self->{buffer} = [];2741}27422743=head2 _logopen27442745Internal method. Returns true if the log file is open, false otherwise.27462747=cut2748sub _logopen2749{2750my$self=shift;27512752return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2753return0;2754}27552756=head2 debug info warn fatal27572758These four methods are wrappers to _log. They provide the actual interface for2759logging data.27602761=cut2762sub debug {my$self=shift;$self->_log("debug",@_); }2763sub info {my$self=shift;$self->_log("info",@_); }2764subwarn{my$self=shift;$self->_log("warn",@_); }2765sub fatal {my$self=shift;$self->_log("fatal",@_); }27662767=head2 _log27682769This is an internal method called by the logging functions. It generates a2770timestamp and pushes the logged line either to file, or internal buffer.27712772=cut2773sub _log2774{2775my$self=shift;2776my$level=shift;27772778return if($self->{nolog} );27792780my@time=localtime;2781my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2782$time[5] +1900,2783$time[4] +1,2784$time[3],2785$time[2],2786$time[1],2787$time[0],2788uc$level,2789);27902791if($self->_logopen)2792{2793print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2794}else{2795push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2796}2797}27982799=head2 DESTROY28002801This method simply closes the file handle if one is open28022803=cut2804sub DESTROY2805{2806my$self=shift;28072808if($self->_logopen)2809{2810close$self->{fh};2811}2812}28132814package GITCVS::updater;28152816####2817#### Copyright The Open University UK - 2006.2818####2819#### Authors: Martyn Smith <martyn@catalyst.net.nz>2820#### Martin Langhoff <martin@catalyst.net.nz>2821####2822####28232824use strict;2825use warnings;2826use DBI;28272828=head1 METHODS28292830=cut28312832=head2 new28332834=cut2835sub new2836{2837my$class=shift;2838my$config=shift;2839my$module=shift;2840my$log=shift;28412842die"Need to specify a git repository"unless(defined($config)and-d $config);2843die"Need to specify a module"unless(defined($module) );28442845$class=ref($class) ||$class;28462847my$self= {};28482849bless$self,$class;28502851$self->{valid_tables} = {'revision'=>1,2852'revision_ix1'=>1,2853'revision_ix2'=>1,2854'head'=>1,2855'head_ix1'=>1,2856'properties'=>1,2857'commitmsgs'=>1};28582859$self->{module} =$module;2860$self->{git_path} =$config."/";28612862$self->{log} =$log;28632864die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );28652866$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2867$cfg->{gitcvs}{dbdriver} ||"SQLite";2868$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2869$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2870$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2871$cfg->{gitcvs}{dbuser} ||"";2872$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2873$cfg->{gitcvs}{dbpass} ||"";2874$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2875$cfg->{gitcvs}{dbtablenameprefix} ||"";2876my%mapping= ( m =>$module,2877 a =>$state->{method},2878 u =>getlogin||getpwuid($<) || $<,2879 G =>$self->{git_path},2880 g => mangle_dirname($self->{git_path}),2881);2882$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2883$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2884$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2885$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});28862887die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2888die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2889$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2890$self->{dbuser},2891$self->{dbpass});2892die"Error connecting to database\n"unlessdefined$self->{dbh};28932894$self->{tables} = {};2895foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2896{2897$self->{tables}{$table} =1;2898}28992900# Construct the revision table if required2901unless($self->{tables}{$self->tablename("revision")} )2902{2903my$tablename=$self->tablename("revision");2904my$ix1name=$self->tablename("revision_ix1");2905my$ix2name=$self->tablename("revision_ix2");2906$self->{dbh}->do("2907 CREATE TABLE$tablename(2908 name TEXT NOT NULL,2909 revision INTEGER NOT NULL,2910 filehash TEXT NOT NULL,2911 commithash TEXT NOT NULL,2912 author TEXT NOT NULL,2913 modified TEXT NOT NULL,2914 mode TEXT NOT NULL2915 )2916 ");2917$self->{dbh}->do("2918 CREATE INDEX$ix1name2919 ON$tablename(name,revision)2920 ");2921$self->{dbh}->do("2922 CREATE INDEX$ix2name2923 ON$tablename(name,commithash)2924 ");2925}29262927# Construct the head table if required2928unless($self->{tables}{$self->tablename("head")} )2929{2930my$tablename=$self->tablename("head");2931my$ix1name=$self->tablename("head_ix1");2932$self->{dbh}->do("2933 CREATE TABLE$tablename(2934 name TEXT NOT NULL,2935 revision INTEGER NOT NULL,2936 filehash TEXT NOT NULL,2937 commithash TEXT NOT NULL,2938 author TEXT NOT NULL,2939 modified TEXT NOT NULL,2940 mode TEXT NOT NULL2941 )2942 ");2943$self->{dbh}->do("2944 CREATE INDEX$ix1name2945 ON$tablename(name)2946 ");2947}29482949# Construct the properties table if required2950unless($self->{tables}{$self->tablename("properties")} )2951{2952my$tablename=$self->tablename("properties");2953$self->{dbh}->do("2954 CREATE TABLE$tablename(2955 key TEXT NOT NULL PRIMARY KEY,2956 value TEXT2957 )2958 ");2959}29602961# Construct the commitmsgs table if required2962unless($self->{tables}{$self->tablename("commitmsgs")} )2963{2964my$tablename=$self->tablename("commitmsgs");2965$self->{dbh}->do("2966 CREATE TABLE$tablename(2967 key TEXT NOT NULL PRIMARY KEY,2968 value TEXT2969 )2970 ");2971}29722973return$self;2974}29752976=head2 tablename29772978=cut2979sub tablename2980{2981my$self=shift;2982my$name=shift;29832984if(exists$self->{valid_tables}{$name}) {2985return$self->{dbtablenameprefix} .$name;2986}else{2987returnundef;2988}2989}29902991=head2 update29922993=cut2994sub update2995{2996my$self=shift;29972998# first lets get the commit list2999$ENV{GIT_DIR} =$self->{git_path};30003001my$commitsha1=`git rev-parse$self->{module}`;3002chomp$commitsha1;30033004my$commitinfo=`git cat-file commit$self->{module} 2>&1`;3005unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)3006{3007die("Invalid module '$self->{module}'");3008}300930103011my$git_log;3012my$lastcommit=$self->_get_prop("last_commit");30133014if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date3015return1;3016}30173018# Start exclusive lock here...3019$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";30203021# TODO: log processing is memory bound3022# if we can parse into a 2nd file that is in reverse order3023# we can probably do something really efficient3024my@git_log_params= ('--pretty','--parents','--topo-order');30253026if(defined$lastcommit) {3027push@git_log_params,"$lastcommit..$self->{module}";3028}else{3029push@git_log_params,$self->{module};3030}3031# git-rev-list is the backend / plumbing version of git-log3032open(GITLOG,'-|','git','rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";30333034my@commits;30353036my%commit= ();30373038while( <GITLOG> )3039{3040chomp;3041if(m/^commit\s+(.*)$/) {3042# on ^commit lines put the just seen commit in the stack3043# and prime things for the next one3044if(keys%commit) {3045my%copy=%commit;3046unshift@commits, \%copy;3047%commit= ();3048}3049my@parents=split(m/\s+/,$1);3050$commit{hash} =shift@parents;3051$commit{parents} = \@parents;3052}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {3053# on rfc822-like lines seen before we see any message,3054# lowercase the entry and put it in the hash as key-value3055$commit{lc($1)} =$2;3056}else{3057# message lines - skip initial empty line3058# and trim whitespace3059if(!exists($commit{message}) &&m/^\s*$/) {3060# define it to mark the end of headers3061$commit{message} ='';3062next;3063}3064s/^\s+//;s/\s+$//;# trim ws3065$commit{message} .=$_."\n";3066}3067}3068close GITLOG;30693070unshift@commits, \%commitif(keys%commit);30713072# Now all the commits are in the @commits bucket3073# ordered by time DESC. for each commit that needs processing,3074# determine whether it's following the last head we've seen or if3075# it's on its own branch, grab a file list, and add whatever's changed3076# NOTE: $lastcommit refers to the last commit from previous run3077# $lastpicked is the last commit we picked in this run3078my$lastpicked;3079my$head= {};3080if(defined$lastcommit) {3081$lastpicked=$lastcommit;3082}30833084my$committotal=scalar(@commits);3085my$commitcount=0;30863087# Load the head table into $head (for cached lookups during the update process)3088foreachmy$file( @{$self->gethead()} )3089{3090$head->{$file->{name}} =$file;3091}30923093foreachmy$commit(@commits)3094{3095$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");3096if(defined$lastpicked)3097{3098if(!in_array($lastpicked, @{$commit->{parents}}))3099{3100# skip, we'll see this delta3101# as part of a merge later3102# warn "skipping off-track $commit->{hash}\n";3103next;3104}elsif(@{$commit->{parents}} >1) {3105# it is a merge commit, for each parent that is3106# not $lastpicked, see if we can get a log3107# from the merge-base to that parent to put it3108# in the message as a merge summary.3109my@parents= @{$commit->{parents}};3110foreachmy$parent(@parents) {3111# git-merge-base can potentially (but rarely) throw3112# several candidate merge bases. let's assume3113# that the first one is the best one.3114if($parenteq$lastpicked) {3115next;3116}3117my$base=eval{3118 safe_pipe_capture('git','merge-base',3119$lastpicked,$parent);3120};3121# The two branches may not be related at all,3122# in which case merge base simply fails to find3123# any, but that's Ok.3124next if($@);31253126chomp$base;3127if($base) {3128my@merged;3129# print "want to log between $base $parent \n";3130open(GITLOG,'-|','git','log','--pretty=medium',"$base..$parent")3131or die"Cannot call git-log:$!";3132my$mergedhash;3133while(<GITLOG>) {3134chomp;3135if(!defined$mergedhash) {3136if(m/^commit\s+(.+)$/) {3137$mergedhash=$1;3138}else{3139next;3140}3141}else{3142# grab the first line that looks non-rfc8223143# aka has content after leading space3144if(m/^\s+(\S.*)$/) {3145my$title=$1;3146$title=substr($title,0,100);# truncate3147unshift@merged,"$mergedhash$title";3148undef$mergedhash;3149}3150}3151}3152close GITLOG;3153if(@merged) {3154$commit->{mergemsg} =$commit->{message};3155$commit->{mergemsg} .="\nSummary of merged commits:\n\n";3156foreachmy$summary(@merged) {3157$commit->{mergemsg} .="\t$summary\n";3158}3159$commit->{mergemsg} .="\n\n";3160# print "Message for $commit->{hash} \n$commit->{mergemsg}";3161}3162}3163}3164}3165}31663167# convert the date to CVS-happy format3168$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);31693170if(defined($lastpicked) )3171{3172my$filepipe=open(FILELIST,'-|','git','diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");3173local($/) ="\0";3174while( <FILELIST> )3175{3176chomp;3177unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)3178{3179die("Couldn't process git-diff-tree line :$_");3180}3181my($mode,$hash,$change) = ($1,$2,$3);3182my$name= <FILELIST>;3183chomp($name);31843185# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");31863187my$git_perms="";3188$git_perms.="r"if($mode&4);3189$git_perms.="w"if($mode&2);3190$git_perms.="x"if($mode&1);3191$git_perms="rw"if($git_permseq"");31923193if($changeeq"D")3194{3195#$log->debug("DELETE $name");3196$head->{$name} = {3197 name =>$name,3198 revision =>$head->{$name}{revision} +1,3199 filehash =>"deleted",3200 commithash =>$commit->{hash},3201 modified =>$commit->{date},3202 author =>$commit->{author},3203 mode =>$git_perms,3204};3205$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3206}3207elsif($changeeq"M"||$changeeq"T")3208{3209#$log->debug("MODIFIED $name");3210$head->{$name} = {3211 name =>$name,3212 revision =>$head->{$name}{revision} +1,3213 filehash =>$hash,3214 commithash =>$commit->{hash},3215 modified =>$commit->{date},3216 author =>$commit->{author},3217 mode =>$git_perms,3218};3219$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3220}3221elsif($changeeq"A")3222{3223#$log->debug("ADDED $name");3224$head->{$name} = {3225 name =>$name,3226 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,3227 filehash =>$hash,3228 commithash =>$commit->{hash},3229 modified =>$commit->{date},3230 author =>$commit->{author},3231 mode =>$git_perms,3232};3233$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3234}3235else3236{3237$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");3238die;3239}3240}3241close FILELIST;3242}else{3243# this is used to detect files removed from the repo3244my$seen_files= {};32453246my$filepipe=open(FILELIST,'-|','git','ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");3247local$/="\0";3248while( <FILELIST> )3249{3250chomp;3251unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)3252{3253die("Couldn't process git-ls-tree line :$_");3254}32553256my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);32573258$seen_files->{$git_filename} =1;32593260my($oldhash,$oldrevision,$oldmode) = (3261$head->{$git_filename}{filehash},3262$head->{$git_filename}{revision},3263$head->{$git_filename}{mode}3264);32653266if($git_perms=~/^\d\d\d(\d)\d\d/o)3267{3268$git_perms="";3269$git_perms.="r"if($1&4);3270$git_perms.="w"if($1&2);3271$git_perms.="x"if($1&1);3272}else{3273$git_perms="rw";3274}32753276# unless the file exists with the same hash, we need to update it ...3277unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3278{3279my$newrevision= ($oldrevisionor0) +1;32803281$head->{$git_filename} = {3282 name =>$git_filename,3283 revision =>$newrevision,3284 filehash =>$git_hash,3285 commithash =>$commit->{hash},3286 modified =>$commit->{date},3287 author =>$commit->{author},3288 mode =>$git_perms,3289};329032913292$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3293}3294}3295close FILELIST;32963297# Detect deleted files3298foreachmy$file(keys%$head)3299{3300unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3301{3302$head->{$file}{revision}++;3303$head->{$file}{filehash} ="deleted";3304$head->{$file}{commithash} =$commit->{hash};3305$head->{$file}{modified} =$commit->{date};3306$head->{$file}{author} =$commit->{author};33073308$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3309}3310}3311# END : "Detect deleted files"3312}331333143315if(exists$commit->{mergemsg})3316{3317$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3318}33193320$lastpicked=$commit->{hash};33213322$self->_set_prop("last_commit",$commit->{hash});3323}33243325$self->delete_head();3326foreachmy$file(keys%$head)3327{3328$self->insert_head(3329$file,3330$head->{$file}{revision},3331$head->{$file}{filehash},3332$head->{$file}{commithash},3333$head->{$file}{modified},3334$head->{$file}{author},3335$head->{$file}{mode},3336);3337}3338# invalidate the gethead cache3339$self->{gethead_cache} =undef;334033413342# Ending exclusive lock here3343$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3344}33453346sub insert_rev3347{3348my$self=shift;3349my$name=shift;3350my$revision=shift;3351my$filehash=shift;3352my$commithash=shift;3353my$modified=shift;3354my$author=shift;3355my$mode=shift;3356my$tablename=$self->tablename("revision");33573358my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3359$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3360}33613362sub insert_mergelog3363{3364my$self=shift;3365my$key=shift;3366my$value=shift;3367my$tablename=$self->tablename("commitmsgs");33683369my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3370$insert_mergelog->execute($key,$value);3371}33723373sub delete_head3374{3375my$self=shift;3376my$tablename=$self->tablename("head");33773378my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3379$delete_head->execute();3380}33813382sub insert_head3383{3384my$self=shift;3385my$name=shift;3386my$revision=shift;3387my$filehash=shift;3388my$commithash=shift;3389my$modified=shift;3390my$author=shift;3391my$mode=shift;3392my$tablename=$self->tablename("head");33933394my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3395$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3396}33973398sub _headrev3399{3400my$self=shift;3401my$filename=shift;3402my$tablename=$self->tablename("head");34033404my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3405$db_query->execute($filename);3406my($hash,$revision,$mode) =$db_query->fetchrow_array;34073408return($hash,$revision,$mode);3409}34103411sub _get_prop3412{3413my$self=shift;3414my$key=shift;3415my$tablename=$self->tablename("properties");34163417my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3418$db_query->execute($key);3419my($value) =$db_query->fetchrow_array;34203421return$value;3422}34233424sub _set_prop3425{3426my$self=shift;3427my$key=shift;3428my$value=shift;3429my$tablename=$self->tablename("properties");34303431my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3432$db_query->execute($value,$key);34333434unless($db_query->rows)3435{3436$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3437$db_query->execute($key,$value);3438}34393440return$value;3441}34423443=head2 gethead34443445=cut34463447sub gethead3448{3449my$self=shift;3450my$tablename=$self->tablename("head");34513452return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );34533454my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3455$db_query->execute();34563457my$tree= [];3458while(my$file=$db_query->fetchrow_hashref)3459{3460push@$tree,$file;3461}34623463$self->{gethead_cache} =$tree;34643465return$tree;3466}34673468=head2 getlog34693470=cut34713472sub getlog3473{3474my$self=shift;3475my$filename=shift;3476my$tablename=$self->tablename("revision");34773478my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3479$db_query->execute($filename);34803481my$tree= [];3482while(my$file=$db_query->fetchrow_hashref)3483{3484push@$tree,$file;3485}34863487return$tree;3488}34893490=head2 getmeta34913492This function takes a filename (with path) argument and returns a hashref of3493metadata for that file.34943495=cut34963497sub getmeta3498{3499my$self=shift;3500my$filename=shift;3501my$revision=shift;3502my$tablename_rev=$self->tablename("revision");3503my$tablename_head=$self->tablename("head");35043505my$db_query;3506if(defined($revision)and$revision=~/^\d+$/)3507{3508$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3509$db_query->execute($filename,$revision);3510}3511elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3512{3513$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3514$db_query->execute($filename,$revision);3515}else{3516$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3517$db_query->execute($filename);3518}35193520return$db_query->fetchrow_hashref;3521}35223523=head2 commitmessage35243525this function takes a commithash and returns the commit message for that commit35263527=cut3528sub commitmessage3529{3530my$self=shift;3531my$commithash=shift;3532my$tablename=$self->tablename("commitmsgs");35333534die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);35353536my$db_query;3537$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3538$db_query->execute($commithash);35393540my($message) =$db_query->fetchrow_array;35413542if(defined($message) )3543{3544$message.=" "if($message=~/\n$/);3545return$message;3546}35473548my@lines= safe_pipe_capture("git","cat-file","commit",$commithash);3549shift@lineswhile($lines[0] =~/\S/);3550$message=join("",@lines);3551$message.=" "if($message=~/\n$/);3552return$message;3553}35543555=head2 gethistory35563557This function takes a filename (with path) argument and returns an arrayofarrays3558containing revision,filehash,commithash ordered by revision descending35593560=cut3561sub gethistory3562{3563my$self=shift;3564my$filename=shift;3565my$tablename=$self->tablename("revision");35663567my$db_query;3568$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3569$db_query->execute($filename);35703571return$db_query->fetchall_arrayref;3572}35733574=head2 gethistorydense35753576This function takes a filename (with path) argument and returns an arrayofarrays3577containing revision,filehash,commithash ordered by revision descending.35783579This version of gethistory skips deleted entries -- so it is useful for annotate.3580The 'dense' part is a reference to a '--dense' option available for git-rev-list3581and other git tools that depend on it.35823583=cut3584sub gethistorydense3585{3586my$self=shift;3587my$filename=shift;3588my$tablename=$self->tablename("revision");35893590my$db_query;3591$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3592$db_query->execute($filename);35933594return$db_query->fetchall_arrayref;3595}35963597=head2 in_array()35983599from Array::PAT - mimics the in_array() function3600found in PHP. Yuck but works for small arrays.36013602=cut3603sub in_array3604{3605my($check,@array) =@_;3606my$retval=0;3607foreachmy$test(@array){3608if($checkeq$test){3609$retval=1;3610}3611}3612return$retval;3613}36143615=head2 safe_pipe_capture36163617an alternative to `command` that allows input to be passed as an array3618to work around shell problems with weird characters in arguments36193620=cut3621sub safe_pipe_capture {36223623my@output;36243625if(my$pid=open my$child,'-|') {3626@output= (<$child>);3627close$childor die join(' ',@_).":$!$?";3628}else{3629exec(@_)or die"$!$?";# exec() can fail the executable can't be found3630}3631returnwantarray?@output:join('',@output);3632}36333634=head2 mangle_dirname36353636create a string from a directory name that is suitable to use as3637part of a filename, mainly by converting all chars except \w.- to _36383639=cut3640sub mangle_dirname {3641my$dirname=shift;3642return unlessdefined$dirname;36433644$dirname=~s/[^\w.-]/_/g;36453646return$dirname;3647}36483649=head2 mangle_tablename36503651create a string from a that is suitable to use as part of an SQL table3652name, mainly by converting all chars except \w to _36533654=cut3655sub mangle_tablename {3656my$tablename=shift;3657return unlessdefined$tablename;36583659$tablename=~s/[^\w_]/_/g;36603661return$tablename;3662}366336641;