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@laptop.org> 12#### 13#### 14#### Released under the GNU Public License, version 2. 15#### 16#### 17 18use5.008; 19use strict; 20use warnings; 21use bytes; 22 23use Fcntl; 24use File::Temp qw/tempdir tempfile/; 25use File::Path qw/rmtree/; 26use File::Basename; 27use Getopt::Long qw(:config require_order no_ignore_case); 28 29my$VERSION='@@GIT_VERSION@@'; 30 31my$log= GITCVS::log->new(); 32my$cfg; 33 34my$DATE_LIST= { 35 Jan =>"01", 36 Feb =>"02", 37 Mar =>"03", 38 Apr =>"04", 39 May =>"05", 40 Jun =>"06", 41 Jul =>"07", 42 Aug =>"08", 43 Sep =>"09", 44 Oct =>"10", 45 Nov =>"11", 46 Dec =>"12", 47}; 48 49# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 50$| =1; 51 52#### Definition and mappings of functions #### 53 54my$methods= { 55'Root'=> \&req_Root, 56'Valid-responses'=> \&req_Validresponses, 57'valid-requests'=> \&req_validrequests, 58'Directory'=> \&req_Directory, 59'Entry'=> \&req_Entry, 60'Modified'=> \&req_Modified, 61'Unchanged'=> \&req_Unchanged, 62'Questionable'=> \&req_Questionable, 63'Argument'=> \&req_Argument, 64'Argumentx'=> \&req_Argument, 65'expand-modules'=> \&req_expandmodules, 66'add'=> \&req_add, 67'remove'=> \&req_remove, 68'co'=> \&req_co, 69'update'=> \&req_update, 70'ci'=> \&req_ci, 71'diff'=> \&req_diff, 72'log'=> \&req_log, 73'rlog'=> \&req_log, 74'tag'=> \&req_CATCHALL, 75'status'=> \&req_status, 76'admin'=> \&req_CATCHALL, 77'history'=> \&req_CATCHALL, 78'watchers'=> \&req_EMPTY, 79'editors'=> \&req_EMPTY, 80'noop'=> \&req_EMPTY, 81'annotate'=> \&req_annotate, 82'Global_option'=> \&req_Globaloption, 83#'annotate' => \&req_CATCHALL, 84}; 85 86############################################## 87 88 89# $state holds all the bits of information the clients sends us that could 90# potentially be useful when it comes to actually _doing_ something. 91my$state= { prependdir =>''}; 92 93# Work is for managing temporary working directory 94my$work= 95{ 96state=>undef,# undef, 1 (empty), 2 (with stuff) 97 workDir =>undef, 98index=>undef, 99 emptyDir =>undef, 100 tmpDir =>undef 101}; 102 103$log->info("--------------- STARTING -----------------"); 104 105my$usage= 106"Usage: git cvsserver [options] [pserver|server] [<directory> ...]\n". 107" --base-path <path> : Prepend to requested CVSROOT\n". 108" Can be read from GIT_CVSSERVER_BASE_PATH\n". 109" --strict-paths : Don't allow recursing into subdirectories\n". 110" --export-all : Don't check for gitcvs.enabled in config\n". 111" --version, -V : Print version information and exit\n". 112" --help, -h, -H : Print usage information and exit\n". 113"\n". 114"<directory> ... is a list of allowed directories. If no directories\n". 115"are given, all are allowed. This is an additional restriction, gitcvs\n". 116"access still needs to be enabled by the gitcvs.enabled config option.\n". 117"Alternately, one directory may be specified in GIT_CVSSERVER_ROOT.\n"; 118 119my@opts= ('help|h|H','version|V', 120'base-path=s','strict-paths','export-all'); 121GetOptions($state,@opts) 122or die$usage; 123 124if($state->{version}) { 125print"git-cvsserver version$VERSION\n"; 126exit; 127} 128if($state->{help}) { 129print$usage; 130exit; 131} 132 133my$TEMP_DIR= tempdir( CLEANUP =>1); 134$log->debug("Temporary directory is '$TEMP_DIR'"); 135 136$state->{method} ='ext'; 137if(@ARGV) { 138if($ARGV[0]eq'pserver') { 139$state->{method} ='pserver'; 140shift@ARGV; 141}elsif($ARGV[0]eq'server') { 142shift@ARGV; 143} 144} 145 146# everything else is a directory 147$state->{allowed_roots} = [@ARGV]; 148 149# don't export the whole system unless the users requests it 150if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 151die"--export-all can only be used together with an explicit whitelist\n"; 152} 153 154# Environment handling for running under git-shell 155if(exists$ENV{GIT_CVSSERVER_BASE_PATH}) { 156if($state->{'base-path'}) { 157die"Cannot specify base path both ways.\n"; 158} 159my$base_path=$ENV{GIT_CVSSERVER_BASE_PATH}; 160$state->{'base-path'} =$base_path; 161$log->debug("Picked up base path '$base_path' from environment.\n"); 162} 163if(exists$ENV{GIT_CVSSERVER_ROOT}) { 164if(@{$state->{allowed_roots}}) { 165die"Cannot specify roots both ways:@ARGV\n"; 166} 167my$allowed_root=$ENV{GIT_CVSSERVER_ROOT}; 168$state->{allowed_roots} = [$allowed_root]; 169$log->debug("Picked up allowed root '$allowed_root' from environment.\n"); 170} 171 172# if we are called with a pserver argument, 173# deal with the authentication cat before entering the 174# main loop 175if($state->{method}eq'pserver') { 176my$line= <STDIN>;chomp$line; 177unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 178die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 179} 180my$request=$1; 181$line= <STDIN>;chomp$line; 182unless(req_Root('root',$line)) {# reuse Root 183print"E Invalid root$line\n"; 184exit1; 185} 186$line= <STDIN>;chomp$line; 187my$user=$line; 188$line= <STDIN>;chomp$line; 189my$password=$line; 190 191if($usereq'anonymous') { 192# "A" will be 1 byte, use length instead in case the 193# encryption method ever changes (yeah, right!) 194if(length($password) >1) { 195print"E Don't supply a password for the `anonymous' user\n"; 196print"I HATE YOU\n"; 197exit1; 198} 199 200# Fall through to LOVE 201}else{ 202# Trying to authenticate a user 203if(not exists$cfg->{gitcvs}->{authdb}) { 204print"E the repo config file needs a [gitcvs] section with an 'authdb' parameter set to the filename of the authentication database\n"; 205print"I HATE YOU\n"; 206exit1; 207} 208 209my$authdb=$cfg->{gitcvs}->{authdb}; 210 211unless(-e $authdb) { 212print"E The authentication database specified in [gitcvs.authdb] does not exist\n"; 213print"I HATE YOU\n"; 214exit1; 215} 216 217my$auth_ok; 218open my$passwd,"<",$authdbor die$!; 219while(<$passwd>) { 220if(m{^\Q$user\E:(.*)}) { 221if(crypt($user, descramble($password))eq$1) { 222$auth_ok=1; 223} 224}; 225} 226close$passwd; 227 228unless($auth_ok) { 229print"I HATE YOU\n"; 230exit1; 231} 232 233# Fall through to LOVE 234} 235 236# For checking whether the user is anonymous on commit 237$state->{user} =$user; 238 239$line= <STDIN>;chomp$line; 240unless($lineeq"END$requestREQUEST") { 241die"E Do not understand$line-- expecting END$requestREQUEST\n"; 242} 243print"I LOVE YOU\n"; 244exit if$requesteq'VERIFICATION';# cvs login 245# and now back to our regular programme... 246} 247 248# Keep going until the client closes the connection 249while(<STDIN>) 250{ 251chomp; 252 253# Check to see if we've seen this method, and call appropriate function. 254if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 255{ 256# use the $methods hash to call the appropriate sub for this command 257#$log->info("Method : $1"); 258&{$methods->{$1}}($1,$2); 259}else{ 260# log fatal because we don't understand this function. If this happens 261# we're fairly screwed because we don't know if the client is expecting 262# a response. If it is, the client will hang, we'll hang, and the whole 263# thing will be custard. 264$log->fatal("Don't understand command$_\n"); 265die("Unknown command$_"); 266} 267} 268 269$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 270$log->info("--------------- FINISH -----------------"); 271 272chdir'/'; 273exit0; 274 275# Magic catchall method. 276# This is the method that will handle all commands we haven't yet 277# implemented. It simply sends a warning to the log file indicating a 278# command that hasn't been implemented has been invoked. 279sub req_CATCHALL 280{ 281my($cmd,$data) =@_; 282$log->warn("Unhandled command : req_$cmd:$data"); 283} 284 285# This method invariably succeeds with an empty response. 286sub req_EMPTY 287{ 288print"ok\n"; 289} 290 291# Root pathname \n 292# Response expected: no. Tell the server which CVSROOT to use. Note that 293# pathname is a local directory and not a fully qualified CVSROOT variable. 294# pathname must already exist; if creating a new root, use the init 295# request, not Root. pathname does not include the hostname of the server, 296# how to access the server, etc.; by the time the CVS protocol is in use, 297# connection, authentication, etc., are already taken care of. The Root 298# request must be sent only once, and it must be sent before any requests 299# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 300sub req_Root 301{ 302my($cmd,$data) =@_; 303$log->debug("req_Root :$data"); 304 305unless($data=~ m#^/#) { 306print"error 1 Root must be an absolute pathname\n"; 307return0; 308} 309 310my$cvsroot=$state->{'base-path'} ||''; 311$cvsroot=~ s#/+$##; 312$cvsroot.=$data; 313 314if($state->{CVSROOT} 315&& ($state->{CVSROOT}ne$cvsroot)) { 316print"error 1 Conflicting roots specified\n"; 317return0; 318} 319 320$state->{CVSROOT} =$cvsroot; 321 322$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 323 324if(@{$state->{allowed_roots}}) { 325my$allowed=0; 326foreachmy$dir(@{$state->{allowed_roots}}) { 327next unless$dir=~ m#^/#; 328$dir=~ s#/+$##; 329if($state->{'strict-paths'}) { 330if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 331$allowed=1; 332last; 333} 334}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 335$allowed=1; 336last; 337} 338} 339 340unless($allowed) { 341print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 342print"E\n"; 343print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 344return0; 345} 346} 347 348unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 349print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 350print"E\n"; 351print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 352return0; 353} 354 355my@gitvars=`git config -l`; 356if($?) { 357print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 358print"E\n"; 359print"error 1 - problem executing git-config\n"; 360return0; 361} 362foreachmy$line(@gitvars) 363{ 364next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 365unless($2) { 366$cfg->{$1}{$3} =$4; 367}else{ 368$cfg->{$1}{$2}{$3} =$4; 369} 370} 371 372my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 373||$cfg->{gitcvs}{enabled}); 374unless($state->{'export-all'} || 375($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 376print"E GITCVS emulation needs to be enabled on this repo\n"; 377print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 378print"E\n"; 379print"error 1 GITCVS emulation disabled\n"; 380return0; 381} 382 383my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 384if($logfile) 385{ 386$log->setfile($logfile); 387}else{ 388$log->nofile(); 389} 390 391return1; 392} 393 394# Global_option option \n 395# Response expected: no. Transmit one of the global options `-q', `-Q', 396# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 397# variations (such as combining of options) are allowed. For graceful 398# handling of valid-requests, it is probably better to make new global 399# options separate requests, rather than trying to add them to this 400# request. 401sub req_Globaloption 402{ 403my($cmd,$data) =@_; 404$log->debug("req_Globaloption :$data"); 405$state->{globaloptions}{$data} =1; 406} 407 408# Valid-responses request-list \n 409# Response expected: no. Tell the server what responses the client will 410# accept. request-list is a space separated list of tokens. 411sub req_Validresponses 412{ 413my($cmd,$data) =@_; 414$log->debug("req_Validresponses :$data"); 415 416# TODO : re-enable this, currently it's not particularly useful 417#$state->{validresponses} = [ split /\s+/, $data ]; 418} 419 420# valid-requests \n 421# Response expected: yes. Ask the server to send back a Valid-requests 422# response. 423sub req_validrequests 424{ 425my($cmd,$data) =@_; 426 427$log->debug("req_validrequests"); 428 429$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 430$log->debug("SEND : ok"); 431 432print"Valid-requests ".join(" ",keys%$methods) ."\n"; 433print"ok\n"; 434} 435 436# Directory local-directory \n 437# Additional data: repository \n. Response expected: no. Tell the server 438# what directory to use. The repository should be a directory name from a 439# previous server response. Note that this both gives a default for Entry 440# and Modified and also for ci and the other commands; normal usage is to 441# send Directory for each directory in which there will be an Entry or 442# Modified, and then a final Directory for the original directory, then the 443# command. The local-directory is relative to the top level at which the 444# command is occurring (i.e. the last Directory which is sent before the 445# command); to indicate that top level, `.' should be sent for 446# local-directory. 447sub req_Directory 448{ 449my($cmd,$data) =@_; 450 451my$repository= <STDIN>; 452chomp$repository; 453 454 455$state->{localdir} =$data; 456$state->{repository} =$repository; 457$state->{path} =$repository; 458$state->{path} =~s/^\Q$state->{CVSROOT}\E\///; 459$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 460$state->{path} .="/"if($state->{path} =~ /\S/ ); 461 462$state->{directory} =$state->{localdir}; 463$state->{directory} =""if($state->{directory}eq"."); 464$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 465 466if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 467{ 468$log->info("Setting prepend to '$state->{path}'"); 469$state->{prependdir} =$state->{path}; 470foreachmy$entry(keys%{$state->{entries}} ) 471{ 472$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 473delete$state->{entries}{$entry}; 474} 475} 476 477if(defined($state->{prependdir} ) ) 478{ 479$log->debug("Prepending '$state->{prependdir}' to state|directory"); 480$state->{directory} =$state->{prependdir} .$state->{directory} 481} 482$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 483} 484 485# Entry entry-line \n 486# Response expected: no. Tell the server what version of a file is on the 487# local machine. The name in entry-line is a name relative to the directory 488# most recently specified with Directory. If the user is operating on only 489# some files in a directory, Entry requests for only those files need be 490# included. If an Entry request is sent without Modified, Is-modified, or 491# Unchanged, it means the file is lost (does not exist in the working 492# directory). If both Entry and one of Modified, Is-modified, or Unchanged 493# are sent for the same file, Entry must be sent first. For a given file, 494# one can send Modified, Is-modified, or Unchanged, but not more than one 495# of these three. 496sub req_Entry 497{ 498my($cmd,$data) =@_; 499 500#$log->debug("req_Entry : $data"); 501 502my@data=split(/\//,$data); 503 504$state->{entries}{$state->{directory}.$data[1]} = { 505 revision =>$data[2], 506 conflict =>$data[3], 507 options =>$data[4], 508 tag_or_date =>$data[5], 509}; 510 511$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 512} 513 514# Questionable filename \n 515# Response expected: no. Additional data: no. Tell the server to check 516# whether filename should be ignored, and if not, next time the server 517# sends responses, send (in a M response) `?' followed by the directory and 518# filename. filename must not contain `/'; it needs to be a file in the 519# directory named by the most recent Directory request. 520sub req_Questionable 521{ 522my($cmd,$data) =@_; 523 524$log->debug("req_Questionable :$data"); 525$state->{entries}{$state->{directory}.$data}{questionable} =1; 526} 527 528# add \n 529# Response expected: yes. Add a file or directory. This uses any previous 530# Argument, Directory, Entry, or Modified requests, if they have been sent. 531# The last Directory sent specifies the working directory at the time of 532# the operation. To add a directory, send the directory to be added using 533# Directory and Argument requests. 534sub req_add 535{ 536my($cmd,$data) =@_; 537 538 argsplit("add"); 539 540my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 541$updater->update(); 542 543 argsfromdir($updater); 544 545my$addcount=0; 546 547foreachmy$filename( @{$state->{args}} ) 548{ 549$filename= filecleanup($filename); 550 551my$meta=$updater->getmeta($filename); 552my$wrev= revparse($filename); 553 554if($wrev&&$meta&& ($wrev<0)) 555{ 556# previously removed file, add back 557$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 558 559print"MT +updated\n"; 560print"MT text U\n"; 561print"MT fname$filename\n"; 562print"MT newline\n"; 563print"MT -updated\n"; 564 565unless($state->{globaloptions}{-n} ) 566{ 567my($filepart,$dirpart) = filenamesplit($filename,1); 568 569print"Created$dirpart\n"; 570print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 571 572# this is an "entries" line 573my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 574$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 575print"/$filepart/1.$meta->{revision}//$kopts/\n"; 576# permissions 577$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 578print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 579# transmit file 580 transmitfile($meta->{filehash}); 581} 582 583next; 584} 585 586unless(defined($state->{entries}{$filename}{modified_filename} ) ) 587{ 588print"E cvs add: nothing known about `$filename'\n"; 589next; 590} 591# TODO : check we're not squashing an already existing file 592if(defined($state->{entries}{$filename}{revision} ) ) 593{ 594print"E cvs add: `$filename' has already been entered\n"; 595next; 596} 597 598my($filepart,$dirpart) = filenamesplit($filename,1); 599 600print"E cvs add: scheduling file `$filename' for addition\n"; 601 602print"Checked-in$dirpart\n"; 603print"$filename\n"; 604my$kopts= kopts_from_path($filename,"file", 605$state->{entries}{$filename}{modified_filename}); 606print"/$filepart/0//$kopts/\n"; 607 608my$requestedKopts=$state->{opt}{k}; 609if(defined($requestedKopts)) 610{ 611$requestedKopts="-k$requestedKopts"; 612} 613else 614{ 615$requestedKopts=""; 616} 617if($koptsne$requestedKopts) 618{ 619$log->warn("Ignoring requested -k='$requestedKopts'" 620." for '$filename'; detected -k='$kopts' instead"); 621#TODO: Also have option to send warning to user? 622} 623 624$addcount++; 625} 626 627if($addcount==1) 628{ 629print"E cvs add: use `cvs commit' to add this file permanently\n"; 630} 631elsif($addcount>1) 632{ 633print"E cvs add: use `cvs commit' to add these files permanently\n"; 634} 635 636print"ok\n"; 637} 638 639# remove \n 640# Response expected: yes. Remove a file. This uses any previous Argument, 641# Directory, Entry, or Modified requests, if they have been sent. The last 642# Directory sent specifies the working directory at the time of the 643# operation. Note that this request does not actually do anything to the 644# repository; the only effect of a successful remove request is to supply 645# the client with a new entries line containing `-' to indicate a removed 646# file. In fact, the client probably could perform this operation without 647# contacting the server, although using remove may cause the server to 648# perform a few more checks. The client sends a subsequent ci request to 649# actually record the removal in the repository. 650sub req_remove 651{ 652my($cmd,$data) =@_; 653 654 argsplit("remove"); 655 656# Grab a handle to the SQLite db and do any necessary updates 657my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 658$updater->update(); 659 660#$log->debug("add state : " . Dumper($state)); 661 662my$rmcount=0; 663 664foreachmy$filename( @{$state->{args}} ) 665{ 666$filename= filecleanup($filename); 667 668if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 669{ 670print"E cvs remove: file `$filename' still in working directory\n"; 671next; 672} 673 674my$meta=$updater->getmeta($filename); 675my$wrev= revparse($filename); 676 677unless(defined($wrev) ) 678{ 679print"E cvs remove: nothing known about `$filename'\n"; 680next; 681} 682 683if(defined($wrev)and$wrev<0) 684{ 685print"E cvs remove: file `$filename' already scheduled for removal\n"; 686next; 687} 688 689unless($wrev==$meta->{revision} ) 690{ 691# TODO : not sure if the format of this message is quite correct. 692print"E cvs remove: Up to date check failed for `$filename'\n"; 693next; 694} 695 696 697my($filepart,$dirpart) = filenamesplit($filename,1); 698 699print"E cvs remove: scheduling `$filename' for removal\n"; 700 701print"Checked-in$dirpart\n"; 702print"$filename\n"; 703my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash}); 704print"/$filepart/-1.$wrev//$kopts/\n"; 705 706$rmcount++; 707} 708 709if($rmcount==1) 710{ 711print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 712} 713elsif($rmcount>1) 714{ 715print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 716} 717 718print"ok\n"; 719} 720 721# Modified filename \n 722# Response expected: no. Additional data: mode, \n, file transmission. Send 723# the server a copy of one locally modified file. filename is a file within 724# the most recent directory sent with Directory; it must not contain `/'. 725# If the user is operating on only some files in a directory, only those 726# files need to be included. This can also be sent without Entry, if there 727# is no entry for the file. 728sub req_Modified 729{ 730my($cmd,$data) =@_; 731 732my$mode= <STDIN>; 733defined$mode 734or(print"E end of file reading mode for$data\n"),return; 735chomp$mode; 736my$size= <STDIN>; 737defined$size 738or(print"E end of file reading size of$data\n"),return; 739chomp$size; 740 741# Grab config information 742my$blocksize=8192; 743my$bytesleft=$size; 744my$tmp; 745 746# Get a filehandle/name to write it to 747my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 748 749# Loop over file data writing out to temporary file. 750while($bytesleft) 751{ 752$blocksize=$bytesleftif($bytesleft<$blocksize); 753read STDIN,$tmp,$blocksize; 754print$fh $tmp; 755$bytesleft-=$blocksize; 756} 757 758close$fh 759or(print"E failed to write temporary,$filename:$!\n"),return; 760 761# Ensure we have something sensible for the file mode 762if($mode=~/u=(\w+)/) 763{ 764$mode=$1; 765}else{ 766$mode="rw"; 767} 768 769# Save the file data in $state 770$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 771$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 772$state->{entries}{$state->{directory}.$data}{modified_hash} =`git hash-object$filename`; 773$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 774 775 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 776} 777 778# Unchanged filename\n 779# Response expected: no. Tell the server that filename has not been 780# modified in the checked out directory. The filename is a file within the 781# most recent directory sent with Directory; it must not contain `/'. 782sub req_Unchanged 783{ 784 my ($cmd,$data) =@_; 785 786$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 787 788 #$log->debug("req_Unchanged :$data"); 789} 790 791# Argument text\n 792# Response expected: no. Save argument for use in a subsequent command. 793# Arguments accumulate until an argument-using command is given, at which 794# point they are forgotten. 795# Argumentx text\n 796# Response expected: no. Append\nfollowed by text to the current argument 797# being saved. 798sub req_Argument 799{ 800 my ($cmd,$data) =@_; 801 802 # Argumentx means: append to last Argument (with a newline in front) 803 804$log->debug("$cmd:$data"); 805 806 if ($cmdeq 'Argumentx') { 807 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 808 } else { 809 push @{$state->{arguments}},$data; 810 } 811} 812 813# expand-modules\n 814# Response expected: yes. Expand the modules which are specified in the 815# arguments. Returns the data in Module-expansion responses. Note that the 816# server can assume that this is checkout or export, not rtag or rdiff; the 817# latter do not access the working directory and thus have no need to 818# expand modules on the client side. Expand may not be the best word for 819# what this request does. It does not necessarily tell you all the files 820# contained in a module, for example. Basically it is a way of telling you 821# which working directories the server needs to know about in order to 822# handle a checkout of the specified modules. For example, suppose that the 823# server has a module defined by 824# aliasmodule -a 1dir 825# That is, one can check out aliasmodule and it will take 1dir in the 826# repository and check it out to 1dir in the working directory. Now suppose 827# the client already has this module checked out and is planning on using 828# the co request to update it. Without using expand-modules, the client 829# would have two bad choices: it could either send information about all 830# working directories under the current directory, which could be 831# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 832# stands for 1dir, and neglect to send information for 1dir, which would 833# lead to incorrect operation. With expand-modules, the client would first 834# ask for the module to be expanded: 835sub req_expandmodules 836{ 837 my ($cmd,$data) =@_; 838 839 argsplit(); 840 841$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 842 843 unless ( ref$state->{arguments} eq "ARRAY" ) 844 { 845 print "ok\n"; 846 return; 847 } 848 849 foreach my$module( @{$state->{arguments}} ) 850 { 851$log->debug("SEND : Module-expansion$module"); 852 print "Module-expansion$module\n"; 853 } 854 855 print "ok\n"; 856 statecleanup(); 857} 858 859# co\n 860# Response expected: yes. Get files from the repository. This uses any 861# previous Argument, Directory, Entry, or Modified requests, if they have 862# been sent. Arguments to this command are module names; the client cannot 863# know what directories they correspond to except by (1) just sending the 864# co request, and then seeing what directory names the server sends back in 865# its responses, and (2) the expand-modules request. 866sub req_co 867{ 868 my ($cmd,$data) =@_; 869 870 argsplit("co"); 871 872 # Provide list of modules, if -c was used. 873 if (exists$state->{opt}{c}) { 874 my$showref= `git show-ref --heads`; 875 for my$line(split '\n',$showref) { 876 if ($line=~ m% refs/heads/(.*)$%) { 877 print "M$1\t$1\n"; 878 } 879 } 880 print "ok\n"; 881 return 1; 882 } 883 884 my$module=$state->{args}[0]; 885$state->{module} =$module; 886 my$checkout_path=$module; 887 888 # use the user specified directory if we're given it 889$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 890 891$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 892 893$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 894 895$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 896 897# Grab a handle to the SQLite db and do any necessary updates 898my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 899$updater->update(); 900 901$checkout_path=~ s|/$||;# get rid of trailing slashes 902 903# Eclipse seems to need the Clear-sticky command 904# to prepare the 'Entries' file for the new directory. 905print"Clear-sticky$checkout_path/\n"; 906print$state->{CVSROOT} ."/$module/\n"; 907print"Clear-static-directory$checkout_path/\n"; 908print$state->{CVSROOT} ."/$module/\n"; 909print"Clear-sticky$checkout_path/\n";# yes, twice 910print$state->{CVSROOT} ."/$module/\n"; 911print"Template$checkout_path/\n"; 912print$state->{CVSROOT} ."/$module/\n"; 913print"0\n"; 914 915# instruct the client that we're checking out to $checkout_path 916print"E cvs checkout: Updating$checkout_path\n"; 917 918my%seendirs= (); 919my$lastdir=''; 920 921# recursive 922sub prepdir { 923my($dir,$repodir,$remotedir,$seendirs) =@_; 924my$parent= dirname($dir); 925$dir=~ s|/+$||; 926$repodir=~ s|/+$||; 927$remotedir=~ s|/+$||; 928$parent=~ s|/+$||; 929$log->debug("announcedir$dir,$repodir,$remotedir"); 930 931if($parenteq'.'||$parenteq'./') { 932$parent=''; 933} 934# recurse to announce unseen parents first 935if(length($parent) && !exists($seendirs->{$parent})) { 936 prepdir($parent,$repodir,$remotedir,$seendirs); 937} 938# Announce that we are going to modify at the parent level 939if($parent) { 940print"E cvs checkout: Updating$remotedir/$parent\n"; 941}else{ 942print"E cvs checkout: Updating$remotedir\n"; 943} 944print"Clear-sticky$remotedir/$parent/\n"; 945print"$repodir/$parent/\n"; 946 947print"Clear-static-directory$remotedir/$dir/\n"; 948print"$repodir/$dir/\n"; 949print"Clear-sticky$remotedir/$parent/\n";# yes, twice 950print"$repodir/$parent/\n"; 951print"Template$remotedir/$dir/\n"; 952print"$repodir/$dir/\n"; 953print"0\n"; 954 955$seendirs->{$dir} =1; 956} 957 958foreachmy$git( @{$updater->gethead} ) 959{ 960# Don't want to check out deleted files 961next if($git->{filehash}eq"deleted"); 962 963my$fullName=$git->{name}; 964($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 965 966if(length($git->{dir}) &&$git->{dir}ne'./' 967&&$git->{dir}ne$lastdir) { 968unless(exists($seendirs{$git->{dir}})) { 969 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 970$checkout_path, \%seendirs); 971$lastdir=$git->{dir}; 972$seendirs{$git->{dir}} =1; 973} 974print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 975} 976 977# modification time of this file 978print"Mod-time$git->{modified}\n"; 979 980# print some information to the client 981if(defined($git->{dir} )and$git->{dir}ne"./") 982{ 983print"M U$checkout_path/$git->{dir}$git->{name}\n"; 984}else{ 985print"M U$checkout_path/$git->{name}\n"; 986} 987 988# instruct client we're sending a file to put in this path 989print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 990 991print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 992 993# this is an "entries" line 994my$kopts= kopts_from_path($fullName,"sha1",$git->{filehash}); 995print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 996# permissions 997print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 998 999# transmit file1000 transmitfile($git->{filehash});1001}10021003print"ok\n";10041005 statecleanup();1006}10071008# update \n1009# Response expected: yes. Actually do a cvs update command. This uses any1010# previous Argument, Directory, Entry, or Modified requests, if they have1011# been sent. The last Directory sent specifies the working directory at the1012# time of the operation. The -I option is not used--files which the client1013# can decide whether to ignore are not mentioned and the client sends the1014# Questionable request for others.1015sub req_update1016{1017my($cmd,$data) =@_;10181019$log->debug("req_update : ". (defined($data) ?$data:"[NULL]"));10201021 argsplit("update");10221023#1024# It may just be a client exploring the available heads/modules1025# in that case, list them as top level directories and leave it1026# at that. Eclipse uses this technique to offer you a list of1027# projects (heads in this case) to checkout.1028#1029if($state->{module}eq'') {1030my$showref=`git show-ref --heads`;1031print"E cvs update: Updating .\n";1032formy$line(split'\n',$showref) {1033if($line=~ m% refs/heads/(.*)$%) {1034print"E cvs update: New directory `$1'\n";1035}1036}1037print"ok\n";1038return1;1039}104010411042# Grab a handle to the SQLite db and do any necessary updates1043my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);10441045$updater->update();10461047 argsfromdir($updater);10481049#$log->debug("update state : " . Dumper($state));10501051my$last_dirname="///";10521053# foreach file specified on the command line ...1054foreachmy$filename( @{$state->{args}} )1055{1056$filename= filecleanup($filename);10571058$log->debug("Processing file$filename");10591060unless($state->{globaloptions}{-Q} ||$state->{globaloptions}{-q} )1061{1062my$cur_dirname= dirname($filename);1063if($cur_dirnamene$last_dirname)1064{1065$last_dirname=$cur_dirname;1066if($cur_dirnameeq"")1067{1068$cur_dirname=".";1069}1070print"E cvs update: Updating$cur_dirname\n";1071}1072}10731074# if we have a -C we should pretend we never saw modified stuff1075if(exists($state->{opt}{C} ) )1076{1077delete$state->{entries}{$filename}{modified_hash};1078delete$state->{entries}{$filename}{modified_filename};1079$state->{entries}{$filename}{unchanged} =1;1080}10811082my$meta;1083if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/)1084{1085$meta=$updater->getmeta($filename,$1);1086}else{1087$meta=$updater->getmeta($filename);1088}10891090# If -p was given, "print" the contents of the requested revision.1091if(exists($state->{opt}{p} ) ) {1092if(defined($meta->{revision} ) ) {1093$log->info("Printing '$filename' revision ".$meta->{revision});10941095 transmitfile($meta->{filehash}, {print=>1});1096}10971098next;1099}11001101if( !defined$meta)1102{1103$meta= {1104 name =>$filename,1105 revision =>0,1106 filehash =>'added'1107};1108}11091110my$oldmeta=$meta;11111112my$wrev= revparse($filename);11131114# If the working copy is an old revision, lets get that version too for comparison.1115if(defined($wrev)and$wrev!=$meta->{revision} )1116{1117$oldmeta=$updater->getmeta($filename,$wrev);1118}11191120#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");11211122# Files are up to date if the working copy and repo copy have the same revision,1123# and the working copy is unmodified _and_ the user hasn't specified -C1124next if(defined($wrev)1125and defined($meta->{revision})1126and$wrev==$meta->{revision}1127and$state->{entries}{$filename}{unchanged}1128and not exists($state->{opt}{C} ) );11291130# If the working copy and repo copy have the same revision,1131# but the working copy is modified, tell the client it's modified1132if(defined($wrev)1133and defined($meta->{revision})1134and$wrev==$meta->{revision}1135and defined($state->{entries}{$filename}{modified_hash})1136and not exists($state->{opt}{C} ) )1137{1138$log->info("Tell the client the file is modified");1139print"MT text M\n";1140print"MT fname$filename\n";1141print"MT newline\n";1142next;1143}11441145if($meta->{filehash}eq"deleted")1146{1147my($filepart,$dirpart) = filenamesplit($filename,1);11481149$log->info("Removing '$filename' from working copy (no longer in the repo)");11501151print"E cvs update: `$filename' is no longer in the repository\n";1152# Don't want to actually _DO_ the update if -n specified1153unless($state->{globaloptions}{-n} ) {1154print"Removed$dirpart\n";1155print"$filepart\n";1156}1157}1158elsif(not defined($state->{entries}{$filename}{modified_hash} )1159or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1160or$meta->{filehash}eq'added')1161{1162# normal update, just send the new revision (either U=Update,1163# or A=Add, or R=Remove)1164if(defined($wrev) &&$wrev<0)1165{1166$log->info("Tell the client the file is scheduled for removal");1167print"MT text R\n";1168print"MT fname$filename\n";1169print"MT newline\n";1170next;1171}1172elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1173{1174$log->info("Tell the client the file is scheduled for addition");1175print"MT text A\n";1176print"MT fname$filename\n";1177print"MT newline\n";1178next;11791180}1181else{1182$log->info("Updating '$filename' to ".$meta->{revision});1183print"MT +updated\n";1184print"MT text U\n";1185print"MT fname$filename\n";1186print"MT newline\n";1187print"MT -updated\n";1188}11891190my($filepart,$dirpart) = filenamesplit($filename,1);11911192# Don't want to actually _DO_ the update if -n specified1193unless($state->{globaloptions}{-n} )1194{1195if(defined($wrev) )1196{1197# instruct client we're sending a file to put in this path as a replacement1198print"Update-existing$dirpart\n";1199$log->debug("Updating existing file 'Update-existing$dirpart'");1200}else{1201# instruct client we're sending a file to put in this path as a new file1202print"Clear-static-directory$dirpart\n";1203print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1204print"Clear-sticky$dirpart\n";1205print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";12061207$log->debug("Creating new file 'Created$dirpart'");1208print"Created$dirpart\n";1209}1210print$state->{CVSROOT} ."/$state->{module}/$filename\n";12111212# this is an "entries" line1213my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1214$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1215print"/$filepart/1.$meta->{revision}//$kopts/\n";12161217# permissions1218$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1219print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12201221# transmit file1222 transmitfile($meta->{filehash});1223}1224}else{1225$log->info("Updating '$filename'");1226my($filepart,$dirpart) = filenamesplit($meta->{name},1);12271228my$mergeDir= setupTmpDir();12291230my$file_local=$filepart.".mine";1231my$mergedFile="$mergeDir/$file_local";1232system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1233my$file_old=$filepart.".".$oldmeta->{revision};1234 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1235my$file_new=$filepart.".".$meta->{revision};1236 transmitfile($meta->{filehash}, { targetfile =>$file_new});12371238# we need to merge with the local changes ( M=successful merge, C=conflict merge )1239$log->info("Merging$file_local,$file_old,$file_new");1240print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";12411242$log->debug("Temporary directory for merge is$mergeDir");12431244my$return=system("git","merge-file",$file_local,$file_old,$file_new);1245$return>>=8;12461247 cleanupTmpDir();12481249if($return==0)1250{1251$log->info("Merged successfully");1252print"M M$filename\n";1253$log->debug("Merged$dirpart");12541255# Don't want to actually _DO_ the update if -n specified1256unless($state->{globaloptions}{-n} )1257{1258print"Merged$dirpart\n";1259$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1260print$state->{CVSROOT} ."/$state->{module}/$filename\n";1261my$kopts= kopts_from_path("$dirpart/$filepart",1262"file",$mergedFile);1263$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1264print"/$filepart/1.$meta->{revision}//$kopts/\n";1265}1266}1267elsif($return==1)1268{1269$log->info("Merged with conflicts");1270print"E cvs update: conflicts found in$filename\n";1271print"M C$filename\n";12721273# Don't want to actually _DO_ the update if -n specified1274unless($state->{globaloptions}{-n} )1275{1276print"Merged$dirpart\n";1277print$state->{CVSROOT} ."/$state->{module}/$filename\n";1278my$kopts= kopts_from_path("$dirpart/$filepart",1279"file",$mergedFile);1280print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1281}1282}1283else1284{1285$log->warn("Merge failed");1286next;1287}12881289# Don't want to actually _DO_ the update if -n specified1290unless($state->{globaloptions}{-n} )1291{1292# permissions1293$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1294print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12951296# transmit file, format is single integer on a line by itself (file1297# size) followed by the file contents1298# TODO : we should copy files in blocks1299my$data=`cat$mergedFile`;1300$log->debug("File size : " . length($data));1301 print length($data) . "\n";1302 print$data;1303 }1304 }13051306 }13071308 print "ok\n";1309}13101311sub req_ci1312{1313 my ($cmd,$data) =@_;13141315 argsplit("ci");13161317 #$log->debug("State : " . Dumper($state));13181319$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));13201321 if ($state->{method} eq 'pserver' and$state->{user} eq 'anonymous' )1322 {1323 print "error 1 anonymous user cannot commit via pserver\n";1324 cleanupWorkTree();1325 exit;1326 }13271328 if ( -e$state->{CVSROOT} . "/index" )1329 {1330$log->warn("file 'index' already exists in the git repository");1331 print "error 1 Index already exists in git repo\n";1332 cleanupWorkTree();1333 exit;1334 }13351336 # Grab a handle to the SQLite db and do any necessary updates1337 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1338$updater->update();13391340 # Remember where the head was at the beginning.1341 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1342 chomp$parenthash;1343 if ($parenthash!~ /^[0-9a-f]{40}$/) {1344 print "error 1 pserver cannot find the current HEAD of module";1345 cleanupWorkTree();1346 exit;1347 }13481349 setupWorkTree($parenthash);13501351$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");13521353$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");13541355 my@committedfiles= ();1356 my%oldmeta;13571358 # foreach file specified on the command line ...1359 foreach my$filename( @{$state->{args}} )1360 {1361 my$committedfile=$filename;1362$filename= filecleanup($filename);13631364 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );13651366 my$meta=$updater->getmeta($filename);1367$oldmeta{$filename} =$meta;13681369 my$wrev= revparse($filename);13701371 my ($filepart,$dirpart) = filenamesplit($filename);13721373 # do a checkout of the file if it is part of this tree1374 if ($wrev) {1375 system('git', 'checkout-index', '-f', '-u',$filename);1376 unless ($?== 0) {1377 die "Error running git-checkout-index -f -u$filename:$!";1378 }1379 }13801381 my$addflag= 0;1382 my$rmflag= 0;1383$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1384$addflag= 1 unless ( -e$filename);13851386 # Do up to date checking1387 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1388 {1389 # fail everything if an up to date check fails1390 print "error 1 Up to date check failed for$filename\n";1391 cleanupWorkTree();1392 exit;1393 }13941395 push@committedfiles,$committedfile;1396$log->info("Committing$filename");13971398 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13991400 unless ($rmflag)1401 {1402$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1403 rename$state->{entries}{$filename}{modified_filename},$filename;14041405 # Calculate modes to remove1406 my$invmode= "";1407 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }14081409$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1410 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1411 }14121413 if ($rmflag)1414 {1415$log->info("Removing file '$filename'");1416 unlink($filename);1417 system("git", "update-index", "--remove",$filename);1418 }1419 elsif ($addflag)1420 {1421$log->info("Adding file '$filename'");1422 system("git", "update-index", "--add",$filename);1423 } else {1424$log->info("Updating file '$filename'");1425 system("git", "update-index",$filename);1426 }1427 }14281429 unless ( scalar(@committedfiles) > 0 )1430 {1431 print "E No files to commit\n";1432 print "ok\n";1433 cleanupWorkTree();1434 return;1435 }14361437 my$treehash= `git write-tree`;1438 chomp$treehash;14391440$log->debug("Treehash :$treehash, Parenthash :$parenthash");14411442 # write our commit message out if we have one ...1443 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1444 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1445 if ( defined ($cfg->{gitcvs}{commitmsgannotation} ) ) {1446 if ($cfg->{gitcvs}{commitmsgannotation} !~ /^\s*$/) {1447 print$msg_fh"\n\n".$cfg->{gitcvs}{commitmsgannotation}."\n"1448 }1449 } else {1450 print$msg_fh"\n\nvia git-CVS emulator\n";1451 }1452 close$msg_fh;14531454 my$commithash= `git commit-tree $treehash-p $parenthash<$msg_filename`;1455chomp($commithash);1456$log->info("Commit hash :$commithash");14571458unless($commithash=~/[a-zA-Z0-9]{40}/)1459{1460$log->warn("Commit failed (Invalid commit hash)");1461print"error 1 Commit failed (unknown reason)\n";1462 cleanupWorkTree();1463exit;1464}14651466### Emulate git-receive-pack by running hooks/update1467my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1468$parenthash,$commithash);1469if( -x $hook[0] ) {1470unless(system(@hook) ==0)1471{1472$log->warn("Commit failed (update hook declined to update ref)");1473print"error 1 Commit failed (update hook declined)\n";1474 cleanupWorkTree();1475exit;1476}1477}14781479### Update the ref1480if(system(qw(git update-ref -m),"cvsserver ci",1481"refs/heads/$state->{module}",$commithash,$parenthash)) {1482$log->warn("update-ref for$state->{module} failed.");1483print"error 1 Cannot commit -- update first\n";1484 cleanupWorkTree();1485exit;1486}14871488### Emulate git-receive-pack by running hooks/post-receive1489my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1490if( -x $hook) {1491open(my$pipe,"|$hook") ||die"can't fork$!";14921493local$SIG{PIPE} =sub{die'pipe broke'};14941495print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";14961497close$pipe||die"bad pipe:$!$?";1498}14991500$updater->update();15011502### Then hooks/post-update1503$hook=$ENV{GIT_DIR}.'hooks/post-update';1504if(-x $hook) {1505system($hook,"refs/heads/$state->{module}");1506}15071508# foreach file specified on the command line ...1509foreachmy$filename(@committedfiles)1510{1511$filename= filecleanup($filename);15121513my$meta=$updater->getmeta($filename);1514unless(defined$meta->{revision}) {1515$meta->{revision} =1;1516}15171518my($filepart,$dirpart) = filenamesplit($filename,1);15191520$log->debug("Checked-in$dirpart:$filename");15211522print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1523if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1524{1525print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1526print"Remove-entry$dirpart\n";1527print"$filename\n";1528}else{1529if($meta->{revision} ==1) {1530print"M initial revision: 1.1\n";1531}else{1532print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1533}1534print"Checked-in$dirpart\n";1535print"$filename\n";1536my$kopts= kopts_from_path($filename,"sha1",$meta->{filehash});1537print"/$filepart/1.$meta->{revision}//$kopts/\n";1538}1539}15401541 cleanupWorkTree();1542print"ok\n";1543}15441545sub req_status1546{1547my($cmd,$data) =@_;15481549 argsplit("status");15501551$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1552#$log->debug("status state : " . Dumper($state));15531554# Grab a handle to the SQLite db and do any necessary updates1555my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1556$updater->update();15571558# if no files were specified, we need to work out what files we should be providing status on ...1559 argsfromdir($updater);15601561# foreach file specified on the command line ...1562foreachmy$filename( @{$state->{args}} )1563{1564$filename= filecleanup($filename);15651566next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;15671568my$meta=$updater->getmeta($filename);1569my$oldmeta=$meta;15701571my$wrev= revparse($filename);15721573# If the working copy is an old revision, lets get that version too for comparison.1574if(defined($wrev)and$wrev!=$meta->{revision} )1575{1576$oldmeta=$updater->getmeta($filename,$wrev);1577}15781579# TODO : All possible statuses aren't yet implemented1580my$status;1581# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1582$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1583and1584( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1585or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1586);15871588# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1589$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1590and1591($state->{entries}{$filename}{unchanged}1592or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1593);15941595# Need checkout if it exists in the repo but doesn't have a working copy1596$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );15971598# Locally modified if working copy and repo copy have the same revision but there are local changes1599$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );16001601# Needs Merge if working copy revision is less than repo copy and there are local changes1602$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );16031604$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1605$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1606$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1607$status||="File had conflicts on merge"if(0);16081609$status||="Unknown";16101611my($filepart) = filenamesplit($filename);16121613print"M ===================================================================\n";1614print"M File:$filepart\tStatus:$status\n";1615if(defined($state->{entries}{$filename}{revision}) )1616{1617print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1618}else{1619print"M Working revision:\tNo entry for$filename\n";1620}1621if(defined($meta->{revision}) )1622{1623print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1624print"M Sticky Tag:\t\t(none)\n";1625print"M Sticky Date:\t\t(none)\n";1626print"M Sticky Options:\t\t(none)\n";1627}else{1628print"M Repository revision:\tNo revision control file\n";1629}1630print"M\n";1631}16321633print"ok\n";1634}16351636sub req_diff1637{1638my($cmd,$data) =@_;16391640 argsplit("diff");16411642$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1643#$log->debug("status state : " . Dumper($state));16441645my($revision1,$revision2);1646if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1647{1648$revision1=$state->{opt}{r}[0];1649$revision2=$state->{opt}{r}[1];1650}else{1651$revision1=$state->{opt}{r};1652}16531654$revision1=~s/^1\.//if(defined($revision1) );1655$revision2=~s/^1\.//if(defined($revision2) );16561657$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );16581659# Grab a handle to the SQLite db and do any necessary updates1660my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1661$updater->update();16621663# if no files were specified, we need to work out what files we should be providing status on ...1664 argsfromdir($updater);16651666# foreach file specified on the command line ...1667foreachmy$filename( @{$state->{args}} )1668{1669$filename= filecleanup($filename);16701671my($fh,$file1,$file2,$meta1,$meta2,$filediff);16721673my$wrev= revparse($filename);16741675# We need _something_ to diff against1676next unless(defined($wrev) );16771678# if we have a -r switch, use it1679if(defined($revision1) )1680{1681(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1682$meta1=$updater->getmeta($filename,$revision1);1683unless(defined($meta1)and$meta1->{filehash}ne"deleted")1684{1685print"E File$filenameat revision 1.$revision1doesn't exist\n";1686next;1687}1688 transmitfile($meta1->{filehash}, { targetfile =>$file1});1689}1690# otherwise we just use the working copy revision1691else1692{1693(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1694$meta1=$updater->getmeta($filename,$wrev);1695 transmitfile($meta1->{filehash}, { targetfile =>$file1});1696}16971698# if we have a second -r switch, use it too1699if(defined($revision2) )1700{1701(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1702$meta2=$updater->getmeta($filename,$revision2);17031704unless(defined($meta2)and$meta2->{filehash}ne"deleted")1705{1706print"E File$filenameat revision 1.$revision2doesn't exist\n";1707next;1708}17091710 transmitfile($meta2->{filehash}, { targetfile =>$file2});1711}1712# otherwise we just use the working copy1713else1714{1715$file2=$state->{entries}{$filename}{modified_filename};1716}17171718# if we have been given -r, and we don't have a $file2 yet, lets get one1719if(defined($revision1)and not defined($file2) )1720{1721(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1722$meta2=$updater->getmeta($filename,$wrev);1723 transmitfile($meta2->{filehash}, { targetfile =>$file2});1724}17251726# We need to have retrieved something useful1727next unless(defined($meta1) );17281729# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1730next if(not defined($meta2)and$wrev==$meta1->{revision}1731and1732( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1733or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1734);17351736# Apparently we only show diffs for locally modified files1737next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );17381739print"M Index:$filename\n";1740print"M ===================================================================\n";1741print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1742print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1743print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1744print"M diff ";1745foreachmy$opt(keys%{$state->{opt}} )1746{1747if(ref$state->{opt}{$opt}eq"ARRAY")1748{1749foreachmy$value( @{$state->{opt}{$opt}} )1750{1751print"-$opt$value";1752}1753}else{1754print"-$opt";1755print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1756}1757}1758print"$filename\n";17591760$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));17611762($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);17631764if(exists$state->{opt}{u} )1765{1766system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1767}else{1768system("diff$file1$file2>$filediff");1769}17701771while( <$fh> )1772{1773print"M$_";1774}1775close$fh;1776}17771778print"ok\n";1779}17801781sub req_log1782{1783my($cmd,$data) =@_;17841785 argsplit("log");17861787$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1788#$log->debug("log state : " . Dumper($state));17891790my($minrev,$maxrev);1791if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1792{1793my$control=$2;1794$minrev=$1;1795$maxrev=$3;1796$minrev=~s/^1\.//if(defined($minrev) );1797$maxrev=~s/^1\.//if(defined($maxrev) );1798$minrev++if(defined($minrev)and$controleq"::");1799}18001801# Grab a handle to the SQLite db and do any necessary updates1802my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1803$updater->update();18041805# if no files were specified, we need to work out what files we should be providing status on ...1806 argsfromdir($updater);18071808# foreach file specified on the command line ...1809foreachmy$filename( @{$state->{args}} )1810{1811$filename= filecleanup($filename);18121813my$headmeta=$updater->getmeta($filename);18141815my$revisions=$updater->getlog($filename);1816my$totalrevisions=scalar(@$revisions);18171818if(defined($minrev) )1819{1820$log->debug("Removing revisions less than$minrev");1821while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1822{1823pop@$revisions;1824}1825}1826if(defined($maxrev) )1827{1828$log->debug("Removing revisions greater than$maxrev");1829while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1830{1831shift@$revisions;1832}1833}18341835next unless(scalar(@$revisions) );18361837print"M\n";1838print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1839print"M Working file:$filename\n";1840print"M head: 1.$headmeta->{revision}\n";1841print"M branch:\n";1842print"M locks: strict\n";1843print"M access list:\n";1844print"M symbolic names:\n";1845print"M keyword substitution: kv\n";1846print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1847print"M description:\n";18481849foreachmy$revision(@$revisions)1850{1851print"M ----------------------------\n";1852print"M revision 1.$revision->{revision}\n";1853# reformat the date for log output1854$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}) );1855$revision->{author} = cvs_author($revision->{author});1856print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1857my$commitmessage=$updater->commitmessage($revision->{commithash});1858$commitmessage=~s/^/M /mg;1859print$commitmessage."\n";1860}1861print"M =============================================================================\n";1862}18631864print"ok\n";1865}18661867sub req_annotate1868{1869my($cmd,$data) =@_;18701871 argsplit("annotate");18721873$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1874#$log->debug("status state : " . Dumper($state));18751876# Grab a handle to the SQLite db and do any necessary updates1877my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1878$updater->update();18791880# if no files were specified, we need to work out what files we should be providing annotate on ...1881 argsfromdir($updater);18821883# we'll need a temporary checkout dir1884 setupWorkTree();18851886$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");18871888# foreach file specified on the command line ...1889foreachmy$filename( @{$state->{args}} )1890{1891$filename= filecleanup($filename);18921893my$meta=$updater->getmeta($filename);18941895next unless($meta->{revision} );18961897# get all the commits that this file was in1898# in dense format -- aka skip dead revisions1899my$revisions=$updater->gethistorydense($filename);1900my$lastseenin=$revisions->[0][2];19011902# populate the temporary index based on the latest commit were we saw1903# the file -- but do it cheaply without checking out any files1904# TODO: if we got a revision from the client, use that instead1905# to look up the commithash in sqlite (still good to default to1906# the current head as we do now)1907system("git","read-tree",$lastseenin);1908unless($?==0)1909{1910print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1911return;1912}1913$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");19141915# do a checkout of the file1916system('git','checkout-index','-f','-u',$filename);1917unless($?==0) {1918print"E error running git-checkout-index -f -u$filename:$!\n";1919return;1920}19211922$log->info("Annotate$filename");19231924# Prepare a file with the commits from the linearized1925# history that annotate should know about. This prevents1926# git-jsannotate telling us about commits we are hiding1927# from the client.19281929my$a_hints="$work->{workDir}/.annotate_hints";1930if(!open(ANNOTATEHINTS,'>',$a_hints)) {1931print"E failed to open '$a_hints' for writing:$!\n";1932return;1933}1934for(my$i=0;$i<@$revisions;$i++)1935{1936print ANNOTATEHINTS $revisions->[$i][2];1937if($i+1<@$revisions) {# have we got a parent?1938print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1939}1940print ANNOTATEHINTS "\n";1941}19421943print ANNOTATEHINTS "\n";1944close ANNOTATEHINTS1945or(print"E failed to write$a_hints:$!\n"),return;19461947my@cmd= (qw(git annotate -l -S),$a_hints,$filename);1948if(!open(ANNOTATE,"-|",@cmd)) {1949print"E error invoking ".join(' ',@cmd) .":$!\n";1950return;1951}1952my$metadata= {};1953print"E Annotations for$filename\n";1954print"E ***************\n";1955while( <ANNOTATE> )1956{1957if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1958{1959my$commithash=$1;1960my$data=$2;1961unless(defined($metadata->{$commithash} ) )1962{1963$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1964$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1965$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1966}1967printf("M 1.%-5d (%-8s%10s):%s\n",1968$metadata->{$commithash}{revision},1969$metadata->{$commithash}{author},1970$metadata->{$commithash}{modified},1971$data1972);1973}else{1974$log->warn("Error in annotate output! LINE:$_");1975print"E Annotate error\n";1976next;1977}1978}1979close ANNOTATE;1980}19811982# done; get out of the tempdir1983 cleanupWorkTree();19841985print"ok\n";19861987}19881989# This method takes the state->{arguments} array and produces two new arrays.1990# The first is $state->{args} which is everything before the '--' argument, and1991# the second is $state->{files} which is everything after it.1992sub argsplit1993{1994$state->{args} = [];1995$state->{files} = [];1996$state->{opt} = {};19971998return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19992000my$type=shift;20012002if(defined($type) )2003{2004my$opt= {};2005$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");2006$opt= { v =>0, l =>0, R =>0}if($typeeq"status");2007$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");2008$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");2009$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");2010$opt= { k =>1, m =>1}if($typeeq"add");2011$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");2012$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");201320142015while(scalar( @{$state->{arguments}} ) >0)2016{2017my$arg=shift@{$state->{arguments}};20182019next if($argeq"--");2020next unless($arg=~/\S/);20212022# if the argument looks like a switch2023if($arg=~/^-(\w)(.*)/)2024{2025# if it's a switch that takes an argument2026if($opt->{$1} )2027{2028# If this switch has already been provided2029if($opt->{$1} >1and exists($state->{opt}{$1} ) )2030{2031$state->{opt}{$1} = [$state->{opt}{$1} ];2032if(length($2) >0)2033{2034push@{$state->{opt}{$1}},$2;2035}else{2036push@{$state->{opt}{$1}},shift@{$state->{arguments}};2037}2038}else{2039# if there's extra data in the arg, use that as the argument for the switch2040if(length($2) >0)2041{2042$state->{opt}{$1} =$2;2043}else{2044$state->{opt}{$1} =shift@{$state->{arguments}};2045}2046}2047}else{2048$state->{opt}{$1} =undef;2049}2050}2051else2052{2053push@{$state->{args}},$arg;2054}2055}2056}2057else2058{2059my$mode=0;20602061foreachmy$value( @{$state->{arguments}} )2062{2063if($valueeq"--")2064{2065$mode++;2066next;2067}2068push@{$state->{args}},$valueif($mode==0);2069push@{$state->{files}},$valueif($mode==1);2070}2071}2072}20732074# This method uses $state->{directory} to populate $state->{args} with a list of filenames2075sub argsfromdir2076{2077my$updater=shift;20782079$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");20802081return if(scalar( @{$state->{args}} ) >1);20822083my@gethead= @{$updater->gethead};20842085# push added files2086foreachmy$file(keys%{$state->{entries}}) {2087if(exists$state->{entries}{$file}{revision} &&2088$state->{entries}{$file}{revision} ==0)2089{2090push@gethead, { name =>$file, filehash =>'added'};2091}2092}20932094if(scalar(@{$state->{args}}) ==1)2095{2096my$arg=$state->{args}[0];2097$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );20982099$log->info("Only one arg specified, checking for directory expansion on '$arg'");21002101foreachmy$file(@gethead)2102{2103next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2104next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2105push@{$state->{args}},$file->{name};2106}21072108shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2109}else{2110$log->info("Only one arg specified, populating file list automatically");21112112$state->{args} = [];21132114foreachmy$file(@gethead)2115{2116next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2117next unless($file->{name} =~s/^$state->{prependdir}//);2118push@{$state->{args}},$file->{name};2119}2120}2121}21222123# This method cleans up the $state variable after a command that uses arguments has run2124sub statecleanup2125{2126$state->{files} = [];2127$state->{args} = [];2128$state->{arguments} = [];2129$state->{entries} = {};2130}21312132sub revparse2133{2134my$filename=shift;21352136returnundefunless(defined($state->{entries}{$filename}{revision} ) );21372138return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2139return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);21402141returnundef;2142}21432144# This method takes a file hash and does a CVS "file transfer". Its2145# exact behaviour depends on a second, optional hash table argument:2146# - If $options->{targetfile}, dump the contents to that file;2147# - If $options->{print}, use M/MT to transmit the contents one line2148# at a time;2149# - Otherwise, transmit the size of the file, followed by the file2150# contents.2151sub transmitfile2152{2153my$filehash=shift;2154my$options=shift;21552156if(defined($filehash)and$filehasheq"deleted")2157{2158$log->warn("filehash is 'deleted'");2159return;2160}21612162die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);21632164my$type=`git cat-file -t$filehash`;2165 chomp$type;21662167 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );21682169 my$size= `git cat-file -s $filehash`;2170chomp$size;21712172$log->debug("transmitfile($filehash) size=$size, type=$type");21732174if(open my$fh,'-|',"git","cat-file","blob",$filehash)2175{2176if(defined($options->{targetfile} ) )2177{2178my$targetfile=$options->{targetfile};2179open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2180print NEWFILE $_while( <$fh> );2181close NEWFILE or die("Failed to write '$targetfile':$!");2182}elsif(defined($options->{print} ) &&$options->{print} ) {2183while( <$fh> ) {2184if(/\n\z/) {2185print'M ',$_;2186}else{2187print'MT text ',$_,"\n";2188}2189}2190}else{2191print"$size\n";2192printwhile( <$fh> );2193}2194close$fhor die("Couldn't close filehandle for transmitfile():$!");2195}else{2196die("Couldn't execute git-cat-file");2197}2198}21992200# This method takes a file name, and returns ( $dirpart, $filepart ) which2201# refers to the directory portion and the file portion of the filename2202# respectively2203sub filenamesplit2204{2205my$filename=shift;2206my$fixforlocaldir=shift;22072208my($filepart,$dirpart) = ($filename,".");2209($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2210$dirpart.="/";22112212if($fixforlocaldir)2213{2214$dirpart=~s/^$state->{prependdir}//;2215}22162217return($filepart,$dirpart);2218}22192220sub filecleanup2221{2222my$filename=shift;22232224returnundefunless(defined($filename));2225if($filename=~/^\// )2226{2227print"E absolute filenames '$filename' not supported by server\n";2228returnundef;2229}22302231$filename=~s/^\.\///g;2232$filename=$state->{prependdir} .$filename;2233return$filename;2234}22352236sub validateGitDir2237{2238if( !defined($state->{CVSROOT}) )2239{2240print"error 1 CVSROOT not specified\n";2241 cleanupWorkTree();2242exit;2243}2244if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2245{2246print"error 1 Internally inconsistent CVSROOT\n";2247 cleanupWorkTree();2248exit;2249}2250}22512252# Setup working directory in a work tree with the requested version2253# loaded in the index.2254sub setupWorkTree2255{2256my($ver) =@_;22572258 validateGitDir();22592260if( (defined($work->{state}) &&$work->{state} !=1) ||2261defined($work->{tmpDir}) )2262{2263$log->warn("Bad work tree state management");2264print"error 1 Internal setup multiple work trees without cleanup\n";2265 cleanupWorkTree();2266exit;2267}22682269$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);22702271if( !defined($work->{index}) )2272{2273(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2274}22752276chdir$work->{workDir}or2277die"Unable to chdir to$work->{workDir}\n";22782279$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");22802281$ENV{GIT_WORK_TREE} =".";2282$ENV{GIT_INDEX_FILE} =$work->{index};2283$work->{state} =2;22842285if($ver)2286{2287system("git","read-tree",$ver);2288unless($?==0)2289{2290$log->warn("Error running git-read-tree");2291die"Error running git-read-tree$verin$work->{workDir}$!\n";2292}2293}2294# else # req_annotate reads tree for each file2295}22962297# Ensure current directory is in some kind of working directory,2298# with a recent version loaded in the index.2299sub ensureWorkTree2300{2301if(defined($work->{tmpDir}) )2302{2303$log->warn("Bad work tree state management [ensureWorkTree()]");2304print"error 1 Internal setup multiple dirs without cleanup\n";2305 cleanupWorkTree();2306exit;2307}2308if($work->{state} )2309{2310return;2311}23122313 validateGitDir();23142315if( !defined($work->{emptyDir}) )2316{2317$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2318}2319chdir$work->{emptyDir}or2320die"Unable to chdir to$work->{emptyDir}\n";23212322my$ver=`git show-ref -s refs/heads/$state->{module}`;2323chomp$ver;2324if($ver!~/^[0-9a-f]{40}$/)2325{2326$log->warn("Error from git show-ref -s refs/head$state->{module}");2327print"error 1 cannot find the current HEAD of module";2328 cleanupWorkTree();2329exit;2330}23312332if( !defined($work->{index}) )2333{2334(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2335}23362337$ENV{GIT_WORK_TREE} =".";2338$ENV{GIT_INDEX_FILE} =$work->{index};2339$work->{state} =1;23402341system("git","read-tree",$ver);2342unless($?==0)2343{2344die"Error running git-read-tree$ver$!\n";2345}2346}23472348# Cleanup working directory that is not needed any longer.2349sub cleanupWorkTree2350{2351if( !$work->{state} )2352{2353return;2354}23552356chdir"/"or die"Unable to chdir '/'\n";23572358if(defined($work->{workDir}) )2359{2360 rmtree($work->{workDir} );2361undef$work->{workDir};2362}2363undef$work->{state};2364}23652366# Setup a temporary directory (not a working tree), typically for2367# merging dirty state as in req_update.2368sub setupTmpDir2369{2370$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2371chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";23722373return$work->{tmpDir};2374}23752376# Clean up a previously setupTmpDir. Restore previous work tree if2377# appropriate.2378sub cleanupTmpDir2379{2380if( !defined($work->{tmpDir}) )2381{2382$log->warn("cleanup tmpdir that has not been setup");2383die"Cleanup tmpDir that has not been setup\n";2384}2385if(defined($work->{state}) )2386{2387if($work->{state} ==1)2388{2389chdir$work->{emptyDir}or2390die"Unable to chdir to$work->{emptyDir}\n";2391}2392elsif($work->{state} ==2)2393{2394chdir$work->{workDir}or2395die"Unable to chdir to$work->{emptyDir}\n";2396}2397else2398{2399$log->warn("Inconsistent work dir state");2400die"Inconsistent work dir state\n";2401}2402}2403else2404{2405chdir"/"or die"Unable to chdir '/'\n";2406}2407}24082409# Given a path, this function returns a string containing the kopts2410# that should go into that path's Entries line. For example, a binary2411# file should get -kb.2412sub kopts_from_path2413{2414my($path,$srcType,$name) =@_;24152416if(defined($cfg->{gitcvs}{usecrlfattr} )and2417$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2418{2419my($val) = check_attr("text",$path);2420if($valeq"unspecified")2421{2422$val= check_attr("crlf",$path);2423}2424if($valeq"unset")2425{2426return"-kb"2427}2428elsif( check_attr("eol",$path)ne"unspecified"||2429$valeq"set"||$valeq"input")2430{2431return"";2432}2433else2434{2435$log->info("Unrecognized check_attr crlf$path:$val");2436}2437}24382439if(defined($cfg->{gitcvs}{allbinary} ) )2440{2441if( ($cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i) )2442{2443return"-kb";2444}2445elsif( ($cfg->{gitcvs}{allbinary} =~/^\s*guess\s*$/i) )2446{2447if($srcTypeeq"sha1Or-k"&&2448!defined($name) )2449{2450my($ret)=$state->{entries}{$path}{options};2451if( !defined($ret) )2452{2453$ret=$state->{opt}{k};2454if(defined($ret))2455{2456$ret="-k$ret";2457}2458else2459{2460$ret="";2461}2462}2463if( ! ($ret=~/^(|-kb|-kkv|-kkvl|-kk|-ko|-kv)$/) )2464{2465print"E Bad -k option\n";2466$log->warn("Bad -k option:$ret");2467die"Error: Bad -k option:$ret\n";2468}24692470return$ret;2471}2472else2473{2474if( is_binary($srcType,$name) )2475{2476$log->debug("... as binary");2477return"-kb";2478}2479else2480{2481$log->debug("... as text");2482}2483}2484}2485}2486# Return "" to give no special treatment to any path2487return"";2488}24892490sub check_attr2491{2492my($attr,$path) =@_;2493 ensureWorkTree();2494if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2495{2496my$val= <$fh>;2497close$fh;2498$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2499return$val;2500}2501else2502{2503returnundef;2504}2505}25062507# This should have the same heuristics as convert.c:is_binary() and related.2508# Note that the bare CR test is done by callers in convert.c.2509sub is_binary2510{2511my($srcType,$name) =@_;2512$log->debug("is_binary($srcType,$name)");25132514# Minimize amount of interpreted code run in the inner per-character2515# loop for large files, by totalling each character value and2516# then analyzing the totals.2517my@counts;2518my$i;2519for($i=0;$i<256;$i++)2520{2521$counts[$i]=0;2522}25232524my$fh= open_blob_or_die($srcType,$name);2525my$line;2526while(defined($line=<$fh>) )2527{2528# Any '\0' and bare CR are considered binary.2529if($line=~/\0|(\r[^\n])/)2530{2531close($fh);2532return1;2533}25342535# Count up each character in the line:2536my$len=length($line);2537for($i=0;$i<$len;$i++)2538{2539$counts[ord(substr($line,$i,1))]++;2540}2541}2542close$fh;25432544# Don't count CR and LF as either printable/nonprintable2545$counts[ord("\n")]=0;2546$counts[ord("\r")]=0;25472548# Categorize individual character count into printable and nonprintable:2549my$printable=0;2550my$nonprintable=0;2551for($i=0;$i<256;$i++)2552{2553if($i<32&&2554$i!=ord("\b") &&2555$i!=ord("\t") &&2556$i!=033&&# ESC2557$i!=014)# FF2558{2559$nonprintable+=$counts[$i];2560}2561elsif($i==127)# DEL2562{2563$nonprintable+=$counts[$i];2564}2565else2566{2567$printable+=$counts[$i];2568}2569}25702571return($printable>>7) <$nonprintable;2572}25732574# Returns open file handle. Possible invocations:2575# - open_blob_or_die("file",$filename);2576# - open_blob_or_die("sha1",$filehash);2577sub open_blob_or_die2578{2579my($srcType,$name) =@_;2580my($fh);2581if($srcTypeeq"file")2582{2583if( !open$fh,"<",$name)2584{2585$log->warn("Unable to open file$name:$!");2586die"Unable to open file$name:$!\n";2587}2588}2589elsif($srcTypeeq"sha1"||$srcTypeeq"sha1Or-k")2590{2591unless(defined($name)and$name=~/^[a-zA-Z0-9]{40}$/)2592{2593$log->warn("Need filehash");2594die"Need filehash\n";2595}25962597my$type=`git cat-file -t$name`;2598 chomp$type;25992600 unless ( defined ($type) and$typeeq "blob" )2601 {2602$log->warn("Invalid type '$type' for '$name'");2603 die ( "Invalid type '$type' (expected 'blob')" )2604 }26052606 my$size= `git cat-file -s $name`;2607chomp$size;26082609$log->debug("open_blob_or_die($name) size=$size, type=$type");26102611unless(open$fh,'-|',"git","cat-file","blob",$name)2612{2613$log->warn("Unable to open sha1$name");2614die"Unable to open sha1$name\n";2615}2616}2617else2618{2619$log->warn("Unknown type of blob source:$srcType");2620die"Unknown type of blob source:$srcType\n";2621}2622return$fh;2623}26242625# Generate a CVS author name from Git author information, by taking the local2626# part of the email address and replacing characters not in the Portable2627# Filename Character Set (see IEEE Std 1003.1-2001, 3.276) by underscores. CVS2628# Login names are Unix login names, which should be restricted to this2629# character set.2630sub cvs_author2631{2632my$author_line=shift;2633(my$author) =$author_line=~/<([^@>]*)/;26342635$author=~s/[^-a-zA-Z0-9_.]/_/g;2636$author=~s/^-/_/;26372638$author;2639}264026412642sub descramble2643{2644# This table is from src/scramble.c in the CVS source2645my@SHIFTS= (26460,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,264716,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,2648114,120,53,79,96,109,72,108,70,64,76,67,116,74,68,87,2649111,52,75,119,49,34,82,81,95,65,112,86,118,110,122,105,265041,57,83,43,46,102,40,89,38,103,45,50,42,123,91,35,2651125,55,54,66,124,126,59,47,92,71,115,78,88,107,106,56,265236,121,117,104,101,100,69,73,99,63,94,93,39,37,61,48,265358,113,32,90,44,98,60,51,33,97,62,77,84,80,85,223,2654225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190,2655199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193,2656174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212,2657207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246,2658192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176,2659227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127,2660182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195,2661243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,1522662);2663my($str) =@_;26642665# This should never happen, the same password format (A) has been2666# used by CVS since the beginning of time2667{2668my$fmt=substr($str,0,1);2669die"invalid password format `$fmt'"unless$fmteq'A';2670}26712672my@str=unpack"C*",substr($str,1);2673my$ret=join'',map{chr$SHIFTS[$_] }@str;2674return$ret;2675}267626772678package GITCVS::log;26792680####2681#### Copyright The Open University UK - 2006.2682####2683#### Authors: Martyn Smith <martyn@catalyst.net.nz>2684#### Martin Langhoff <martin@laptop.org>2685####2686####26872688use strict;2689use warnings;26902691=head1 NAME26922693GITCVS::log26942695=head1 DESCRIPTION26962697This module provides very crude logging with a similar interface to2698Log::Log4perl26992700=head1 METHODS27012702=cut27032704=head2 new27052706Creates a new log object, optionally you can specify a filename here to2707indicate the file to log to. If no log file is specified, you can specify one2708later with method setfile, or indicate you no longer want logging with method2709nofile.27102711Until one of these methods is called, all log calls will buffer messages ready2712to write out.27132714=cut2715sub new2716{2717my$class=shift;2718my$filename=shift;27192720my$self= {};27212722bless$self,$class;27232724if(defined($filename) )2725{2726open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2727}27282729return$self;2730}27312732=head2 setfile27332734This methods takes a filename, and attempts to open that file as the log file.2735If successful, all buffered data is written out to the file, and any further2736logging is written directly to the file.27372738=cut2739sub setfile2740{2741my$self=shift;2742my$filename=shift;27432744if(defined($filename) )2745{2746open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2747}27482749return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");27502751while(my$line=shift@{$self->{buffer}} )2752{2753print{$self->{fh}}$line;2754}2755}27562757=head2 nofile27582759This method indicates no logging is going to be used. It flushes any entries in2760the internal buffer, and sets a flag to ensure no further data is put there.27612762=cut2763sub nofile2764{2765my$self=shift;27662767$self->{nolog} =1;27682769return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");27702771$self->{buffer} = [];2772}27732774=head2 _logopen27752776Internal method. Returns true if the log file is open, false otherwise.27772778=cut2779sub _logopen2780{2781my$self=shift;27822783return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2784return0;2785}27862787=head2 debug info warn fatal27882789These four methods are wrappers to _log. They provide the actual interface for2790logging data.27912792=cut2793sub debug {my$self=shift;$self->_log("debug",@_); }2794sub info {my$self=shift;$self->_log("info",@_); }2795subwarn{my$self=shift;$self->_log("warn",@_); }2796sub fatal {my$self=shift;$self->_log("fatal",@_); }27972798=head2 _log27992800This is an internal method called by the logging functions. It generates a2801timestamp and pushes the logged line either to file, or internal buffer.28022803=cut2804sub _log2805{2806my$self=shift;2807my$level=shift;28082809return if($self->{nolog} );28102811my@time=localtime;2812my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2813$time[5] +1900,2814$time[4] +1,2815$time[3],2816$time[2],2817$time[1],2818$time[0],2819uc$level,2820);28212822if($self->_logopen)2823{2824print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2825}else{2826push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2827}2828}28292830=head2 DESTROY28312832This method simply closes the file handle if one is open28332834=cut2835sub DESTROY2836{2837my$self=shift;28382839if($self->_logopen)2840{2841close$self->{fh};2842}2843}28442845package GITCVS::updater;28462847####2848#### Copyright The Open University UK - 2006.2849####2850#### Authors: Martyn Smith <martyn@catalyst.net.nz>2851#### Martin Langhoff <martin@laptop.org>2852####2853####28542855use strict;2856use warnings;2857use DBI;28582859=head1 METHODS28602861=cut28622863=head2 new28642865=cut2866sub new2867{2868my$class=shift;2869my$config=shift;2870my$module=shift;2871my$log=shift;28722873die"Need to specify a git repository"unless(defined($config)and-d $config);2874die"Need to specify a module"unless(defined($module) );28752876$class=ref($class) ||$class;28772878my$self= {};28792880bless$self,$class;28812882$self->{valid_tables} = {'revision'=>1,2883'revision_ix1'=>1,2884'revision_ix2'=>1,2885'head'=>1,2886'head_ix1'=>1,2887'properties'=>1,2888'commitmsgs'=>1};28892890$self->{module} =$module;2891$self->{git_path} =$config."/";28922893$self->{log} =$log;28942895die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );28962897$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2898$cfg->{gitcvs}{dbdriver} ||"SQLite";2899$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2900$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2901$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2902$cfg->{gitcvs}{dbuser} ||"";2903$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2904$cfg->{gitcvs}{dbpass} ||"";2905$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2906$cfg->{gitcvs}{dbtablenameprefix} ||"";2907my%mapping= ( m =>$module,2908 a =>$state->{method},2909 u =>getlogin||getpwuid($<) || $<,2910 G =>$self->{git_path},2911 g => mangle_dirname($self->{git_path}),2912);2913$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2914$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2915$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2916$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});29172918die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2919die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2920$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2921$self->{dbuser},2922$self->{dbpass});2923die"Error connecting to database\n"unlessdefined$self->{dbh};29242925$self->{tables} = {};2926foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2927{2928$self->{tables}{$table} =1;2929}29302931# Construct the revision table if required2932unless($self->{tables}{$self->tablename("revision")} )2933{2934my$tablename=$self->tablename("revision");2935my$ix1name=$self->tablename("revision_ix1");2936my$ix2name=$self->tablename("revision_ix2");2937$self->{dbh}->do("2938 CREATE TABLE$tablename(2939 name TEXT NOT NULL,2940 revision INTEGER NOT NULL,2941 filehash TEXT NOT NULL,2942 commithash TEXT NOT NULL,2943 author TEXT NOT NULL,2944 modified TEXT NOT NULL,2945 mode TEXT NOT NULL2946 )2947 ");2948$self->{dbh}->do("2949 CREATE INDEX$ix1name2950 ON$tablename(name,revision)2951 ");2952$self->{dbh}->do("2953 CREATE INDEX$ix2name2954 ON$tablename(name,commithash)2955 ");2956}29572958# Construct the head table if required2959unless($self->{tables}{$self->tablename("head")} )2960{2961my$tablename=$self->tablename("head");2962my$ix1name=$self->tablename("head_ix1");2963$self->{dbh}->do("2964 CREATE TABLE$tablename(2965 name TEXT NOT NULL,2966 revision INTEGER NOT NULL,2967 filehash TEXT NOT NULL,2968 commithash TEXT NOT NULL,2969 author TEXT NOT NULL,2970 modified TEXT NOT NULL,2971 mode TEXT NOT NULL2972 )2973 ");2974$self->{dbh}->do("2975 CREATE INDEX$ix1name2976 ON$tablename(name)2977 ");2978}29792980# Construct the properties table if required2981unless($self->{tables}{$self->tablename("properties")} )2982{2983my$tablename=$self->tablename("properties");2984$self->{dbh}->do("2985 CREATE TABLE$tablename(2986 key TEXT NOT NULL PRIMARY KEY,2987 value TEXT2988 )2989 ");2990}29912992# Construct the commitmsgs table if required2993unless($self->{tables}{$self->tablename("commitmsgs")} )2994{2995my$tablename=$self->tablename("commitmsgs");2996$self->{dbh}->do("2997 CREATE TABLE$tablename(2998 key TEXT NOT NULL PRIMARY KEY,2999 value TEXT3000 )3001 ");3002}30033004return$self;3005}30063007=head2 tablename30083009=cut3010sub tablename3011{3012my$self=shift;3013my$name=shift;30143015if(exists$self->{valid_tables}{$name}) {3016return$self->{dbtablenameprefix} .$name;3017}else{3018returnundef;3019}3020}30213022=head2 update30233024=cut3025sub update3026{3027my$self=shift;30283029# first lets get the commit list3030$ENV{GIT_DIR} =$self->{git_path};30313032my$commitsha1=`git rev-parse$self->{module}`;3033chomp$commitsha1;30343035my$commitinfo=`git cat-file commit$self->{module} 2>&1`;3036unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)3037{3038die("Invalid module '$self->{module}'");3039}304030413042my$git_log;3043my$lastcommit=$self->_get_prop("last_commit");30443045if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date3046return1;3047}30483049# Start exclusive lock here...3050$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";30513052# TODO: log processing is memory bound3053# if we can parse into a 2nd file that is in reverse order3054# we can probably do something really efficient3055my@git_log_params= ('--pretty','--parents','--topo-order');30563057if(defined$lastcommit) {3058push@git_log_params,"$lastcommit..$self->{module}";3059}else{3060push@git_log_params,$self->{module};3061}3062# git-rev-list is the backend / plumbing version of git-log3063open(GITLOG,'-|','git','rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";30643065my@commits;30663067my%commit= ();30683069while( <GITLOG> )3070{3071chomp;3072if(m/^commit\s+(.*)$/) {3073# on ^commit lines put the just seen commit in the stack3074# and prime things for the next one3075if(keys%commit) {3076my%copy=%commit;3077unshift@commits, \%copy;3078%commit= ();3079}3080my@parents=split(m/\s+/,$1);3081$commit{hash} =shift@parents;3082$commit{parents} = \@parents;3083}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {3084# on rfc822-like lines seen before we see any message,3085# lowercase the entry and put it in the hash as key-value3086$commit{lc($1)} =$2;3087}else{3088# message lines - skip initial empty line3089# and trim whitespace3090if(!exists($commit{message}) &&m/^\s*$/) {3091# define it to mark the end of headers3092$commit{message} ='';3093next;3094}3095s/^\s+//;s/\s+$//;# trim ws3096$commit{message} .=$_."\n";3097}3098}3099close GITLOG;31003101unshift@commits, \%commitif(keys%commit);31023103# Now all the commits are in the @commits bucket3104# ordered by time DESC. for each commit that needs processing,3105# determine whether it's following the last head we've seen or if3106# it's on its own branch, grab a file list, and add whatever's changed3107# NOTE: $lastcommit refers to the last commit from previous run3108# $lastpicked is the last commit we picked in this run3109my$lastpicked;3110my$head= {};3111if(defined$lastcommit) {3112$lastpicked=$lastcommit;3113}31143115my$committotal=scalar(@commits);3116my$commitcount=0;31173118# Load the head table into $head (for cached lookups during the update process)3119foreachmy$file( @{$self->gethead()} )3120{3121$head->{$file->{name}} =$file;3122}31233124foreachmy$commit(@commits)3125{3126$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");3127if(defined$lastpicked)3128{3129if(!in_array($lastpicked, @{$commit->{parents}}))3130{3131# skip, we'll see this delta3132# as part of a merge later3133# warn "skipping off-track $commit->{hash}\n";3134next;3135}elsif(@{$commit->{parents}} >1) {3136# it is a merge commit, for each parent that is3137# not $lastpicked, see if we can get a log3138# from the merge-base to that parent to put it3139# in the message as a merge summary.3140my@parents= @{$commit->{parents}};3141foreachmy$parent(@parents) {3142# git-merge-base can potentially (but rarely) throw3143# several candidate merge bases. let's assume3144# that the first one is the best one.3145if($parenteq$lastpicked) {3146next;3147}3148my$base=eval{3149 safe_pipe_capture('git','merge-base',3150$lastpicked,$parent);3151};3152# The two branches may not be related at all,3153# in which case merge base simply fails to find3154# any, but that's Ok.3155next if($@);31563157chomp$base;3158if($base) {3159my@merged;3160# print "want to log between $base $parent \n";3161open(GITLOG,'-|','git','log','--pretty=medium',"$base..$parent")3162or die"Cannot call git-log:$!";3163my$mergedhash;3164while(<GITLOG>) {3165chomp;3166if(!defined$mergedhash) {3167if(m/^commit\s+(.+)$/) {3168$mergedhash=$1;3169}else{3170next;3171}3172}else{3173# grab the first line that looks non-rfc8223174# aka has content after leading space3175if(m/^\s+(\S.*)$/) {3176my$title=$1;3177$title=substr($title,0,100);# truncate3178unshift@merged,"$mergedhash$title";3179undef$mergedhash;3180}3181}3182}3183close GITLOG;3184if(@merged) {3185$commit->{mergemsg} =$commit->{message};3186$commit->{mergemsg} .="\nSummary of merged commits:\n\n";3187foreachmy$summary(@merged) {3188$commit->{mergemsg} .="\t$summary\n";3189}3190$commit->{mergemsg} .="\n\n";3191# print "Message for $commit->{hash} \n$commit->{mergemsg}";3192}3193}3194}3195}3196}31973198# convert the date to CVS-happy format3199$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);32003201if(defined($lastpicked) )3202{3203my$filepipe=open(FILELIST,'-|','git','diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");3204local($/) ="\0";3205while( <FILELIST> )3206{3207chomp;3208unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)3209{3210die("Couldn't process git-diff-tree line :$_");3211}3212my($mode,$hash,$change) = ($1,$2,$3);3213my$name= <FILELIST>;3214chomp($name);32153216# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");32173218my$git_perms="";3219$git_perms.="r"if($mode&4);3220$git_perms.="w"if($mode&2);3221$git_perms.="x"if($mode&1);3222$git_perms="rw"if($git_permseq"");32233224if($changeeq"D")3225{3226#$log->debug("DELETE $name");3227$head->{$name} = {3228 name =>$name,3229 revision =>$head->{$name}{revision} +1,3230 filehash =>"deleted",3231 commithash =>$commit->{hash},3232 modified =>$commit->{date},3233 author =>$commit->{author},3234 mode =>$git_perms,3235};3236$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3237}3238elsif($changeeq"M"||$changeeq"T")3239{3240#$log->debug("MODIFIED $name");3241$head->{$name} = {3242 name =>$name,3243 revision =>$head->{$name}{revision} +1,3244 filehash =>$hash,3245 commithash =>$commit->{hash},3246 modified =>$commit->{date},3247 author =>$commit->{author},3248 mode =>$git_perms,3249};3250$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3251}3252elsif($changeeq"A")3253{3254#$log->debug("ADDED $name");3255$head->{$name} = {3256 name =>$name,3257 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,3258 filehash =>$hash,3259 commithash =>$commit->{hash},3260 modified =>$commit->{date},3261 author =>$commit->{author},3262 mode =>$git_perms,3263};3264$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3265}3266else3267{3268$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");3269die;3270}3271}3272close FILELIST;3273}else{3274# this is used to detect files removed from the repo3275my$seen_files= {};32763277my$filepipe=open(FILELIST,'-|','git','ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");3278local$/="\0";3279while( <FILELIST> )3280{3281chomp;3282unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)3283{3284die("Couldn't process git-ls-tree line :$_");3285}32863287my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);32883289$seen_files->{$git_filename} =1;32903291my($oldhash,$oldrevision,$oldmode) = (3292$head->{$git_filename}{filehash},3293$head->{$git_filename}{revision},3294$head->{$git_filename}{mode}3295);32963297if($git_perms=~/^\d\d\d(\d)\d\d/o)3298{3299$git_perms="";3300$git_perms.="r"if($1&4);3301$git_perms.="w"if($1&2);3302$git_perms.="x"if($1&1);3303}else{3304$git_perms="rw";3305}33063307# unless the file exists with the same hash, we need to update it ...3308unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3309{3310my$newrevision= ($oldrevisionor0) +1;33113312$head->{$git_filename} = {3313 name =>$git_filename,3314 revision =>$newrevision,3315 filehash =>$git_hash,3316 commithash =>$commit->{hash},3317 modified =>$commit->{date},3318 author =>$commit->{author},3319 mode =>$git_perms,3320};332133223323$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3324}3325}3326close FILELIST;33273328# Detect deleted files3329foreachmy$file(keys%$head)3330{3331unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3332{3333$head->{$file}{revision}++;3334$head->{$file}{filehash} ="deleted";3335$head->{$file}{commithash} =$commit->{hash};3336$head->{$file}{modified} =$commit->{date};3337$head->{$file}{author} =$commit->{author};33383339$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3340}3341}3342# END : "Detect deleted files"3343}334433453346if(exists$commit->{mergemsg})3347{3348$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3349}33503351$lastpicked=$commit->{hash};33523353$self->_set_prop("last_commit",$commit->{hash});3354}33553356$self->delete_head();3357foreachmy$file(keys%$head)3358{3359$self->insert_head(3360$file,3361$head->{$file}{revision},3362$head->{$file}{filehash},3363$head->{$file}{commithash},3364$head->{$file}{modified},3365$head->{$file}{author},3366$head->{$file}{mode},3367);3368}3369# invalidate the gethead cache3370$self->{gethead_cache} =undef;337133723373# Ending exclusive lock here3374$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3375}33763377sub insert_rev3378{3379my$self=shift;3380my$name=shift;3381my$revision=shift;3382my$filehash=shift;3383my$commithash=shift;3384my$modified=shift;3385my$author=shift;3386my$mode=shift;3387my$tablename=$self->tablename("revision");33883389my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3390$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3391}33923393sub insert_mergelog3394{3395my$self=shift;3396my$key=shift;3397my$value=shift;3398my$tablename=$self->tablename("commitmsgs");33993400my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3401$insert_mergelog->execute($key,$value);3402}34033404sub delete_head3405{3406my$self=shift;3407my$tablename=$self->tablename("head");34083409my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3410$delete_head->execute();3411}34123413sub insert_head3414{3415my$self=shift;3416my$name=shift;3417my$revision=shift;3418my$filehash=shift;3419my$commithash=shift;3420my$modified=shift;3421my$author=shift;3422my$mode=shift;3423my$tablename=$self->tablename("head");34243425my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3426$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3427}34283429sub _headrev3430{3431my$self=shift;3432my$filename=shift;3433my$tablename=$self->tablename("head");34343435my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3436$db_query->execute($filename);3437my($hash,$revision,$mode) =$db_query->fetchrow_array;34383439return($hash,$revision,$mode);3440}34413442sub _get_prop3443{3444my$self=shift;3445my$key=shift;3446my$tablename=$self->tablename("properties");34473448my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3449$db_query->execute($key);3450my($value) =$db_query->fetchrow_array;34513452return$value;3453}34543455sub _set_prop3456{3457my$self=shift;3458my$key=shift;3459my$value=shift;3460my$tablename=$self->tablename("properties");34613462my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3463$db_query->execute($value,$key);34643465unless($db_query->rows)3466{3467$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3468$db_query->execute($key,$value);3469}34703471return$value;3472}34733474=head2 gethead34753476=cut34773478sub gethead3479{3480my$self=shift;3481my$tablename=$self->tablename("head");34823483return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );34843485my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3486$db_query->execute();34873488my$tree= [];3489while(my$file=$db_query->fetchrow_hashref)3490{3491push@$tree,$file;3492}34933494$self->{gethead_cache} =$tree;34953496return$tree;3497}34983499=head2 getlog35003501=cut35023503sub getlog3504{3505my$self=shift;3506my$filename=shift;3507my$tablename=$self->tablename("revision");35083509my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3510$db_query->execute($filename);35113512my$tree= [];3513while(my$file=$db_query->fetchrow_hashref)3514{3515push@$tree,$file;3516}35173518return$tree;3519}35203521=head2 getmeta35223523This function takes a filename (with path) argument and returns a hashref of3524metadata for that file.35253526=cut35273528sub getmeta3529{3530my$self=shift;3531my$filename=shift;3532my$revision=shift;3533my$tablename_rev=$self->tablename("revision");3534my$tablename_head=$self->tablename("head");35353536my$db_query;3537if(defined($revision)and$revision=~/^\d+$/)3538{3539$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3540$db_query->execute($filename,$revision);3541}3542elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3543{3544$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3545$db_query->execute($filename,$revision);3546}else{3547$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3548$db_query->execute($filename);3549}35503551return$db_query->fetchrow_hashref;3552}35533554=head2 commitmessage35553556this function takes a commithash and returns the commit message for that commit35573558=cut3559sub commitmessage3560{3561my$self=shift;3562my$commithash=shift;3563my$tablename=$self->tablename("commitmsgs");35643565die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);35663567my$db_query;3568$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3569$db_query->execute($commithash);35703571my($message) =$db_query->fetchrow_array;35723573if(defined($message) )3574{3575$message.=" "if($message=~/\n$/);3576return$message;3577}35783579my@lines= safe_pipe_capture("git","cat-file","commit",$commithash);3580shift@lineswhile($lines[0] =~/\S/);3581$message=join("",@lines);3582$message.=" "if($message=~/\n$/);3583return$message;3584}35853586=head2 gethistory35873588This function takes a filename (with path) argument and returns an arrayofarrays3589containing revision,filehash,commithash ordered by revision descending35903591=cut3592sub gethistory3593{3594my$self=shift;3595my$filename=shift;3596my$tablename=$self->tablename("revision");35973598my$db_query;3599$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3600$db_query->execute($filename);36013602return$db_query->fetchall_arrayref;3603}36043605=head2 gethistorydense36063607This function takes a filename (with path) argument and returns an arrayofarrays3608containing revision,filehash,commithash ordered by revision descending.36093610This version of gethistory skips deleted entries -- so it is useful for annotate.3611The 'dense' part is a reference to a '--dense' option available for git-rev-list3612and other git tools that depend on it.36133614=cut3615sub gethistorydense3616{3617my$self=shift;3618my$filename=shift;3619my$tablename=$self->tablename("revision");36203621my$db_query;3622$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3623$db_query->execute($filename);36243625return$db_query->fetchall_arrayref;3626}36273628=head2 in_array()36293630from Array::PAT - mimics the in_array() function3631found in PHP. Yuck but works for small arrays.36323633=cut3634sub in_array3635{3636my($check,@array) =@_;3637my$retval=0;3638foreachmy$test(@array){3639if($checkeq$test){3640$retval=1;3641}3642}3643return$retval;3644}36453646=head2 safe_pipe_capture36473648an alternative to `command` that allows input to be passed as an array3649to work around shell problems with weird characters in arguments36503651=cut3652sub safe_pipe_capture {36533654my@output;36553656if(my$pid=open my$child,'-|') {3657@output= (<$child>);3658close$childor die join(' ',@_).":$!$?";3659}else{3660exec(@_)or die"$!$?";# exec() can fail the executable can't be found3661}3662returnwantarray?@output:join('',@output);3663}36643665=head2 mangle_dirname36663667create a string from a directory name that is suitable to use as3668part of a filename, mainly by converting all chars except \w.- to _36693670=cut3671sub mangle_dirname {3672my$dirname=shift;3673return unlessdefined$dirname;36743675$dirname=~s/[^\w.-]/_/g;36763677return$dirname;3678}36793680=head2 mangle_tablename36813682create a string from a that is suitable to use as part of an SQL table3683name, mainly by converting all chars except \w to _36843685=cut3686sub mangle_tablename {3687my$tablename=shift;3688return unlessdefined$tablename;36893690$tablename=~s/[^\w_]/_/g;36913692return$tablename;3693}369436951;