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::Basename; 25 26my$log= GITCVS::log->new(); 27my$cfg; 28 29my$DATE_LIST= { 30 Jan =>"01", 31 Feb =>"02", 32 Mar =>"03", 33 Apr =>"04", 34 May =>"05", 35 Jun =>"06", 36 Jul =>"07", 37 Aug =>"08", 38 Sep =>"09", 39 Oct =>"10", 40 Nov =>"11", 41 Dec =>"12", 42}; 43 44# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 45$| =1; 46 47#### Definition and mappings of functions #### 48 49my$methods= { 50'Root'=> \&req_Root, 51'Valid-responses'=> \&req_Validresponses, 52'valid-requests'=> \&req_validrequests, 53'Directory'=> \&req_Directory, 54'Entry'=> \&req_Entry, 55'Modified'=> \&req_Modified, 56'Unchanged'=> \&req_Unchanged, 57'Questionable'=> \&req_Questionable, 58'Argument'=> \&req_Argument, 59'Argumentx'=> \&req_Argument, 60'expand-modules'=> \&req_expandmodules, 61'add'=> \&req_add, 62'remove'=> \&req_remove, 63'co'=> \&req_co, 64'update'=> \&req_update, 65'ci'=> \&req_ci, 66'diff'=> \&req_diff, 67'log'=> \&req_log, 68'rlog'=> \&req_log, 69'tag'=> \&req_CATCHALL, 70'status'=> \&req_status, 71'admin'=> \&req_CATCHALL, 72'history'=> \&req_CATCHALL, 73'watchers'=> \&req_CATCHALL, 74'editors'=> \&req_CATCHALL, 75'annotate'=> \&req_annotate, 76'Global_option'=> \&req_Globaloption, 77#'annotate' => \&req_CATCHALL, 78}; 79 80############################################## 81 82 83# $state holds all the bits of information the clients sends us that could 84# potentially be useful when it comes to actually _doing_ something. 85my$state= { prependdir =>''}; 86$log->info("--------------- STARTING -----------------"); 87 88my$TEMP_DIR= tempdir( CLEANUP =>1); 89$log->debug("Temporary directory is '$TEMP_DIR'"); 90 91# if we are called with a pserver argument, 92# deal with the authentication cat before entering the 93# main loop 94if(@ARGV&&$ARGV[0]eq'pserver') { 95my$line= <STDIN>;chomp$line; 96unless($lineeq'BEGIN AUTH REQUEST') { 97die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 98} 99$line= <STDIN>;chomp$line; 100 req_Root('root',$line)# reuse Root 101or die"E Invalid root$line\n"; 102$line= <STDIN>;chomp$line; 103unless($lineeq'anonymous') { 104print"E Only anonymous user allowed via pserver\n"; 105print"I HATE YOU\n"; 106} 107$line= <STDIN>;chomp$line;# validate the password? 108$line= <STDIN>;chomp$line; 109unless($lineeq'END AUTH REQUEST') { 110die"E Do not understand$line-- expecting END AUTH REQUEST\n"; 111} 112print"I LOVE YOU\n"; 113# and now back to our regular programme... 114} 115 116# Keep going until the client closes the connection 117while(<STDIN>) 118{ 119chomp; 120 121# Check to see if we've seen this method, and call appropriate function. 122if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 123{ 124# use the $methods hash to call the appropriate sub for this command 125#$log->info("Method : $1"); 126&{$methods->{$1}}($1,$2); 127}else{ 128# log fatal because we don't understand this function. If this happens 129# we're fairly screwed because we don't know if the client is expecting 130# a response. If it is, the client will hang, we'll hang, and the whole 131# thing will be custard. 132$log->fatal("Don't understand command$_\n"); 133die("Unknown command$_"); 134} 135} 136 137$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 138$log->info("--------------- FINISH -----------------"); 139 140# Magic catchall method. 141# This is the method that will handle all commands we haven't yet 142# implemented. It simply sends a warning to the log file indicating a 143# command that hasn't been implemented has been invoked. 144sub req_CATCHALL 145{ 146my($cmd,$data) =@_; 147$log->warn("Unhandled command : req_$cmd:$data"); 148} 149 150 151# Root pathname \n 152# Response expected: no. Tell the server which CVSROOT to use. Note that 153# pathname is a local directory and not a fully qualified CVSROOT variable. 154# pathname must already exist; if creating a new root, use the init 155# request, not Root. pathname does not include the hostname of the server, 156# how to access the server, etc.; by the time the CVS protocol is in use, 157# connection, authentication, etc., are already taken care of. The Root 158# request must be sent only once, and it must be sent before any requests 159# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 160sub req_Root 161{ 162my($cmd,$data) =@_; 163$log->debug("req_Root :$data"); 164 165$state->{CVSROOT} =$data; 166 167$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 168unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 169print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 170print"E\n"; 171print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 172return0; 173} 174 175my@gitvars=`git-config -l`; 176if($?) { 177print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 178print"E\n"; 179print"error 1 - problem executing git-config\n"; 180return0; 181} 182foreachmy$line(@gitvars) 183{ 184next unless($line=~/^(.*?)\.(.*?)=(.*)$/); 185$cfg->{$1}{$2} =$3; 186} 187 188unless(defined($cfg->{gitcvs}{enabled} )and$cfg->{gitcvs}{enabled} =~/^\s*(1|true|yes)\s*$/i) 189{ 190print"E GITCVS emulation needs to be enabled on this repo\n"; 191print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 192print"E\n"; 193print"error 1 GITCVS emulation disabled\n"; 194return0; 195} 196 197if(defined($cfg->{gitcvs}{logfile} ) ) 198{ 199$log->setfile($cfg->{gitcvs}{logfile}); 200}else{ 201$log->nofile(); 202} 203 204return1; 205} 206 207# Global_option option \n 208# Response expected: no. Transmit one of the global options `-q', `-Q', 209# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 210# variations (such as combining of options) are allowed. For graceful 211# handling of valid-requests, it is probably better to make new global 212# options separate requests, rather than trying to add them to this 213# request. 214sub req_Globaloption 215{ 216my($cmd,$data) =@_; 217$log->debug("req_Globaloption :$data"); 218$state->{globaloptions}{$data} =1; 219} 220 221# Valid-responses request-list \n 222# Response expected: no. Tell the server what responses the client will 223# accept. request-list is a space separated list of tokens. 224sub req_Validresponses 225{ 226my($cmd,$data) =@_; 227$log->debug("req_Validresponses :$data"); 228 229# TODO : re-enable this, currently it's not particularly useful 230#$state->{validresponses} = [ split /\s+/, $data ]; 231} 232 233# valid-requests \n 234# Response expected: yes. Ask the server to send back a Valid-requests 235# response. 236sub req_validrequests 237{ 238my($cmd,$data) =@_; 239 240$log->debug("req_validrequests"); 241 242$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 243$log->debug("SEND : ok"); 244 245print"Valid-requests ".join(" ",keys%$methods) ."\n"; 246print"ok\n"; 247} 248 249# Directory local-directory \n 250# Additional data: repository \n. Response expected: no. Tell the server 251# what directory to use. The repository should be a directory name from a 252# previous server response. Note that this both gives a default for Entry 253# and Modified and also for ci and the other commands; normal usage is to 254# send Directory for each directory in which there will be an Entry or 255# Modified, and then a final Directory for the original directory, then the 256# command. The local-directory is relative to the top level at which the 257# command is occurring (i.e. the last Directory which is sent before the 258# command); to indicate that top level, `.' should be sent for 259# local-directory. 260sub req_Directory 261{ 262my($cmd,$data) =@_; 263 264my$repository= <STDIN>; 265chomp$repository; 266 267 268$state->{localdir} =$data; 269$state->{repository} =$repository; 270$state->{path} =$repository; 271$state->{path} =~s/^$state->{CVSROOT}\///; 272$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 273$state->{path} .="/"if($state->{path} =~ /\S/ ); 274 275$state->{directory} =$state->{localdir}; 276$state->{directory} =""if($state->{directory}eq"."); 277$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 278 279if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 280{ 281$log->info("Setting prepend to '$state->{path}'"); 282$state->{prependdir} =$state->{path}; 283foreachmy$entry(keys%{$state->{entries}} ) 284{ 285$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 286delete$state->{entries}{$entry}; 287} 288} 289 290if(defined($state->{prependdir} ) ) 291{ 292$log->debug("Prepending '$state->{prependdir}' to state|directory"); 293$state->{directory} =$state->{prependdir} .$state->{directory} 294} 295$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 296} 297 298# Entry entry-line \n 299# Response expected: no. Tell the server what version of a file is on the 300# local machine. The name in entry-line is a name relative to the directory 301# most recently specified with Directory. If the user is operating on only 302# some files in a directory, Entry requests for only those files need be 303# included. If an Entry request is sent without Modified, Is-modified, or 304# Unchanged, it means the file is lost (does not exist in the working 305# directory). If both Entry and one of Modified, Is-modified, or Unchanged 306# are sent for the same file, Entry must be sent first. For a given file, 307# one can send Modified, Is-modified, or Unchanged, but not more than one 308# of these three. 309sub req_Entry 310{ 311my($cmd,$data) =@_; 312 313#$log->debug("req_Entry : $data"); 314 315my@data=split(/\//,$data); 316 317$state->{entries}{$state->{directory}.$data[1]} = { 318 revision =>$data[2], 319 conflict =>$data[3], 320 options =>$data[4], 321 tag_or_date =>$data[5], 322}; 323 324$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 325} 326 327# Questionable filename \n 328# Response expected: no. Additional data: no. Tell the server to check 329# whether filename should be ignored, and if not, next time the server 330# sends responses, send (in a M response) `?' followed by the directory and 331# filename. filename must not contain `/'; it needs to be a file in the 332# directory named by the most recent Directory request. 333sub req_Questionable 334{ 335my($cmd,$data) =@_; 336 337$log->debug("req_Questionable :$data"); 338$state->{entries}{$state->{directory}.$data}{questionable} =1; 339} 340 341# add \n 342# Response expected: yes. Add a file or directory. This uses any previous 343# Argument, Directory, Entry, or Modified requests, if they have been sent. 344# The last Directory sent specifies the working directory at the time of 345# the operation. To add a directory, send the directory to be added using 346# Directory and Argument requests. 347sub req_add 348{ 349my($cmd,$data) =@_; 350 351 argsplit("add"); 352 353my$addcount=0; 354 355foreachmy$filename( @{$state->{args}} ) 356{ 357$filename= filecleanup($filename); 358 359unless(defined($state->{entries}{$filename}{modified_filename} ) ) 360{ 361print"E cvs add: nothing known about `$filename'\n"; 362next; 363} 364# TODO : check we're not squashing an already existing file 365if(defined($state->{entries}{$filename}{revision} ) ) 366{ 367print"E cvs add: `$filename' has already been entered\n"; 368next; 369} 370 371my($filepart,$dirpart) = filenamesplit($filename,1); 372 373print"E cvs add: scheduling file `$filename' for addition\n"; 374 375print"Checked-in$dirpart\n"; 376print"$filename\n"; 377my$kopts= kopts_from_path($filepart); 378print"/$filepart/0//$kopts/\n"; 379 380$addcount++; 381} 382 383if($addcount==1) 384{ 385print"E cvs add: use `cvs commit' to add this file permanently\n"; 386} 387elsif($addcount>1) 388{ 389print"E cvs add: use `cvs commit' to add these files permanently\n"; 390} 391 392print"ok\n"; 393} 394 395# remove \n 396# Response expected: yes. Remove a file. This uses any previous Argument, 397# Directory, Entry, or Modified requests, if they have been sent. The last 398# Directory sent specifies the working directory at the time of the 399# operation. Note that this request does not actually do anything to the 400# repository; the only effect of a successful remove request is to supply 401# the client with a new entries line containing `-' to indicate a removed 402# file. In fact, the client probably could perform this operation without 403# contacting the server, although using remove may cause the server to 404# perform a few more checks. The client sends a subsequent ci request to 405# actually record the removal in the repository. 406sub req_remove 407{ 408my($cmd,$data) =@_; 409 410 argsplit("remove"); 411 412# Grab a handle to the SQLite db and do any necessary updates 413my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 414$updater->update(); 415 416#$log->debug("add state : " . Dumper($state)); 417 418my$rmcount=0; 419 420foreachmy$filename( @{$state->{args}} ) 421{ 422$filename= filecleanup($filename); 423 424if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 425{ 426print"E cvs remove: file `$filename' still in working directory\n"; 427next; 428} 429 430my$meta=$updater->getmeta($filename); 431my$wrev= revparse($filename); 432 433unless(defined($wrev) ) 434{ 435print"E cvs remove: nothing known about `$filename'\n"; 436next; 437} 438 439if(defined($wrev)and$wrev<0) 440{ 441print"E cvs remove: file `$filename' already scheduled for removal\n"; 442next; 443} 444 445unless($wrev==$meta->{revision} ) 446{ 447# TODO : not sure if the format of this message is quite correct. 448print"E cvs remove: Up to date check failed for `$filename'\n"; 449next; 450} 451 452 453my($filepart,$dirpart) = filenamesplit($filename,1); 454 455print"E cvs remove: scheduling `$filename' for removal\n"; 456 457print"Checked-in$dirpart\n"; 458print"$filename\n"; 459my$kopts= kopts_from_path($filepart); 460print"/$filepart/-1.$wrev//$kopts/\n"; 461 462$rmcount++; 463} 464 465if($rmcount==1) 466{ 467print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 468} 469elsif($rmcount>1) 470{ 471print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 472} 473 474print"ok\n"; 475} 476 477# Modified filename \n 478# Response expected: no. Additional data: mode, \n, file transmission. Send 479# the server a copy of one locally modified file. filename is a file within 480# the most recent directory sent with Directory; it must not contain `/'. 481# If the user is operating on only some files in a directory, only those 482# files need to be included. This can also be sent without Entry, if there 483# is no entry for the file. 484sub req_Modified 485{ 486my($cmd,$data) =@_; 487 488my$mode= <STDIN>; 489chomp$mode; 490my$size= <STDIN>; 491chomp$size; 492 493# Grab config information 494my$blocksize=8192; 495my$bytesleft=$size; 496my$tmp; 497 498# Get a filehandle/name to write it to 499my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 500 501# Loop over file data writing out to temporary file. 502while($bytesleft) 503{ 504$blocksize=$bytesleftif($bytesleft<$blocksize); 505read STDIN,$tmp,$blocksize; 506print$fh $tmp; 507$bytesleft-=$blocksize; 508} 509 510close$fh; 511 512# Ensure we have something sensible for the file mode 513if($mode=~/u=(\w+)/) 514{ 515$mode=$1; 516}else{ 517$mode="rw"; 518} 519 520# Save the file data in $state 521$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 522$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 523$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 524$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 525 526 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 527} 528 529# Unchanged filename\n 530# Response expected: no. Tell the server that filename has not been 531# modified in the checked out directory. The filename is a file within the 532# most recent directory sent with Directory; it must not contain `/'. 533sub req_Unchanged 534{ 535 my ($cmd,$data) =@_; 536 537$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 538 539 #$log->debug("req_Unchanged :$data"); 540} 541 542# Argument text\n 543# Response expected: no. Save argument for use in a subsequent command. 544# Arguments accumulate until an argument-using command is given, at which 545# point they are forgotten. 546# Argumentx text\n 547# Response expected: no. Append\nfollowed by text to the current argument 548# being saved. 549sub req_Argument 550{ 551 my ($cmd,$data) =@_; 552 553 # Argumentx means: append to last Argument (with a newline in front) 554 555$log->debug("$cmd:$data"); 556 557 if ($cmdeq 'Argumentx') { 558 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 559 } else { 560 push @{$state->{arguments}},$data; 561 } 562} 563 564# expand-modules\n 565# Response expected: yes. Expand the modules which are specified in the 566# arguments. Returns the data in Module-expansion responses. Note that the 567# server can assume that this is checkout or export, not rtag or rdiff; the 568# latter do not access the working directory and thus have no need to 569# expand modules on the client side. Expand may not be the best word for 570# what this request does. It does not necessarily tell you all the files 571# contained in a module, for example. Basically it is a way of telling you 572# which working directories the server needs to know about in order to 573# handle a checkout of the specified modules. For example, suppose that the 574# server has a module defined by 575# aliasmodule -a 1dir 576# That is, one can check out aliasmodule and it will take 1dir in the 577# repository and check it out to 1dir in the working directory. Now suppose 578# the client already has this module checked out and is planning on using 579# the co request to update it. Without using expand-modules, the client 580# would have two bad choices: it could either send information about all 581# working directories under the current directory, which could be 582# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 583# stands for 1dir, and neglect to send information for 1dir, which would 584# lead to incorrect operation. With expand-modules, the client would first 585# ask for the module to be expanded: 586sub req_expandmodules 587{ 588 my ($cmd,$data) =@_; 589 590 argsplit(); 591 592$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 593 594 unless ( ref$state->{arguments} eq "ARRAY" ) 595 { 596 print "ok\n"; 597 return; 598 } 599 600 foreach my$module( @{$state->{arguments}} ) 601 { 602$log->debug("SEND : Module-expansion$module"); 603 print "Module-expansion$module\n"; 604 } 605 606 print "ok\n"; 607 statecleanup(); 608} 609 610# co\n 611# Response expected: yes. Get files from the repository. This uses any 612# previous Argument, Directory, Entry, or Modified requests, if they have 613# been sent. Arguments to this command are module names; the client cannot 614# know what directories they correspond to except by (1) just sending the 615# co request, and then seeing what directory names the server sends back in 616# its responses, and (2) the expand-modules request. 617sub req_co 618{ 619 my ($cmd,$data) =@_; 620 621 argsplit("co"); 622 623 my$module=$state->{args}[0]; 624 my$checkout_path=$module; 625 626 # use the user specified directory if we're given it 627$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 628 629$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 630 631$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 632 633$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 634 635# Grab a handle to the SQLite db and do any necessary updates 636my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 637$updater->update(); 638 639$checkout_path=~ s|/$||;# get rid of trailing slashes 640 641# Eclipse seems to need the Clear-sticky command 642# to prepare the 'Entries' file for the new directory. 643print"Clear-sticky$checkout_path/\n"; 644print$state->{CVSROOT} ."/$module/\n"; 645print"Clear-static-directory$checkout_path/\n"; 646print$state->{CVSROOT} ."/$module/\n"; 647print"Clear-sticky$checkout_path/\n";# yes, twice 648print$state->{CVSROOT} ."/$module/\n"; 649print"Template$checkout_path/\n"; 650print$state->{CVSROOT} ."/$module/\n"; 651print"0\n"; 652 653# instruct the client that we're checking out to $checkout_path 654print"E cvs checkout: Updating$checkout_path\n"; 655 656my%seendirs= (); 657my$lastdir=''; 658 659# recursive 660sub prepdir { 661my($dir,$repodir,$remotedir,$seendirs) =@_; 662my$parent= dirname($dir); 663$dir=~ s|/+$||; 664$repodir=~ s|/+$||; 665$remotedir=~ s|/+$||; 666$parent=~ s|/+$||; 667$log->debug("announcedir$dir,$repodir,$remotedir"); 668 669if($parenteq'.'||$parenteq'./') { 670$parent=''; 671} 672# recurse to announce unseen parents first 673if(length($parent) && !exists($seendirs->{$parent})) { 674 prepdir($parent,$repodir,$remotedir,$seendirs); 675} 676# Announce that we are going to modify at the parent level 677if($parent) { 678print"E cvs checkout: Updating$remotedir/$parent\n"; 679}else{ 680print"E cvs checkout: Updating$remotedir\n"; 681} 682print"Clear-sticky$remotedir/$parent/\n"; 683print"$repodir/$parent/\n"; 684 685print"Clear-static-directory$remotedir/$dir/\n"; 686print"$repodir/$dir/\n"; 687print"Clear-sticky$remotedir/$parent/\n";# yes, twice 688print"$repodir/$parent/\n"; 689print"Template$remotedir/$dir/\n"; 690print"$repodir/$dir/\n"; 691print"0\n"; 692 693$seendirs->{$dir} =1; 694} 695 696foreachmy$git( @{$updater->gethead} ) 697{ 698# Don't want to check out deleted files 699next if($git->{filehash}eq"deleted"); 700 701($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 702 703if(length($git->{dir}) &&$git->{dir}ne'./' 704&&$git->{dir}ne$lastdir) { 705unless(exists($seendirs{$git->{dir}})) { 706 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 707$checkout_path, \%seendirs); 708$lastdir=$git->{dir}; 709$seendirs{$git->{dir}} =1; 710} 711print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 712} 713 714# modification time of this file 715print"Mod-time$git->{modified}\n"; 716 717# print some information to the client 718if(defined($git->{dir} )and$git->{dir}ne"./") 719{ 720print"M U$checkout_path/$git->{dir}$git->{name}\n"; 721}else{ 722print"M U$checkout_path/$git->{name}\n"; 723} 724 725# instruct client we're sending a file to put in this path 726print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 727 728print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 729 730# this is an "entries" line 731my$kopts= kopts_from_path($git->{name}); 732print"/$git->{name}/1.$git->{revision}//$kopts/\n"; 733# permissions 734print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 735 736# transmit file 737 transmitfile($git->{filehash}); 738} 739 740print"ok\n"; 741 742 statecleanup(); 743} 744 745# update \n 746# Response expected: yes. Actually do a cvs update command. This uses any 747# previous Argument, Directory, Entry, or Modified requests, if they have 748# been sent. The last Directory sent specifies the working directory at the 749# time of the operation. The -I option is not used--files which the client 750# can decide whether to ignore are not mentioned and the client sends the 751# Questionable request for others. 752sub req_update 753{ 754my($cmd,$data) =@_; 755 756$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 757 758 argsplit("update"); 759 760# 761# It may just be a client exploring the available heads/modules 762# in that case, list them as top level directories and leave it 763# at that. Eclipse uses this technique to offer you a list of 764# projects (heads in this case) to checkout. 765# 766if($state->{module}eq'') { 767print"E cvs update: Updating .\n"; 768opendir HEADS,$state->{CVSROOT} .'/refs/heads'; 769while(my$head=readdir(HEADS)) { 770if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 771print"E cvs update: New directory `$head'\n"; 772} 773} 774closedir HEADS; 775print"ok\n"; 776return1; 777} 778 779 780# Grab a handle to the SQLite db and do any necessary updates 781my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 782 783$updater->update(); 784 785 argsfromdir($updater); 786 787#$log->debug("update state : " . Dumper($state)); 788 789# foreach file specified on the command line ... 790foreachmy$filename( @{$state->{args}} ) 791{ 792$filename= filecleanup($filename); 793 794$log->debug("Processing file$filename"); 795 796# if we have a -C we should pretend we never saw modified stuff 797if(exists($state->{opt}{C} ) ) 798{ 799delete$state->{entries}{$filename}{modified_hash}; 800delete$state->{entries}{$filename}{modified_filename}; 801$state->{entries}{$filename}{unchanged} =1; 802} 803 804my$meta; 805if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 806{ 807$meta=$updater->getmeta($filename,$1); 808}else{ 809$meta=$updater->getmeta($filename); 810} 811 812if( !defined$meta) 813{ 814$meta= { 815 name =>$filename, 816 revision =>0, 817 filehash =>'added' 818}; 819} 820 821my$oldmeta=$meta; 822 823my$wrev= revparse($filename); 824 825# If the working copy is an old revision, lets get that version too for comparison. 826if(defined($wrev)and$wrev!=$meta->{revision} ) 827{ 828$oldmeta=$updater->getmeta($filename,$wrev); 829} 830 831#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 832 833# Files are up to date if the working copy and repo copy have the same revision, 834# and the working copy is unmodified _and_ the user hasn't specified -C 835next if(defined($wrev) 836and defined($meta->{revision}) 837and$wrev==$meta->{revision} 838and$state->{entries}{$filename}{unchanged} 839and not exists($state->{opt}{C} ) ); 840 841# If the working copy and repo copy have the same revision, 842# but the working copy is modified, tell the client it's modified 843if(defined($wrev) 844and defined($meta->{revision}) 845and$wrev==$meta->{revision} 846and defined($state->{entries}{$filename}{modified_hash}) 847and not exists($state->{opt}{C} ) ) 848{ 849$log->info("Tell the client the file is modified"); 850print"MT text M\n"; 851print"MT fname$filename\n"; 852print"MT newline\n"; 853next; 854} 855 856if($meta->{filehash}eq"deleted") 857{ 858my($filepart,$dirpart) = filenamesplit($filename,1); 859 860$log->info("Removing '$filename' from working copy (no longer in the repo)"); 861 862print"E cvs update: `$filename' is no longer in the repository\n"; 863# Don't want to actually _DO_ the update if -n specified 864unless($state->{globaloptions}{-n} ) { 865print"Removed$dirpart\n"; 866print"$filepart\n"; 867} 868} 869elsif(not defined($state->{entries}{$filename}{modified_hash} ) 870or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} 871or$meta->{filehash}eq'added') 872{ 873# normal update, just send the new revision (either U=Update, 874# or A=Add, or R=Remove) 875if(defined($wrev) &&$wrev<0) 876{ 877$log->info("Tell the client the file is scheduled for removal"); 878print"MT text R\n"; 879print"MT fname$filename\n"; 880print"MT newline\n"; 881next; 882} 883elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) ) 884{ 885$log->info("Tell the client the file is scheduled for addition"); 886print"MT text A\n"; 887print"MT fname$filename\n"; 888print"MT newline\n"; 889next; 890 891} 892else{ 893$log->info("Updating '$filename' to ".$meta->{revision}); 894print"MT +updated\n"; 895print"MT text U\n"; 896print"MT fname$filename\n"; 897print"MT newline\n"; 898print"MT -updated\n"; 899} 900 901my($filepart,$dirpart) = filenamesplit($filename,1); 902 903# Don't want to actually _DO_ the update if -n specified 904unless($state->{globaloptions}{-n} ) 905{ 906if(defined($wrev) ) 907{ 908# instruct client we're sending a file to put in this path as a replacement 909print"Update-existing$dirpart\n"; 910$log->debug("Updating existing file 'Update-existing$dirpart'"); 911}else{ 912# instruct client we're sending a file to put in this path as a new file 913print"Clear-static-directory$dirpart\n"; 914print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 915print"Clear-sticky$dirpart\n"; 916print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 917 918$log->debug("Creating new file 'Created$dirpart'"); 919print"Created$dirpart\n"; 920} 921print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 922 923# this is an "entries" line 924my$kopts= kopts_from_path($filepart); 925$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 926print"/$filepart/1.$meta->{revision}//$kopts/\n"; 927 928# permissions 929$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 930print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 931 932# transmit file 933 transmitfile($meta->{filehash}); 934} 935}else{ 936$log->info("Updating '$filename'"); 937my($filepart,$dirpart) = filenamesplit($meta->{name},1); 938 939my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/"; 940 941chdir$dir; 942my$file_local=$filepart.".mine"; 943system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local); 944my$file_old=$filepart.".".$oldmeta->{revision}; 945 transmitfile($oldmeta->{filehash},$file_old); 946my$file_new=$filepart.".".$meta->{revision}; 947 transmitfile($meta->{filehash},$file_new); 948 949# we need to merge with the local changes ( M=successful merge, C=conflict merge ) 950$log->info("Merging$file_local,$file_old,$file_new"); 951print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n"; 952 953$log->debug("Temporary directory for merge is$dir"); 954 955my$return=system("git","merge-file",$file_local,$file_old,$file_new); 956$return>>=8; 957 958if($return==0) 959{ 960$log->info("Merged successfully"); 961print"M M$filename\n"; 962$log->debug("Merged$dirpart"); 963 964# Don't want to actually _DO_ the update if -n specified 965unless($state->{globaloptions}{-n} ) 966{ 967print"Merged$dirpart\n"; 968$log->debug($state->{CVSROOT} ."/$state->{module}/$filename"); 969print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 970my$kopts= kopts_from_path($filepart); 971$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 972print"/$filepart/1.$meta->{revision}//$kopts/\n"; 973} 974} 975elsif($return==1) 976{ 977$log->info("Merged with conflicts"); 978print"E cvs update: conflicts found in$filename\n"; 979print"M C$filename\n"; 980 981# Don't want to actually _DO_ the update if -n specified 982unless($state->{globaloptions}{-n} ) 983{ 984print"Merged$dirpart\n"; 985print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 986my$kopts= kopts_from_path($filepart); 987print"/$filepart/1.$meta->{revision}/+/$kopts/\n"; 988} 989} 990else 991{ 992$log->warn("Merge failed"); 993next; 994} 995 996# Don't want to actually _DO_ the update if -n specified 997unless($state->{globaloptions}{-n} ) 998{ 999# permissions1000$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1001print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10021003# transmit file, format is single integer on a line by itself (file1004# size) followed by the file contents1005# TODO : we should copy files in blocks1006my$data=`cat$file_local`;1007$log->debug("File size : " . length($data));1008 print length($data) . "\n";1009 print$data;1010 }10111012 chdir "/";1013 }10141015 }10161017 print "ok\n";1018}10191020sub req_ci1021{1022 my ($cmd,$data) =@_;10231024 argsplit("ci");10251026 #$log->debug("State : " . Dumper($state));10271028$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));10291030 if (@ARGV&&$ARGV[0] eq 'pserver')1031 {1032 print "error 1 pserver access cannot commit\n";1033 exit;1034 }10351036 if ( -e$state->{CVSROOT} . "/index" )1037 {1038$log->warn("file 'index' already exists in the git repository");1039 print "error 1 Index already exists in git repo\n";1040 exit;1041 }10421043 # Grab a handle to the SQLite db and do any necessary updates1044 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1045$updater->update();10461047 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1048 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1049$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");10501051$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1052$ENV{GIT_INDEX_FILE} =$file_index;10531054 # Remember where the head was at the beginning.1055 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1056 chomp$parenthash;1057 if ($parenthash!~ /^[0-9a-f]{40}$/) {1058 print "error 1 pserver cannot find the current HEAD of module";1059 exit;1060 }10611062 chdir$tmpdir;10631064 # populate the temporary index based1065 system("git-read-tree",$parenthash);1066 unless ($?== 0)1067 {1068 die "Error running git-read-tree$state->{module}$file_index$!";1069 }1070$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");10711072 my@committedfiles= ();1073 my%oldmeta;10741075 # foreach file specified on the command line ...1076 foreach my$filename( @{$state->{args}} )1077 {1078 my$committedfile=$filename;1079$filename= filecleanup($filename);10801081 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10821083 my$meta=$updater->getmeta($filename);1084$oldmeta{$filename} =$meta;10851086 my$wrev= revparse($filename);10871088 my ($filepart,$dirpart) = filenamesplit($filename);10891090 # do a checkout of the file if it part of this tree1091 if ($wrev) {1092 system('git-checkout-index', '-f', '-u',$filename);1093 unless ($?== 0) {1094 die "Error running git-checkout-index -f -u$filename:$!";1095 }1096 }10971098 my$addflag= 0;1099 my$rmflag= 0;1100$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1101$addflag= 1 unless ( -e$filename);11021103 # Do up to date checking1104 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1105 {1106 # fail everything if an up to date check fails1107 print "error 1 Up to date check failed for$filename\n";1108 chdir "/";1109 exit;1110 }11111112 push@committedfiles,$committedfile;1113$log->info("Committing$filename");11141115 system("mkdir","-p",$dirpart) unless ( -d$dirpart);11161117 unless ($rmflag)1118 {1119$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1120 rename$state->{entries}{$filename}{modified_filename},$filename;11211122 # Calculate modes to remove1123 my$invmode= "";1124 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }11251126$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1127 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1128 }11291130 if ($rmflag)1131 {1132$log->info("Removing file '$filename'");1133 unlink($filename);1134 system("git-update-index", "--remove",$filename);1135 }1136 elsif ($addflag)1137 {1138$log->info("Adding file '$filename'");1139 system("git-update-index", "--add",$filename);1140 } else {1141$log->info("Updating file '$filename'");1142 system("git-update-index",$filename);1143 }1144 }11451146 unless ( scalar(@committedfiles) > 0 )1147 {1148 print "E No files to commit\n";1149 print "ok\n";1150 chdir "/";1151 return;1152 }11531154 my$treehash= `git-write-tree`;1155 chomp$treehash;11561157$log->debug("Treehash :$treehash, Parenthash :$parenthash");11581159 # write our commit message out if we have one ...1160 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1161 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1162 print$msg_fh"\n\nvia git-CVS emulator\n";1163 close$msg_fh;11641165 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1166chomp($commithash);1167$log->info("Commit hash :$commithash");11681169unless($commithash=~/[a-zA-Z0-9]{40}/)1170{1171$log->warn("Commit failed (Invalid commit hash)");1172print"error 1 Commit failed (unknown reason)\n";1173chdir"/";1174exit;1175}11761177# Check that this is allowed, just as we would with a receive-pack1178my@cmd= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1179$parenthash,$commithash);1180if( -x $cmd[0] ) {1181unless(system(@cmd) ==0)1182{1183$log->warn("Commit failed (update hook declined to update ref)");1184print"error 1 Commit failed (update hook declined)\n";1185chdir"/";1186exit;1187}1188}11891190if(system(qw(git update-ref -m),"cvsserver ci",1191"refs/heads/$state->{module}",$commithash,$parenthash)) {1192$log->warn("update-ref for$state->{module} failed.");1193print"error 1 Cannot commit -- update first\n";1194exit;1195}11961197$updater->update();11981199# foreach file specified on the command line ...1200foreachmy$filename(@committedfiles)1201{1202$filename= filecleanup($filename);12031204my$meta=$updater->getmeta($filename);1205unless(defined$meta->{revision}) {1206$meta->{revision} =1;1207}12081209my($filepart,$dirpart) = filenamesplit($filename,1);12101211$log->debug("Checked-in$dirpart:$filename");12121213print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1214if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1215{1216print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1217print"Remove-entry$dirpart\n";1218print"$filename\n";1219}else{1220if($meta->{revision} ==1) {1221print"M initial revision: 1.1\n";1222}else{1223print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1224}1225print"Checked-in$dirpart\n";1226print"$filename\n";1227my$kopts= kopts_from_path($filepart);1228print"/$filepart/1.$meta->{revision}//$kopts/\n";1229}1230}12311232chdir"/";1233print"ok\n";1234}12351236sub req_status1237{1238my($cmd,$data) =@_;12391240 argsplit("status");12411242$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1243#$log->debug("status state : " . Dumper($state));12441245# Grab a handle to the SQLite db and do any necessary updates1246my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1247$updater->update();12481249# if no files were specified, we need to work out what files we should be providing status on ...1250 argsfromdir($updater);12511252# foreach file specified on the command line ...1253foreachmy$filename( @{$state->{args}} )1254{1255$filename= filecleanup($filename);12561257my$meta=$updater->getmeta($filename);1258my$oldmeta=$meta;12591260my$wrev= revparse($filename);12611262# If the working copy is an old revision, lets get that version too for comparison.1263if(defined($wrev)and$wrev!=$meta->{revision} )1264{1265$oldmeta=$updater->getmeta($filename,$wrev);1266}12671268# TODO : All possible statuses aren't yet implemented1269my$status;1270# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1271$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1272and1273( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1274or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1275);12761277# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1278$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1279and1280($state->{entries}{$filename}{unchanged}1281or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1282);12831284# Need checkout if it exists in the repo but doesn't have a working copy1285$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12861287# Locally modified if working copy and repo copy have the same revision but there are local changes1288$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12891290# Needs Merge if working copy revision is less than repo copy and there are local changes1291$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12921293$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1294$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1295$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1296$status||="File had conflicts on merge"if(0);12971298$status||="Unknown";12991300print"M ===================================================================\n";1301print"M File:$filename\tStatus:$status\n";1302if(defined($state->{entries}{$filename}{revision}) )1303{1304print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1305}else{1306print"M Working revision:\tNo entry for$filename\n";1307}1308if(defined($meta->{revision}) )1309{1310print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1311print"M Sticky Tag:\t\t(none)\n";1312print"M Sticky Date:\t\t(none)\n";1313print"M Sticky Options:\t\t(none)\n";1314}else{1315print"M Repository revision:\tNo revision control file\n";1316}1317print"M\n";1318}13191320print"ok\n";1321}13221323sub req_diff1324{1325my($cmd,$data) =@_;13261327 argsplit("diff");13281329$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1330#$log->debug("status state : " . Dumper($state));13311332my($revision1,$revision2);1333if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1334{1335$revision1=$state->{opt}{r}[0];1336$revision2=$state->{opt}{r}[1];1337}else{1338$revision1=$state->{opt}{r};1339}13401341$revision1=~s/^1\.//if(defined($revision1) );1342$revision2=~s/^1\.//if(defined($revision2) );13431344$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );13451346# Grab a handle to the SQLite db and do any necessary updates1347my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1348$updater->update();13491350# if no files were specified, we need to work out what files we should be providing status on ...1351 argsfromdir($updater);13521353# foreach file specified on the command line ...1354foreachmy$filename( @{$state->{args}} )1355{1356$filename= filecleanup($filename);13571358my($fh,$file1,$file2,$meta1,$meta2,$filediff);13591360my$wrev= revparse($filename);13611362# We need _something_ to diff against1363next unless(defined($wrev) );13641365# if we have a -r switch, use it1366if(defined($revision1) )1367{1368(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1369$meta1=$updater->getmeta($filename,$revision1);1370unless(defined($meta1)and$meta1->{filehash}ne"deleted")1371{1372print"E File$filenameat revision 1.$revision1doesn't exist\n";1373next;1374}1375 transmitfile($meta1->{filehash},$file1);1376}1377# otherwise we just use the working copy revision1378else1379{1380(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1381$meta1=$updater->getmeta($filename,$wrev);1382 transmitfile($meta1->{filehash},$file1);1383}13841385# if we have a second -r switch, use it too1386if(defined($revision2) )1387{1388(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1389$meta2=$updater->getmeta($filename,$revision2);13901391unless(defined($meta2)and$meta2->{filehash}ne"deleted")1392{1393print"E File$filenameat revision 1.$revision2doesn't exist\n";1394next;1395}13961397 transmitfile($meta2->{filehash},$file2);1398}1399# otherwise we just use the working copy1400else1401{1402$file2=$state->{entries}{$filename}{modified_filename};1403}14041405# if we have been given -r, and we don't have a $file2 yet, lets get one1406if(defined($revision1)and not defined($file2) )1407{1408(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1409$meta2=$updater->getmeta($filename,$wrev);1410 transmitfile($meta2->{filehash},$file2);1411}14121413# We need to have retrieved something useful1414next unless(defined($meta1) );14151416# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1417next if(not defined($meta2)and$wrev==$meta1->{revision}1418and1419( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1420or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1421);14221423# Apparently we only show diffs for locally modified files1424next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );14251426print"M Index:$filename\n";1427print"M ===================================================================\n";1428print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1429print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1430print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1431print"M diff ";1432foreachmy$opt(keys%{$state->{opt}} )1433{1434if(ref$state->{opt}{$opt}eq"ARRAY")1435{1436foreachmy$value( @{$state->{opt}{$opt}} )1437{1438print"-$opt$value";1439}1440}else{1441print"-$opt";1442print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1443}1444}1445print"$filename\n";14461447$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));14481449($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);14501451if(exists$state->{opt}{u} )1452{1453system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1454}else{1455system("diff$file1$file2>$filediff");1456}14571458while( <$fh> )1459{1460print"M$_";1461}1462close$fh;1463}14641465print"ok\n";1466}14671468sub req_log1469{1470my($cmd,$data) =@_;14711472 argsplit("log");14731474$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1475#$log->debug("log state : " . Dumper($state));14761477my($minrev,$maxrev);1478if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1479{1480my$control=$2;1481$minrev=$1;1482$maxrev=$3;1483$minrev=~s/^1\.//if(defined($minrev) );1484$maxrev=~s/^1\.//if(defined($maxrev) );1485$minrev++if(defined($minrev)and$controleq"::");1486}14871488# Grab a handle to the SQLite db and do any necessary updates1489my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1490$updater->update();14911492# if no files were specified, we need to work out what files we should be providing status on ...1493 argsfromdir($updater);14941495# foreach file specified on the command line ...1496foreachmy$filename( @{$state->{args}} )1497{1498$filename= filecleanup($filename);14991500my$headmeta=$updater->getmeta($filename);15011502my$revisions=$updater->getlog($filename);1503my$totalrevisions=scalar(@$revisions);15041505if(defined($minrev) )1506{1507$log->debug("Removing revisions less than$minrev");1508while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1509{1510pop@$revisions;1511}1512}1513if(defined($maxrev) )1514{1515$log->debug("Removing revisions greater than$maxrev");1516while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1517{1518shift@$revisions;1519}1520}15211522next unless(scalar(@$revisions) );15231524print"M\n";1525print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1526print"M Working file:$filename\n";1527print"M head: 1.$headmeta->{revision}\n";1528print"M branch:\n";1529print"M locks: strict\n";1530print"M access list:\n";1531print"M symbolic names:\n";1532print"M keyword substitution: kv\n";1533print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1534print"M description:\n";15351536foreachmy$revision(@$revisions)1537{1538print"M ----------------------------\n";1539print"M revision 1.$revision->{revision}\n";1540# reformat the date for log output1541$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}) );1542$revision->{author} =~s/\s+.*//;1543$revision->{author} =~s/^(.{8}).*/$1/;1544print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1545my$commitmessage=$updater->commitmessage($revision->{commithash});1546$commitmessage=~s/^/M /mg;1547print$commitmessage."\n";1548}1549print"M =============================================================================\n";1550}15511552print"ok\n";1553}15541555sub req_annotate1556{1557my($cmd,$data) =@_;15581559 argsplit("annotate");15601561$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1562#$log->debug("status state : " . Dumper($state));15631564# Grab a handle to the SQLite db and do any necessary updates1565my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1566$updater->update();15671568# if no files were specified, we need to work out what files we should be providing annotate on ...1569 argsfromdir($updater);15701571# we'll need a temporary checkout dir1572my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1573my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1574$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15751576$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1577$ENV{GIT_INDEX_FILE} =$file_index;15781579chdir$tmpdir;15801581# foreach file specified on the command line ...1582foreachmy$filename( @{$state->{args}} )1583{1584$filename= filecleanup($filename);15851586my$meta=$updater->getmeta($filename);15871588next unless($meta->{revision} );15891590# get all the commits that this file was in1591# in dense format -- aka skip dead revisions1592my$revisions=$updater->gethistorydense($filename);1593my$lastseenin=$revisions->[0][2];15941595# populate the temporary index based on the latest commit were we saw1596# the file -- but do it cheaply without checking out any files1597# TODO: if we got a revision from the client, use that instead1598# to look up the commithash in sqlite (still good to default to1599# the current head as we do now)1600system("git-read-tree",$lastseenin);1601unless($?==0)1602{1603die"Error running git-read-tree$lastseenin$file_index$!";1604}1605$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");16061607# do a checkout of the file1608system('git-checkout-index','-f','-u',$filename);1609unless($?==0) {1610die"Error running git-checkout-index -f -u$filename:$!";1611}16121613$log->info("Annotate$filename");16141615# Prepare a file with the commits from the linearized1616# history that annotate should know about. This prevents1617# git-jsannotate telling us about commits we are hiding1618# from the client.16191620open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1621for(my$i=0;$i<@$revisions;$i++)1622{1623print ANNOTATEHINTS $revisions->[$i][2];1624if($i+1<@$revisions) {# have we got a parent?1625print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1626}1627print ANNOTATEHINTS "\n";1628}16291630print ANNOTATEHINTS "\n";1631close ANNOTATEHINTS;16321633my$annotatecmd='git-annotate';1634open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1635or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1636my$metadata= {};1637print"E Annotations for$filename\n";1638print"E ***************\n";1639while( <ANNOTATE> )1640{1641if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1642{1643my$commithash=$1;1644my$data=$2;1645unless(defined($metadata->{$commithash} ) )1646{1647$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1648$metadata->{$commithash}{author} =~s/\s+.*//;1649$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1650$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1651}1652printf("M 1.%-5d (%-8s%10s):%s\n",1653$metadata->{$commithash}{revision},1654$metadata->{$commithash}{author},1655$metadata->{$commithash}{modified},1656$data1657);1658}else{1659$log->warn("Error in annotate output! LINE:$_");1660print"E Annotate error\n";1661next;1662}1663}1664close ANNOTATE;1665}16661667# done; get out of the tempdir1668chdir"/";16691670print"ok\n";16711672}16731674# This method takes the state->{arguments} array and produces two new arrays.1675# The first is $state->{args} which is everything before the '--' argument, and1676# the second is $state->{files} which is everything after it.1677sub argsplit1678{1679return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16801681my$type=shift;16821683$state->{args} = [];1684$state->{files} = [];1685$state->{opt} = {};16861687if(defined($type) )1688{1689my$opt= {};1690$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");1691$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1692$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");1693$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1694$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1695$opt= { k =>1, m =>1}if($typeeq"add");1696$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1697$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");169816991700while(scalar( @{$state->{arguments}} ) >0)1701{1702my$arg=shift@{$state->{arguments}};17031704next if($argeq"--");1705next unless($arg=~/\S/);17061707# if the argument looks like a switch1708if($arg=~/^-(\w)(.*)/)1709{1710# if it's a switch that takes an argument1711if($opt->{$1} )1712{1713# If this switch has already been provided1714if($opt->{$1} >1and exists($state->{opt}{$1} ) )1715{1716$state->{opt}{$1} = [$state->{opt}{$1} ];1717if(length($2) >0)1718{1719push@{$state->{opt}{$1}},$2;1720}else{1721push@{$state->{opt}{$1}},shift@{$state->{arguments}};1722}1723}else{1724# if there's extra data in the arg, use that as the argument for the switch1725if(length($2) >0)1726{1727$state->{opt}{$1} =$2;1728}else{1729$state->{opt}{$1} =shift@{$state->{arguments}};1730}1731}1732}else{1733$state->{opt}{$1} =undef;1734}1735}1736else1737{1738push@{$state->{args}},$arg;1739}1740}1741}1742else1743{1744my$mode=0;17451746foreachmy$value( @{$state->{arguments}} )1747{1748if($valueeq"--")1749{1750$mode++;1751next;1752}1753push@{$state->{args}},$valueif($mode==0);1754push@{$state->{files}},$valueif($mode==1);1755}1756}1757}17581759# This method uses $state->{directory} to populate $state->{args} with a list of filenames1760sub argsfromdir1761{1762my$updater=shift;17631764$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17651766return if(scalar( @{$state->{args}} ) >1);17671768my@gethead= @{$updater->gethead};17691770# push added files1771foreachmy$file(keys%{$state->{entries}}) {1772if(exists$state->{entries}{$file}{revision} &&1773$state->{entries}{$file}{revision} ==0)1774{1775push@gethead, { name =>$file, filehash =>'added'};1776}1777}17781779if(scalar(@{$state->{args}}) ==1)1780{1781my$arg=$state->{args}[0];1782$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17831784$log->info("Only one arg specified, checking for directory expansion on '$arg'");17851786foreachmy$file(@gethead)1787{1788next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1789next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1790push@{$state->{args}},$file->{name};1791}17921793shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1794}else{1795$log->info("Only one arg specified, populating file list automatically");17961797$state->{args} = [];17981799foreachmy$file(@gethead)1800{1801next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1802next unless($file->{name} =~s/^$state->{prependdir}//);1803push@{$state->{args}},$file->{name};1804}1805}1806}18071808# This method cleans up the $state variable after a command that uses arguments has run1809sub statecleanup1810{1811$state->{files} = [];1812$state->{args} = [];1813$state->{arguments} = [];1814$state->{entries} = {};1815}18161817sub revparse1818{1819my$filename=shift;18201821returnundefunless(defined($state->{entries}{$filename}{revision} ) );18221823return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1824return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);18251826returnundef;1827}18281829# This method takes a file hash and does a CVS "file transfer" which transmits the1830# size of the file, and then the file contents.1831# If a second argument $targetfile is given, the file is instead written out to1832# a file by the name of $targetfile1833sub transmitfile1834{1835my$filehash=shift;1836my$targetfile=shift;18371838if(defined($filehash)and$filehasheq"deleted")1839{1840$log->warn("filehash is 'deleted'");1841return;1842}18431844die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);18451846my$type=`git-cat-file -t$filehash`;1847 chomp$type;18481849 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );18501851 my$size= `git-cat-file -s $filehash`;1852chomp$size;18531854$log->debug("transmitfile($filehash) size=$size, type=$type");18551856if(open my$fh,'-|',"git-cat-file","blob",$filehash)1857{1858if(defined($targetfile) )1859{1860open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1861print NEWFILE $_while( <$fh> );1862close NEWFILE;1863}else{1864print"$size\n";1865printwhile( <$fh> );1866}1867close$fhor die("Couldn't close filehandle for transmitfile()");1868}else{1869die("Couldn't execute git-cat-file");1870}1871}18721873# This method takes a file name, and returns ( $dirpart, $filepart ) which1874# refers to the directory portion and the file portion of the filename1875# respectively1876sub filenamesplit1877{1878my$filename=shift;1879my$fixforlocaldir=shift;18801881my($filepart,$dirpart) = ($filename,".");1882($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1883$dirpart.="/";18841885if($fixforlocaldir)1886{1887$dirpart=~s/^$state->{prependdir}//;1888}18891890return($filepart,$dirpart);1891}18921893sub filecleanup1894{1895my$filename=shift;18961897returnundefunless(defined($filename));1898if($filename=~/^\// )1899{1900print"E absolute filenames '$filename' not supported by server\n";1901returnundef;1902}19031904$filename=~s/^\.\///g;1905$filename=$state->{prependdir} .$filename;1906return$filename;1907}19081909# Given a path, this function returns a string containing the kopts1910# that should go into that path's Entries line. For example, a binary1911# file should get -kb.1912sub kopts_from_path1913{1914my($path) =@_;19151916# Once it exists, the git attributes system should be used to look up1917# what attributes apply to this path.19181919# Until then, take the setting from the config file1920unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)1921{1922# Return "" to give no special treatment to any path1923return"";1924}else{1925# Alternatively, to have all files treated as if they are binary (which1926# is more like git itself), always return the "-kb" option1927return"-kb";1928}1929}19301931package GITCVS::log;19321933####1934#### Copyright The Open University UK - 2006.1935####1936#### Authors: Martyn Smith <martyn@catalyst.net.nz>1937#### Martin Langhoff <martin@catalyst.net.nz>1938####1939####19401941use strict;1942use warnings;19431944=head1 NAME19451946GITCVS::log19471948=head1 DESCRIPTION19491950This module provides very crude logging with a similar interface to1951Log::Log4perl19521953=head1 METHODS19541955=cut19561957=head2 new19581959Creates a new log object, optionally you can specify a filename here to1960indicate the file to log to. If no log file is specified, you can specify one1961later with method setfile, or indicate you no longer want logging with method1962nofile.19631964Until one of these methods is called, all log calls will buffer messages ready1965to write out.19661967=cut1968sub new1969{1970my$class=shift;1971my$filename=shift;19721973my$self= {};19741975bless$self,$class;19761977if(defined($filename) )1978{1979open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1980}19811982return$self;1983}19841985=head2 setfile19861987This methods takes a filename, and attempts to open that file as the log file.1988If successful, all buffered data is written out to the file, and any further1989logging is written directly to the file.19901991=cut1992sub setfile1993{1994my$self=shift;1995my$filename=shift;19961997if(defined($filename) )1998{1999open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");2000}20012002return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");20032004while(my$line=shift@{$self->{buffer}} )2005{2006print{$self->{fh}}$line;2007}2008}20092010=head2 nofile20112012This method indicates no logging is going to be used. It flushes any entries in2013the internal buffer, and sets a flag to ensure no further data is put there.20142015=cut2016sub nofile2017{2018my$self=shift;20192020$self->{nolog} =1;20212022return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");20232024$self->{buffer} = [];2025}20262027=head2 _logopen20282029Internal method. Returns true if the log file is open, false otherwise.20302031=cut2032sub _logopen2033{2034my$self=shift;20352036return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2037return0;2038}20392040=head2 debug info warn fatal20412042These four methods are wrappers to _log. They provide the actual interface for2043logging data.20442045=cut2046sub debug {my$self=shift;$self->_log("debug",@_); }2047sub info {my$self=shift;$self->_log("info",@_); }2048subwarn{my$self=shift;$self->_log("warn",@_); }2049sub fatal {my$self=shift;$self->_log("fatal",@_); }20502051=head2 _log20522053This is an internal method called by the logging functions. It generates a2054timestamp and pushes the logged line either to file, or internal buffer.20552056=cut2057sub _log2058{2059my$self=shift;2060my$level=shift;20612062return if($self->{nolog} );20632064my@time=localtime;2065my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2066$time[5] +1900,2067$time[4] +1,2068$time[3],2069$time[2],2070$time[1],2071$time[0],2072uc$level,2073);20742075if($self->_logopen)2076{2077print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2078}else{2079push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2080}2081}20822083=head2 DESTROY20842085This method simply closes the file handle if one is open20862087=cut2088sub DESTROY2089{2090my$self=shift;20912092if($self->_logopen)2093{2094close$self->{fh};2095}2096}20972098package GITCVS::updater;20992100####2101#### Copyright The Open University UK - 2006.2102####2103#### Authors: Martyn Smith <martyn@catalyst.net.nz>2104#### Martin Langhoff <martin@catalyst.net.nz>2105####2106####21072108use strict;2109use warnings;2110use DBI;21112112=head1 METHODS21132114=cut21152116=head2 new21172118=cut2119sub new2120{2121my$class=shift;2122my$config=shift;2123my$module=shift;2124my$log=shift;21252126die"Need to specify a git repository"unless(defined($config)and-d $config);2127die"Need to specify a module"unless(defined($module) );21282129$class=ref($class) ||$class;21302131my$self= {};21322133bless$self,$class;21342135$self->{dbdir} =$config."/";2136die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );21372138$self->{module} =$module;2139$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";21402141$self->{git_path} =$config."/";21422143$self->{log} =$log;21442145die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );21462147$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");21482149$self->{tables} = {};2150foreachmy$table($self->{dbh}->tables)2151{2152$table=~s/^"//;2153$table=~s/"$//;2154$self->{tables}{$table} =1;2155}21562157# Construct the revision table if required2158unless($self->{tables}{revision} )2159{2160$self->{dbh}->do("2161 CREATE TABLE revision (2162 name TEXT NOT NULL,2163 revision INTEGER NOT NULL,2164 filehash TEXT NOT NULL,2165 commithash TEXT NOT NULL,2166 author TEXT NOT NULL,2167 modified TEXT NOT NULL,2168 mode TEXT NOT NULL2169 )2170 ");2171$self->{dbh}->do("2172 CREATE INDEX revision_ix12173 ON revision (name,revision)2174 ");2175$self->{dbh}->do("2176 CREATE INDEX revision_ix22177 ON revision (name,commithash)2178 ");2179}21802181# Construct the head table if required2182unless($self->{tables}{head} )2183{2184$self->{dbh}->do("2185 CREATE TABLE head (2186 name TEXT NOT NULL,2187 revision INTEGER NOT NULL,2188 filehash TEXT NOT NULL,2189 commithash TEXT NOT NULL,2190 author TEXT NOT NULL,2191 modified TEXT NOT NULL,2192 mode TEXT NOT NULL2193 )2194 ");2195$self->{dbh}->do("2196 CREATE INDEX head_ix12197 ON head (name)2198 ");2199}22002201# Construct the properties table if required2202unless($self->{tables}{properties} )2203{2204$self->{dbh}->do("2205 CREATE TABLE properties (2206 key TEXT NOT NULL PRIMARY KEY,2207 value TEXT2208 )2209 ");2210}22112212# Construct the commitmsgs table if required2213unless($self->{tables}{commitmsgs} )2214{2215$self->{dbh}->do("2216 CREATE TABLE commitmsgs (2217 key TEXT NOT NULL PRIMARY KEY,2218 value TEXT2219 )2220 ");2221}22222223return$self;2224}22252226=head2 update22272228=cut2229sub update2230{2231my$self=shift;22322233# first lets get the commit list2234$ENV{GIT_DIR} =$self->{git_path};22352236my$commitsha1=`git rev-parse$self->{module}`;2237chomp$commitsha1;22382239my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2240unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2241{2242die("Invalid module '$self->{module}'");2243}224422452246my$git_log;2247my$lastcommit=$self->_get_prop("last_commit");22482249if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2250return1;2251}22522253# Start exclusive lock here...2254$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";22552256# TODO: log processing is memory bound2257# if we can parse into a 2nd file that is in reverse order2258# we can probably do something really efficient2259my@git_log_params= ('--pretty','--parents','--topo-order');22602261if(defined$lastcommit) {2262push@git_log_params,"$lastcommit..$self->{module}";2263}else{2264push@git_log_params,$self->{module};2265}2266# git-rev-list is the backend / plumbing version of git-log2267open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";22682269my@commits;22702271my%commit= ();22722273while( <GITLOG> )2274{2275chomp;2276if(m/^commit\s+(.*)$/) {2277# on ^commit lines put the just seen commit in the stack2278# and prime things for the next one2279if(keys%commit) {2280my%copy=%commit;2281unshift@commits, \%copy;2282%commit= ();2283}2284my@parents=split(m/\s+/,$1);2285$commit{hash} =shift@parents;2286$commit{parents} = \@parents;2287}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2288# on rfc822-like lines seen before we see any message,2289# lowercase the entry and put it in the hash as key-value2290$commit{lc($1)} =$2;2291}else{2292# message lines - skip initial empty line2293# and trim whitespace2294if(!exists($commit{message}) &&m/^\s*$/) {2295# define it to mark the end of headers2296$commit{message} ='';2297next;2298}2299s/^\s+//;s/\s+$//;# trim ws2300$commit{message} .=$_."\n";2301}2302}2303close GITLOG;23042305unshift@commits, \%commitif(keys%commit);23062307# Now all the commits are in the @commits bucket2308# ordered by time DESC. for each commit that needs processing,2309# determine whether it's following the last head we've seen or if2310# it's on its own branch, grab a file list, and add whatever's changed2311# NOTE: $lastcommit refers to the last commit from previous run2312# $lastpicked is the last commit we picked in this run2313my$lastpicked;2314my$head= {};2315if(defined$lastcommit) {2316$lastpicked=$lastcommit;2317}23182319my$committotal=scalar(@commits);2320my$commitcount=0;23212322# Load the head table into $head (for cached lookups during the update process)2323foreachmy$file( @{$self->gethead()} )2324{2325$head->{$file->{name}} =$file;2326}23272328foreachmy$commit(@commits)2329{2330$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2331if(defined$lastpicked)2332{2333if(!in_array($lastpicked, @{$commit->{parents}}))2334{2335# skip, we'll see this delta2336# as part of a merge later2337# warn "skipping off-track $commit->{hash}\n";2338next;2339}elsif(@{$commit->{parents}} >1) {2340# it is a merge commit, for each parent that is2341# not $lastpicked, see if we can get a log2342# from the merge-base to that parent to put it2343# in the message as a merge summary.2344my@parents= @{$commit->{parents}};2345foreachmy$parent(@parents) {2346# git-merge-base can potentially (but rarely) throw2347# several candidate merge bases. let's assume2348# that the first one is the best one.2349if($parenteq$lastpicked) {2350next;2351}2352open my$p,'git-merge-base '.$lastpicked.' '2353.$parent.'|';2354my@output= (<$p>);2355close$p;2356my$base=join('',@output);2357chomp$base;2358if($base) {2359my@merged;2360# print "want to log between $base $parent \n";2361open(GITLOG,'-|','git-log',"$base..$parent")2362or die"Cannot call git-log:$!";2363my$mergedhash;2364while(<GITLOG>) {2365chomp;2366if(!defined$mergedhash) {2367if(m/^commit\s+(.+)$/) {2368$mergedhash=$1;2369}else{2370next;2371}2372}else{2373# grab the first line that looks non-rfc8222374# aka has content after leading space2375if(m/^\s+(\S.*)$/) {2376my$title=$1;2377$title=substr($title,0,100);# truncate2378unshift@merged,"$mergedhash$title";2379undef$mergedhash;2380}2381}2382}2383close GITLOG;2384if(@merged) {2385$commit->{mergemsg} =$commit->{message};2386$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2387foreachmy$summary(@merged) {2388$commit->{mergemsg} .="\t$summary\n";2389}2390$commit->{mergemsg} .="\n\n";2391# print "Message for $commit->{hash} \n$commit->{mergemsg}";2392}2393}2394}2395}2396}23972398# convert the date to CVS-happy format2399$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);24002401if(defined($lastpicked) )2402{2403my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2404local($/) ="\0";2405while( <FILELIST> )2406{2407chomp;2408unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2409{2410die("Couldn't process git-diff-tree line :$_");2411}2412my($mode,$hash,$change) = ($1,$2,$3);2413my$name= <FILELIST>;2414chomp($name);24152416# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");24172418my$git_perms="";2419$git_perms.="r"if($mode&4);2420$git_perms.="w"if($mode&2);2421$git_perms.="x"if($mode&1);2422$git_perms="rw"if($git_permseq"");24232424if($changeeq"D")2425{2426#$log->debug("DELETE $name");2427$head->{$name} = {2428 name =>$name,2429 revision =>$head->{$name}{revision} +1,2430 filehash =>"deleted",2431 commithash =>$commit->{hash},2432 modified =>$commit->{date},2433 author =>$commit->{author},2434 mode =>$git_perms,2435};2436$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2437}2438elsif($changeeq"M")2439{2440#$log->debug("MODIFIED $name");2441$head->{$name} = {2442 name =>$name,2443 revision =>$head->{$name}{revision} +1,2444 filehash =>$hash,2445 commithash =>$commit->{hash},2446 modified =>$commit->{date},2447 author =>$commit->{author},2448 mode =>$git_perms,2449};2450$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2451}2452elsif($changeeq"A")2453{2454#$log->debug("ADDED $name");2455$head->{$name} = {2456 name =>$name,2457 revision =>1,2458 filehash =>$hash,2459 commithash =>$commit->{hash},2460 modified =>$commit->{date},2461 author =>$commit->{author},2462 mode =>$git_perms,2463};2464$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2465}2466else2467{2468$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2469die;2470}2471}2472close FILELIST;2473}else{2474# this is used to detect files removed from the repo2475my$seen_files= {};24762477my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2478local$/="\0";2479while( <FILELIST> )2480{2481chomp;2482unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2483{2484die("Couldn't process git-ls-tree line :$_");2485}24862487my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);24882489$seen_files->{$git_filename} =1;24902491my($oldhash,$oldrevision,$oldmode) = (2492$head->{$git_filename}{filehash},2493$head->{$git_filename}{revision},2494$head->{$git_filename}{mode}2495);24962497if($git_perms=~/^\d\d\d(\d)\d\d/o)2498{2499$git_perms="";2500$git_perms.="r"if($1&4);2501$git_perms.="w"if($1&2);2502$git_perms.="x"if($1&1);2503}else{2504$git_perms="rw";2505}25062507# unless the file exists with the same hash, we need to update it ...2508unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2509{2510my$newrevision= ($oldrevisionor0) +1;25112512$head->{$git_filename} = {2513 name =>$git_filename,2514 revision =>$newrevision,2515 filehash =>$git_hash,2516 commithash =>$commit->{hash},2517 modified =>$commit->{date},2518 author =>$commit->{author},2519 mode =>$git_perms,2520};252125222523$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2524}2525}2526close FILELIST;25272528# Detect deleted files2529foreachmy$file(keys%$head)2530{2531unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2532{2533$head->{$file}{revision}++;2534$head->{$file}{filehash} ="deleted";2535$head->{$file}{commithash} =$commit->{hash};2536$head->{$file}{modified} =$commit->{date};2537$head->{$file}{author} =$commit->{author};25382539$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2540}2541}2542# END : "Detect deleted files"2543}254425452546if(exists$commit->{mergemsg})2547{2548$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2549}25502551$lastpicked=$commit->{hash};25522553$self->_set_prop("last_commit",$commit->{hash});2554}25552556$self->delete_head();2557foreachmy$file(keys%$head)2558{2559$self->insert_head(2560$file,2561$head->{$file}{revision},2562$head->{$file}{filehash},2563$head->{$file}{commithash},2564$head->{$file}{modified},2565$head->{$file}{author},2566$head->{$file}{mode},2567);2568}2569# invalidate the gethead cache2570$self->{gethead_cache} =undef;257125722573# Ending exclusive lock here2574$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2575}25762577sub insert_rev2578{2579my$self=shift;2580my$name=shift;2581my$revision=shift;2582my$filehash=shift;2583my$commithash=shift;2584my$modified=shift;2585my$author=shift;2586my$mode=shift;25872588my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2589$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2590}25912592sub insert_mergelog2593{2594my$self=shift;2595my$key=shift;2596my$value=shift;25972598my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2599$insert_mergelog->execute($key,$value);2600}26012602sub delete_head2603{2604my$self=shift;26052606my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2607$delete_head->execute();2608}26092610sub insert_head2611{2612my$self=shift;2613my$name=shift;2614my$revision=shift;2615my$filehash=shift;2616my$commithash=shift;2617my$modified=shift;2618my$author=shift;2619my$mode=shift;26202621my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2622$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2623}26242625sub _headrev2626{2627my$self=shift;2628my$filename=shift;26292630my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2631$db_query->execute($filename);2632my($hash,$revision,$mode) =$db_query->fetchrow_array;26332634return($hash,$revision,$mode);2635}26362637sub _get_prop2638{2639my$self=shift;2640my$key=shift;26412642my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2643$db_query->execute($key);2644my($value) =$db_query->fetchrow_array;26452646return$value;2647}26482649sub _set_prop2650{2651my$self=shift;2652my$key=shift;2653my$value=shift;26542655my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2656$db_query->execute($value,$key);26572658unless($db_query->rows)2659{2660$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2661$db_query->execute($key,$value);2662}26632664return$value;2665}26662667=head2 gethead26682669=cut26702671sub gethead2672{2673my$self=shift;26742675return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );26762677my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2678$db_query->execute();26792680my$tree= [];2681while(my$file=$db_query->fetchrow_hashref)2682{2683push@$tree,$file;2684}26852686$self->{gethead_cache} =$tree;26872688return$tree;2689}26902691=head2 getlog26922693=cut26942695sub getlog2696{2697my$self=shift;2698my$filename=shift;26992700my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2701$db_query->execute($filename);27022703my$tree= [];2704while(my$file=$db_query->fetchrow_hashref)2705{2706push@$tree,$file;2707}27082709return$tree;2710}27112712=head2 getmeta27132714This function takes a filename (with path) argument and returns a hashref of2715metadata for that file.27162717=cut27182719sub getmeta2720{2721my$self=shift;2722my$filename=shift;2723my$revision=shift;27242725my$db_query;2726if(defined($revision)and$revision=~/^\d+$/)2727{2728$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2729$db_query->execute($filename,$revision);2730}2731elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2732{2733$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2734$db_query->execute($filename,$revision);2735}else{2736$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2737$db_query->execute($filename);2738}27392740return$db_query->fetchrow_hashref;2741}27422743=head2 commitmessage27442745this function takes a commithash and returns the commit message for that commit27462747=cut2748sub commitmessage2749{2750my$self=shift;2751my$commithash=shift;27522753die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);27542755my$db_query;2756$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2757$db_query->execute($commithash);27582759my($message) =$db_query->fetchrow_array;27602761if(defined($message) )2762{2763$message.=" "if($message=~/\n$/);2764return$message;2765}27662767my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2768shift@lineswhile($lines[0] =~/\S/);2769$message=join("",@lines);2770$message.=" "if($message=~/\n$/);2771return$message;2772}27732774=head2 gethistory27752776This function takes a filename (with path) argument and returns an arrayofarrays2777containing revision,filehash,commithash ordered by revision descending27782779=cut2780sub gethistory2781{2782my$self=shift;2783my$filename=shift;27842785my$db_query;2786$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2787$db_query->execute($filename);27882789return$db_query->fetchall_arrayref;2790}27912792=head2 gethistorydense27932794This function takes a filename (with path) argument and returns an arrayofarrays2795containing revision,filehash,commithash ordered by revision descending.27962797This version of gethistory skips deleted entries -- so it is useful for annotate.2798The 'dense' part is a reference to a '--dense' option available for git-rev-list2799and other git tools that depend on it.28002801=cut2802sub gethistorydense2803{2804my$self=shift;2805my$filename=shift;28062807my$db_query;2808$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2809$db_query->execute($filename);28102811return$db_query->fetchall_arrayref;2812}28132814=head2 in_array()28152816from Array::PAT - mimics the in_array() function2817found in PHP. Yuck but works for small arrays.28182819=cut2820sub in_array2821{2822my($check,@array) =@_;2823my$retval=0;2824foreachmy$test(@array){2825if($checkeq$test){2826$retval=1;2827}2828}2829return$retval;2830}28312832=head2 safe_pipe_capture28332834an alternative to `command` that allows input to be passed as an array2835to work around shell problems with weird characters in arguments28362837=cut2838sub safe_pipe_capture {28392840my@output;28412842if(my$pid=open my$child,'-|') {2843@output= (<$child>);2844close$childor die join(' ',@_).":$!$?";2845}else{2846exec(@_)or die"$!$?";# exec() can fail the executable can't be found2847}2848returnwantarray?@output:join('',@output);2849}2850285128521;