1#!/usr/bin/perl 2 3#### 4#### This application is a CVS emulation layer for git. 5#### It is intended for clients to connect over SSH. 6#### See the documentation for more details. 7#### 8#### Copyright The Open University UK - 2006. 9#### 10#### Authors: Martyn Smith <martyn@catalyst.net.nz> 11#### Martin Langhoff <martin@catalyst.net.nz> 12#### 13#### 14#### Released under the GNU Public License, version 2. 15#### 16#### 17 18use strict; 19use warnings; 20use bytes; 21 22use Fcntl; 23use File::Temp qw/tempdir tempfile/; 24use File::Path qw/rmtree/; 25use File::Basename; 26use Getopt::Long qw(:config require_order no_ignore_case); 27 28my$VERSION='@@GIT_VERSION@@'; 29 30my$log= GITCVS::log->new(); 31my$cfg; 32 33my$DATE_LIST= { 34 Jan =>"01", 35 Feb =>"02", 36 Mar =>"03", 37 Apr =>"04", 38 May =>"05", 39 Jun =>"06", 40 Jul =>"07", 41 Aug =>"08", 42 Sep =>"09", 43 Oct =>"10", 44 Nov =>"11", 45 Dec =>"12", 46}; 47 48# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 49$| =1; 50 51#### Definition and mappings of functions #### 52 53my$methods= { 54'Root'=> \&req_Root, 55'Valid-responses'=> \&req_Validresponses, 56'valid-requests'=> \&req_validrequests, 57'Directory'=> \&req_Directory, 58'Entry'=> \&req_Entry, 59'Modified'=> \&req_Modified, 60'Unchanged'=> \&req_Unchanged, 61'Questionable'=> \&req_Questionable, 62'Argument'=> \&req_Argument, 63'Argumentx'=> \&req_Argument, 64'expand-modules'=> \&req_expandmodules, 65'add'=> \&req_add, 66'remove'=> \&req_remove, 67'co'=> \&req_co, 68'update'=> \&req_update, 69'ci'=> \&req_ci, 70'diff'=> \&req_diff, 71'log'=> \&req_log, 72'rlog'=> \&req_log, 73'tag'=> \&req_CATCHALL, 74'status'=> \&req_status, 75'admin'=> \&req_CATCHALL, 76'history'=> \&req_CATCHALL, 77'watchers'=> \&req_EMPTY, 78'editors'=> \&req_EMPTY, 79'annotate'=> \&req_annotate, 80'Global_option'=> \&req_Globaloption, 81#'annotate' => \&req_CATCHALL, 82}; 83 84############################################## 85 86 87# $state holds all the bits of information the clients sends us that could 88# potentially be useful when it comes to actually _doing_ something. 89my$state= { prependdir =>''}; 90 91# Work is for managing temporary working directory 92my$work= 93{ 94state=>undef,# undef, 1 (empty), 2 (with stuff) 95 workDir =>undef, 96index=>undef, 97 emptyDir =>undef, 98 tmpDir =>undef 99}; 100 101$log->info("--------------- STARTING -----------------"); 102 103my$usage= 104"Usage: git-cvsserver [options] [pserver|server] [<directory> ...]\n". 105" --base-path <path> : Prepend to requested CVSROOT\n". 106" --strict-paths : Don't allow recursing into subdirectories\n". 107" --export-all : Don't check for gitcvs.enabled in config\n". 108" --version, -V : Print version information and exit\n". 109" --help, -h, -H : Print usage information and exit\n". 110"\n". 111"<directory> ... is a list of allowed directories. If no directories\n". 112"are given, all are allowed. This is an additional restriction, gitcvs\n". 113"access still needs to be enabled by the gitcvs.enabled config option.\n"; 114 115my@opts= ('help|h|H','version|V', 116'base-path=s','strict-paths','export-all'); 117GetOptions($state,@opts) 118or die$usage; 119 120if($state->{version}) { 121print"git-cvsserver version$VERSION\n"; 122exit; 123} 124if($state->{help}) { 125print$usage; 126exit; 127} 128 129my$TEMP_DIR= tempdir( CLEANUP =>1); 130$log->debug("Temporary directory is '$TEMP_DIR'"); 131 132$state->{method} ='ext'; 133if(@ARGV) { 134if($ARGV[0]eq'pserver') { 135$state->{method} ='pserver'; 136shift@ARGV; 137}elsif($ARGV[0]eq'server') { 138shift@ARGV; 139} 140} 141 142# everything else is a directory 143$state->{allowed_roots} = [@ARGV]; 144 145# don't export the whole system unless the users requests it 146if($state->{'export-all'} && !@{$state->{allowed_roots}}) { 147die"--export-all can only be used together with an explicit whitelist\n"; 148} 149 150# if we are called with a pserver argument, 151# deal with the authentication cat before entering the 152# main loop 153if($state->{method}eq'pserver') { 154my$line= <STDIN>;chomp$line; 155unless($line=~/^BEGIN (AUTH|VERIFICATION) REQUEST$/) { 156die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 157} 158my$request=$1; 159$line= <STDIN>;chomp$line; 160unless(req_Root('root',$line)) {# reuse Root 161print"E Invalid root$line\n"; 162exit1; 163} 164$line= <STDIN>;chomp$line; 165unless($lineeq'anonymous') { 166print"E Only anonymous user allowed via pserver\n"; 167print"I HATE YOU\n"; 168exit1; 169} 170$line= <STDIN>;chomp$line;# validate the password? 171$line= <STDIN>;chomp$line; 172unless($lineeq"END$requestREQUEST") { 173die"E Do not understand$line-- expecting END$requestREQUEST\n"; 174} 175print"I LOVE YOU\n"; 176exit if$requesteq'VERIFICATION';# cvs login 177# and now back to our regular programme... 178} 179 180# Keep going until the client closes the connection 181while(<STDIN>) 182{ 183chomp; 184 185# Check to see if we've seen this method, and call appropriate function. 186if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 187{ 188# use the $methods hash to call the appropriate sub for this command 189#$log->info("Method : $1"); 190&{$methods->{$1}}($1,$2); 191}else{ 192# log fatal because we don't understand this function. If this happens 193# we're fairly screwed because we don't know if the client is expecting 194# a response. If it is, the client will hang, we'll hang, and the whole 195# thing will be custard. 196$log->fatal("Don't understand command$_\n"); 197die("Unknown command$_"); 198} 199} 200 201$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 202$log->info("--------------- FINISH -----------------"); 203 204chdir'/'; 205exit0; 206 207# Magic catchall method. 208# This is the method that will handle all commands we haven't yet 209# implemented. It simply sends a warning to the log file indicating a 210# command that hasn't been implemented has been invoked. 211sub req_CATCHALL 212{ 213my($cmd,$data) =@_; 214$log->warn("Unhandled command : req_$cmd:$data"); 215} 216 217# This method invariably succeeds with an empty response. 218sub req_EMPTY 219{ 220print"ok\n"; 221} 222 223# Root pathname \n 224# Response expected: no. Tell the server which CVSROOT to use. Note that 225# pathname is a local directory and not a fully qualified CVSROOT variable. 226# pathname must already exist; if creating a new root, use the init 227# request, not Root. pathname does not include the hostname of the server, 228# how to access the server, etc.; by the time the CVS protocol is in use, 229# connection, authentication, etc., are already taken care of. The Root 230# request must be sent only once, and it must be sent before any requests 231# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 232sub req_Root 233{ 234my($cmd,$data) =@_; 235$log->debug("req_Root :$data"); 236 237unless($data=~ m#^/#) { 238print"error 1 Root must be an absolute pathname\n"; 239return0; 240} 241 242my$cvsroot=$state->{'base-path'} ||''; 243$cvsroot=~ s#/+$##; 244$cvsroot.=$data; 245 246if($state->{CVSROOT} 247&& ($state->{CVSROOT}ne$cvsroot)) { 248print"error 1 Conflicting roots specified\n"; 249return0; 250} 251 252$state->{CVSROOT} =$cvsroot; 253 254$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 255 256if(@{$state->{allowed_roots}}) { 257my$allowed=0; 258foreachmy$dir(@{$state->{allowed_roots}}) { 259next unless$dir=~ m#^/#; 260$dir=~ s#/+$##; 261if($state->{'strict-paths'}) { 262if($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) { 263$allowed=1; 264last; 265} 266}elsif($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) { 267$allowed=1; 268last; 269} 270} 271 272unless($allowed) { 273print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 274print"E\n"; 275print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 276return0; 277} 278} 279 280unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 281print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 282print"E\n"; 283print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 284return0; 285} 286 287my@gitvars=`git-config -l`; 288if($?) { 289print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 290print"E\n"; 291print"error 1 - problem executing git-config\n"; 292return0; 293} 294foreachmy$line(@gitvars) 295{ 296next unless($line=~/^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/); 297unless($2) { 298$cfg->{$1}{$3} =$4; 299}else{ 300$cfg->{$1}{$2}{$3} =$4; 301} 302} 303 304my$enabled= ($cfg->{gitcvs}{$state->{method}}{enabled} 305||$cfg->{gitcvs}{enabled}); 306unless($state->{'export-all'} || 307($enabled&&$enabled=~/^\s*(1|true|yes)\s*$/i)) { 308print"E GITCVS emulation needs to be enabled on this repo\n"; 309print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 310print"E\n"; 311print"error 1 GITCVS emulation disabled\n"; 312return0; 313} 314 315my$logfile=$cfg->{gitcvs}{$state->{method}}{logfile} ||$cfg->{gitcvs}{logfile}; 316if($logfile) 317{ 318$log->setfile($logfile); 319}else{ 320$log->nofile(); 321} 322 323return1; 324} 325 326# Global_option option \n 327# Response expected: no. Transmit one of the global options `-q', `-Q', 328# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 329# variations (such as combining of options) are allowed. For graceful 330# handling of valid-requests, it is probably better to make new global 331# options separate requests, rather than trying to add them to this 332# request. 333sub req_Globaloption 334{ 335my($cmd,$data) =@_; 336$log->debug("req_Globaloption :$data"); 337$state->{globaloptions}{$data} =1; 338} 339 340# Valid-responses request-list \n 341# Response expected: no. Tell the server what responses the client will 342# accept. request-list is a space separated list of tokens. 343sub req_Validresponses 344{ 345my($cmd,$data) =@_; 346$log->debug("req_Validresponses :$data"); 347 348# TODO : re-enable this, currently it's not particularly useful 349#$state->{validresponses} = [ split /\s+/, $data ]; 350} 351 352# valid-requests \n 353# Response expected: yes. Ask the server to send back a Valid-requests 354# response. 355sub req_validrequests 356{ 357my($cmd,$data) =@_; 358 359$log->debug("req_validrequests"); 360 361$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 362$log->debug("SEND : ok"); 363 364print"Valid-requests ".join(" ",keys%$methods) ."\n"; 365print"ok\n"; 366} 367 368# Directory local-directory \n 369# Additional data: repository \n. Response expected: no. Tell the server 370# what directory to use. The repository should be a directory name from a 371# previous server response. Note that this both gives a default for Entry 372# and Modified and also for ci and the other commands; normal usage is to 373# send Directory for each directory in which there will be an Entry or 374# Modified, and then a final Directory for the original directory, then the 375# command. The local-directory is relative to the top level at which the 376# command is occurring (i.e. the last Directory which is sent before the 377# command); to indicate that top level, `.' should be sent for 378# local-directory. 379sub req_Directory 380{ 381my($cmd,$data) =@_; 382 383my$repository= <STDIN>; 384chomp$repository; 385 386 387$state->{localdir} =$data; 388$state->{repository} =$repository; 389$state->{path} =$repository; 390$state->{path} =~s/^$state->{CVSROOT}\///; 391$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 392$state->{path} .="/"if($state->{path} =~ /\S/ ); 393 394$state->{directory} =$state->{localdir}; 395$state->{directory} =""if($state->{directory}eq"."); 396$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 397 398if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 399{ 400$log->info("Setting prepend to '$state->{path}'"); 401$state->{prependdir} =$state->{path}; 402foreachmy$entry(keys%{$state->{entries}} ) 403{ 404$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 405delete$state->{entries}{$entry}; 406} 407} 408 409if(defined($state->{prependdir} ) ) 410{ 411$log->debug("Prepending '$state->{prependdir}' to state|directory"); 412$state->{directory} =$state->{prependdir} .$state->{directory} 413} 414$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 415} 416 417# Entry entry-line \n 418# Response expected: no. Tell the server what version of a file is on the 419# local machine. The name in entry-line is a name relative to the directory 420# most recently specified with Directory. If the user is operating on only 421# some files in a directory, Entry requests for only those files need be 422# included. If an Entry request is sent without Modified, Is-modified, or 423# Unchanged, it means the file is lost (does not exist in the working 424# directory). If both Entry and one of Modified, Is-modified, or Unchanged 425# are sent for the same file, Entry must be sent first. For a given file, 426# one can send Modified, Is-modified, or Unchanged, but not more than one 427# of these three. 428sub req_Entry 429{ 430my($cmd,$data) =@_; 431 432#$log->debug("req_Entry : $data"); 433 434my@data=split(/\//,$data); 435 436$state->{entries}{$state->{directory}.$data[1]} = { 437 revision =>$data[2], 438 conflict =>$data[3], 439 options =>$data[4], 440 tag_or_date =>$data[5], 441}; 442 443$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 444} 445 446# Questionable filename \n 447# Response expected: no. Additional data: no. Tell the server to check 448# whether filename should be ignored, and if not, next time the server 449# sends responses, send (in a M response) `?' followed by the directory and 450# filename. filename must not contain `/'; it needs to be a file in the 451# directory named by the most recent Directory request. 452sub req_Questionable 453{ 454my($cmd,$data) =@_; 455 456$log->debug("req_Questionable :$data"); 457$state->{entries}{$state->{directory}.$data}{questionable} =1; 458} 459 460# add \n 461# Response expected: yes. Add a file or directory. This uses any previous 462# Argument, Directory, Entry, or Modified requests, if they have been sent. 463# The last Directory sent specifies the working directory at the time of 464# the operation. To add a directory, send the directory to be added using 465# Directory and Argument requests. 466sub req_add 467{ 468my($cmd,$data) =@_; 469 470 argsplit("add"); 471 472my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 473$updater->update(); 474 475 argsfromdir($updater); 476 477my$addcount=0; 478 479foreachmy$filename( @{$state->{args}} ) 480{ 481$filename= filecleanup($filename); 482 483my$meta=$updater->getmeta($filename); 484my$wrev= revparse($filename); 485 486if($wrev&&$meta&& ($wrev<0)) 487{ 488# previously removed file, add back 489$log->info("added file$filenamewas previously removed, send 1.$meta->{revision}"); 490 491print"MT +updated\n"; 492print"MT text U\n"; 493print"MT fname$filename\n"; 494print"MT newline\n"; 495print"MT -updated\n"; 496 497unless($state->{globaloptions}{-n} ) 498{ 499my($filepart,$dirpart) = filenamesplit($filename,1); 500 501print"Created$dirpart\n"; 502print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 503 504# this is an "entries" line 505my$kopts= kopts_from_path($filename); 506$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 507print"/$filepart/1.$meta->{revision}//$kopts/\n"; 508# permissions 509$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 510print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 511# transmit file 512 transmitfile($meta->{filehash}); 513} 514 515next; 516} 517 518unless(defined($state->{entries}{$filename}{modified_filename} ) ) 519{ 520print"E cvs add: nothing known about `$filename'\n"; 521next; 522} 523# TODO : check we're not squashing an already existing file 524if(defined($state->{entries}{$filename}{revision} ) ) 525{ 526print"E cvs add: `$filename' has already been entered\n"; 527next; 528} 529 530my($filepart,$dirpart) = filenamesplit($filename,1); 531 532print"E cvs add: scheduling file `$filename' for addition\n"; 533 534print"Checked-in$dirpart\n"; 535print"$filename\n"; 536my$kopts= kopts_from_path($filename); 537print"/$filepart/0//$kopts/\n"; 538 539my$requestedKopts=$state->{opt}{k}; 540if(defined($requestedKopts)) 541{ 542$requestedKopts="-k$requestedKopts"; 543} 544else 545{ 546$requestedKopts=""; 547} 548if($koptsne$requestedKopts) 549{ 550$log->warn("Ignoring requested -k='$requestedKopts'" 551." for '$filename'; detected -k='$kopts' instead"); 552#TODO: Also have option to send warning to user? 553} 554 555$addcount++; 556} 557 558if($addcount==1) 559{ 560print"E cvs add: use `cvs commit' to add this file permanently\n"; 561} 562elsif($addcount>1) 563{ 564print"E cvs add: use `cvs commit' to add these files permanently\n"; 565} 566 567print"ok\n"; 568} 569 570# remove \n 571# Response expected: yes. Remove a file. This uses any previous Argument, 572# Directory, Entry, or Modified requests, if they have been sent. The last 573# Directory sent specifies the working directory at the time of the 574# operation. Note that this request does not actually do anything to the 575# repository; the only effect of a successful remove request is to supply 576# the client with a new entries line containing `-' to indicate a removed 577# file. In fact, the client probably could perform this operation without 578# contacting the server, although using remove may cause the server to 579# perform a few more checks. The client sends a subsequent ci request to 580# actually record the removal in the repository. 581sub req_remove 582{ 583my($cmd,$data) =@_; 584 585 argsplit("remove"); 586 587# Grab a handle to the SQLite db and do any necessary updates 588my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 589$updater->update(); 590 591#$log->debug("add state : " . Dumper($state)); 592 593my$rmcount=0; 594 595foreachmy$filename( @{$state->{args}} ) 596{ 597$filename= filecleanup($filename); 598 599if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 600{ 601print"E cvs remove: file `$filename' still in working directory\n"; 602next; 603} 604 605my$meta=$updater->getmeta($filename); 606my$wrev= revparse($filename); 607 608unless(defined($wrev) ) 609{ 610print"E cvs remove: nothing known about `$filename'\n"; 611next; 612} 613 614if(defined($wrev)and$wrev<0) 615{ 616print"E cvs remove: file `$filename' already scheduled for removal\n"; 617next; 618} 619 620unless($wrev==$meta->{revision} ) 621{ 622# TODO : not sure if the format of this message is quite correct. 623print"E cvs remove: Up to date check failed for `$filename'\n"; 624next; 625} 626 627 628my($filepart,$dirpart) = filenamesplit($filename,1); 629 630print"E cvs remove: scheduling `$filename' for removal\n"; 631 632print"Checked-in$dirpart\n"; 633print"$filename\n"; 634my$kopts= kopts_from_path($filename); 635print"/$filepart/-1.$wrev//$kopts/\n"; 636 637$rmcount++; 638} 639 640if($rmcount==1) 641{ 642print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 643} 644elsif($rmcount>1) 645{ 646print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 647} 648 649print"ok\n"; 650} 651 652# Modified filename \n 653# Response expected: no. Additional data: mode, \n, file transmission. Send 654# the server a copy of one locally modified file. filename is a file within 655# the most recent directory sent with Directory; it must not contain `/'. 656# If the user is operating on only some files in a directory, only those 657# files need to be included. This can also be sent without Entry, if there 658# is no entry for the file. 659sub req_Modified 660{ 661my($cmd,$data) =@_; 662 663my$mode= <STDIN>; 664defined$mode 665or(print"E end of file reading mode for$data\n"),return; 666chomp$mode; 667my$size= <STDIN>; 668defined$size 669or(print"E end of file reading size of$data\n"),return; 670chomp$size; 671 672# Grab config information 673my$blocksize=8192; 674my$bytesleft=$size; 675my$tmp; 676 677# Get a filehandle/name to write it to 678my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 679 680# Loop over file data writing out to temporary file. 681while($bytesleft) 682{ 683$blocksize=$bytesleftif($bytesleft<$blocksize); 684read STDIN,$tmp,$blocksize; 685print$fh $tmp; 686$bytesleft-=$blocksize; 687} 688 689close$fh 690or(print"E failed to write temporary,$filename:$!\n"),return; 691 692# Ensure we have something sensible for the file mode 693if($mode=~/u=(\w+)/) 694{ 695$mode=$1; 696}else{ 697$mode="rw"; 698} 699 700# Save the file data in $state 701$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 702$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 703$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 704$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 705 706 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 707} 708 709# Unchanged filename\n 710# Response expected: no. Tell the server that filename has not been 711# modified in the checked out directory. The filename is a file within the 712# most recent directory sent with Directory; it must not contain `/'. 713sub req_Unchanged 714{ 715 my ($cmd,$data) =@_; 716 717$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 718 719 #$log->debug("req_Unchanged :$data"); 720} 721 722# Argument text\n 723# Response expected: no. Save argument for use in a subsequent command. 724# Arguments accumulate until an argument-using command is given, at which 725# point they are forgotten. 726# Argumentx text\n 727# Response expected: no. Append\nfollowed by text to the current argument 728# being saved. 729sub req_Argument 730{ 731 my ($cmd,$data) =@_; 732 733 # Argumentx means: append to last Argument (with a newline in front) 734 735$log->debug("$cmd:$data"); 736 737 if ($cmdeq 'Argumentx') { 738 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 739 } else { 740 push @{$state->{arguments}},$data; 741 } 742} 743 744# expand-modules\n 745# Response expected: yes. Expand the modules which are specified in the 746# arguments. Returns the data in Module-expansion responses. Note that the 747# server can assume that this is checkout or export, not rtag or rdiff; the 748# latter do not access the working directory and thus have no need to 749# expand modules on the client side. Expand may not be the best word for 750# what this request does. It does not necessarily tell you all the files 751# contained in a module, for example. Basically it is a way of telling you 752# which working directories the server needs to know about in order to 753# handle a checkout of the specified modules. For example, suppose that the 754# server has a module defined by 755# aliasmodule -a 1dir 756# That is, one can check out aliasmodule and it will take 1dir in the 757# repository and check it out to 1dir in the working directory. Now suppose 758# the client already has this module checked out and is planning on using 759# the co request to update it. Without using expand-modules, the client 760# would have two bad choices: it could either send information about all 761# working directories under the current directory, which could be 762# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 763# stands for 1dir, and neglect to send information for 1dir, which would 764# lead to incorrect operation. With expand-modules, the client would first 765# ask for the module to be expanded: 766sub req_expandmodules 767{ 768 my ($cmd,$data) =@_; 769 770 argsplit(); 771 772$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 773 774 unless ( ref$state->{arguments} eq "ARRAY" ) 775 { 776 print "ok\n"; 777 return; 778 } 779 780 foreach my$module( @{$state->{arguments}} ) 781 { 782$log->debug("SEND : Module-expansion$module"); 783 print "Module-expansion$module\n"; 784 } 785 786 print "ok\n"; 787 statecleanup(); 788} 789 790# co\n 791# Response expected: yes. Get files from the repository. This uses any 792# previous Argument, Directory, Entry, or Modified requests, if they have 793# been sent. Arguments to this command are module names; the client cannot 794# know what directories they correspond to except by (1) just sending the 795# co request, and then seeing what directory names the server sends back in 796# its responses, and (2) the expand-modules request. 797sub req_co 798{ 799 my ($cmd,$data) =@_; 800 801 argsplit("co"); 802 803 my$module=$state->{args}[0]; 804$state->{module} =$module; 805 my$checkout_path=$module; 806 807 # use the user specified directory if we're given it 808$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 809 810$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 811 812$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 813 814$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 815 816# Grab a handle to the SQLite db and do any necessary updates 817my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 818$updater->update(); 819 820$checkout_path=~ s|/$||;# get rid of trailing slashes 821 822# Eclipse seems to need the Clear-sticky command 823# to prepare the 'Entries' file for the new directory. 824print"Clear-sticky$checkout_path/\n"; 825print$state->{CVSROOT} ."/$module/\n"; 826print"Clear-static-directory$checkout_path/\n"; 827print$state->{CVSROOT} ."/$module/\n"; 828print"Clear-sticky$checkout_path/\n";# yes, twice 829print$state->{CVSROOT} ."/$module/\n"; 830print"Template$checkout_path/\n"; 831print$state->{CVSROOT} ."/$module/\n"; 832print"0\n"; 833 834# instruct the client that we're checking out to $checkout_path 835print"E cvs checkout: Updating$checkout_path\n"; 836 837my%seendirs= (); 838my$lastdir=''; 839 840# recursive 841sub prepdir { 842my($dir,$repodir,$remotedir,$seendirs) =@_; 843my$parent= dirname($dir); 844$dir=~ s|/+$||; 845$repodir=~ s|/+$||; 846$remotedir=~ s|/+$||; 847$parent=~ s|/+$||; 848$log->debug("announcedir$dir,$repodir,$remotedir"); 849 850if($parenteq'.'||$parenteq'./') { 851$parent=''; 852} 853# recurse to announce unseen parents first 854if(length($parent) && !exists($seendirs->{$parent})) { 855 prepdir($parent,$repodir,$remotedir,$seendirs); 856} 857# Announce that we are going to modify at the parent level 858if($parent) { 859print"E cvs checkout: Updating$remotedir/$parent\n"; 860}else{ 861print"E cvs checkout: Updating$remotedir\n"; 862} 863print"Clear-sticky$remotedir/$parent/\n"; 864print"$repodir/$parent/\n"; 865 866print"Clear-static-directory$remotedir/$dir/\n"; 867print"$repodir/$dir/\n"; 868print"Clear-sticky$remotedir/$parent/\n";# yes, twice 869print"$repodir/$parent/\n"; 870print"Template$remotedir/$dir/\n"; 871print"$repodir/$dir/\n"; 872print"0\n"; 873 874$seendirs->{$dir} =1; 875} 876 877foreachmy$git( @{$updater->gethead} ) 878{ 879# Don't want to check out deleted files 880next if($git->{filehash}eq"deleted"); 881 882my$fullName=$git->{name}; 883($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 884 885if(length($git->{dir}) &&$git->{dir}ne'./' 886&&$git->{dir}ne$lastdir) { 887unless(exists($seendirs{$git->{dir}})) { 888 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 889$checkout_path, \%seendirs); 890$lastdir=$git->{dir}; 891$seendirs{$git->{dir}} =1; 892} 893print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 894} 895 896# modification time of this file 897print"Mod-time$git->{modified}\n"; 898 899# print some information to the client 900if(defined($git->{dir} )and$git->{dir}ne"./") 901{ 902print"M U$checkout_path/$git->{dir}$git->{name}\n"; 903}else{ 904print"M U$checkout_path/$git->{name}\n"; 905} 906 907# instruct client we're sending a file to put in this path 908print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 909 910print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 911 912# this is an "entries" line 913my$kopts= kopts_from_path($fullName); 914print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 915# permissions 916print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 917 918# transmit file 919 transmitfile($git->{filehash}); 920} 921 922print"ok\n"; 923 924 statecleanup(); 925} 926 927# update \n 928# Response expected: yes. Actually do a cvs update command. This uses any 929# previous Argument, Directory, Entry, or Modified requests, if they have 930# been sent. The last Directory sent specifies the working directory at the 931# time of the operation. The -I option is not used--files which the client 932# can decide whether to ignore are not mentioned and the client sends the 933# Questionable request for others. 934sub req_update 935{ 936my($cmd,$data) =@_; 937 938$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 939 940 argsplit("update"); 941 942# 943# It may just be a client exploring the available heads/modules 944# in that case, list them as top level directories and leave it 945# at that. Eclipse uses this technique to offer you a list of 946# projects (heads in this case) to checkout. 947# 948if($state->{module}eq'') { 949my$heads_dir=$state->{CVSROOT} .'/refs/heads'; 950if(!opendir HEADS,$heads_dir) { 951print"E [server aborted]: Failed to open directory, " 952."$heads_dir:$!\nerror\n"; 953return0; 954} 955print"E cvs update: Updating .\n"; 956while(my$head=readdir(HEADS)) { 957if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 958print"E cvs update: New directory `$head'\n"; 959} 960} 961closedir HEADS; 962print"ok\n"; 963return1; 964} 965 966 967# Grab a handle to the SQLite db and do any necessary updates 968my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 969 970$updater->update(); 971 972 argsfromdir($updater); 973 974#$log->debug("update state : " . Dumper($state)); 975 976# foreach file specified on the command line ... 977foreachmy$filename( @{$state->{args}} ) 978{ 979$filename= filecleanup($filename); 980 981$log->debug("Processing file$filename"); 982 983# if we have a -C we should pretend we never saw modified stuff 984if(exists($state->{opt}{C} ) ) 985{ 986delete$state->{entries}{$filename}{modified_hash}; 987delete$state->{entries}{$filename}{modified_filename}; 988$state->{entries}{$filename}{unchanged} =1; 989} 990 991my$meta; 992if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 993{ 994$meta=$updater->getmeta($filename,$1); 995}else{ 996$meta=$updater->getmeta($filename); 997} 998 999# If -p was given, "print" the contents of the requested revision.1000if(exists($state->{opt}{p} ) ) {1001if(defined($meta->{revision} ) ) {1002$log->info("Printing '$filename' revision ".$meta->{revision});10031004 transmitfile($meta->{filehash}, {print=>1});1005}10061007next;1008}10091010if( !defined$meta)1011{1012$meta= {1013 name =>$filename,1014 revision =>0,1015 filehash =>'added'1016};1017}10181019my$oldmeta=$meta;10201021my$wrev= revparse($filename);10221023# If the working copy is an old revision, lets get that version too for comparison.1024if(defined($wrev)and$wrev!=$meta->{revision} )1025{1026$oldmeta=$updater->getmeta($filename,$wrev);1027}10281029#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");10301031# Files are up to date if the working copy and repo copy have the same revision,1032# and the working copy is unmodified _and_ the user hasn't specified -C1033next if(defined($wrev)1034and defined($meta->{revision})1035and$wrev==$meta->{revision}1036and$state->{entries}{$filename}{unchanged}1037and not exists($state->{opt}{C} ) );10381039# If the working copy and repo copy have the same revision,1040# but the working copy is modified, tell the client it's modified1041if(defined($wrev)1042and defined($meta->{revision})1043and$wrev==$meta->{revision}1044and defined($state->{entries}{$filename}{modified_hash})1045and not exists($state->{opt}{C} ) )1046{1047$log->info("Tell the client the file is modified");1048print"MT text M\n";1049print"MT fname$filename\n";1050print"MT newline\n";1051next;1052}10531054if($meta->{filehash}eq"deleted")1055{1056my($filepart,$dirpart) = filenamesplit($filename,1);10571058$log->info("Removing '$filename' from working copy (no longer in the repo)");10591060print"E cvs update: `$filename' is no longer in the repository\n";1061# Don't want to actually _DO_ the update if -n specified1062unless($state->{globaloptions}{-n} ) {1063print"Removed$dirpart\n";1064print"$filepart\n";1065}1066}1067elsif(not defined($state->{entries}{$filename}{modified_hash} )1068or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash}1069or$meta->{filehash}eq'added')1070{1071# normal update, just send the new revision (either U=Update,1072# or A=Add, or R=Remove)1073if(defined($wrev) &&$wrev<0)1074{1075$log->info("Tell the client the file is scheduled for removal");1076print"MT text R\n";1077print"MT fname$filename\n";1078print"MT newline\n";1079next;1080}1081elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) )1082{1083$log->info("Tell the client the file is scheduled for addition");1084print"MT text A\n";1085print"MT fname$filename\n";1086print"MT newline\n";1087next;10881089}1090else{1091$log->info("Updating '$filename' to ".$meta->{revision});1092print"MT +updated\n";1093print"MT text U\n";1094print"MT fname$filename\n";1095print"MT newline\n";1096print"MT -updated\n";1097}10981099my($filepart,$dirpart) = filenamesplit($filename,1);11001101# Don't want to actually _DO_ the update if -n specified1102unless($state->{globaloptions}{-n} )1103{1104if(defined($wrev) )1105{1106# instruct client we're sending a file to put in this path as a replacement1107print"Update-existing$dirpart\n";1108$log->debug("Updating existing file 'Update-existing$dirpart'");1109}else{1110# instruct client we're sending a file to put in this path as a new file1111print"Clear-static-directory$dirpart\n";1112print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";1113print"Clear-sticky$dirpart\n";1114print$state->{CVSROOT} ."/$state->{module}/$dirpart\n";11151116$log->debug("Creating new file 'Created$dirpart'");1117print"Created$dirpart\n";1118}1119print$state->{CVSROOT} ."/$state->{module}/$filename\n";11201121# this is an "entries" line1122my$kopts= kopts_from_path($filename);1123$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1124print"/$filepart/1.$meta->{revision}//$kopts/\n";11251126# permissions1127$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1128print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";11291130# transmit file1131 transmitfile($meta->{filehash});1132}1133}else{1134$log->info("Updating '$filename'");1135my($filepart,$dirpart) = filenamesplit($meta->{name},1);11361137my$mergeDir= setupTmpDir();11381139my$file_local=$filepart.".mine";1140my$mergedFile="$mergeDir/$file_local";1141system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local);1142my$file_old=$filepart.".".$oldmeta->{revision};1143 transmitfile($oldmeta->{filehash}, { targetfile =>$file_old});1144my$file_new=$filepart.".".$meta->{revision};1145 transmitfile($meta->{filehash}, { targetfile =>$file_new});11461147# we need to merge with the local changes ( M=successful merge, C=conflict merge )1148$log->info("Merging$file_local,$file_old,$file_new");1149print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n";11501151$log->debug("Temporary directory for merge is$mergeDir");11521153my$return=system("git","merge-file",$file_local,$file_old,$file_new);1154$return>>=8;11551156 cleanupTmpDir();11571158if($return==0)1159{1160$log->info("Merged successfully");1161print"M M$filename\n";1162$log->debug("Merged$dirpart");11631164# Don't want to actually _DO_ the update if -n specified1165unless($state->{globaloptions}{-n} )1166{1167print"Merged$dirpart\n";1168$log->debug($state->{CVSROOT} ."/$state->{module}/$filename");1169print$state->{CVSROOT} ."/$state->{module}/$filename\n";1170my$kopts= kopts_from_path("$dirpart/$filepart");1171$log->debug("/$filepart/1.$meta->{revision}//$kopts/");1172print"/$filepart/1.$meta->{revision}//$kopts/\n";1173}1174}1175elsif($return==1)1176{1177$log->info("Merged with conflicts");1178print"E cvs update: conflicts found in$filename\n";1179print"M C$filename\n";11801181# Don't want to actually _DO_ the update if -n specified1182unless($state->{globaloptions}{-n} )1183{1184print"Merged$dirpart\n";1185print$state->{CVSROOT} ."/$state->{module}/$filename\n";1186my$kopts= kopts_from_path("$dirpart/$filepart");1187print"/$filepart/1.$meta->{revision}/+/$kopts/\n";1188}1189}1190else1191{1192$log->warn("Merge failed");1193next;1194}11951196# Don't want to actually _DO_ the update if -n specified1197unless($state->{globaloptions}{-n} )1198{1199# permissions1200$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1201print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";12021203# transmit file, format is single integer on a line by itself (file1204# size) followed by the file contents1205# TODO : we should copy files in blocks1206my$data=`cat$mergedFile`;1207$log->debug("File size : " . length($data));1208 print length($data) . "\n";1209 print$data;1210 }1211 }12121213 }12141215 print "ok\n";1216}12171218sub req_ci1219{1220 my ($cmd,$data) =@_;12211222 argsplit("ci");12231224 #$log->debug("State : " . Dumper($state));12251226$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));12271228 if ($state->{method} eq 'pserver')1229 {1230 print "error 1 pserver access cannot commit\n";1231 cleanupWorkTree();1232 exit;1233 }12341235 if ( -e$state->{CVSROOT} . "/index" )1236 {1237$log->warn("file 'index' already exists in the git repository");1238 print "error 1 Index already exists in git repo\n";1239 cleanupWorkTree();1240 exit;1241 }12421243 # Grab a handle to the SQLite db and do any necessary updates1244 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1245$updater->update();12461247 # Remember where the head was at the beginning.1248 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1249 chomp$parenthash;1250 if ($parenthash!~ /^[0-9a-f]{40}$/) {1251 print "error 1 pserver cannot find the current HEAD of module";1252 cleanupWorkTree();1253 exit;1254 }12551256 setupWorkTree($parenthash);12571258$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");12591260$log->info("Created index '$work->{index}' for head$state->{module} - exit status$?");12611262 my@committedfiles= ();1263 my%oldmeta;12641265 # foreach file specified on the command line ...1266 foreach my$filename( @{$state->{args}} )1267 {1268 my$committedfile=$filename;1269$filename= filecleanup($filename);12701271 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );12721273 my$meta=$updater->getmeta($filename);1274$oldmeta{$filename} =$meta;12751276 my$wrev= revparse($filename);12771278 my ($filepart,$dirpart) = filenamesplit($filename);12791280 # do a checkout of the file if it is part of this tree1281 if ($wrev) {1282 system('git-checkout-index', '-f', '-u',$filename);1283 unless ($?== 0) {1284 die "Error running git-checkout-index -f -u$filename:$!";1285 }1286 }12871288 my$addflag= 0;1289 my$rmflag= 0;1290$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1291$addflag= 1 unless ( -e$filename);12921293 # Do up to date checking1294 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1295 {1296 # fail everything if an up to date check fails1297 print "error 1 Up to date check failed for$filename\n";1298 cleanupWorkTree();1299 exit;1300 }13011302 push@committedfiles,$committedfile;1303$log->info("Committing$filename");13041305 system("mkdir","-p",$dirpart) unless ( -d$dirpart);13061307 unless ($rmflag)1308 {1309$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1310 rename$state->{entries}{$filename}{modified_filename},$filename;13111312 # Calculate modes to remove1313 my$invmode= "";1314 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }13151316$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1317 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1318 }13191320 if ($rmflag)1321 {1322$log->info("Removing file '$filename'");1323 unlink($filename);1324 system("git-update-index", "--remove",$filename);1325 }1326 elsif ($addflag)1327 {1328$log->info("Adding file '$filename'");1329 system("git-update-index", "--add",$filename);1330 } else {1331$log->info("Updating file '$filename'");1332 system("git-update-index",$filename);1333 }1334 }13351336 unless ( scalar(@committedfiles) > 0 )1337 {1338 print "E No files to commit\n";1339 print "ok\n";1340 cleanupWorkTree();1341 return;1342 }13431344 my$treehash= `git-write-tree`;1345 chomp$treehash;13461347$log->debug("Treehash :$treehash, Parenthash :$parenthash");13481349 # write our commit message out if we have one ...1350 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1351 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1352 print$msg_fh"\n\nvia git-CVS emulator\n";1353 close$msg_fh;13541355 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1356chomp($commithash);1357$log->info("Commit hash :$commithash");13581359unless($commithash=~/[a-zA-Z0-9]{40}/)1360{1361$log->warn("Commit failed (Invalid commit hash)");1362print"error 1 Commit failed (unknown reason)\n";1363 cleanupWorkTree();1364exit;1365}13661367### Emulate git-receive-pack by running hooks/update1368my@hook= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1369$parenthash,$commithash);1370if( -x $hook[0] ) {1371unless(system(@hook) ==0)1372{1373$log->warn("Commit failed (update hook declined to update ref)");1374print"error 1 Commit failed (update hook declined)\n";1375 cleanupWorkTree();1376exit;1377}1378}13791380### Update the ref1381if(system(qw(git update-ref -m),"cvsserver ci",1382"refs/heads/$state->{module}",$commithash,$parenthash)) {1383$log->warn("update-ref for$state->{module} failed.");1384print"error 1 Cannot commit -- update first\n";1385 cleanupWorkTree();1386exit;1387}13881389### Emulate git-receive-pack by running hooks/post-receive1390my$hook=$ENV{GIT_DIR}.'hooks/post-receive';1391if( -x $hook) {1392open(my$pipe,"|$hook") ||die"can't fork$!";13931394local$SIG{PIPE} =sub{die'pipe broke'};13951396print$pipe"$parenthash$commithashrefs/heads/$state->{module}\n";13971398close$pipe||die"bad pipe:$!$?";1399}14001401### Then hooks/post-update1402$hook=$ENV{GIT_DIR}.'hooks/post-update';1403if(-x $hook) {1404system($hook,"refs/heads/$state->{module}");1405}14061407$updater->update();14081409# foreach file specified on the command line ...1410foreachmy$filename(@committedfiles)1411{1412$filename= filecleanup($filename);14131414my$meta=$updater->getmeta($filename);1415unless(defined$meta->{revision}) {1416$meta->{revision} =1;1417}14181419my($filepart,$dirpart) = filenamesplit($filename,1);14201421$log->debug("Checked-in$dirpart:$filename");14221423print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1424if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1425{1426print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1427print"Remove-entry$dirpart\n";1428print"$filename\n";1429}else{1430if($meta->{revision} ==1) {1431print"M initial revision: 1.1\n";1432}else{1433print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1434}1435print"Checked-in$dirpart\n";1436print"$filename\n";1437my$kopts= kopts_from_path($filename);1438print"/$filepart/1.$meta->{revision}//$kopts/\n";1439}1440}14411442 cleanupWorkTree();1443print"ok\n";1444}14451446sub req_status1447{1448my($cmd,$data) =@_;14491450 argsplit("status");14511452$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1453#$log->debug("status state : " . Dumper($state));14541455# Grab a handle to the SQLite db and do any necessary updates1456my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1457$updater->update();14581459# if no files were specified, we need to work out what files we should be providing status on ...1460 argsfromdir($updater);14611462# foreach file specified on the command line ...1463foreachmy$filename( @{$state->{args}} )1464{1465$filename= filecleanup($filename);14661467next ifexists($state->{opt}{l}) &&index($filename,'/',length($state->{prependdir})) >=0;14681469my$meta=$updater->getmeta($filename);1470my$oldmeta=$meta;14711472my$wrev= revparse($filename);14731474# If the working copy is an old revision, lets get that version too for comparison.1475if(defined($wrev)and$wrev!=$meta->{revision} )1476{1477$oldmeta=$updater->getmeta($filename,$wrev);1478}14791480# TODO : All possible statuses aren't yet implemented1481my$status;1482# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1483$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1484and1485( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1486or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1487);14881489# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1490$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1491and1492($state->{entries}{$filename}{unchanged}1493or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1494);14951496# Need checkout if it exists in the repo but doesn't have a working copy1497$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );14981499# Locally modified if working copy and repo copy have the same revision but there are local changes1500$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );15011502# Needs Merge if working copy revision is less than repo copy and there are local changes1503$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );15041505$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1506$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1507$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1508$status||="File had conflicts on merge"if(0);15091510$status||="Unknown";15111512my($filepart) = filenamesplit($filename);15131514print"M ===================================================================\n";1515print"M File:$filepart\tStatus:$status\n";1516if(defined($state->{entries}{$filename}{revision}) )1517{1518print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1519}else{1520print"M Working revision:\tNo entry for$filename\n";1521}1522if(defined($meta->{revision}) )1523{1524print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1525print"M Sticky Tag:\t\t(none)\n";1526print"M Sticky Date:\t\t(none)\n";1527print"M Sticky Options:\t\t(none)\n";1528}else{1529print"M Repository revision:\tNo revision control file\n";1530}1531print"M\n";1532}15331534print"ok\n";1535}15361537sub req_diff1538{1539my($cmd,$data) =@_;15401541 argsplit("diff");15421543$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1544#$log->debug("status state : " . Dumper($state));15451546my($revision1,$revision2);1547if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1548{1549$revision1=$state->{opt}{r}[0];1550$revision2=$state->{opt}{r}[1];1551}else{1552$revision1=$state->{opt}{r};1553}15541555$revision1=~s/^1\.//if(defined($revision1) );1556$revision2=~s/^1\.//if(defined($revision2) );15571558$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );15591560# Grab a handle to the SQLite db and do any necessary updates1561my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1562$updater->update();15631564# if no files were specified, we need to work out what files we should be providing status on ...1565 argsfromdir($updater);15661567# foreach file specified on the command line ...1568foreachmy$filename( @{$state->{args}} )1569{1570$filename= filecleanup($filename);15711572my($fh,$file1,$file2,$meta1,$meta2,$filediff);15731574my$wrev= revparse($filename);15751576# We need _something_ to diff against1577next unless(defined($wrev) );15781579# if we have a -r switch, use it1580if(defined($revision1) )1581{1582(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1583$meta1=$updater->getmeta($filename,$revision1);1584unless(defined($meta1)and$meta1->{filehash}ne"deleted")1585{1586print"E File$filenameat revision 1.$revision1doesn't exist\n";1587next;1588}1589 transmitfile($meta1->{filehash}, { targetfile =>$file1});1590}1591# otherwise we just use the working copy revision1592else1593{1594(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1595$meta1=$updater->getmeta($filename,$wrev);1596 transmitfile($meta1->{filehash}, { targetfile =>$file1});1597}15981599# if we have a second -r switch, use it too1600if(defined($revision2) )1601{1602(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1603$meta2=$updater->getmeta($filename,$revision2);16041605unless(defined($meta2)and$meta2->{filehash}ne"deleted")1606{1607print"E File$filenameat revision 1.$revision2doesn't exist\n";1608next;1609}16101611 transmitfile($meta2->{filehash}, { targetfile =>$file2});1612}1613# otherwise we just use the working copy1614else1615{1616$file2=$state->{entries}{$filename}{modified_filename};1617}16181619# if we have been given -r, and we don't have a $file2 yet, lets get one1620if(defined($revision1)and not defined($file2) )1621{1622(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1623$meta2=$updater->getmeta($filename,$wrev);1624 transmitfile($meta2->{filehash}, { targetfile =>$file2});1625}16261627# We need to have retrieved something useful1628next unless(defined($meta1) );16291630# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1631next if(not defined($meta2)and$wrev==$meta1->{revision}1632and1633( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1634or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1635);16361637# Apparently we only show diffs for locally modified files1638next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );16391640print"M Index:$filename\n";1641print"M ===================================================================\n";1642print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1643print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1644print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1645print"M diff ";1646foreachmy$opt(keys%{$state->{opt}} )1647{1648if(ref$state->{opt}{$opt}eq"ARRAY")1649{1650foreachmy$value( @{$state->{opt}{$opt}} )1651{1652print"-$opt$value";1653}1654}else{1655print"-$opt";1656print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1657}1658}1659print"$filename\n";16601661$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));16621663($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);16641665if(exists$state->{opt}{u} )1666{1667system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1668}else{1669system("diff$file1$file2>$filediff");1670}16711672while( <$fh> )1673{1674print"M$_";1675}1676close$fh;1677}16781679print"ok\n";1680}16811682sub req_log1683{1684my($cmd,$data) =@_;16851686 argsplit("log");16871688$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1689#$log->debug("log state : " . Dumper($state));16901691my($minrev,$maxrev);1692if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1693{1694my$control=$2;1695$minrev=$1;1696$maxrev=$3;1697$minrev=~s/^1\.//if(defined($minrev) );1698$maxrev=~s/^1\.//if(defined($maxrev) );1699$minrev++if(defined($minrev)and$controleq"::");1700}17011702# Grab a handle to the SQLite db and do any necessary updates1703my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1704$updater->update();17051706# if no files were specified, we need to work out what files we should be providing status on ...1707 argsfromdir($updater);17081709# foreach file specified on the command line ...1710foreachmy$filename( @{$state->{args}} )1711{1712$filename= filecleanup($filename);17131714my$headmeta=$updater->getmeta($filename);17151716my$revisions=$updater->getlog($filename);1717my$totalrevisions=scalar(@$revisions);17181719if(defined($minrev) )1720{1721$log->debug("Removing revisions less than$minrev");1722while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1723{1724pop@$revisions;1725}1726}1727if(defined($maxrev) )1728{1729$log->debug("Removing revisions greater than$maxrev");1730while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1731{1732shift@$revisions;1733}1734}17351736next unless(scalar(@$revisions) );17371738print"M\n";1739print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1740print"M Working file:$filename\n";1741print"M head: 1.$headmeta->{revision}\n";1742print"M branch:\n";1743print"M locks: strict\n";1744print"M access list:\n";1745print"M symbolic names:\n";1746print"M keyword substitution: kv\n";1747print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1748print"M description:\n";17491750foreachmy$revision(@$revisions)1751{1752print"M ----------------------------\n";1753print"M revision 1.$revision->{revision}\n";1754# reformat the date for log output1755$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}) );1756$revision->{author} = cvs_author($revision->{author});1757print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1758my$commitmessage=$updater->commitmessage($revision->{commithash});1759$commitmessage=~s/^/M /mg;1760print$commitmessage."\n";1761}1762print"M =============================================================================\n";1763}17641765print"ok\n";1766}17671768sub req_annotate1769{1770my($cmd,$data) =@_;17711772 argsplit("annotate");17731774$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1775#$log->debug("status state : " . Dumper($state));17761777# Grab a handle to the SQLite db and do any necessary updates1778my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1779$updater->update();17801781# if no files were specified, we need to work out what files we should be providing annotate on ...1782 argsfromdir($updater);17831784# we'll need a temporary checkout dir1785 setupWorkTree();17861787$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");17881789# foreach file specified on the command line ...1790foreachmy$filename( @{$state->{args}} )1791{1792$filename= filecleanup($filename);17931794my$meta=$updater->getmeta($filename);17951796next unless($meta->{revision} );17971798# get all the commits that this file was in1799# in dense format -- aka skip dead revisions1800my$revisions=$updater->gethistorydense($filename);1801my$lastseenin=$revisions->[0][2];18021803# populate the temporary index based on the latest commit were we saw1804# the file -- but do it cheaply without checking out any files1805# TODO: if we got a revision from the client, use that instead1806# to look up the commithash in sqlite (still good to default to1807# the current head as we do now)1808system("git-read-tree",$lastseenin);1809unless($?==0)1810{1811print"E error running git-read-tree$lastseenin$ENV{GIT_INDEX_FILE}$!\n";1812return;1813}1814$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit$lastseenin- exit status$?");18151816# do a checkout of the file1817system('git-checkout-index','-f','-u',$filename);1818unless($?==0) {1819print"E error running git-checkout-index -f -u$filename:$!\n";1820return;1821}18221823$log->info("Annotate$filename");18241825# Prepare a file with the commits from the linearized1826# history that annotate should know about. This prevents1827# git-jsannotate telling us about commits we are hiding1828# from the client.18291830my$a_hints="$work->{workDir}/.annotate_hints";1831if(!open(ANNOTATEHINTS,'>',$a_hints)) {1832print"E failed to open '$a_hints' for writing:$!\n";1833return;1834}1835for(my$i=0;$i<@$revisions;$i++)1836{1837print ANNOTATEHINTS $revisions->[$i][2];1838if($i+1<@$revisions) {# have we got a parent?1839print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1840}1841print ANNOTATEHINTS "\n";1842}18431844print ANNOTATEHINTS "\n";1845close ANNOTATEHINTS1846or(print"E failed to write$a_hints:$!\n"),return;18471848my@cmd= (qw(git-annotate -l -S),$a_hints,$filename);1849if(!open(ANNOTATE,"-|",@cmd)) {1850print"E error invoking ".join(' ',@cmd) .":$!\n";1851return;1852}1853my$metadata= {};1854print"E Annotations for$filename\n";1855print"E ***************\n";1856while( <ANNOTATE> )1857{1858if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1859{1860my$commithash=$1;1861my$data=$2;1862unless(defined($metadata->{$commithash} ) )1863{1864$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1865$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});1866$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1867}1868printf("M 1.%-5d (%-8s%10s):%s\n",1869$metadata->{$commithash}{revision},1870$metadata->{$commithash}{author},1871$metadata->{$commithash}{modified},1872$data1873);1874}else{1875$log->warn("Error in annotate output! LINE:$_");1876print"E Annotate error\n";1877next;1878}1879}1880close ANNOTATE;1881}18821883# done; get out of the tempdir1884 cleanupWorkDir();18851886print"ok\n";18871888}18891890# This method takes the state->{arguments} array and produces two new arrays.1891# The first is $state->{args} which is everything before the '--' argument, and1892# the second is $state->{files} which is everything after it.1893sub argsplit1894{1895$state->{args} = [];1896$state->{files} = [];1897$state->{opt} = {};18981899return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");19001901my$type=shift;19021903if(defined($type) )1904{1905my$opt= {};1906$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");1907$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1908$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");1909$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1910$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1911$opt= { k =>1, m =>1}if($typeeq"add");1912$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1913$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");191419151916while(scalar( @{$state->{arguments}} ) >0)1917{1918my$arg=shift@{$state->{arguments}};19191920next if($argeq"--");1921next unless($arg=~/\S/);19221923# if the argument looks like a switch1924if($arg=~/^-(\w)(.*)/)1925{1926# if it's a switch that takes an argument1927if($opt->{$1} )1928{1929# If this switch has already been provided1930if($opt->{$1} >1and exists($state->{opt}{$1} ) )1931{1932$state->{opt}{$1} = [$state->{opt}{$1} ];1933if(length($2) >0)1934{1935push@{$state->{opt}{$1}},$2;1936}else{1937push@{$state->{opt}{$1}},shift@{$state->{arguments}};1938}1939}else{1940# if there's extra data in the arg, use that as the argument for the switch1941if(length($2) >0)1942{1943$state->{opt}{$1} =$2;1944}else{1945$state->{opt}{$1} =shift@{$state->{arguments}};1946}1947}1948}else{1949$state->{opt}{$1} =undef;1950}1951}1952else1953{1954push@{$state->{args}},$arg;1955}1956}1957}1958else1959{1960my$mode=0;19611962foreachmy$value( @{$state->{arguments}} )1963{1964if($valueeq"--")1965{1966$mode++;1967next;1968}1969push@{$state->{args}},$valueif($mode==0);1970push@{$state->{files}},$valueif($mode==1);1971}1972}1973}19741975# This method uses $state->{directory} to populate $state->{args} with a list of filenames1976sub argsfromdir1977{1978my$updater=shift;19791980$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");19811982return if(scalar( @{$state->{args}} ) >1);19831984my@gethead= @{$updater->gethead};19851986# push added files1987foreachmy$file(keys%{$state->{entries}}) {1988if(exists$state->{entries}{$file}{revision} &&1989$state->{entries}{$file}{revision} ==0)1990{1991push@gethead, { name =>$file, filehash =>'added'};1992}1993}19941995if(scalar(@{$state->{args}}) ==1)1996{1997my$arg=$state->{args}[0];1998$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );19992000$log->info("Only one arg specified, checking for directory expansion on '$arg'");20012002foreachmy$file(@gethead)2003{2004next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2005next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);2006push@{$state->{args}},$file->{name};2007}20082009shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);2010}else{2011$log->info("Only one arg specified, populating file list automatically");20122013$state->{args} = [];20142015foreachmy$file(@gethead)2016{2017next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );2018next unless($file->{name} =~s/^$state->{prependdir}//);2019push@{$state->{args}},$file->{name};2020}2021}2022}20232024# This method cleans up the $state variable after a command that uses arguments has run2025sub statecleanup2026{2027$state->{files} = [];2028$state->{args} = [];2029$state->{arguments} = [];2030$state->{entries} = {};2031}20322033sub revparse2034{2035my$filename=shift;20362037returnundefunless(defined($state->{entries}{$filename}{revision} ) );20382039return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);2040return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);20412042returnundef;2043}20442045# This method takes a file hash and does a CVS "file transfer". Its2046# exact behaviour depends on a second, optional hash table argument:2047# - If $options->{targetfile}, dump the contents to that file;2048# - If $options->{print}, use M/MT to transmit the contents one line2049# at a time;2050# - Otherwise, transmit the size of the file, followed by the file2051# contents.2052sub transmitfile2053{2054my$filehash=shift;2055my$options=shift;20562057if(defined($filehash)and$filehasheq"deleted")2058{2059$log->warn("filehash is 'deleted'");2060return;2061}20622063die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);20642065my$type=`git-cat-file -t$filehash`;2066 chomp$type;20672068 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );20692070 my$size= `git-cat-file -s $filehash`;2071chomp$size;20722073$log->debug("transmitfile($filehash) size=$size, type=$type");20742075if(open my$fh,'-|',"git-cat-file","blob",$filehash)2076{2077if(defined($options->{targetfile} ) )2078{2079my$targetfile=$options->{targetfile};2080open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");2081print NEWFILE $_while( <$fh> );2082close NEWFILE or die("Failed to write '$targetfile':$!");2083}elsif(defined($options->{print} ) &&$options->{print} ) {2084while( <$fh> ) {2085if(/\n\z/) {2086print'M ',$_;2087}else{2088print'MT text ',$_,"\n";2089}2090}2091}else{2092print"$size\n";2093printwhile( <$fh> );2094}2095close$fhor die("Couldn't close filehandle for transmitfile():$!");2096}else{2097die("Couldn't execute git-cat-file");2098}2099}21002101# This method takes a file name, and returns ( $dirpart, $filepart ) which2102# refers to the directory portion and the file portion of the filename2103# respectively2104sub filenamesplit2105{2106my$filename=shift;2107my$fixforlocaldir=shift;21082109my($filepart,$dirpart) = ($filename,".");2110($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );2111$dirpart.="/";21122113if($fixforlocaldir)2114{2115$dirpart=~s/^$state->{prependdir}//;2116}21172118return($filepart,$dirpart);2119}21202121sub filecleanup2122{2123my$filename=shift;21242125returnundefunless(defined($filename));2126if($filename=~/^\// )2127{2128print"E absolute filenames '$filename' not supported by server\n";2129returnundef;2130}21312132$filename=~s/^\.\///g;2133$filename=$state->{prependdir} .$filename;2134return$filename;2135}21362137sub validateGitDir2138{2139if( !defined($state->{CVSROOT}) )2140{2141print"error 1 CVSROOT not specified\n";2142 cleanupWorkTree();2143exit;2144}2145if($ENV{GIT_DIR}ne($state->{CVSROOT} .'/') )2146{2147print"error 1 Internally inconsistent CVSROOT\n";2148 cleanupWorkTree();2149exit;2150}2151}21522153# Setup working directory in a work tree with the requested version2154# loaded in the index.2155sub setupWorkTree2156{2157my($ver) =@_;21582159 validateGitDir();21602161if( (defined($work->{state}) &&$work->{state} !=1) ||2162defined($work->{tmpDir}) )2163{2164$log->warn("Bad work tree state management");2165print"error 1 Internal setup multiple work trees without cleanup\n";2166 cleanupWorkTree();2167exit;2168}21692170$work->{workDir} = tempdir ( DIR =>$TEMP_DIR);21712172if( !defined($work->{index}) )2173{2174(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2175}21762177chdir$work->{workDir}or2178die"Unable to chdir to$work->{workDir}\n";21792180$log->info("Setting up GIT_WORK_TREE as '.' in '$work->{workDir}', index file is '$work->{index}'");21812182$ENV{GIT_WORK_TREE} =".";2183$ENV{GIT_INDEX_FILE} =$work->{index};2184$work->{state} =2;21852186if($ver)2187{2188system("git","read-tree",$ver);2189unless($?==0)2190{2191$log->warn("Error running git-read-tree");2192die"Error running git-read-tree$verin$work->{workDir}$!\n";2193}2194}2195# else # req_annotate reads tree for each file2196}21972198# Ensure current directory is in some kind of working directory,2199# with a recent version loaded in the index.2200sub ensureWorkTree2201{2202if(defined($work->{tmpDir}) )2203{2204$log->warn("Bad work tree state management [ensureWorkTree()]");2205print"error 1 Internal setup multiple dirs without cleanup\n";2206 cleanupWorkTree();2207exit;2208}2209if($work->{state} )2210{2211return;2212}22132214 validateGitDir();22152216if( !defined($work->{emptyDir}) )2217{2218$work->{emptyDir} = tempdir ( DIR =>$TEMP_DIR, OPEN =>0);2219}2220chdir$work->{emptyDir}or2221die"Unable to chdir to$work->{emptyDir}\n";22222223my$ver=`git show-ref -s refs/heads/$state->{module}`;2224chomp$ver;2225if($ver!~/^[0-9a-f]{40}$/)2226{2227$log->warn("Error from git show-ref -s refs/head$state->{module}");2228print"error 1 cannot find the current HEAD of module";2229 cleanupWorkTree();2230exit;2231}22322233if( !defined($work->{index}) )2234{2235(undef,$work->{index}) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);2236}22372238$ENV{GIT_WORK_TREE} =".";2239$ENV{GIT_INDEX_FILE} =$work->{index};2240$work->{state} =1;22412242system("git","read-tree",$ver);2243unless($?==0)2244{2245die"Error running git-read-tree$ver$!\n";2246}2247}22482249# Cleanup working directory that is not needed any longer.2250sub cleanupWorkTree2251{2252if( !$work->{state} )2253{2254return;2255}22562257chdir"/"or die"Unable to chdir '/'\n";22582259if(defined($work->{workDir}) )2260{2261 rmtree($work->{workDir} );2262undef$work->{workDir};2263}2264undef$work->{state};2265}22662267# Setup a temporary directory (not a working tree), typically for2268# merging dirty state as in req_update.2269sub setupTmpDir2270{2271$work->{tmpDir} = tempdir ( DIR =>$TEMP_DIR);2272chdir$work->{tmpDir}or die"Unable to chdir$work->{tmpDir}\n";22732274return$work->{tmpDir};2275}22762277# Clean up a previously setupTmpDir. Restore previous work tree if2278# appropriate.2279sub cleanupTmpDir2280{2281if( !defined($work->{tmpDir}) )2282{2283$log->warn("cleanup tmpdir that has not been setup");2284die"Cleanup tmpDir that has not been setup\n";2285}2286if(defined($work->{state}) )2287{2288if($work->{state} ==1)2289{2290chdir$work->{emptyDir}or2291die"Unable to chdir to$work->{emptyDir}\n";2292}2293elsif($work->{state} ==2)2294{2295chdir$work->{workDir}or2296die"Unable to chdir to$work->{emptyDir}\n";2297}2298else2299{2300$log->warn("Inconsistent work dir state");2301die"Inconsistent work dir state\n";2302}2303}2304else2305{2306chdir"/"or die"Unable to chdir '/'\n";2307}2308}23092310# Given a path, this function returns a string containing the kopts2311# that should go into that path's Entries line. For example, a binary2312# file should get -kb.2313sub kopts_from_path2314{2315my($path) =@_;23162317if(defined($cfg->{gitcvs}{usecrlfattr} )and2318$cfg->{gitcvs}{usecrlfattr} =~/\s*(1|true|yes)\s*$/i)2319{2320my($val) = check_attr("crlf",$path);2321if($valeq"set")2322{2323return"";2324}2325elsif($valeq"unset")2326{2327return"-kb"2328}2329else2330{2331$log->info("Unrecognized check_attr crlf$path:$val");2332}2333}23342335unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)2336{2337# Return "" to give no special treatment to any path2338return"";2339}else{2340# Alternatively, to have all files treated as if they are binary (which2341# is more like git itself), always return the "-kb" option2342return"-kb";2343}2344}23452346sub check_attr2347{2348my($attr,$path) =@_;2349 ensureWorkTree();2350if(open my$fh,'-|',"git","check-attr",$attr,"--",$path)2351{2352my$val= <$fh>;2353close$fh;2354$val=~s/.*: ([^:\r\n]*)\s*$/$1/;2355return$val;2356}2357else2358{2359returnundef;2360}2361}23622363# Generate a CVS author name from Git author information, by taking2364# the first eight characters of the user part of the email address.2365sub cvs_author2366{2367my$author_line=shift;2368(my$author) =$author_line=~/<([^>@]{1,8})/;23692370$author;2371}23722373package GITCVS::log;23742375####2376#### Copyright The Open University UK - 2006.2377####2378#### Authors: Martyn Smith <martyn@catalyst.net.nz>2379#### Martin Langhoff <martin@catalyst.net.nz>2380####2381####23822383use strict;2384use warnings;23852386=head1 NAME23872388GITCVS::log23892390=head1 DESCRIPTION23912392This module provides very crude logging with a similar interface to2393Log::Log4perl23942395=head1 METHODS23962397=cut23982399=head2 new24002401Creates a new log object, optionally you can specify a filename here to2402indicate the file to log to. If no log file is specified, you can specify one2403later with method setfile, or indicate you no longer want logging with method2404nofile.24052406Until one of these methods is called, all log calls will buffer messages ready2407to write out.24082409=cut2410sub new2411{2412my$class=shift;2413my$filename=shift;24142415my$self= {};24162417bless$self,$class;24182419if(defined($filename) )2420{2421open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2422}24232424return$self;2425}24262427=head2 setfile24282429This methods takes a filename, and attempts to open that file as the log file.2430If successful, all buffered data is written out to the file, and any further2431logging is written directly to the file.24322433=cut2434sub setfile2435{2436my$self=shift;2437my$filename=shift;24382439if(defined($filename) )2440{2441open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2442}24432444return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");24452446while(my$line=shift@{$self->{buffer}} )2447{2448print{$self->{fh}}$line;2449}2450}24512452=head2 nofile24532454This method indicates no logging is going to be used. It flushes any entries in2455the internal buffer, and sets a flag to ensure no further data is put there.24562457=cut2458sub nofile2459{2460my$self=shift;24612462$self->{nolog} =1;24632464return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");24652466$self->{buffer} = [];2467}24682469=head2 _logopen24702471Internal method. Returns true if the log file is open, false otherwise.24722473=cut2474sub _logopen2475{2476my$self=shift;24772478return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2479return0;2480}24812482=head2 debug info warn fatal24832484These four methods are wrappers to _log. They provide the actual interface for2485logging data.24862487=cut2488sub debug {my$self=shift;$self->_log("debug",@_); }2489sub info {my$self=shift;$self->_log("info",@_); }2490subwarn{my$self=shift;$self->_log("warn",@_); }2491sub fatal {my$self=shift;$self->_log("fatal",@_); }24922493=head2 _log24942495This is an internal method called by the logging functions. It generates a2496timestamp and pushes the logged line either to file, or internal buffer.24972498=cut2499sub _log2500{2501my$self=shift;2502my$level=shift;25032504return if($self->{nolog} );25052506my@time=localtime;2507my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2508$time[5] +1900,2509$time[4] +1,2510$time[3],2511$time[2],2512$time[1],2513$time[0],2514uc$level,2515);25162517if($self->_logopen)2518{2519print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2520}else{2521push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2522}2523}25242525=head2 DESTROY25262527This method simply closes the file handle if one is open25282529=cut2530sub DESTROY2531{2532my$self=shift;25332534if($self->_logopen)2535{2536close$self->{fh};2537}2538}25392540package GITCVS::updater;25412542####2543#### Copyright The Open University UK - 2006.2544####2545#### Authors: Martyn Smith <martyn@catalyst.net.nz>2546#### Martin Langhoff <martin@catalyst.net.nz>2547####2548####25492550use strict;2551use warnings;2552use DBI;25532554=head1 METHODS25552556=cut25572558=head2 new25592560=cut2561sub new2562{2563my$class=shift;2564my$config=shift;2565my$module=shift;2566my$log=shift;25672568die"Need to specify a git repository"unless(defined($config)and-d $config);2569die"Need to specify a module"unless(defined($module) );25702571$class=ref($class) ||$class;25722573my$self= {};25742575bless$self,$class;25762577$self->{valid_tables} = {'revision'=>1,2578'revision_ix1'=>1,2579'revision_ix2'=>1,2580'head'=>1,2581'head_ix1'=>1,2582'properties'=>1,2583'commitmsgs'=>1};25842585$self->{module} =$module;2586$self->{git_path} =$config."/";25872588$self->{log} =$log;25892590die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );25912592$self->{dbdriver} =$cfg->{gitcvs}{$state->{method}}{dbdriver} ||2593$cfg->{gitcvs}{dbdriver} ||"SQLite";2594$self->{dbname} =$cfg->{gitcvs}{$state->{method}}{dbname} ||2595$cfg->{gitcvs}{dbname} ||"%Ggitcvs.%m.sqlite";2596$self->{dbuser} =$cfg->{gitcvs}{$state->{method}}{dbuser} ||2597$cfg->{gitcvs}{dbuser} ||"";2598$self->{dbpass} =$cfg->{gitcvs}{$state->{method}}{dbpass} ||2599$cfg->{gitcvs}{dbpass} ||"";2600$self->{dbtablenameprefix} =$cfg->{gitcvs}{$state->{method}}{dbtablenameprefix} ||2601$cfg->{gitcvs}{dbtablenameprefix} ||"";2602my%mapping= ( m =>$module,2603 a =>$state->{method},2604 u =>getlogin||getpwuid($<) || $<,2605 G =>$self->{git_path},2606 g => mangle_dirname($self->{git_path}),2607);2608$self->{dbname} =~s/%([mauGg])/$mapping{$1}/eg;2609$self->{dbuser} =~s/%([mauGg])/$mapping{$1}/eg;2610$self->{dbtablenameprefix} =~s/%([mauGg])/$mapping{$1}/eg;2611$self->{dbtablenameprefix} = mangle_tablename($self->{dbtablenameprefix});26122613die"Invalid char ':' in dbdriver"if$self->{dbdriver} =~/:/;2614die"Invalid char ';' in dbname"if$self->{dbname} =~/;/;2615$self->{dbh} = DBI->connect("dbi:$self->{dbdriver}:dbname=$self->{dbname}",2616$self->{dbuser},2617$self->{dbpass});2618die"Error connecting to database\n"unlessdefined$self->{dbh};26192620$self->{tables} = {};2621foreachmy$table(keys%{$self->{dbh}->table_info(undef,undef,undef,'TABLE')->fetchall_hashref('TABLE_NAME')} )2622{2623$self->{tables}{$table} =1;2624}26252626# Construct the revision table if required2627unless($self->{tables}{$self->tablename("revision")} )2628{2629my$tablename=$self->tablename("revision");2630my$ix1name=$self->tablename("revision_ix1");2631my$ix2name=$self->tablename("revision_ix2");2632$self->{dbh}->do("2633 CREATE TABLE$tablename(2634 name TEXT NOT NULL,2635 revision INTEGER NOT NULL,2636 filehash TEXT NOT NULL,2637 commithash TEXT NOT NULL,2638 author TEXT NOT NULL,2639 modified TEXT NOT NULL,2640 mode TEXT NOT NULL2641 )2642 ");2643$self->{dbh}->do("2644 CREATE INDEX$ix1name2645 ON$tablename(name,revision)2646 ");2647$self->{dbh}->do("2648 CREATE INDEX$ix2name2649 ON$tablename(name,commithash)2650 ");2651}26522653# Construct the head table if required2654unless($self->{tables}{$self->tablename("head")} )2655{2656my$tablename=$self->tablename("head");2657my$ix1name=$self->tablename("head_ix1");2658$self->{dbh}->do("2659 CREATE TABLE$tablename(2660 name TEXT NOT NULL,2661 revision INTEGER NOT NULL,2662 filehash TEXT NOT NULL,2663 commithash TEXT NOT NULL,2664 author TEXT NOT NULL,2665 modified TEXT NOT NULL,2666 mode TEXT NOT NULL2667 )2668 ");2669$self->{dbh}->do("2670 CREATE INDEX$ix1name2671 ON$tablename(name)2672 ");2673}26742675# Construct the properties table if required2676unless($self->{tables}{$self->tablename("properties")} )2677{2678my$tablename=$self->tablename("properties");2679$self->{dbh}->do("2680 CREATE TABLE$tablename(2681 key TEXT NOT NULL PRIMARY KEY,2682 value TEXT2683 )2684 ");2685}26862687# Construct the commitmsgs table if required2688unless($self->{tables}{$self->tablename("commitmsgs")} )2689{2690my$tablename=$self->tablename("commitmsgs");2691$self->{dbh}->do("2692 CREATE TABLE$tablename(2693 key TEXT NOT NULL PRIMARY KEY,2694 value TEXT2695 )2696 ");2697}26982699return$self;2700}27012702=head2 tablename27032704=cut2705sub tablename2706{2707my$self=shift;2708my$name=shift;27092710if(exists$self->{valid_tables}{$name}) {2711return$self->{dbtablenameprefix} .$name;2712}else{2713returnundef;2714}2715}27162717=head2 update27182719=cut2720sub update2721{2722my$self=shift;27232724# first lets get the commit list2725$ENV{GIT_DIR} =$self->{git_path};27262727my$commitsha1=`git rev-parse$self->{module}`;2728chomp$commitsha1;27292730my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2731unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2732{2733die("Invalid module '$self->{module}'");2734}273527362737my$git_log;2738my$lastcommit=$self->_get_prop("last_commit");27392740if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2741return1;2742}27432744# Start exclusive lock here...2745$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";27462747# TODO: log processing is memory bound2748# if we can parse into a 2nd file that is in reverse order2749# we can probably do something really efficient2750my@git_log_params= ('--pretty','--parents','--topo-order');27512752if(defined$lastcommit) {2753push@git_log_params,"$lastcommit..$self->{module}";2754}else{2755push@git_log_params,$self->{module};2756}2757# git-rev-list is the backend / plumbing version of git-log2758open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";27592760my@commits;27612762my%commit= ();27632764while( <GITLOG> )2765{2766chomp;2767if(m/^commit\s+(.*)$/) {2768# on ^commit lines put the just seen commit in the stack2769# and prime things for the next one2770if(keys%commit) {2771my%copy=%commit;2772unshift@commits, \%copy;2773%commit= ();2774}2775my@parents=split(m/\s+/,$1);2776$commit{hash} =shift@parents;2777$commit{parents} = \@parents;2778}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2779# on rfc822-like lines seen before we see any message,2780# lowercase the entry and put it in the hash as key-value2781$commit{lc($1)} =$2;2782}else{2783# message lines - skip initial empty line2784# and trim whitespace2785if(!exists($commit{message}) &&m/^\s*$/) {2786# define it to mark the end of headers2787$commit{message} ='';2788next;2789}2790s/^\s+//;s/\s+$//;# trim ws2791$commit{message} .=$_."\n";2792}2793}2794close GITLOG;27952796unshift@commits, \%commitif(keys%commit);27972798# Now all the commits are in the @commits bucket2799# ordered by time DESC. for each commit that needs processing,2800# determine whether it's following the last head we've seen or if2801# it's on its own branch, grab a file list, and add whatever's changed2802# NOTE: $lastcommit refers to the last commit from previous run2803# $lastpicked is the last commit we picked in this run2804my$lastpicked;2805my$head= {};2806if(defined$lastcommit) {2807$lastpicked=$lastcommit;2808}28092810my$committotal=scalar(@commits);2811my$commitcount=0;28122813# Load the head table into $head (for cached lookups during the update process)2814foreachmy$file( @{$self->gethead()} )2815{2816$head->{$file->{name}} =$file;2817}28182819foreachmy$commit(@commits)2820{2821$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2822if(defined$lastpicked)2823{2824if(!in_array($lastpicked, @{$commit->{parents}}))2825{2826# skip, we'll see this delta2827# as part of a merge later2828# warn "skipping off-track $commit->{hash}\n";2829next;2830}elsif(@{$commit->{parents}} >1) {2831# it is a merge commit, for each parent that is2832# not $lastpicked, see if we can get a log2833# from the merge-base to that parent to put it2834# in the message as a merge summary.2835my@parents= @{$commit->{parents}};2836foreachmy$parent(@parents) {2837# git-merge-base can potentially (but rarely) throw2838# several candidate merge bases. let's assume2839# that the first one is the best one.2840if($parenteq$lastpicked) {2841next;2842}2843my$base=eval{2844 safe_pipe_capture('git-merge-base',2845$lastpicked,$parent);2846};2847# The two branches may not be related at all,2848# in which case merge base simply fails to find2849# any, but that's Ok.2850next if($@);28512852chomp$base;2853if($base) {2854my@merged;2855# print "want to log between $base $parent \n";2856open(GITLOG,'-|','git-log','--pretty=medium',"$base..$parent")2857or die"Cannot call git-log:$!";2858my$mergedhash;2859while(<GITLOG>) {2860chomp;2861if(!defined$mergedhash) {2862if(m/^commit\s+(.+)$/) {2863$mergedhash=$1;2864}else{2865next;2866}2867}else{2868# grab the first line that looks non-rfc8222869# aka has content after leading space2870if(m/^\s+(\S.*)$/) {2871my$title=$1;2872$title=substr($title,0,100);# truncate2873unshift@merged,"$mergedhash$title";2874undef$mergedhash;2875}2876}2877}2878close GITLOG;2879if(@merged) {2880$commit->{mergemsg} =$commit->{message};2881$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2882foreachmy$summary(@merged) {2883$commit->{mergemsg} .="\t$summary\n";2884}2885$commit->{mergemsg} .="\n\n";2886# print "Message for $commit->{hash} \n$commit->{mergemsg}";2887}2888}2889}2890}2891}28922893# convert the date to CVS-happy format2894$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);28952896if(defined($lastpicked) )2897{2898my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2899local($/) ="\0";2900while( <FILELIST> )2901{2902chomp;2903unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2904{2905die("Couldn't process git-diff-tree line :$_");2906}2907my($mode,$hash,$change) = ($1,$2,$3);2908my$name= <FILELIST>;2909chomp($name);29102911# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");29122913my$git_perms="";2914$git_perms.="r"if($mode&4);2915$git_perms.="w"if($mode&2);2916$git_perms.="x"if($mode&1);2917$git_perms="rw"if($git_permseq"");29182919if($changeeq"D")2920{2921#$log->debug("DELETE $name");2922$head->{$name} = {2923 name =>$name,2924 revision =>$head->{$name}{revision} +1,2925 filehash =>"deleted",2926 commithash =>$commit->{hash},2927 modified =>$commit->{date},2928 author =>$commit->{author},2929 mode =>$git_perms,2930};2931$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2932}2933elsif($changeeq"M"||$changeeq"T")2934{2935#$log->debug("MODIFIED $name");2936$head->{$name} = {2937 name =>$name,2938 revision =>$head->{$name}{revision} +1,2939 filehash =>$hash,2940 commithash =>$commit->{hash},2941 modified =>$commit->{date},2942 author =>$commit->{author},2943 mode =>$git_perms,2944};2945$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2946}2947elsif($changeeq"A")2948{2949#$log->debug("ADDED $name");2950$head->{$name} = {2951 name =>$name,2952 revision =>$head->{$name}{revision} ?$head->{$name}{revision}+1:1,2953 filehash =>$hash,2954 commithash =>$commit->{hash},2955 modified =>$commit->{date},2956 author =>$commit->{author},2957 mode =>$git_perms,2958};2959$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2960}2961else2962{2963$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2964die;2965}2966}2967close FILELIST;2968}else{2969# this is used to detect files removed from the repo2970my$seen_files= {};29712972my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2973local$/="\0";2974while( <FILELIST> )2975{2976chomp;2977unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2978{2979die("Couldn't process git-ls-tree line :$_");2980}29812982my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);29832984$seen_files->{$git_filename} =1;29852986my($oldhash,$oldrevision,$oldmode) = (2987$head->{$git_filename}{filehash},2988$head->{$git_filename}{revision},2989$head->{$git_filename}{mode}2990);29912992if($git_perms=~/^\d\d\d(\d)\d\d/o)2993{2994$git_perms="";2995$git_perms.="r"if($1&4);2996$git_perms.="w"if($1&2);2997$git_perms.="x"if($1&1);2998}else{2999$git_perms="rw";3000}30013002# unless the file exists with the same hash, we need to update it ...3003unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)3004{3005my$newrevision= ($oldrevisionor0) +1;30063007$head->{$git_filename} = {3008 name =>$git_filename,3009 revision =>$newrevision,3010 filehash =>$git_hash,3011 commithash =>$commit->{hash},3012 modified =>$commit->{date},3013 author =>$commit->{author},3014 mode =>$git_perms,3015};301630173018$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);3019}3020}3021close FILELIST;30223023# Detect deleted files3024foreachmy$file(keys%$head)3025{3026unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")3027{3028$head->{$file}{revision}++;3029$head->{$file}{filehash} ="deleted";3030$head->{$file}{commithash} =$commit->{hash};3031$head->{$file}{modified} =$commit->{date};3032$head->{$file}{author} =$commit->{author};30333034$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});3035}3036}3037# END : "Detect deleted files"3038}303930403041if(exists$commit->{mergemsg})3042{3043$self->insert_mergelog($commit->{hash},$commit->{mergemsg});3044}30453046$lastpicked=$commit->{hash};30473048$self->_set_prop("last_commit",$commit->{hash});3049}30503051$self->delete_head();3052foreachmy$file(keys%$head)3053{3054$self->insert_head(3055$file,3056$head->{$file}{revision},3057$head->{$file}{filehash},3058$head->{$file}{commithash},3059$head->{$file}{modified},3060$head->{$file}{author},3061$head->{$file}{mode},3062);3063}3064# invalidate the gethead cache3065$self->{gethead_cache} =undef;306630673068# Ending exclusive lock here3069$self->{dbh}->commit()or die"Failed to commit changes to SQLite";3070}30713072sub insert_rev3073{3074my$self=shift;3075my$name=shift;3076my$revision=shift;3077my$filehash=shift;3078my$commithash=shift;3079my$modified=shift;3080my$author=shift;3081my$mode=shift;3082my$tablename=$self->tablename("revision");30833084my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3085$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3086}30873088sub insert_mergelog3089{3090my$self=shift;3091my$key=shift;3092my$value=shift;3093my$tablename=$self->tablename("commitmsgs");30943095my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3096$insert_mergelog->execute($key,$value);3097}30983099sub delete_head3100{3101my$self=shift;3102my$tablename=$self->tablename("head");31033104my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM$tablename",{},1);3105$delete_head->execute();3106}31073108sub insert_head3109{3110my$self=shift;3111my$name=shift;3112my$revision=shift;3113my$filehash=shift;3114my$commithash=shift;3115my$modified=shift;3116my$author=shift;3117my$mode=shift;3118my$tablename=$self->tablename("head");31193120my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO$tablename(name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);3121$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);3122}31233124sub _headrev3125{3126my$self=shift;3127my$filename=shift;3128my$tablename=$self->tablename("head");31293130my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM$tablenameWHERE name=?",{},1);3131$db_query->execute($filename);3132my($hash,$revision,$mode) =$db_query->fetchrow_array;31333134return($hash,$revision,$mode);3135}31363137sub _get_prop3138{3139my$self=shift;3140my$key=shift;3141my$tablename=$self->tablename("properties");31423143my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3144$db_query->execute($key);3145my($value) =$db_query->fetchrow_array;31463147return$value;3148}31493150sub _set_prop3151{3152my$self=shift;3153my$key=shift;3154my$value=shift;3155my$tablename=$self->tablename("properties");31563157my$db_query=$self->{dbh}->prepare_cached("UPDATE$tablenameSET value=? WHERE key=?",{},1);3158$db_query->execute($value,$key);31593160unless($db_query->rows)3161{3162$db_query=$self->{dbh}->prepare_cached("INSERT INTO$tablename(key, value) VALUES (?,?)",{},1);3163$db_query->execute($key,$value);3164}31653166return$value;3167}31683169=head2 gethead31703171=cut31723173sub gethead3174{3175my$self=shift;3176my$tablename=$self->tablename("head");31773178return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );31793180my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM$tablenameORDER BY name ASC",{},1);3181$db_query->execute();31823183my$tree= [];3184while(my$file=$db_query->fetchrow_hashref)3185{3186push@$tree,$file;3187}31883189$self->{gethead_cache} =$tree;31903191return$tree;3192}31933194=head2 getlog31953196=cut31973198sub getlog3199{3200my$self=shift;3201my$filename=shift;3202my$tablename=$self->tablename("revision");32033204my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3205$db_query->execute($filename);32063207my$tree= [];3208while(my$file=$db_query->fetchrow_hashref)3209{3210push@$tree,$file;3211}32123213return$tree;3214}32153216=head2 getmeta32173218This function takes a filename (with path) argument and returns a hashref of3219metadata for that file.32203221=cut32223223sub getmeta3224{3225my$self=shift;3226my$filename=shift;3227my$revision=shift;3228my$tablename_rev=$self->tablename("revision");3229my$tablename_head=$self->tablename("head");32303231my$db_query;3232if(defined($revision)and$revision=~/^\d+$/)3233{3234$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND revision=?",{},1);3235$db_query->execute($filename,$revision);3236}3237elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)3238{3239$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_revWHERE name=? AND commithash=?",{},1);3240$db_query->execute($filename,$revision);3241}else{3242$db_query=$self->{dbh}->prepare_cached("SELECT * FROM$tablename_headWHERE name=?",{},1);3243$db_query->execute($filename);3244}32453246return$db_query->fetchrow_hashref;3247}32483249=head2 commitmessage32503251this function takes a commithash and returns the commit message for that commit32523253=cut3254sub commitmessage3255{3256my$self=shift;3257my$commithash=shift;3258my$tablename=$self->tablename("commitmsgs");32593260die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);32613262my$db_query;3263$db_query=$self->{dbh}->prepare_cached("SELECT value FROM$tablenameWHERE key=?",{},1);3264$db_query->execute($commithash);32653266my($message) =$db_query->fetchrow_array;32673268if(defined($message) )3269{3270$message.=" "if($message=~/\n$/);3271return$message;3272}32733274my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);3275shift@lineswhile($lines[0] =~/\S/);3276$message=join("",@lines);3277$message.=" "if($message=~/\n$/);3278return$message;3279}32803281=head2 gethistory32823283This function takes a filename (with path) argument and returns an arrayofarrays3284containing revision,filehash,commithash ordered by revision descending32853286=cut3287sub gethistory3288{3289my$self=shift;3290my$filename=shift;3291my$tablename=$self->tablename("revision");32923293my$db_query;3294$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? ORDER BY revision DESC",{},1);3295$db_query->execute($filename);32963297return$db_query->fetchall_arrayref;3298}32993300=head2 gethistorydense33013302This function takes a filename (with path) argument and returns an arrayofarrays3303containing revision,filehash,commithash ordered by revision descending.33043305This version of gethistory skips deleted entries -- so it is useful for annotate.3306The 'dense' part is a reference to a '--dense' option available for git-rev-list3307and other git tools that depend on it.33083309=cut3310sub gethistorydense3311{3312my$self=shift;3313my$filename=shift;3314my$tablename=$self->tablename("revision");33153316my$db_query;3317$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM$tablenameWHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);3318$db_query->execute($filename);33193320return$db_query->fetchall_arrayref;3321}33223323=head2 in_array()33243325from Array::PAT - mimics the in_array() function3326found in PHP. Yuck but works for small arrays.33273328=cut3329sub in_array3330{3331my($check,@array) =@_;3332my$retval=0;3333foreachmy$test(@array){3334if($checkeq$test){3335$retval=1;3336}3337}3338return$retval;3339}33403341=head2 safe_pipe_capture33423343an alternative to `command` that allows input to be passed as an array3344to work around shell problems with weird characters in arguments33453346=cut3347sub safe_pipe_capture {33483349my@output;33503351if(my$pid=open my$child,'-|') {3352@output= (<$child>);3353close$childor die join(' ',@_).":$!$?";3354}else{3355exec(@_)or die"$!$?";# exec() can fail the executable can't be found3356}3357returnwantarray?@output:join('',@output);3358}33593360=head2 mangle_dirname33613362create a string from a directory name that is suitable to use as3363part of a filename, mainly by converting all chars except \w.- to _33643365=cut3366sub mangle_dirname {3367my$dirname=shift;3368return unlessdefined$dirname;33693370$dirname=~s/[^\w.-]/_/g;33713372return$dirname;3373}33743375=head2 mangle_tablename33763377create a string from a that is suitable to use as part of an SQL table3378name, mainly by converting all chars except \w to _33793380=cut3381sub mangle_tablename {3382my$tablename=shift;3383return unlessdefined$tablename;33843385$tablename=~s/[^\w_]/_/g;33863387return$tablename;3388}338933901;