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" --strict-paths : Don't allow recursing into subdirectories\n". 108" --export-all : Don't check for gitcvs.enabled in config\n". 109" --version, -V : Print version information and exit\n". 110" --help, -h, -H : Print usage information and exit\n". 111"\n". 112"<directory> ... is a list of allowed directories. If no directories\n". 113"are given, all are allowed. This is an additional restriction, gitcvs\n". 114"access still needs to be enabled by the gitcvs.enabled config option.\n"; 115 116my@opts= ('help|h|H','version|V', 117'base-path=s','strict-paths','export-all'); 118GetOptions($state,@opts) 119or die$usage; 120 121if($state->{version}) { 122print"git-cvsserver version$VERSION\n"; 123exit; 124} 125if($state->{help}) { 126print$usage; 127exit; 128} 129 130my$TEMP_DIR= tempdir( CLEANUP =>1); 131$log->debug("Temporary directory is '$TEMP_DIR'"); 132 133$state->{method} ='ext'; 134if(@ARGV) { 135if($ARGV[0]eq'pserver') { 136$state->{method} ='pserver'; 137shift@ARGV; 138}elsif($ARGV[0]eq'server') { 139shift@ARGV; 140} 141} 142 143# everything else is a directory 144$state->{allowed_roots} = [@ARGV]; 145 146# don't export the whole system unless the users requests it 147if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 148die"--export-all can only be used together with an explicit whitelist\n"; 149} 150 151# if we are called with a pserver argument, 152# deal with the authentication cat before entering the 153# main loop 154if($state->{method}eq'pserver') { 155my$line= <STDIN>;chomp$line; 156unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 157die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 158} 159my$request=$1; 160$line= <STDIN>;chomp$line; 161unless(req_Root('root',$line)) {# reuse Root 162print"E Invalid root$line\n"; 163exit1; 164} 165$line= <STDIN>;chomp$line; 166unless($lineeq'anonymous') { 167print"E Only anonymous user allowed via pserver\n"; 168print"I HATE YOU\n"; 169exit1; 170} 171$line= <STDIN>;chomp$line;# validate the password? 172$line= <STDIN>;chomp$line; 173unless($lineeq"END$requestREQUEST") { 174die"E Do not understand$line-- expecting END$requestREQUEST\n"; 175} 176print"I LOVE YOU\n"; 177exit if$requesteq'VERIFICATION';# cvs login 178# and now back to our regular programme... 179} 180 181# Keep going until the client closes the connection 182while(<STDIN>) 183{ 184chomp; 185 186# Check to see if we've seen this method, and call appropriate function. 187if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 188{ 189# use the $methods hash to call the appropriate sub for this command 190#$log->info("Method : $1"); 191&{$methods->{$1}}($1,$2); 192}else{ 193# log fatal because we don't understand this function. If this happens 194# we're fairly screwed because we don't know if the client is expecting 195# a response. If it is, the client will hang, we'll hang, and the whole 196# thing will be custard. 197$log->fatal("Don't understand command$_\n"); 198die("Unknown command$_"); 199} 200} 201 202$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 203$log->info("--------------- FINISH -----------------"); 204 205chdir'/'; 206exit0; 207 208# Magic catchall method. 209# This is the method that will handle all commands we haven't yet 210# implemented. It simply sends a warning to the log file indicating a 211# command that hasn't been implemented has been invoked. 212sub req_CATCHALL 213{ 214my($cmd,$data) =@_; 215$log->warn("Unhandled command : req_$cmd:$data"); 216} 217 218# This method invariably succeeds with an empty response. 219sub req_EMPTY 220{ 221print"ok\n"; 222} 223 224# Root pathname \n 225# Response expected: no. Tell the server which CVSROOT to use. Note that 226# pathname is a local directory and not a fully qualified CVSROOT variable. 227# pathname must already exist; if creating a new root, use the init 228# request, not Root. pathname does not include the hostname of the server, 229# how to access the server, etc.; by the time the CVS protocol is in use, 230# connection, authentication, etc., are already taken care of. The Root 231# request must be sent only once, and it must be sent before any requests 232# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 233sub req_Root 234{ 235my($cmd,$data) =@_; 236$log->debug("req_Root :$data"); 237 238unless($data=~ m#^/#) { 239print"error 1 Root must be an absolute pathname\n"; 240return0; 241} 242 243my$cvsroot=$state->{'base-path'} ||''; 244$cvsroot=~ s#/+$##; 245$cvsroot.=$data; 246 247if($state->{CVSROOT} 248&& ($state->{CVSROOT}ne$cvsroot)) { 249print"error 1 Conflicting roots specified\n"; 250return0; 251} 252 253$state->{CVSROOT} =$cvsroot; 254 255$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 256 257if(@{$state->{allowed_roots}}) { 258my$allowed=0; 259foreachmy$dir(@{$state->{allowed_roots}}) { 260next unless$dir=~ m#^/#; 261$dir=~ s#/+$##; 262if($state->{'strict-paths'}) { 263if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 264$allowed=1; 265last; 266} 267}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 268$allowed=1; 269last; 270} 271} 272 273unless($allowed) { 274print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 275print"E\n"; 276print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 277return0; 278} 279} 280 281unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 282print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 283print"E\n"; 284print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 285return0; 286} 287 288my@gitvars=`git config -l`; 289if($?) { 290print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 291print"E\n"; 292print"error 1 - problem executing git-config\n"; 293return0; 294} 295foreachmy$line(@gitvars) 296{ 297next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 298unless($2) { 299$cfg->{$1}{$3} =$4; 300}else{ 301$cfg->{$1}{$2}{$3} =$4; 302} 303} 304 305my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 306||$cfg->{gitcvs}{enabled}); 307unless($state->{'export-all'} || 308($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 309print"E GITCVS emulation needs to be enabled on this repo\n"; 310print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 311print"E\n"; 312print"error 1 GITCVS emulation disabled\n"; 313return0; 314} 315 316my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 317if($logfile) 318{ 319$log->setfile($logfile); 320}else{ 321$log->nofile(); 322} 323 324return1; 325} 326 327# Global_option option \n 328# Response expected: no. Transmit one of the global options `-q', `-Q', 329# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 330# variations (such as combining of options) are allowed. For graceful 331# handling of valid-requests, it is probably better to make new global 332# options separate requests, rather than trying to add them to this 333# request. 334sub req_Globaloption 335{ 336my($cmd,$data) =@_; 337$log->debug("req_Globaloption :$data"); 338$state->{globaloptions}{$data} =1; 339} 340 341# Valid-responses request-list \n 342# Response expected: no. Tell the server what responses the client will 343# accept. request-list is a space separated list of tokens. 344sub req_Validresponses 345{ 346my($cmd,$data) =@_; 347$log->debug("req_Validresponses :$data"); 348 349# TODO : re-enable this, currently it's not particularly useful 350#$state->{validresponses} = [ split /\s+/, $data ]; 351} 352 353# valid-requests \n 354# Response expected: yes. Ask the server to send back a Valid-requests 355# response. 356sub req_validrequests 357{ 358my($cmd,$data) =@_; 359 360$log->debug("req_validrequests"); 361 362$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 363$log->debug("SEND : ok"); 364 365print"Valid-requests ".join(" ",keys%$methods) ."\n"; 366print"ok\n"; 367} 368 369# Directory local-directory \n 370# Additional data: repository \n. Response expected: no. Tell the server 371# what directory to use. The repository should be a directory name from a 372# previous server response. Note that this both gives a default for Entry 373# and Modified and also for ci and the other commands; normal usage is to 374# send Directory for each directory in which there will be an Entry or 375# Modified, and then a final Directory for the original directory, then the 376# command. The local-directory is relative to the top level at which the 377# command is occurring (i.e. the last Directory which is sent before the 378# command); to indicate that top level, `.' should be sent for 379# local-directory. 380sub req_Directory 381{ 382my($cmd,$data) =@_; 383 384my$repository= <STDIN>; 385chomp$repository; 386 387 388$state->{localdir} =$data; 389$state->{repository} =$repository; 390$state->{path} =$repository; 391$state->{path} =~s/^\Q$state->{CVSROOT}\E\///; 392$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 393$state->{path} .="/"if($state->{path} =~ /\S/ ); 394 395$state->{directory} =$state->{localdir}; 396$state->{directory} =""if($state->{directory}eq"."); 397$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 398 399if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 400{ 401$log->info("Setting prepend to '$state->{path}'"); 402$state->{prependdir} =$state->{path}; 403foreachmy$entry(keys%{$state->{entries}} ) 404{ 405$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 406delete$state->{entries}{$entry}; 407} 408} 409 410if(defined($state->{prependdir} ) ) 411{ 412$log->debug("Prepending '$state->{prependdir}' to state|directory"); 413$state->{directory} =$state->{prependdir} .$state->{directory} 414} 415$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 416} 417 418# Entry entry-line \n 419# Response expected: no. Tell the server what version of a file is on the 420# local machine. The name in entry-line is a name relative to the directory 421# most recently specified with Directory. If the user is operating on only 422# some files in a directory, Entry requests for only those files need be 423# included. If an Entry request is sent without Modified, Is-modified, or 424# Unchanged, it means the file is lost (does not exist in the working 425# directory). If both Entry and one of Modified, Is-modified, or Unchanged 426# are sent for the same file, Entry must be sent first. For a given file, 427# one can send Modified, Is-modified, or Unchanged, but not more than one 428# of these three. 429sub req_Entry 430{ 431my($cmd,$data) =@_; 432 433#$log->debug("req_Entry : $data"); 434 435my@data=split(/\//,$data); 436 437$state->{entries}{$state->{directory}.$data[1]} = { 438 revision =>$data[2], 439 conflict =>$data[3], 440 options =>$data[4], 441 tag_or_date =>$data[5], 442}; 443 444$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 445} 446 447# Questionable filename \n 448# Response expected: no. Additional data: no. Tell the server to check 449# whether filename should be ignored, and if not, next time the server 450# sends responses, send (in a M response) `?' followed by the directory and 451# filename. filename must not contain `/'; it needs to be a file in the 452# directory named by the most recent Directory request. 453sub req_Questionable 454{ 455my($cmd,$data) =@_; 456 457$log->debug("req_Questionable :$data"); 458$state->{entries}{$state->{directory}.$data}{questionable} =1; 459} 460 461# add \n 462# Response expected: yes. Add a file or directory. This uses any previous 463# Argument, Directory, Entry, or Modified requests, if they have been sent. 464# The last Directory sent specifies the working directory at the time of 465# the operation. To add a directory, send the directory to be added using 466# Directory and Argument requests. 467sub req_add 468{ 469my($cmd,$data) =@_; 470 471 argsplit("add"); 472 473my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 474$updater->update(); 475 476 argsfromdir($updater); 477 478my$addcount=0; 479 480foreachmy$filename( @{$state->{args}} ) 481{ 482$filename= filecleanup($filename); 483 484my$meta=$updater->getmeta($filename); 485my$wrev= revparse($filename); 486 487if($wrev&&$meta&& ($wrev<0)) 488{ 489# previously removed file, add back 490$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 491 492print"MT +updated\n"; 493print"MT text U\n"; 494print"MT fname$filename\n"; 495print"MT newline\n"; 496print"MT -updated\n"; 497 498unless($state->{globaloptions}{-n} ) 499{ 500my($filepart,$dirpart) = filenamesplit($filename,1); 501 502print"Created$dirpart\n"; 503print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 504 505# this is an "entries" line 506my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 507$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 508print"/$filepart/1.$meta->{revision}//$kopts/\n"; 509# permissions 510$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 511print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 512# transmit file 513 transmitfile($meta->{filehash}); 514} 515 516next; 517} 518 519unless(defined($state->{entries}{$filename}{modified_filename} ) ) 520{ 521print"E cvs add: nothing known about `$filename'\n"; 522next; 523} 524# TODO : check we're not squashing an already existing file 525if(defined($state->{entries}{$filename}{revision} ) ) 526{ 527print"E cvs add: `$filename' has already been entered\n"; 528next; 529} 530 531my($filepart,$dirpart) = filenamesplit($filename,1); 532 533print"E cvs add: scheduling file `$filename' for addition\n"; 534 535print"Checked-in$dirpart\n"; 536print"$filename\n"; 537my$kopts= kopts_from_path($filename,"file", 538$state->{entries}{$filename}{modified_filename}); 539print"/$filepart/0//$kopts/\n"; 540 541my$requestedKopts=$state->{opt}{k}; 542if(defined($requestedKopts)) 543{ 544$requestedKopts="-k$requestedKopts"; 545} 546else 547{ 548$requestedKopts=""; 549} 550if($koptsne$requestedKopts) 551{ 552$log->warn("Ignoring requested -k='$requestedKopts'" 553." for '$filename'; detected -k='$kopts' instead"); 554#TODO: Also have option to send warning to user? 555} 556 557$addcount++; 558} 559 560if($addcount==1) 561{ 562print"E cvs add: use `cvs commit' to add this file permanently\n"; 563} 564elsif($addcount>1) 565{ 566print"E cvs add: use `cvs commit' to add these files permanently\n"; 567} 568 569print"ok\n"; 570} 571 572# remove \n 573# Response expected: yes. Remove a file. This uses any previous Argument, 574# Directory, Entry, or Modified requests, if they have been sent. The last 575# Directory sent specifies the working directory at the time of the 576# operation. Note that this request does not actually do anything to the 577# repository; the only effect of a successful remove request is to supply 578# the client with a new entries line containing `-' to indicate a removed 579# file. In fact, the client probably could perform this operation without 580# contacting the server, although using remove may cause the server to 581# perform a few more checks. The client sends a subsequent ci request to 582# actually record the removal in the repository. 583sub req_remove 584{ 585my($cmd,$data) =@_; 586 587 argsplit("remove"); 588 589# Grab a handle to the SQLite db and do any necessary updates 590my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 591$updater->update(); 592 593#$log->debug("add state : " . Dumper($state)); 594 595my$rmcount=0; 596 597foreachmy$filename( @{$state->{args}} ) 598{ 599$filename= filecleanup($filename); 600 601if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 602{ 603print"E cvs remove: file `$filename' still in working directory\n"; 604next; 605} 606 607my$meta=$updater->getmeta($filename); 608my$wrev= revparse($filename); 609 610unless(defined($wrev) ) 611{ 612print"E cvs remove: nothing known about `$filename'\n"; 613next; 614} 615 616if(defined($wrev)and$wrev<0) 617{ 618print"E cvs remove: file `$filename' already scheduled for removal\n"; 619next; 620} 621 622unless($wrev==$meta->{revision} ) 623{ 624# TODO : not sure if the format of this message is quite correct. 625print"E cvs remove: Up to date check failed for `$filename'\n"; 626next; 627} 628 629 630my($filepart,$dirpart) = filenamesplit($filename,1); 631 632print"E cvs remove: scheduling `$filename' for removal\n"; 633 634print"Checked-in$dirpart\n"; 635print"$filename\n"; 636my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 637print"/$filepart/-1.$wrev//$kopts/\n"; 638 639$rmcount++; 640} 641 642if($rmcount==1) 643{ 644print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 645} 646elsif($rmcount>1) 647{ 648print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 649} 650 651print"ok\n"; 652} 653 654# Modified filename \n 655# Response expected: no. Additional data: mode, \n, file transmission. Send 656# the server a copy of one locally modified file. filename is a file within 657# the most recent directory sent with Directory; it must not contain `/'. 658# If the user is operating on only some files in a directory, only those 659# files need to be included. This can also be sent without Entry, if there 660# is no entry for the file. 661sub req_Modified 662{ 663my($cmd,$data) =@_; 664 665my$mode= <STDIN>; 666defined$mode 667or(print"E end of file reading mode for$data\n"),return; 668chomp$mode; 669my$size= <STDIN>; 670defined$size 671or(print"E end of file reading size of$data\n"),return; 672chomp$size; 673 674# Grab config information 675my$blocksize=8192; 676my$bytesleft=$size; 677my$tmp; 678 679# Get a filehandle/name to write it to 680my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 681 682# Loop over file data writing out to temporary file. 683while($bytesleft) 684{ 685$blocksize=$bytesleftif($bytesleft<$blocksize); 686read STDIN,$tmp,$blocksize; 687print$fh $tmp; 688$bytesleft-=$blocksize; 689} 690 691close$fh 692or(print"E failed to write temporary,$filename:$!\n"),return; 693 694# Ensure we have something sensible for the file mode 695if($mode=~/u=(\w+)/) 696{ 697$mode=$1; 698}else{ 699$mode="rw"; 700} 701 702# Save the file data in $state 703$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 704$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 705$state->{entries}{$state->{directory}.$data}{modified_hash} =`git hash-object$filename`; 706$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 707 708 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 709} 710 711# Unchanged filename\n 712# Response expected: no. Tell the server that filename has not been 713# modified in the checked out directory. The filename is a file within the 714# most recent directory sent with Directory; it must not contain `/'. 715sub req_Unchanged 716{ 717 my ($cmd,$data) =@_; 718 719$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 720 721 #$log->debug("req_Unchanged :$data"); 722} 723 724# Argument text\n 725# Response expected: no. Save argument for use in a subsequent command. 726# Arguments accumulate until an argument-using command is given, at which 727# point they are forgotten. 728# Argumentx text\n 729# Response expected: no. Append\nfollowed by text to the current argument 730# being saved. 731sub req_Argument 732{ 733 my ($cmd,$data) =@_; 734 735 # Argumentx means: append to last Argument (with a newline in front) 736 737$log->debug("$cmd:$data"); 738 739 if ($cmdeq 'Argumentx') { 740 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 741 } else { 742 push @{$state->{arguments}},$data; 743 } 744} 745 746# expand-modules\n 747# Response expected: yes. Expand the modules which are specified in the 748# arguments. Returns the data in Module-expansion responses. Note that the 749# server can assume that this is checkout or export, not rtag or rdiff; the 750# latter do not access the working directory and thus have no need to 751# expand modules on the client side. Expand may not be the best word for 752# what this request does. It does not necessarily tell you all the files 753# contained in a module, for example. Basically it is a way of telling you 754# which working directories the server needs to know about in order to 755# handle a checkout of the specified modules. For example, suppose that the 756# server has a module defined by 757# aliasmodule -a 1dir 758# That is, one can check out aliasmodule and it will take 1dir in the 759# repository and check it out to 1dir in the working directory. Now suppose 760# the client already has this module checked out and is planning on using 761# the co request to update it. Without using expand-modules, the client 762# would have two bad choices: it could either send information about all 763# working directories under the current directory, which could be 764# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 765# stands for 1dir, and neglect to send information for 1dir, which would 766# lead to incorrect operation. With expand-modules, the client would first 767# ask for the module to be expanded: 768sub req_expandmodules 769{ 770 my ($cmd,$data) =@_; 771 772 argsplit(); 773 774$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 775 776 unless ( ref$state->{arguments} eq "ARRAY" ) 777 { 778 print "ok\n"; 779 return; 780 } 781 782 foreach my$module( @{$state->{arguments}} ) 783 { 784$log->debug("SEND : Module-expansion$module"); 785 print "Module-expansion$module\n"; 786 } 787 788 print "ok\n"; 789 statecleanup(); 790} 791 792# co\n 793# Response expected: yes. Get files from the repository. This uses any 794# previous Argument, Directory, Entry, or Modified requests, if they have 795# been sent. Arguments to this command are module names; the client cannot 796# know what directories they correspond to except by (1) just sending the 797# co request, and then seeing what directory names the server sends back in 798# its responses, and (2) the expand-modules request. 799sub req_co 800{ 801 my ($cmd,$data) =@_; 802 803 argsplit("co"); 804 805 # Provide list of modules, if -c was used. 806 if (exists$state->{opt}{c}) { 807 my$showref= `git show-ref --heads`; 808 for my$line(split '\n',$showref) { 809 if ($line=~ m% refs/heads/(.*)$%) { 810 print "M$1\t$1\n"; 811 } 812 } 813 print "ok\n"; 814 return 1; 815 } 816 817 my$module=$state->{args}[0]; 818$state->{module} =$module; 819 my$checkout_path=$module; 820 821 # use the user specified directory if we're given it 822$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 823 824$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 825 826$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 827 828$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 829 830# Grab a handle to the SQLite db and do any necessary updates 831my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 832$updater->update(); 833 834$checkout_path=~ s|/$||;# get rid of trailing slashes 835 836# Eclipse seems to need the Clear-sticky command 837# to prepare the 'Entries' file for the new directory. 838print"Clear-sticky$checkout_path/\n"; 839print$state->{CVSROOT} ."/$module/\n"; 840print"Clear-static-directory$checkout_path/\n"; 841print$state->{CVSROOT} ."/$module/\n"; 842print"Clear-sticky$checkout_path/\n";# yes, twice 843print$state->{CVSROOT} ."/$module/\n"; 844print"Template$checkout_path/\n"; 845print$state->{CVSROOT} ."/$module/\n"; 846print"0\n"; 847 848# instruct the client that we're checking out to $checkout_path 849print"E cvs checkout: Updating$checkout_path\n"; 850 851my%seendirs= (); 852my$lastdir=''; 853 854# recursive 855sub prepdir { 856my($dir,$repodir,$remotedir,$seendirs) =@_; 857my$parent= dirname($dir); 858$dir=~ s|/+$||; 859$repodir=~ s|/+$||; 860$remotedir=~ s|/+$||; 861$parent=~ s|/+$||; 862$log->debug("announcedir$dir,$repodir,$remotedir"); 863 864if($parenteq'.'||$parenteq'./') { 865$parent=''; 866} 867# recurse to announce unseen parents first 868if(length($parent) && !exists($seendirs->{$parent})) { 869 prepdir($parent,$repodir,$remotedir,$seendirs); 870} 871# Announce that we are going to modify at the parent level 872if($parent) { 873print"E cvs checkout: Updating$remotedir/$parent\n"; 874}else{ 875print"E cvs checkout: Updating$remotedir\n"; 876} 877print"Clear-sticky$remotedir/$parent/\n"; 878print"$repodir/$parent/\n"; 879 880print"Clear-static-directory$remotedir/$dir/\n"; 881print"$repodir/$dir/\n"; 882print"Clear-sticky$remotedir/$parent/\n";# yes, twice 883print"$repodir/$parent/\n"; 884print"Template$remotedir/$dir/\n"; 885print"$repodir/$dir/\n"; 886print"0\n"; 887 888$seendirs->{$dir} =1; 889} 890 891foreachmy$git( @{$updater->gethead} ) 892{ 893# Don't want to check out deleted files 894next if($git->{filehash}eq"deleted"); 895 896my$fullName=$git->{name}; 897($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 898 899if(length($git->{dir}) &&$git->{dir}ne'./' 900&&$git->{dir}ne$lastdir) { 901unless(exists($seendirs{$git->{dir}})) { 902 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 903$checkout_path, \%seendirs); 904$lastdir=$git->{dir}; 905$seendirs{$git->{dir}} =1; 906} 907print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 908} 909 910# modification time of this file 911print"Mod-time$git->{modified}\n"; 912 913# print some information to the client 914if(defined($git->{dir} )and$git->{dir}ne"./") 915{ 916print"M U$checkout_path/$git->{dir}$git->{name}\n"; 917}else{ 918print"M U$checkout_path/$git->{name}\n"; 919} 920 921# instruct client we're sending a file to put in this path 922print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 923 924print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 925 926# this is an "entries" line 927my$kopts= kopts_from_path($fullName,"sha1",$git->{filehash}); 928print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 929# permissions 930print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 931 932# transmit file 933 transmitfile($git->{filehash}); 934} 935 936print"ok\n"; 937 938 statecleanup(); 939} 940 941# update \n 942# Response expected: yes. Actually do a cvs update command. This uses any 943# previous Argument, Directory, Entry, or Modified requests, if they have 944# been sent. The last Directory sent specifies the working directory at the 945# time of the operation. The -I option is not used--files which the client 946# can decide whether to ignore are not mentioned and the client sends the 947# Questionable request for others. 948sub req_update 949{ 950my($cmd,$data) =@_; 951 952$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 953 954 argsplit("update"); 955 956# 957# It may just be a client exploring the available heads/modules 958# in that case, list them as top level directories and leave it 959# at that. Eclipse uses this technique to offer you a list of 960# projects (heads in this case) to checkout. 961# 962if($state->{module}eq'') { 963my$showref=`git show-ref --heads`; 964print"E cvs update: Updating .\n"; 965formy$line(split'\n',$showref) { 966if($line=~ m% refs/heads/(.*)$%) { 967print"E cvs update: New directory `$1'\n"; 968} 969} 970print"ok\n"; 971return1; 972} 973 974 975# Grab a handle to the SQLite db and do any necessary updates 976my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 977 978$updater->update(); 979 980 argsfromdir($updater); 981 982#$log->debug("update state : " . Dumper($state)); 983 984# foreach file specified on the command line ... 985foreachmy$filename( @{$state->{args}} ) 986{ 987$filename= filecleanup($filename); 988 989$log->debug("Processing file$filename"); 990 991# if we have a -C we should pretend we never saw modified stuff 992if(exists($state->{opt}{C} ) ) 993{ 994delete$state->{entries}{$filename}{modified_hash}; 995delete$state->{entries}{$filename}{modified_filename}; 996$state->{entries}{$filename}{unchanged} =1; 997} 998 999my$meta;1000if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/)1001{1002$meta=$updater->getmeta($filename,$1);1003}else{1004$meta=$updater->getmeta($filename);1005}10061007# If -p was given, "print" the contents of the requested revision.1008if(exists($state->{opt}{p} ) ) {1009if(defined($meta->{revision} ) ) {1010$log->info("Printing '$filename' revision ".$meta->{revision});10111012 transmitfile($meta->{filehash}, {print=>1});1013}10141015next;1016}10171018if( !defined$meta)1019{1020$meta= {1021 name =>$filename,1022 revision =>0,1023 filehash =>'added'1024};1025}10261027my$oldmeta=$meta;10281029my$wrev= revparse($filename);10301031# If the working copy is an old revision, lets get that version too for comparison.1032if(defined($wrev)and$wrev!=$meta->{revision} )1033{1034$oldmeta=$updater->getmeta($filename,$wrev);1035}10361037#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");10381039# Files are up to date if the working copy and repo copy have the same revision,1040# and the working copy is unmodified _and_ the user hasn't specified -C1041next if(defined($wrev)1042and defined($meta->{revision})1043and$wrev==$meta->{revision}1044and$state->{entries}{$filename}{unchanged}1045and not exists($state->{opt}{C} ) );10461047# If the working copy and repo copy have the same revision,1048# but the working copy is modified, tell the client it's modified1049if(defined($wrev)1050and defined($meta->{revision})1051and$wrev==$meta->{revision}1052and defined($state->{entries}{$filename}{modified_hash})1053and not exists($state->{opt}{C} ) )1054{1055$log->info("Tell the client the file is modified");1056print"MT text M\n";1057print"MT fname$filename\n";1058print"MT newline\n";1059next;1060}10611062if($meta->{filehash}eq"deleted")1063{1064my($filepart,$dirpart) = filenamesplit($filename,1);10651066$log->info("Removing '$filename' from working copy (no longer in the repo)");10671068print"E cvs update: `$filename' is no longer in the repository\n";1069# Don't want to actually _DO_ the update if -n specified1070unless($state->{globaloptions}{-n} ) {1071print"Removed$dirpart\n";1072print"$filepart\n";1073}1074}1075elsif(not defined($state->{entries}{$filename}{modified_hash} )1076or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1077or$meta->{filehash}eq'added')1078{1079# normal update, just send the new revision (either U=Update,1080# or A=Add, or R=Remove)1081if(defined($wrev) &&$wrev<0)1082{1083$log->info("Tell the client the file is scheduled for removal");1084print"MT text R\n";1085print"MT fname$filename\n";1086print"MT newline\n";1087next;1088}1089elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1090{1091$log->info("Tell the client the file is scheduled for addition");1092print"MT text A\n";1093print"MT fname$filename\n";1094print"MT newline\n";1095next;10961097}1098else{1099$log->info("Updating '$filename' to ".$meta->{revision});1100print"MT +updated\n";1101print"MT text U\n";1102print"MT fname$filename\n";1103print"MT newline\n";1104print"MT -updated\n";1105}11061107my($filepart,$dirpart) = filenamesplit($filename,1);11081109# Don't want to actually _DO_ the update if -n specified1110unless($state->{globaloptions}{-n} )1111{1112if(defined($wrev) )1113{1114# instruct client we're sending a file to put in this path as a replacement1115print"Update-existing$dirpart\n";1116$log->debug("Updating existing file 'Update-existing$dirpart'");1117}else{1118# instruct client we're sending a file to put in this path as a new file1119print"Clear-static-directory$dirpart\n";1120print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1121print"Clear-sticky$dirpart\n";1122print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";11231124$log->debug("Creating new file 'Created$dirpart'");1125print"Created$dirpart\n";1126}1127print$state->{CVSROOT} ."/$state->{module}/$filename\n";11281129# this is an "entries" line1130my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1131$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1132print"/$filepart/1.$meta->{revision}//$kopts/\n";11331134# permissions1135$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1136print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11371138# transmit file1139 transmitfile($meta->{filehash});1140}1141}else{1142$log->info("Updating '$filename'");1143my($filepart,$dirpart) = filenamesplit($meta->{name},1);11441145my$mergeDir= setupTmpDir();11461147my$file_local=$filepart.".mine";1148my$mergedFile="$mergeDir/$file_local";1149system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1150my$file_old=$filepart.".".$oldmeta->{revision};1151 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1152my$file_new=$filepart.".".$meta->{revision};1153 transmitfile($meta->{filehash}, { targetfile =>$file_new});11541155# we need to merge with the local changes ( M=successful merge, C=conflict merge )1156$log->info("Merging$file_local,$file_old,$file_new");1157print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11581159$log->debug("Temporary directory for merge is$mergeDir");11601161my$return=system("git","merge-file",$file_local,$file_old,$file_new);1162$return>>=8;11631164 cleanupTmpDir();11651166if($return==0)1167{1168$log->info("Merged successfully");1169print"M M$filename\n";1170$log->debug("Merged$dirpart");11711172# Don't want to actually _DO_ the update if -n specified1173unless($state->{globaloptions}{-n} )1174{1175print"Merged$dirpart\n";1176$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1177print$state->{CVSROOT} ."/$state->{module}/$filename\n";1178my$kopts= kopts_from_path("$dirpart/$filepart",1179"file",$mergedFile);1180$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1181print"/$filepart/1.$meta->{revision}//$kopts/\n";1182}1183}1184elsif($return==1)1185{1186$log->info("Merged with conflicts");1187print"E cvs update: conflicts found in$filename\n";1188print"M C$filename\n";11891190# Don't want to actually _DO_ the update if -n specified1191unless($state->{globaloptions}{-n} )1192{1193print"Merged$dirpart\n";1194print$state->{CVSROOT} ."/$state->{module}/$filename\n";1195my$kopts= kopts_from_path("$dirpart/$filepart",1196"file",$mergedFile);1197print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1198}1199}1200else1201{1202$log->warn("Merge failed");1203next;1204}12051206# Don't want to actually _DO_ the update if -n specified1207unless($state->{globaloptions}{-n} )1208{1209# permissions1210$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1211print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12121213# transmit file, format is single integer on a line by itself (file1214# size) followed by the file contents1215# TODO : we should copy files in blocks1216my$data=`cat$mergedFile`;1217$log->debug("File size : " . length($data));1218 print length($data) . "\n";1219 print$data;1220 }1221 }12221223 }12241225 print "ok\n";1226}12271228sub req_ci1229{1230 my ($cmd,$data) =@_;12311232 argsplit("ci");12331234 #$log->debug("State : " . Dumper($state));12351236$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));12371238 if ($state->{method} eq 'pserver')1239 {1240 print "error 1 pserver access cannot commit\n";1241 cleanupWorkTree();1242 exit;1243 }12441245 if ( -e$state->{CVSROOT} . "/index" )1246 {1247$log->warn("file 'index' already exists in the git repository");1248 print "error 1 Index already exists in git repo\n";1249 cleanupWorkTree();1250 exit;1251 }12521253 # Grab a handle to the SQLite db and do any necessary updates1254 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1255$updater->update();12561257 # Remember where the head was at the beginning.1258 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1259 chomp$parenthash;1260 if ($parenthash!~ /^[0-9a-f]{40}$/) {1261 print "error 1 pserver cannot find the current HEAD of module";1262 cleanupWorkTree();1263 exit;1264 }12651266 setupWorkTree($parenthash);12671268$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");12691270$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");12711272 my@committedfiles= ();1273 my%oldmeta;12741275 # foreach file specified on the command line ...1276 foreach my$filename( @{$state->{args}} )1277 {1278 my$committedfile=$filename;1279$filename= filecleanup($filename);12801281 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12821283 my$meta=$updater->getmeta($filename);1284$oldmeta{$filename} =$meta;12851286 my$wrev= revparse($filename);12871288 my ($filepart,$dirpart) = filenamesplit($filename);12891290 # do a checkout of the file if it is part of this tree1291 if ($wrev) {1292 system('git', 'checkout-index', '-f', '-u',$filename);1293 unless ($?== 0) {1294 die "Error running git-checkout-index -f -u$filename:$!";1295 }1296 }12971298 my$addflag= 0;1299 my$rmflag= 0;1300$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1301$addflag= 1 unless ( -e$filename);13021303 # Do up to date checking1304 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1305 {1306 # fail everything if an up to date check fails1307 print "error 1 Up to date check failed for$filename\n";1308 cleanupWorkTree();1309 exit;1310 }13111312 push@committedfiles,$committedfile;1313$log->info("Committing$filename");13141315 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13161317 unless ($rmflag)1318 {1319$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1320 rename$state->{entries}{$filename}{modified_filename},$filename;13211322 # Calculate modes to remove1323 my$invmode= "";1324 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }13251326$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1327 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1328 }13291330 if ($rmflag)1331 {1332$log->info("Removing file '$filename'");1333 unlink($filename);1334 system("git", "update-index", "--remove",$filename);1335 }1336 elsif ($addflag)1337 {1338$log->info("Adding file '$filename'");1339 system("git", "update-index", "--add",$filename);1340 } else {1341$log->info("Updating file '$filename'");1342 system("git", "update-index",$filename);1343 }1344 }13451346 unless ( scalar(@committedfiles) > 0 )1347 {1348 print "E No files to commit\n";1349 print "ok\n";1350 cleanupWorkTree();1351 return;1352 }13531354 my$treehash= `git write-tree`;1355 chomp$treehash;13561357$log->debug("Treehash :$treehash, Parenthash :$parenthash");13581359 # write our commit message out if we have one ...1360 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1361 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1362 if ( defined ($cfg->{gitcvs}{commitmsgannotation} ) ) {1363 if ($cfg->{gitcvs}{commitmsgannotation} !~ /^\s*$/) {1364 print$msg_fh"\n\n".$cfg->{gitcvs}{commitmsgannotation}."\n"1365 }1366 } else {1367 print$msg_fh"\n\nvia git-CVS emulator\n";1368 }1369 close$msg_fh;13701371 my$commithash= `git commit-tree $treehash-p $parenthash<$msg_filename`;1372chomp($commithash);1373$log->info("Commit hash :$commithash");13741375unless($commithash=~/[a-zA-Z0-9]{40}/)1376{1377$log->warn("Commit failed (Invalid commit hash)");1378print"error 1 Commit failed (unknown reason)\n";1379 cleanupWorkTree();1380exit;1381}13821383### Emulate git-receive-pack by running hooks/update1384my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1385$parenthash,$commithash);1386if( -x $hook[0] ) {1387unless(system(@hook) ==0)1388{1389$log->warn("Commit failed (update hook declined to update ref)");1390print"error 1 Commit failed (update hook declined)\n";1391 cleanupWorkTree();1392exit;1393}1394}13951396### Update the ref1397if(system(qw(git update-ref -m),"cvsserver ci",1398"refs/heads/$state->{module}",$commithash,$parenthash)) {1399$log->warn("update-ref for$state->{module} failed.");1400print"error 1 Cannot commit -- update first\n";1401 cleanupWorkTree();1402exit;1403}14041405### Emulate git-receive-pack by running hooks/post-receive1406my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1407if( -x $hook) {1408open(my$pipe,"|$hook") ||die"can't fork$!";14091410local$SIG{PIPE} =sub{die'pipe broke'};14111412print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";14131414close$pipe||die"bad pipe:$!$?";1415}14161417$updater->update();14181419### Then hooks/post-update1420$hook=$ENV{GIT_DIR}.'hooks/post-update';1421if(-x $hook) {1422system($hook,"refs/heads/$state->{module}");1423}14241425# foreach file specified on the command line ...1426foreachmy$filename(@committedfiles)1427{1428$filename= filecleanup($filename);14291430my$meta=$updater->getmeta($filename);1431unless(defined$meta->{revision}) {1432$meta->{revision} =1;1433}14341435my($filepart,$dirpart) = filenamesplit($filename,1);14361437$log->debug("Checked-in$dirpart:$filename");14381439print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1440if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1441{1442print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1443print"Remove-entry$dirpart\n";1444print"$filename\n";1445}else{1446if($meta->{revision} ==1) {1447print"M initial revision: 1.1\n";1448}else{1449print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1450}1451print"Checked-in$dirpart\n";1452print"$filename\n";1453my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1454print"/$filepart/1.$meta->{revision}//$kopts/\n";1455}1456}14571458 cleanupWorkTree();1459print"ok\n";1460}14611462sub req_status1463{1464my($cmd,$data) =@_;14651466 argsplit("status");14671468$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1469#$log->debug("status state : " . Dumper($state));14701471# Grab a handle to the SQLite db and do any necessary updates1472my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1473$updater->update();14741475# if no files were specified, we need to work out what files we should be providing status on ...1476 argsfromdir($updater);14771478# foreach file specified on the command line ...1479foreachmy$filename( @{$state->{args}} )1480{1481$filename= filecleanup($filename);14821483next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;14841485my$meta=$updater->getmeta($filename);1486my$oldmeta=$meta;14871488my$wrev= revparse($filename);14891490# If the working copy is an old revision, lets get that version too for comparison.1491if(defined($wrev)and$wrev!=$meta->{revision} )1492{1493$oldmeta=$updater->getmeta($filename,$wrev);1494}14951496# TODO : All possible statuses aren't yet implemented1497my$status;1498# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1499$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1500and1501( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1502or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1503);15041505# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1506$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1507and1508($state->{entries}{$filename}{unchanged}1509or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1510);15111512# Need checkout if it exists in the repo but doesn't have a working copy1513$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );15141515# Locally modified if working copy and repo copy have the same revision but there are local changes1516$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );15171518# Needs Merge if working copy revision is less than repo copy and there are local changes1519$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );15201521$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1522$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1523$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1524$status||="File had conflicts on merge"if(0);15251526$status||="Unknown";15271528my($filepart) = filenamesplit($filename);15291530print"M ===================================================================\n";1531print"M File:$filepart\tStatus:$status\n";1532if(defined($state->{entries}{$filename}{revision}) )1533{1534print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1535}else{1536print"M Working revision:\tNo entry for$filename\n";1537}1538if(defined($meta->{revision}) )1539{1540print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1541print"M Sticky Tag:\t\t(none)\n";1542print"M Sticky Date:\t\t(none)\n";1543print"M Sticky Options:\t\t(none)\n";1544}else{1545print"M Repository revision:\tNo revision control file\n";1546}1547print"M\n";1548}15491550print"ok\n";1551}15521553sub req_diff1554{1555my($cmd,$data) =@_;15561557 argsplit("diff");15581559$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1560#$log->debug("status state : " . Dumper($state));15611562my($revision1,$revision2);1563if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1564{1565$revision1=$state->{opt}{r}[0];1566$revision2=$state->{opt}{r}[1];1567}else{1568$revision1=$state->{opt}{r};1569}15701571$revision1=~s/^1\.//if(defined($revision1) );1572$revision2=~s/^1\.//if(defined($revision2) );15731574$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15751576# Grab a handle to the SQLite db and do any necessary updates1577my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1578$updater->update();15791580# if no files were specified, we need to work out what files we should be providing status on ...1581 argsfromdir($updater);15821583# foreach file specified on the command line ...1584foreachmy$filename( @{$state->{args}} )1585{1586$filename= filecleanup($filename);15871588my($fh,$file1,$file2,$meta1,$meta2,$filediff);15891590my$wrev= revparse($filename);15911592# We need _something_ to diff against1593next unless(defined($wrev) );15941595# if we have a -r switch, use it1596if(defined($revision1) )1597{1598(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1599$meta1=$updater->getmeta($filename,$revision1);1600unless(defined($meta1)and$meta1->{filehash}ne"deleted")1601{1602print"E File$filenameat revision 1.$revision1doesn't exist\n";1603next;1604}1605 transmitfile($meta1->{filehash}, { targetfile =>$file1});1606}1607# otherwise we just use the working copy revision1608else1609{1610(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1611$meta1=$updater->getmeta($filename,$wrev);1612 transmitfile($meta1->{filehash}, { targetfile =>$file1});1613}16141615# if we have a second -r switch, use it too1616if(defined($revision2) )1617{1618(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1619$meta2=$updater->getmeta($filename,$revision2);16201621unless(defined($meta2)and$meta2->{filehash}ne"deleted")1622{1623print"E File$filenameat revision 1.$revision2doesn't exist\n";1624next;1625}16261627 transmitfile($meta2->{filehash}, { targetfile =>$file2});1628}1629# otherwise we just use the working copy1630else1631{1632$file2=$state->{entries}{$filename}{modified_filename};1633}16341635# if we have been given -r, and we don't have a $file2 yet, lets get one1636if(defined($revision1)and not defined($file2) )1637{1638(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1639$meta2=$updater->getmeta($filename,$wrev);1640 transmitfile($meta2->{filehash}, { targetfile =>$file2});1641}16421643# We need to have retrieved something useful1644next unless(defined($meta1) );16451646# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1647next if(not defined($meta2)and$wrev==$meta1->{revision}1648and1649( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1650or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1651);16521653# Apparently we only show diffs for locally modified files1654next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16551656print"M Index:$filename\n";1657print"M ===================================================================\n";1658print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1659print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1660print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1661print"M diff ";1662foreachmy$opt(keys%{$state->{opt}} )1663{1664if(ref$state->{opt}{$opt}eq"ARRAY")1665{1666foreachmy$value( @{$state->{opt}{$opt}} )1667{1668print"-$opt$value";1669}1670}else{1671print"-$opt";1672print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1673}1674}1675print"$filename\n";16761677$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16781679($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16801681if(exists$state->{opt}{u} )1682{1683system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1684}else{1685system("diff$file1$file2>$filediff");1686}16871688while( <$fh> )1689{1690print"M$_";1691}1692close$fh;1693}16941695print"ok\n";1696}16971698sub req_log1699{1700my($cmd,$data) =@_;17011702 argsplit("log");17031704$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1705#$log->debug("log state : " . Dumper($state));17061707my($minrev,$maxrev);1708if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1709{1710my$control=$2;1711$minrev=$1;1712$maxrev=$3;1713$minrev=~s/^1\.//if(defined($minrev) );1714$maxrev=~s/^1\.//if(defined($maxrev) );1715$minrev++if(defined($minrev)and$controleq"::");1716}17171718# Grab a handle to the SQLite db and do any necessary updates1719my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1720$updater->update();17211722# if no files were specified, we need to work out what files we should be providing status on ...1723 argsfromdir($updater);17241725# foreach file specified on the command line ...1726foreachmy$filename( @{$state->{args}} )1727{1728$filename= filecleanup($filename);17291730my$headmeta=$updater->getmeta($filename);17311732my$revisions=$updater->getlog($filename);1733my$totalrevisions=scalar(@$revisions);17341735if(defined($minrev) )1736{1737$log->debug("Removing revisions less than$minrev");1738while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1739{1740pop@$revisions;1741}1742}1743if(defined($maxrev) )1744{1745$log->debug("Removing revisions greater than$maxrev");1746while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1747{1748shift@$revisions;1749}1750}17511752next unless(scalar(@$revisions) );17531754print"M\n";1755print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1756print"M Working file:$filename\n";1757print"M head: 1.$headmeta->{revision}\n";1758print"M branch:\n";1759print"M locks: strict\n";1760print"M access list:\n";1761print"M symbolic names:\n";1762print"M keyword substitution: kv\n";1763print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1764print"M description:\n";17651766foreachmy$revision(@$revisions)1767{1768print"M ----------------------------\n";1769print"M revision 1.$revision->{revision}\n";1770# reformat the date for log output1771$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}) );1772$revision->{author} = cvs_author($revision->{author});1773print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1774my$commitmessage=$updater->commitmessage($revision->{commithash});1775$commitmessage=~s/^/M /mg;1776print$commitmessage."\n";1777}1778print"M =============================================================================\n";1779}17801781print"ok\n";1782}17831784sub req_annotate1785{1786my($cmd,$data) =@_;17871788 argsplit("annotate");17891790$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1791#$log->debug("status state : " . Dumper($state));17921793# Grab a handle to the SQLite db and do any necessary updates1794my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1795$updater->update();17961797# if no files were specified, we need to work out what files we should be providing annotate on ...1798 argsfromdir($updater);17991800# we'll need a temporary checkout dir1801 setupWorkTree();18021803$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");18041805# foreach file specified on the command line ...1806foreachmy$filename( @{$state->{args}} )1807{1808$filename= filecleanup($filename);18091810my$meta=$updater->getmeta($filename);18111812next unless($meta->{revision} );18131814# get all the commits that this file was in1815# in dense format -- aka skip dead revisions1816my$revisions=$updater->gethistorydense($filename);1817my$lastseenin=$revisions->[0][2];18181819# populate the temporary index based on the latest commit were we saw1820# the file -- but do it cheaply without checking out any files1821# TODO: if we got a revision from the client, use that instead1822# to look up the commithash in sqlite (still good to default to1823# the current head as we do now)1824system("git","read-tree",$lastseenin);1825unless($?==0)1826{1827print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1828return;1829}1830$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");18311832# do a checkout of the file1833system('git','checkout-index','-f','-u',$filename);1834unless($?==0) {1835print"E error running git-checkout-index -f -u$filename:$!\n";1836return;1837}18381839$log->info("Annotate$filename");18401841# Prepare a file with the commits from the linearized1842# history that annotate should know about. This prevents1843# git-jsannotate telling us about commits we are hiding1844# from the client.18451846my$a_hints="$work->{workDir}/.annotate_hints";1847if(!open(ANNOTATEHINTS,'>',$a_hints)) {1848print"E failed to open '$a_hints' for writing:$!\n";1849return;1850}1851for(my$i=0;$i<@$revisions;$i++)1852{1853print ANNOTATEHINTS $revisions->[$i][2];1854if($i+1<@$revisions) {# have we got a parent?1855print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1856}1857print ANNOTATEHINTS "\n";1858}18591860print ANNOTATEHINTS "\n";1861close ANNOTATEHINTS1862or(print"E failed to write$a_hints:$!\n"),return;18631864my@cmd= (qw(git annotate -l -S),$a_hints,$filename);1865if(!open(ANNOTATE,"-|",@cmd)) {1866print"E error invoking ".join(' ',@cmd) .":$!\n";1867return;1868}1869my$metadata= {};1870print"E Annotations for$filename\n";1871print"E ***************\n";1872while( <ANNOTATE> )1873{1874if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1875{1876my$commithash=$1;1877my$data=$2;1878unless(defined($metadata->{$commithash} ) )1879{1880$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1881$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1882$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1883}1884printf("M 1.%-5d (%-8s%10s):%s\n",1885$metadata->{$commithash}{revision},1886$metadata->{$commithash}{author},1887$metadata->{$commithash}{modified},1888$data1889);1890}else{1891$log->warn("Error in annotate output! LINE:$_");1892print"E Annotate error\n";1893next;1894}1895}1896close ANNOTATE;1897}18981899# done; get out of the tempdir1900 cleanupWorkTree();19011902print"ok\n";19031904}19051906# This method takes the state->{arguments} array and produces two new arrays.1907# The first is $state->{args} which is everything before the '--' argument, and1908# the second is $state->{files} which is everything after it.1909sub argsplit1910{1911$state->{args} = [];1912$state->{files} = [];1913$state->{opt} = {};19141915return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19161917my$type=shift;19181919if(defined($type) )1920{1921my$opt= {};1922$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");1923$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1924$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");1925$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1926$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1927$opt= { k =>1, m =>1}if($typeeq"add");1928$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1929$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");193019311932while(scalar( @{$state->{arguments}} ) >0)1933{1934my$arg=shift@{$state->{arguments}};19351936next if($argeq"--");1937next unless($arg=~/\S/);19381939# if the argument looks like a switch1940if($arg=~/^-(\w)(.*)/)1941{1942# if it's a switch that takes an argument1943if($opt->{$1} )1944{1945# If this switch has already been provided1946if($opt->{$1} >1and exists($state->{opt}{$1} ) )1947{1948$state->{opt}{$1} = [$state->{opt}{$1} ];1949if(length($2) >0)1950{1951push@{$state->{opt}{$1}},$2;1952}else{1953push@{$state->{opt}{$1}},shift@{$state->{arguments}};1954}1955}else{1956# if there's extra data in the arg, use that as the argument for the switch1957if(length($2) >0)1958{1959$state->{opt}{$1} =$2;1960}else{1961$state->{opt}{$1} =shift@{$state->{arguments}};1962}1963}1964}else{1965$state->{opt}{$1} =undef;1966}1967}1968else1969{1970push@{$state->{args}},$arg;1971}1972}1973}1974else1975{1976my$mode=0;19771978foreachmy$value( @{$state->{arguments}} )1979{1980if($valueeq"--")1981{1982$mode++;1983next;1984}1985push@{$state->{args}},$valueif($mode==0);1986push@{$state->{files}},$valueif($mode==1);1987}1988}1989}19901991# This method uses $state->{directory} to populate $state->{args} with a list of filenames1992sub argsfromdir1993{1994my$updater=shift;19951996$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19971998return if(scalar( @{$state->{args}} ) >1);19992000my@gethead= @{$updater->gethead};20012002# push added files2003foreachmy$file(keys%{$state->{entries}}) {2004if(exists$state->{entries}{$file}{revision} &&2005$state->{entries}{$file}{revision} ==0)2006{2007push@gethead, { name =>$file, filehash =>'added'};2008}2009}20102011if(scalar(@{$state->{args}}) ==1)2012{2013my$arg=$state->{args}[0];2014$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );20152016$log->info("Only one arg specified, checking for directory expansion on '$arg'");20172018foreachmy$file(@gethead)2019{2020next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2021next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2022push@{$state->{args}},$file->{name};2023}20242025shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2026}else{2027$log->info("Only one arg specified, populating file list automatically");20282029$state->{args} = [];20302031foreachmy$file(@gethead)2032{2033next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2034next unless($file->{name} =~s/^$state->{prependdir}//);2035push@{$state->{args}},$file->{name};2036}2037}2038}20392040# This method cleans up the $state variable after a command that uses arguments has run2041sub statecleanup2042{2043$state->{files} = [];2044$state->{args} = [];2045$state->{arguments} = [];2046$state->{entries} = {};2047}20482049sub revparse2050{2051my$filename=shift;20522053returnundefunless(defined($state->{entries}{$filename}{revision} ) );20542055return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2056return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20572058returnundef;2059}20602061# This method takes a file hash and does a CVS "file transfer". Its2062# exact behaviour depends on a second, optional hash table argument:2063# - If $options->{targetfile}, dump the contents to that file;2064# - If $options->{print}, use M/MT to transmit the contents one line2065# at a time;2066# - Otherwise, transmit the size of the file, followed by the file2067# contents.2068sub transmitfile2069{2070my$filehash=shift;2071my$options=shift;20722073if(defined($filehash)and$filehasheq"deleted")2074{2075$log->warn("filehash is 'deleted'");2076return;2077}20782079die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20802081my$type=`git cat-file -t$filehash`;2082 chomp$type;20832084 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20852086 my$size= `git cat-file -s $filehash`;2087chomp$size;20882089$log->debug("transmitfile($filehash) size=$size, type=$type");20902091if(open my$fh,'-|',"git","cat-file","blob",$filehash)2092{2093if(defined($options->{targetfile} ) )2094{2095my$targetfile=$options->{targetfile};2096open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2097print NEWFILE $_while( <$fh> );2098close NEWFILE or die("Failed to write '$targetfile':$!");2099}elsif(defined($options->{print} ) &&$options->{print} ) {2100while( <$fh> ) {2101if(/\n\z/) {2102print'M ',$_;2103}else{2104print'MT text ',$_,"\n";2105}2106}2107}else{2108print"$size\n";2109printwhile( <$fh> );2110}2111close$fhor die("Couldn't close filehandle for transmitfile():$!");2112}else{2113die("Couldn't execute git-cat-file");2114}2115}21162117# This method takes a file name, and returns ( $dirpart, $filepart ) which2118# refers to the directory portion and the file portion of the filename2119# respectively2120sub filenamesplit2121{2122my$filename=shift;2123my$fixforlocaldir=shift;21242125my($filepart,$dirpart) = ($filename,".");2126($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2127$dirpart.="/";21282129if($fixforlocaldir)2130{2131$dirpart=~s/^$state->{prependdir}//;2132}21332134return($filepart,$dirpart);2135}21362137sub filecleanup2138{2139my$filename=shift;21402141returnundefunless(defined($filename));2142if($filename=~/^\// )2143{2144print"E absolute filenames '$filename' not supported by server\n";2145returnundef;2146}21472148$filename=~s/^\.\///g;2149$filename=$state->{prependdir} .$filename;2150return$filename;2151}21522153sub validateGitDir2154{2155if( !defined($state->{CVSROOT}) )2156{2157print"error 1 CVSROOT not specified\n";2158 cleanupWorkTree();2159exit;2160}2161if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2162{2163print"error 1 Internally inconsistent CVSROOT\n";2164 cleanupWorkTree();2165exit;2166}2167}21682169# Setup working directory in a work tree with the requested version2170# loaded in the index.2171sub setupWorkTree2172{2173my($ver) =@_;21742175 validateGitDir();21762177if( (defined($work->{state}) &&$work->{state} !=1) ||2178defined($work->{tmpDir}) )2179{2180$log->warn("Bad work tree state management");2181print"error 1 Internal setup multiple work trees without cleanup\n";2182 cleanupWorkTree();2183exit;2184}21852186$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);21872188if( !defined($work->{index}) )2189{2190(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2191}21922193chdir$work->{workDir}or2194die"Unable to chdir to$work->{workDir}\n";21952196$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");21972198$ENV{GIT_WORK_TREE} =".";2199$ENV{GIT_INDEX_FILE} =$work->{index};2200$work->{state} =2;22012202if($ver)2203{2204system("git","read-tree",$ver);2205unless($?==0)2206{2207$log->warn("Error running git-read-tree");2208die"Error running git-read-tree$verin$work->{workDir}$!\n";2209}2210}2211# else # req_annotate reads tree for each file2212}22132214# Ensure current directory is in some kind of working directory,2215# with a recent version loaded in the index.2216sub ensureWorkTree2217{2218if(defined($work->{tmpDir}) )2219{2220$log->warn("Bad work tree state management [ensureWorkTree()]");2221print"error 1 Internal setup multiple dirs without cleanup\n";2222 cleanupWorkTree();2223exit;2224}2225if($work->{state} )2226{2227return;2228}22292230 validateGitDir();22312232if( !defined($work->{emptyDir}) )2233{2234$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2235}2236chdir$work->{emptyDir}or2237die"Unable to chdir to$work->{emptyDir}\n";22382239my$ver=`git show-ref -s refs/heads/$state->{module}`;2240chomp$ver;2241if($ver!~/^[0-9a-f]{40}$/)2242{2243$log->warn("Error from git show-ref -s refs/head$state->{module}");2244print"error 1 cannot find the current HEAD of module";2245 cleanupWorkTree();2246exit;2247}22482249if( !defined($work->{index}) )2250{2251(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2252}22532254$ENV{GIT_WORK_TREE} =".";2255$ENV{GIT_INDEX_FILE} =$work->{index};2256$work->{state} =1;22572258system("git","read-tree",$ver);2259unless($?==0)2260{2261die"Error running git-read-tree$ver$!\n";2262}2263}22642265# Cleanup working directory that is not needed any longer.2266sub cleanupWorkTree2267{2268if( !$work->{state} )2269{2270return;2271}22722273chdir"/"or die"Unable to chdir '/'\n";22742275if(defined($work->{workDir}) )2276{2277 rmtree($work->{workDir} );2278undef$work->{workDir};2279}2280undef$work->{state};2281}22822283# Setup a temporary directory (not a working tree), typically for2284# merging dirty state as in req_update.2285sub setupTmpDir2286{2287$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2288chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";22892290return$work->{tmpDir};2291}22922293# Clean up a previously setupTmpDir. Restore previous work tree if2294# appropriate.2295sub cleanupTmpDir2296{2297if( !defined($work->{tmpDir}) )2298{2299$log->warn("cleanup tmpdir that has not been setup");2300die"Cleanup tmpDir that has not been setup\n";2301}2302if(defined($work->{state}) )2303{2304if($work->{state} ==1)2305{2306chdir$work->{emptyDir}or2307die"Unable to chdir to$work->{emptyDir}\n";2308}2309elsif($work->{state} ==2)2310{2311chdir$work->{workDir}or2312die"Unable to chdir to$work->{emptyDir}\n";2313}2314else2315{2316$log->warn("Inconsistent work dir state");2317die"Inconsistent work dir state\n";2318}2319}2320else2321{2322chdir"/"or die"Unable to chdir '/'\n";2323}2324}23252326# Given a path, this function returns a string containing the kopts2327# that should go into that path's Entries line. For example, a binary2328# file should get -kb.2329sub kopts_from_path2330{2331my($path,$srcType,$name) =@_;23322333if(defined($cfg->{gitcvs}{usecrlfattr} )and2334$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2335{2336my($val) = check_attr("crlf",$path);2337if($valeq"set")2338{2339return"";2340}2341elsif($valeq"unset")2342{2343return"-kb"2344}2345else2346{2347$log->info("Unrecognized check_attr crlf$path:$val");2348}2349}23502351if(defined($cfg->{gitcvs}{allbinary} ) )2352{2353if( ($cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i) )2354{2355return"-kb";2356}2357elsif( ($cfg->{gitcvs}{allbinary} =~/^\s*guess\s*$/i) )2358{2359if($srcTypeeq"sha1Or-k"&&2360!defined($name) )2361{2362my($ret)=$state->{entries}{$path}{options};2363if( !defined($ret) )2364{2365$ret=$state->{opt}{k};2366if(defined($ret))2367{2368$ret="-k$ret";2369}2370else2371{2372$ret="";2373}2374}2375if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )2376{2377print"E Bad -k option\n";2378$log->warn("Bad -k option:$ret");2379die"Error: Bad -k option:$ret\n";2380}23812382return$ret;2383}2384else2385{2386if( is_binary($srcType,$name) )2387{2388$log->debug("... as binary");2389return"-kb";2390}2391else2392{2393$log->debug("... as text");2394}2395}2396}2397}2398# Return "" to give no special treatment to any path2399return"";2400}24012402sub check_attr2403{2404my($attr,$path) =@_;2405 ensureWorkTree();2406if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2407{2408my$val= <$fh>;2409close$fh;2410$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2411return$val;2412}2413else2414{2415returnundef;2416}2417}24182419# This should have the same heuristics as convert.c:is_binary() and related.2420# Note that the bare CR test is done by callers in convert.c.2421sub is_binary2422{2423my($srcType,$name) =@_;2424$log->debug("is_binary($srcType,$name)");24252426# Minimize amount of interpreted code run in the inner per-character2427# loop for large files, by totalling each character value and2428# then analyzing the totals.2429my@counts;2430my$i;2431for($i=0;$i<256;$i++)2432{2433$counts[$i]=0;2434}24352436my$fh= open_blob_or_die($srcType,$name);2437my$line;2438while(defined($line=<$fh>) )2439{2440# Any '\0' and bare CR are considered binary.2441if($line=~/\0|(\r[^\n])/)2442{2443close($fh);2444return1;2445}24462447# Count up each character in the line:2448my$len=length($line);2449for($i=0;$i<$len;$i++)2450{2451$counts[ord(substr($line,$i,1))]++;2452}2453}2454close$fh;24552456# Don't count CR and LF as either printable/nonprintable2457$counts[ord("\n")]=0;2458$counts[ord("\r")]=0;24592460# Categorize individual character count into printable and nonprintable:2461my$printable=0;2462my$nonprintable=0;2463for($i=0;$i<256;$i++)2464{2465if($i<32&&2466$i!=ord("\b") &&2467$i!=ord("\t") &&2468$i!=033&&# ESC2469$i!=014)# FF2470{2471$nonprintable+=$counts[$i];2472}2473elsif($i==127)# DEL2474{2475$nonprintable+=$counts[$i];2476}2477else2478{2479$printable+=$counts[$i];2480}2481}24822483return($printable>>7) <$nonprintable;2484}24852486# Returns open file handle. Possible invocations:2487# - open_blob_or_die("file",$filename);2488# - open_blob_or_die("sha1",$filehash);2489sub open_blob_or_die2490{2491my($srcType,$name) =@_;2492my($fh);2493if($srcTypeeq"file")2494{2495if( !open$fh,"<",$name)2496{2497$log->warn("Unable to open file$name:$!");2498die"Unable to open file$name:$!\n";2499}2500}2501elsif($srcTypeeq"sha1"||$srcTypeeq"sha1Or-k")2502{2503unless(defined($name)and$name=~/^[a-zA-Z0-9]{40}$/)2504{2505$log->warn("Need filehash");2506die"Need filehash\n";2507}25082509my$type=`git cat-file -t$name`;2510 chomp$type;25112512 unless ( defined ($type) and$typeeq "blob" )2513 {2514$log->warn("Invalid type '$type' for '$name'");2515 die ( "Invalid type '$type' (expected 'blob')" )2516 }25172518 my$size= `git cat-file -s $name`;2519chomp$size;25202521$log->debug("open_blob_or_die($name) size=$size, type=$type");25222523unless(open$fh,'-|',"git","cat-file","blob",$name)2524{2525$log->warn("Unable to open sha1$name");2526die"Unable to open sha1$name\n";2527}2528}2529else2530{2531$log->warn("Unknown type of blob source:$srcType");2532die"Unknown type of blob source:$srcType\n";2533}2534return$fh;2535}25362537# Generate a CVS author name from Git author information, by taking the local2538# part of the email address and replacing characters not in the Portable2539# Filename Character Set (see IEEE Std 1003.1-2001, 3.276) by underscores. CVS2540# Login names are Unix login names, which should be restricted to this2541# character set.2542sub cvs_author2543{2544my$author_line=shift;2545(my$author) =$author_line=~/<([^@>]*)/;25462547$author=~s/[^-a-zA-Z0-9_.]/_/g;2548$author=~s/^-/_/;25492550$author;2551}25522553package GITCVS::log;25542555####2556#### Copyright The Open University UK - 2006.2557####2558#### Authors: Martyn Smith <martyn@catalyst.net.nz>2559#### Martin Langhoff <martin@catalyst.net.nz>2560####2561####25622563use strict;2564use warnings;25652566=head1 NAME25672568GITCVS::log25692570=head1 DESCRIPTION25712572This module provides very crude logging with a similar interface to2573Log::Log4perl25742575=head1 METHODS25762577=cut25782579=head2 new25802581Creates a new log object, optionally you can specify a filename here to2582indicate the file to log to. If no log file is specified, you can specify one2583later with method setfile, or indicate you no longer want logging with method2584nofile.25852586Until one of these methods is called, all log calls will buffer messages ready2587to write out.25882589=cut2590sub new2591{2592my$class=shift;2593my$filename=shift;25942595my$self= {};25962597bless$self,$class;25982599if(defined($filename) )2600{2601open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2602}26032604return$self;2605}26062607=head2 setfile26082609This methods takes a filename, and attempts to open that file as the log file.2610If successful, all buffered data is written out to the file, and any further2611logging is written directly to the file.26122613=cut2614sub setfile2615{2616my$self=shift;2617my$filename=shift;26182619if(defined($filename) )2620{2621open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2622}26232624return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26252626while(my$line=shift@{$self->{buffer}} )2627{2628print{$self->{fh}}$line;2629}2630}26312632=head2 nofile26332634This method indicates no logging is going to be used. It flushes any entries in2635the internal buffer, and sets a flag to ensure no further data is put there.26362637=cut2638sub nofile2639{2640my$self=shift;26412642$self->{nolog} =1;26432644return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");26452646$self->{buffer} = [];2647}26482649=head2 _logopen26502651Internal method. Returns true if the log file is open, false otherwise.26522653=cut2654sub _logopen2655{2656my$self=shift;26572658return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2659return0;2660}26612662=head2 debug info warn fatal26632664These four methods are wrappers to _log. They provide the actual interface for2665logging data.26662667=cut2668sub debug {my$self=shift;$self->_log("debug",@_); }2669sub info {my$self=shift;$self->_log("info",@_); }2670subwarn{my$self=shift;$self->_log("warn",@_); }2671sub fatal {my$self=shift;$self->_log("fatal",@_); }26722673=head2 _log26742675This is an internal method called by the logging functions. It generates a2676timestamp and pushes the logged line either to file, or internal buffer.26772678=cut2679sub _log2680{2681my$self=shift;2682my$level=shift;26832684return if($self->{nolog} );26852686my@time=localtime;2687my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2688$time[5] +1900,2689$time[4] +1,2690$time[3],2691$time[2],2692$time[1],2693$time[0],2694uc$level,2695);26962697if($self->_logopen)2698{2699print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2700}else{2701push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2702}2703}27042705=head2 DESTROY27062707This method simply closes the file handle if one is open27082709=cut2710sub DESTROY2711{2712my$self=shift;27132714if($self->_logopen)2715{2716close$self->{fh};2717}2718}27192720package GITCVS::updater;27212722####2723#### Copyright The Open University UK - 2006.2724####2725#### Authors: Martyn Smith <martyn@catalyst.net.nz>2726#### Martin Langhoff <martin@catalyst.net.nz>2727####2728####27292730use strict;2731use warnings;2732use DBI;27332734=head1 METHODS27352736=cut27372738=head2 new27392740=cut2741sub new2742{2743my$class=shift;2744my$config=shift;2745my$module=shift;2746my$log=shift;27472748die"Need to specify a git repository"unless(defined($config)and-d $config);2749die"Need to specify a module"unless(defined($module) );27502751$class=ref($class) ||$class;27522753my$self= {};27542755bless$self,$class;27562757$self->{valid_tables} = {'revision'=>1,2758'revision_ix1'=>1,2759'revision_ix2'=>1,2760'head'=>1,2761'head_ix1'=>1,2762'properties'=>1,2763'commitmsgs'=>1};27642765$self->{module} =$module;2766$self->{git_path} =$config."/";27672768$self->{log} =$log;27692770die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );27712772$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2773$cfg->{gitcvs}{dbdriver} ||"SQLite";2774$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2775$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2776$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2777$cfg->{gitcvs}{dbuser} ||"";2778$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2779$cfg->{gitcvs}{dbpass} ||"";2780$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2781$cfg->{gitcvs}{dbtablenameprefix} ||"";2782my%mapping= ( m =>$module,2783 a =>$state->{method},2784 u =>getlogin||getpwuid($<) || $<,2785 G =>$self->{git_path},2786 g => mangle_dirname($self->{git_path}),2787);2788$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2789$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2790$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2791$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});27922793die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2794die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2795$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2796$self->{dbuser},2797$self->{dbpass});2798die"Error connecting to database\n"unlessdefined$self->{dbh};27992800$self->{tables} = {};2801foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2802{2803$self->{tables}{$table} =1;2804}28052806# Construct the revision table if required2807unless($self->{tables}{$self->tablename("revision")} )2808{2809my$tablename=$self->tablename("revision");2810my$ix1name=$self->tablename("revision_ix1");2811my$ix2name=$self->tablename("revision_ix2");2812$self->{dbh}->do("2813 CREATE TABLE$tablename(2814 name TEXT NOT NULL,2815 revision INTEGER NOT NULL,2816 filehash TEXT NOT NULL,2817 commithash TEXT NOT NULL,2818 author TEXT NOT NULL,2819 modified TEXT NOT NULL,2820 mode TEXT NOT NULL2821 )2822 ");2823$self->{dbh}->do("2824 CREATE INDEX$ix1name2825 ON$tablename(name,revision)2826 ");2827$self->{dbh}->do("2828 CREATE INDEX$ix2name2829 ON$tablename(name,commithash)2830 ");2831}28322833# Construct the head table if required2834unless($self->{tables}{$self->tablename("head")} )2835{2836my$tablename=$self->tablename("head");2837my$ix1name=$self->tablename("head_ix1");2838$self->{dbh}->do("2839 CREATE TABLE$tablename(2840 name TEXT NOT NULL,2841 revision INTEGER NOT NULL,2842 filehash TEXT NOT NULL,2843 commithash TEXT NOT NULL,2844 author TEXT NOT NULL,2845 modified TEXT NOT NULL,2846 mode TEXT NOT NULL2847 )2848 ");2849$self->{dbh}->do("2850 CREATE INDEX$ix1name2851 ON$tablename(name)2852 ");2853}28542855# Construct the properties table if required2856unless($self->{tables}{$self->tablename("properties")} )2857{2858my$tablename=$self->tablename("properties");2859$self->{dbh}->do("2860 CREATE TABLE$tablename(2861 key TEXT NOT NULL PRIMARY KEY,2862 value TEXT2863 )2864 ");2865}28662867# Construct the commitmsgs table if required2868unless($self->{tables}{$self->tablename("commitmsgs")} )2869{2870my$tablename=$self->tablename("commitmsgs");2871$self->{dbh}->do("2872 CREATE TABLE$tablename(2873 key TEXT NOT NULL PRIMARY KEY,2874 value TEXT2875 )2876 ");2877}28782879return$self;2880}28812882=head2 tablename28832884=cut2885sub tablename2886{2887my$self=shift;2888my$name=shift;28892890if(exists$self->{valid_tables}{$name}) {2891return$self->{dbtablenameprefix} .$name;2892}else{2893returnundef;2894}2895}28962897=head2 update28982899=cut2900sub update2901{2902my$self=shift;29032904# first lets get the commit list2905$ENV{GIT_DIR} =$self->{git_path};29062907my$commitsha1=`git rev-parse$self->{module}`;2908chomp$commitsha1;29092910my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2911unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2912{2913die("Invalid module '$self->{module}'");2914}291529162917my$git_log;2918my$lastcommit=$self->_get_prop("last_commit");29192920if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2921return1;2922}29232924# Start exclusive lock here...2925$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";29262927# TODO: log processing is memory bound2928# if we can parse into a 2nd file that is in reverse order2929# we can probably do something really efficient2930my@git_log_params= ('--pretty','--parents','--topo-order');29312932if(defined$lastcommit) {2933push@git_log_params,"$lastcommit..$self->{module}";2934}else{2935push@git_log_params,$self->{module};2936}2937# git-rev-list is the backend / plumbing version of git-log2938open(GITLOG,'-|','git','rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";29392940my@commits;29412942my%commit= ();29432944while( <GITLOG> )2945{2946chomp;2947if(m/^commit\s+(.*)$/) {2948# on ^commit lines put the just seen commit in the stack2949# and prime things for the next one2950if(keys%commit) {2951my%copy=%commit;2952unshift@commits, \%copy;2953%commit= ();2954}2955my@parents=split(m/\s+/,$1);2956$commit{hash} =shift@parents;2957$commit{parents} = \@parents;2958}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2959# on rfc822-like lines seen before we see any message,2960# lowercase the entry and put it in the hash as key-value2961$commit{lc($1)} =$2;2962}else{2963# message lines - skip initial empty line2964# and trim whitespace2965if(!exists($commit{message}) &&m/^\s*$/) {2966# define it to mark the end of headers2967$commit{message} ='';2968next;2969}2970s/^\s+//;s/\s+$//;# trim ws2971$commit{message} .=$_."\n";2972}2973}2974close GITLOG;29752976unshift@commits, \%commitif(keys%commit);29772978# Now all the commits are in the @commits bucket2979# ordered by time DESC. for each commit that needs processing,2980# determine whether it's following the last head we've seen or if2981# it's on its own branch, grab a file list, and add whatever's changed2982# NOTE: $lastcommit refers to the last commit from previous run2983# $lastpicked is the last commit we picked in this run2984my$lastpicked;2985my$head= {};2986if(defined$lastcommit) {2987$lastpicked=$lastcommit;2988}29892990my$committotal=scalar(@commits);2991my$commitcount=0;29922993# Load the head table into $head (for cached lookups during the update process)2994foreachmy$file( @{$self->gethead()} )2995{2996$head->{$file->{name}} =$file;2997}29982999foreachmy$commit(@commits)3000{3001$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");3002if(defined$lastpicked)3003{3004if(!in_array($lastpicked, @{$commit->{parents}}))3005{3006# skip, we'll see this delta3007# as part of a merge later3008# warn "skipping off-track $commit->{hash}\n";3009next;3010}elsif(@{$commit->{parents}} >1) {3011# it is a merge commit, for each parent that is3012# not $lastpicked, see if we can get a log3013# from the merge-base to that parent to put it3014# in the message as a merge summary.3015my@parents= @{$commit->{parents}};3016foreachmy$parent(@parents) {3017# git-merge-base can potentially (but rarely) throw3018# several candidate merge bases. let's assume3019# that the first one is the best one.3020if($parenteq$lastpicked) {3021next;3022}3023my$base=eval{3024 safe_pipe_capture('git','merge-base',3025$lastpicked,$parent);3026};3027# The two branches may not be related at all,3028# in which case merge base simply fails to find3029# any, but that's Ok.3030next if($@);30313032chomp$base;3033if($base) {3034my@merged;3035# print "want to log between $base $parent \n";3036open(GITLOG,'-|','git','log','--pretty=medium',"$base..$parent")3037or die"Cannot call git-log:$!";3038my$mergedhash;3039while(<GITLOG>) {3040chomp;3041if(!defined$mergedhash) {3042if(m/^commit\s+(.+)$/) {3043$mergedhash=$1;3044}else{3045next;3046}3047}else{3048# grab the first line that looks non-rfc8223049# aka has content after leading space3050if(m/^\s+(\S.*)$/) {3051my$title=$1;3052$title=substr($title,0,100);# truncate3053unshift@merged,"$mergedhash$title";3054undef$mergedhash;3055}3056}3057}3058close GITLOG;3059if(@merged) {3060$commit->{mergemsg} =$commit->{message};3061$commit->{mergemsg} .="\nSummary of merged commits:\n\n";3062foreachmy$summary(@merged) {3063$commit->{mergemsg} .="\t$summary\n";3064}3065$commit->{mergemsg} .="\n\n";3066# print "Message for $commit->{hash} \n$commit->{mergemsg}";3067}3068}3069}3070}3071}30723073# convert the date to CVS-happy format3074$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);30753076if(defined($lastpicked) )3077{3078my$filepipe=open(FILELIST,'-|','git','diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");3079local($/) ="\0";3080while( <FILELIST> )3081{3082chomp;3083unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)3084{3085die("Couldn't process git-diff-tree line :$_");3086}3087my($mode,$hash,$change) = ($1,$2,$3);3088my$name= <FILELIST>;3089chomp($name);30903091# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");30923093my$git_perms="";3094$git_perms.="r"if($mode&4);3095$git_perms.="w"if($mode&2);3096$git_perms.="x"if($mode&1);3097$git_perms="rw"if($git_permseq"");30983099if($changeeq"D")3100{3101#$log->debug("DELETE $name");3102$head->{$name} = {3103 name =>$name,3104 revision =>$head->{$name}{revision} +1,3105 filehash =>"deleted",3106 commithash =>$commit->{hash},3107 modified =>$commit->{date},3108 author =>$commit->{author},3109 mode =>$git_perms,3110};3111$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3112}3113elsif($changeeq"M"||$changeeq"T")3114{3115#$log->debug("MODIFIED $name");3116$head->{$name} = {3117 name =>$name,3118 revision =>$head->{$name}{revision} +1,3119 filehash =>$hash,3120 commithash =>$commit->{hash},3121 modified =>$commit->{date},3122 author =>$commit->{author},3123 mode =>$git_perms,3124};3125$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3126}3127elsif($changeeq"A")3128{3129#$log->debug("ADDED $name");3130$head->{$name} = {3131 name =>$name,3132 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,3133 filehash =>$hash,3134 commithash =>$commit->{hash},3135 modified =>$commit->{date},3136 author =>$commit->{author},3137 mode =>$git_perms,3138};3139$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3140}3141else3142{3143$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");3144die;3145}3146}3147close FILELIST;3148}else{3149# this is used to detect files removed from the repo3150my$seen_files= {};31513152my$filepipe=open(FILELIST,'-|','git','ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");3153local$/="\0";3154while( <FILELIST> )3155{3156chomp;3157unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)3158{3159die("Couldn't process git-ls-tree line :$_");3160}31613162my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);31633164$seen_files->{$git_filename} =1;31653166my($oldhash,$oldrevision,$oldmode) = (3167$head->{$git_filename}{filehash},3168$head->{$git_filename}{revision},3169$head->{$git_filename}{mode}3170);31713172if($git_perms=~/^\d\d\d(\d)\d\d/o)3173{3174$git_perms="";3175$git_perms.="r"if($1&4);3176$git_perms.="w"if($1&2);3177$git_perms.="x"if($1&1);3178}else{3179$git_perms="rw";3180}31813182# unless the file exists with the same hash, we need to update it ...3183unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3184{3185my$newrevision= ($oldrevisionor0) +1;31863187$head->{$git_filename} = {3188 name =>$git_filename,3189 revision =>$newrevision,3190 filehash =>$git_hash,3191 commithash =>$commit->{hash},3192 modified =>$commit->{date},3193 author =>$commit->{author},3194 mode =>$git_perms,3195};319631973198$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3199}3200}3201close FILELIST;32023203# Detect deleted files3204foreachmy$file(keys%$head)3205{3206unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3207{3208$head->{$file}{revision}++;3209$head->{$file}{filehash} ="deleted";3210$head->{$file}{commithash} =$commit->{hash};3211$head->{$file}{modified} =$commit->{date};3212$head->{$file}{author} =$commit->{author};32133214$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3215}3216}3217# END : "Detect deleted files"3218}321932203221if(exists$commit->{mergemsg})3222{3223$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3224}32253226$lastpicked=$commit->{hash};32273228$self->_set_prop("last_commit",$commit->{hash});3229}32303231$self->delete_head();3232foreachmy$file(keys%$head)3233{3234$self->insert_head(3235$file,3236$head->{$file}{revision},3237$head->{$file}{filehash},3238$head->{$file}{commithash},3239$head->{$file}{modified},3240$head->{$file}{author},3241$head->{$file}{mode},3242);3243}3244# invalidate the gethead cache3245$self->{gethead_cache} =undef;324632473248# Ending exclusive lock here3249$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3250}32513252sub insert_rev3253{3254my$self=shift;3255my$name=shift;3256my$revision=shift;3257my$filehash=shift;3258my$commithash=shift;3259my$modified=shift;3260my$author=shift;3261my$mode=shift;3262my$tablename=$self->tablename("revision");32633264my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3265$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3266}32673268sub insert_mergelog3269{3270my$self=shift;3271my$key=shift;3272my$value=shift;3273my$tablename=$self->tablename("commitmsgs");32743275my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3276$insert_mergelog->execute($key,$value);3277}32783279sub delete_head3280{3281my$self=shift;3282my$tablename=$self->tablename("head");32833284my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3285$delete_head->execute();3286}32873288sub insert_head3289{3290my$self=shift;3291my$name=shift;3292my$revision=shift;3293my$filehash=shift;3294my$commithash=shift;3295my$modified=shift;3296my$author=shift;3297my$mode=shift;3298my$tablename=$self->tablename("head");32993300my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3301$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3302}33033304sub _headrev3305{3306my$self=shift;3307my$filename=shift;3308my$tablename=$self->tablename("head");33093310my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3311$db_query->execute($filename);3312my($hash,$revision,$mode) =$db_query->fetchrow_array;33133314return($hash,$revision,$mode);3315}33163317sub _get_prop3318{3319my$self=shift;3320my$key=shift;3321my$tablename=$self->tablename("properties");33223323my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3324$db_query->execute($key);3325my($value) =$db_query->fetchrow_array;33263327return$value;3328}33293330sub _set_prop3331{3332my$self=shift;3333my$key=shift;3334my$value=shift;3335my$tablename=$self->tablename("properties");33363337my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3338$db_query->execute($value,$key);33393340unless($db_query->rows)3341{3342$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3343$db_query->execute($key,$value);3344}33453346return$value;3347}33483349=head2 gethead33503351=cut33523353sub gethead3354{3355my$self=shift;3356my$tablename=$self->tablename("head");33573358return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );33593360my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3361$db_query->execute();33623363my$tree= [];3364while(my$file=$db_query->fetchrow_hashref)3365{3366push@$tree,$file;3367}33683369$self->{gethead_cache} =$tree;33703371return$tree;3372}33733374=head2 getlog33753376=cut33773378sub getlog3379{3380my$self=shift;3381my$filename=shift;3382my$tablename=$self->tablename("revision");33833384my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3385$db_query->execute($filename);33863387my$tree= [];3388while(my$file=$db_query->fetchrow_hashref)3389{3390push@$tree,$file;3391}33923393return$tree;3394}33953396=head2 getmeta33973398This function takes a filename (with path) argument and returns a hashref of3399metadata for that file.34003401=cut34023403sub getmeta3404{3405my$self=shift;3406my$filename=shift;3407my$revision=shift;3408my$tablename_rev=$self->tablename("revision");3409my$tablename_head=$self->tablename("head");34103411my$db_query;3412if(defined($revision)and$revision=~/^\d+$/)3413{3414$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3415$db_query->execute($filename,$revision);3416}3417elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3418{3419$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3420$db_query->execute($filename,$revision);3421}else{3422$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3423$db_query->execute($filename);3424}34253426return$db_query->fetchrow_hashref;3427}34283429=head2 commitmessage34303431this function takes a commithash and returns the commit message for that commit34323433=cut3434sub commitmessage3435{3436my$self=shift;3437my$commithash=shift;3438my$tablename=$self->tablename("commitmsgs");34393440die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);34413442my$db_query;3443$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3444$db_query->execute($commithash);34453446my($message) =$db_query->fetchrow_array;34473448if(defined($message) )3449{3450$message.=" "if($message=~/\n$/);3451return$message;3452}34533454my@lines= safe_pipe_capture("git","cat-file","commit",$commithash);3455shift@lineswhile($lines[0] =~/\S/);3456$message=join("",@lines);3457$message.=" "if($message=~/\n$/);3458return$message;3459}34603461=head2 gethistory34623463This function takes a filename (with path) argument and returns an arrayofarrays3464containing revision,filehash,commithash ordered by revision descending34653466=cut3467sub gethistory3468{3469my$self=shift;3470my$filename=shift;3471my$tablename=$self->tablename("revision");34723473my$db_query;3474$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3475$db_query->execute($filename);34763477return$db_query->fetchall_arrayref;3478}34793480=head2 gethistorydense34813482This function takes a filename (with path) argument and returns an arrayofarrays3483containing revision,filehash,commithash ordered by revision descending.34843485This version of gethistory skips deleted entries -- so it is useful for annotate.3486The 'dense' part is a reference to a '--dense' option available for git-rev-list3487and other git tools that depend on it.34883489=cut3490sub gethistorydense3491{3492my$self=shift;3493my$filename=shift;3494my$tablename=$self->tablename("revision");34953496my$db_query;3497$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3498$db_query->execute($filename);34993500return$db_query->fetchall_arrayref;3501}35023503=head2 in_array()35043505from Array::PAT - mimics the in_array() function3506found in PHP. Yuck but works for small arrays.35073508=cut3509sub in_array3510{3511my($check,@array) =@_;3512my$retval=0;3513foreachmy$test(@array){3514if($checkeq$test){3515$retval=1;3516}3517}3518return$retval;3519}35203521=head2 safe_pipe_capture35223523an alternative to `command` that allows input to be passed as an array3524to work around shell problems with weird characters in arguments35253526=cut3527sub safe_pipe_capture {35283529my@output;35303531if(my$pid=open my$child,'-|') {3532@output= (<$child>);3533close$childor die join(' ',@_).":$!$?";3534}else{3535exec(@_)or die"$!$?";# exec() can fail the executable can't be found3536}3537returnwantarray?@output:join('',@output);3538}35393540=head2 mangle_dirname35413542create a string from a directory name that is suitable to use as3543part of a filename, mainly by converting all chars except \w.- to _35443545=cut3546sub mangle_dirname {3547my$dirname=shift;3548return unlessdefined$dirname;35493550$dirname=~s/[^\w.-]/_/g;35513552return$dirname;3553}35543555=head2 mangle_tablename35563557create a string from a that is suitable to use as part of an SQL table3558name, mainly by converting all chars except \w to _35593560=cut3561sub mangle_tablename {3562my$tablename=shift;3563return unlessdefined$tablename;35643565$tablename=~s/[^\w_]/_/g;35663567return$tablename;3568}356935701;