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 not exists($state->{opt}{C} ) ) 847{ 848$log->info("Tell the client the file is modified"); 849print"MT text M\n"; 850print"MT fname$filename\n"; 851print"MT newline\n"; 852next; 853} 854 855if($meta->{filehash}eq"deleted") 856{ 857my($filepart,$dirpart) = filenamesplit($filename,1); 858 859$log->info("Removing '$filename' from working copy (no longer in the repo)"); 860 861print"E cvs update: `$filename' is no longer in the repository\n"; 862# Don't want to actually _DO_ the update if -n specified 863unless($state->{globaloptions}{-n} ) { 864print"Removed$dirpart\n"; 865print"$filepart\n"; 866} 867} 868elsif(not defined($state->{entries}{$filename}{modified_hash} ) 869or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} 870or$meta->{filehash}eq'added') 871{ 872# normal update, just send the new revision (either U=Update, 873# or A=Add, or R=Remove) 874if(defined($wrev) &&$wrev<0) 875{ 876$log->info("Tell the client the file is scheduled for removal"); 877print"MT text R\n"; 878print"MT fname$filename\n"; 879print"MT newline\n"; 880next; 881} 882elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) ) 883{ 884$log->info("Tell the client the file is scheduled for addition"); 885print"MT text A\n"; 886print"MT fname$filename\n"; 887print"MT newline\n"; 888next; 889 890} 891else{ 892$log->info("Updating '$filename' to ".$meta->{revision}); 893print"MT +updated\n"; 894print"MT text U\n"; 895print"MT fname$filename\n"; 896print"MT newline\n"; 897print"MT -updated\n"; 898} 899 900my($filepart,$dirpart) = filenamesplit($filename,1); 901 902# Don't want to actually _DO_ the update if -n specified 903unless($state->{globaloptions}{-n} ) 904{ 905if(defined($wrev) ) 906{ 907# instruct client we're sending a file to put in this path as a replacement 908print"Update-existing$dirpart\n"; 909$log->debug("Updating existing file 'Update-existing$dirpart'"); 910}else{ 911# instruct client we're sending a file to put in this path as a new file 912print"Clear-static-directory$dirpart\n"; 913print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 914print"Clear-sticky$dirpart\n"; 915print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 916 917$log->debug("Creating new file 'Created$dirpart'"); 918print"Created$dirpart\n"; 919} 920print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 921 922# this is an "entries" line 923my$kopts= kopts_from_path($filepart); 924$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 925print"/$filepart/1.$meta->{revision}//$kopts/\n"; 926 927# permissions 928$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 929print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 930 931# transmit file 932 transmitfile($meta->{filehash}); 933} 934}else{ 935$log->info("Updating '$filename'"); 936my($filepart,$dirpart) = filenamesplit($meta->{name},1); 937 938my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/"; 939 940chdir$dir; 941my$file_local=$filepart.".mine"; 942system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local); 943my$file_old=$filepart.".".$oldmeta->{revision}; 944 transmitfile($oldmeta->{filehash},$file_old); 945my$file_new=$filepart.".".$meta->{revision}; 946 transmitfile($meta->{filehash},$file_new); 947 948# we need to merge with the local changes ( M=successful merge, C=conflict merge ) 949$log->info("Merging$file_local,$file_old,$file_new"); 950print"M Merging differences between 1.$oldmeta->{revision} and 1.$meta->{revision} into$filename\n"; 951 952$log->debug("Temporary directory for merge is$dir"); 953 954my$return=system("git","merge-file",$file_local,$file_old,$file_new); 955$return>>=8; 956 957if($return==0) 958{ 959$log->info("Merged successfully"); 960print"M M$filename\n"; 961$log->debug("Merged$dirpart"); 962 963# Don't want to actually _DO_ the update if -n specified 964unless($state->{globaloptions}{-n} ) 965{ 966print"Merged$dirpart\n"; 967$log->debug($state->{CVSROOT} ."/$state->{module}/$filename"); 968print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 969my$kopts= kopts_from_path($filepart); 970$log->debug("/$filepart/1.$meta->{revision}//$kopts/"); 971print"/$filepart/1.$meta->{revision}//$kopts/\n"; 972} 973} 974elsif($return==1) 975{ 976$log->info("Merged with conflicts"); 977print"E cvs update: conflicts found in$filename\n"; 978print"M C$filename\n"; 979 980# Don't want to actually _DO_ the update if -n specified 981unless($state->{globaloptions}{-n} ) 982{ 983print"Merged$dirpart\n"; 984print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 985my$kopts= kopts_from_path($filepart); 986print"/$filepart/1.$meta->{revision}/+/$kopts/\n"; 987} 988} 989else 990{ 991$log->warn("Merge failed"); 992next; 993} 994 995# Don't want to actually _DO_ the update if -n specified 996unless($state->{globaloptions}{-n} ) 997{ 998# permissions 999$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");1000print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";10011002# transmit file, format is single integer on a line by itself (file1003# size) followed by the file contents1004# TODO : we should copy files in blocks1005my$data=`cat$file_local`;1006$log->debug("File size : " . length($data));1007 print length($data) . "\n";1008 print$data;1009 }10101011 chdir "/";1012 }10131014 }10151016 print "ok\n";1017}10181019sub req_ci1020{1021 my ($cmd,$data) =@_;10221023 argsplit("ci");10241025 #$log->debug("State : " . Dumper($state));10261027$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));10281029 if (@ARGV&&$ARGV[0] eq 'pserver')1030 {1031 print "error 1 pserver access cannot commit\n";1032 exit;1033 }10341035 if ( -e$state->{CVSROOT} . "/index" )1036 {1037$log->warn("file 'index' already exists in the git repository");1038 print "error 1 Index already exists in git repo\n";1039 exit;1040 }10411042 # Grab a handle to the SQLite db and do any necessary updates1043 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1044$updater->update();10451046 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1047 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1048$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");10491050$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1051$ENV{GIT_INDEX_FILE} =$file_index;10521053 # Remember where the head was at the beginning.1054 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1055 chomp$parenthash;1056 if ($parenthash!~ /^[0-9a-f]{40}$/) {1057 print "error 1 pserver cannot find the current HEAD of module";1058 exit;1059 }10601061 chdir$tmpdir;10621063 # populate the temporary index based1064 system("git-read-tree",$parenthash);1065 unless ($?== 0)1066 {1067 die "Error running git-read-tree$state->{module}$file_index$!";1068 }1069$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");10701071 my@committedfiles= ();1072 my%oldmeta;10731074 # foreach file specified on the command line ...1075 foreach my$filename( @{$state->{args}} )1076 {1077 my$committedfile=$filename;1078$filename= filecleanup($filename);10791080 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10811082 my$meta=$updater->getmeta($filename);1083$oldmeta{$filename} =$meta;10841085 my$wrev= revparse($filename);10861087 my ($filepart,$dirpart) = filenamesplit($filename);10881089 # do a checkout of the file if it part of this tree1090 if ($wrev) {1091 system('git-checkout-index', '-f', '-u',$filename);1092 unless ($?== 0) {1093 die "Error running git-checkout-index -f -u$filename:$!";1094 }1095 }10961097 my$addflag= 0;1098 my$rmflag= 0;1099$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1100$addflag= 1 unless ( -e$filename);11011102 # Do up to date checking1103 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1104 {1105 # fail everything if an up to date check fails1106 print "error 1 Up to date check failed for$filename\n";1107 chdir "/";1108 exit;1109 }11101111 push@committedfiles,$committedfile;1112$log->info("Committing$filename");11131114 system("mkdir","-p",$dirpart) unless ( -d$dirpart);11151116 unless ($rmflag)1117 {1118$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1119 rename$state->{entries}{$filename}{modified_filename},$filename;11201121 # Calculate modes to remove1122 my$invmode= "";1123 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }11241125$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1126 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1127 }11281129 if ($rmflag)1130 {1131$log->info("Removing file '$filename'");1132 unlink($filename);1133 system("git-update-index", "--remove",$filename);1134 }1135 elsif ($addflag)1136 {1137$log->info("Adding file '$filename'");1138 system("git-update-index", "--add",$filename);1139 } else {1140$log->info("Updating file '$filename'");1141 system("git-update-index",$filename);1142 }1143 }11441145 unless ( scalar(@committedfiles) > 0 )1146 {1147 print "E No files to commit\n";1148 print "ok\n";1149 chdir "/";1150 return;1151 }11521153 my$treehash= `git-write-tree`;1154 chomp$treehash;11551156$log->debug("Treehash :$treehash, Parenthash :$parenthash");11571158 # write our commit message out if we have one ...1159 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1160 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1161 print$msg_fh"\n\nvia git-CVS emulator\n";1162 close$msg_fh;11631164 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1165chomp($commithash);1166$log->info("Commit hash :$commithash");11671168unless($commithash=~/[a-zA-Z0-9]{40}/)1169{1170$log->warn("Commit failed (Invalid commit hash)");1171print"error 1 Commit failed (unknown reason)\n";1172chdir"/";1173exit;1174}11751176# Check that this is allowed, just as we would with a receive-pack1177my@cmd= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1178$parenthash,$commithash);1179if( -x $cmd[0] ) {1180unless(system(@cmd) ==0)1181{1182$log->warn("Commit failed (update hook declined to update ref)");1183print"error 1 Commit failed (update hook declined)\n";1184chdir"/";1185exit;1186}1187}11881189if(system(qw(git update-ref -m),"cvsserver ci",1190"refs/heads/$state->{module}",$commithash,$parenthash)) {1191$log->warn("update-ref for$state->{module} failed.");1192print"error 1 Cannot commit -- update first\n";1193exit;1194}11951196$updater->update();11971198# foreach file specified on the command line ...1199foreachmy$filename(@committedfiles)1200{1201$filename= filecleanup($filename);12021203my$meta=$updater->getmeta($filename);1204unless(defined$meta->{revision}) {1205$meta->{revision} =1;1206}12071208my($filepart,$dirpart) = filenamesplit($filename,1);12091210$log->debug("Checked-in$dirpart:$filename");12111212print"M$state->{CVSROOT}/$state->{module}/$filename,v <--$dirpart$filepart\n";1213if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1214{1215print"M new revision: delete; previous revision: 1.$oldmeta{$filename}{revision}\n";1216print"Remove-entry$dirpart\n";1217print"$filename\n";1218}else{1219if($meta->{revision} ==1) {1220print"M initial revision: 1.1\n";1221}else{1222print"M new revision: 1.$meta->{revision}; previous revision: 1.$oldmeta{$filename}{revision}\n";1223}1224print"Checked-in$dirpart\n";1225print"$filename\n";1226my$kopts= kopts_from_path($filepart);1227print"/$filepart/1.$meta->{revision}//$kopts/\n";1228}1229}12301231chdir"/";1232print"ok\n";1233}12341235sub req_status1236{1237my($cmd,$data) =@_;12381239 argsplit("status");12401241$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1242#$log->debug("status state : " . Dumper($state));12431244# Grab a handle to the SQLite db and do any necessary updates1245my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1246$updater->update();12471248# if no files were specified, we need to work out what files we should be providing status on ...1249 argsfromdir($updater);12501251# foreach file specified on the command line ...1252foreachmy$filename( @{$state->{args}} )1253{1254$filename= filecleanup($filename);12551256my$meta=$updater->getmeta($filename);1257my$oldmeta=$meta;12581259my$wrev= revparse($filename);12601261# If the working copy is an old revision, lets get that version too for comparison.1262if(defined($wrev)and$wrev!=$meta->{revision} )1263{1264$oldmeta=$updater->getmeta($filename,$wrev);1265}12661267# TODO : All possible statuses aren't yet implemented1268my$status;1269# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1270$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1271and1272( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1273or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1274);12751276# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1277$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1278and1279($state->{entries}{$filename}{unchanged}1280or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1281);12821283# Need checkout if it exists in the repo but doesn't have a working copy1284$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12851286# Locally modified if working copy and repo copy have the same revision but there are local changes1287$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12881289# Needs Merge if working copy revision is less than repo copy and there are local changes1290$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12911292$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1293$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1294$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1295$status||="File had conflicts on merge"if(0);12961297$status||="Unknown";12981299print"M ===================================================================\n";1300print"M File:$filename\tStatus:$status\n";1301if(defined($state->{entries}{$filename}{revision}) )1302{1303print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1304}else{1305print"M Working revision:\tNo entry for$filename\n";1306}1307if(defined($meta->{revision}) )1308{1309print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{CVSROOT}/$state->{module}/$filename,v\n";1310print"M Sticky Tag:\t\t(none)\n";1311print"M Sticky Date:\t\t(none)\n";1312print"M Sticky Options:\t\t(none)\n";1313}else{1314print"M Repository revision:\tNo revision control file\n";1315}1316print"M\n";1317}13181319print"ok\n";1320}13211322sub req_diff1323{1324my($cmd,$data) =@_;13251326 argsplit("diff");13271328$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1329#$log->debug("status state : " . Dumper($state));13301331my($revision1,$revision2);1332if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1333{1334$revision1=$state->{opt}{r}[0];1335$revision2=$state->{opt}{r}[1];1336}else{1337$revision1=$state->{opt}{r};1338}13391340$revision1=~s/^1\.//if(defined($revision1) );1341$revision2=~s/^1\.//if(defined($revision2) );13421343$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );13441345# Grab a handle to the SQLite db and do any necessary updates1346my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1347$updater->update();13481349# if no files were specified, we need to work out what files we should be providing status on ...1350 argsfromdir($updater);13511352# foreach file specified on the command line ...1353foreachmy$filename( @{$state->{args}} )1354{1355$filename= filecleanup($filename);13561357my($fh,$file1,$file2,$meta1,$meta2,$filediff);13581359my$wrev= revparse($filename);13601361# We need _something_ to diff against1362next unless(defined($wrev) );13631364# if we have a -r switch, use it1365if(defined($revision1) )1366{1367(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1368$meta1=$updater->getmeta($filename,$revision1);1369unless(defined($meta1)and$meta1->{filehash}ne"deleted")1370{1371print"E File$filenameat revision 1.$revision1doesn't exist\n";1372next;1373}1374 transmitfile($meta1->{filehash},$file1);1375}1376# otherwise we just use the working copy revision1377else1378{1379(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1380$meta1=$updater->getmeta($filename,$wrev);1381 transmitfile($meta1->{filehash},$file1);1382}13831384# if we have a second -r switch, use it too1385if(defined($revision2) )1386{1387(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1388$meta2=$updater->getmeta($filename,$revision2);13891390unless(defined($meta2)and$meta2->{filehash}ne"deleted")1391{1392print"E File$filenameat revision 1.$revision2doesn't exist\n";1393next;1394}13951396 transmitfile($meta2->{filehash},$file2);1397}1398# otherwise we just use the working copy1399else1400{1401$file2=$state->{entries}{$filename}{modified_filename};1402}14031404# if we have been given -r, and we don't have a $file2 yet, lets get one1405if(defined($revision1)and not defined($file2) )1406{1407(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1408$meta2=$updater->getmeta($filename,$wrev);1409 transmitfile($meta2->{filehash},$file2);1410}14111412# We need to have retrieved something useful1413next unless(defined($meta1) );14141415# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1416next if(not defined($meta2)and$wrev==$meta1->{revision}1417and1418( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1419or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1420);14211422# Apparently we only show diffs for locally modified files1423next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );14241425print"M Index:$filename\n";1426print"M ===================================================================\n";1427print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1428print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1429print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1430print"M diff ";1431foreachmy$opt(keys%{$state->{opt}} )1432{1433if(ref$state->{opt}{$opt}eq"ARRAY")1434{1435foreachmy$value( @{$state->{opt}{$opt}} )1436{1437print"-$opt$value";1438}1439}else{1440print"-$opt";1441print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1442}1443}1444print"$filename\n";14451446$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));14471448($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);14491450if(exists$state->{opt}{u} )1451{1452system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1453}else{1454system("diff$file1$file2>$filediff");1455}14561457while( <$fh> )1458{1459print"M$_";1460}1461close$fh;1462}14631464print"ok\n";1465}14661467sub req_log1468{1469my($cmd,$data) =@_;14701471 argsplit("log");14721473$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1474#$log->debug("log state : " . Dumper($state));14751476my($minrev,$maxrev);1477if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1478{1479my$control=$2;1480$minrev=$1;1481$maxrev=$3;1482$minrev=~s/^1\.//if(defined($minrev) );1483$maxrev=~s/^1\.//if(defined($maxrev) );1484$minrev++if(defined($minrev)and$controleq"::");1485}14861487# Grab a handle to the SQLite db and do any necessary updates1488my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1489$updater->update();14901491# if no files were specified, we need to work out what files we should be providing status on ...1492 argsfromdir($updater);14931494# foreach file specified on the command line ...1495foreachmy$filename( @{$state->{args}} )1496{1497$filename= filecleanup($filename);14981499my$headmeta=$updater->getmeta($filename);15001501my$revisions=$updater->getlog($filename);1502my$totalrevisions=scalar(@$revisions);15031504if(defined($minrev) )1505{1506$log->debug("Removing revisions less than$minrev");1507while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1508{1509pop@$revisions;1510}1511}1512if(defined($maxrev) )1513{1514$log->debug("Removing revisions greater than$maxrev");1515while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1516{1517shift@$revisions;1518}1519}15201521next unless(scalar(@$revisions) );15221523print"M\n";1524print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1525print"M Working file:$filename\n";1526print"M head: 1.$headmeta->{revision}\n";1527print"M branch:\n";1528print"M locks: strict\n";1529print"M access list:\n";1530print"M symbolic names:\n";1531print"M keyword substitution: kv\n";1532print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1533print"M description:\n";15341535foreachmy$revision(@$revisions)1536{1537print"M ----------------------------\n";1538print"M revision 1.$revision->{revision}\n";1539# reformat the date for log output1540$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}) );1541$revision->{author} =~s/\s+.*//;1542$revision->{author} =~s/^(.{8}).*/$1/;1543print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1544my$commitmessage=$updater->commitmessage($revision->{commithash});1545$commitmessage=~s/^/M /mg;1546print$commitmessage."\n";1547}1548print"M =============================================================================\n";1549}15501551print"ok\n";1552}15531554sub req_annotate1555{1556my($cmd,$data) =@_;15571558 argsplit("annotate");15591560$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1561#$log->debug("status state : " . Dumper($state));15621563# Grab a handle to the SQLite db and do any necessary updates1564my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1565$updater->update();15661567# if no files were specified, we need to work out what files we should be providing annotate on ...1568 argsfromdir($updater);15691570# we'll need a temporary checkout dir1571my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1572my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1573$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15741575$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1576$ENV{GIT_INDEX_FILE} =$file_index;15771578chdir$tmpdir;15791580# foreach file specified on the command line ...1581foreachmy$filename( @{$state->{args}} )1582{1583$filename= filecleanup($filename);15841585my$meta=$updater->getmeta($filename);15861587next unless($meta->{revision} );15881589# get all the commits that this file was in1590# in dense format -- aka skip dead revisions1591my$revisions=$updater->gethistorydense($filename);1592my$lastseenin=$revisions->[0][2];15931594# populate the temporary index based on the latest commit were we saw1595# the file -- but do it cheaply without checking out any files1596# TODO: if we got a revision from the client, use that instead1597# to look up the commithash in sqlite (still good to default to1598# the current head as we do now)1599system("git-read-tree",$lastseenin);1600unless($?==0)1601{1602die"Error running git-read-tree$lastseenin$file_index$!";1603}1604$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");16051606# do a checkout of the file1607system('git-checkout-index','-f','-u',$filename);1608unless($?==0) {1609die"Error running git-checkout-index -f -u$filename:$!";1610}16111612$log->info("Annotate$filename");16131614# Prepare a file with the commits from the linearized1615# history that annotate should know about. This prevents1616# git-jsannotate telling us about commits we are hiding1617# from the client.16181619open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1620for(my$i=0;$i<@$revisions;$i++)1621{1622print ANNOTATEHINTS $revisions->[$i][2];1623if($i+1<@$revisions) {# have we got a parent?1624print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1625}1626print ANNOTATEHINTS "\n";1627}16281629print ANNOTATEHINTS "\n";1630close ANNOTATEHINTS;16311632my$annotatecmd='git-annotate';1633open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1634or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1635my$metadata= {};1636print"E Annotations for$filename\n";1637print"E ***************\n";1638while( <ANNOTATE> )1639{1640if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1641{1642my$commithash=$1;1643my$data=$2;1644unless(defined($metadata->{$commithash} ) )1645{1646$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1647$metadata->{$commithash}{author} =~s/\s+.*//;1648$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1649$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1650}1651printf("M 1.%-5d (%-8s%10s):%s\n",1652$metadata->{$commithash}{revision},1653$metadata->{$commithash}{author},1654$metadata->{$commithash}{modified},1655$data1656);1657}else{1658$log->warn("Error in annotate output! LINE:$_");1659print"E Annotate error\n";1660next;1661}1662}1663close ANNOTATE;1664}16651666# done; get out of the tempdir1667chdir"/";16681669print"ok\n";16701671}16721673# This method takes the state->{arguments} array and produces two new arrays.1674# The first is $state->{args} which is everything before the '--' argument, and1675# the second is $state->{files} which is everything after it.1676sub argsplit1677{1678return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16791680my$type=shift;16811682$state->{args} = [];1683$state->{files} = [];1684$state->{opt} = {};16851686if(defined($type) )1687{1688my$opt= {};1689$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");1690$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1691$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");1692$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1693$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1694$opt= { k =>1, m =>1}if($typeeq"add");1695$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1696$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");169716981699while(scalar( @{$state->{arguments}} ) >0)1700{1701my$arg=shift@{$state->{arguments}};17021703next if($argeq"--");1704next unless($arg=~/\S/);17051706# if the argument looks like a switch1707if($arg=~/^-(\w)(.*)/)1708{1709# if it's a switch that takes an argument1710if($opt->{$1} )1711{1712# If this switch has already been provided1713if($opt->{$1} >1and exists($state->{opt}{$1} ) )1714{1715$state->{opt}{$1} = [$state->{opt}{$1} ];1716if(length($2) >0)1717{1718push@{$state->{opt}{$1}},$2;1719}else{1720push@{$state->{opt}{$1}},shift@{$state->{arguments}};1721}1722}else{1723# if there's extra data in the arg, use that as the argument for the switch1724if(length($2) >0)1725{1726$state->{opt}{$1} =$2;1727}else{1728$state->{opt}{$1} =shift@{$state->{arguments}};1729}1730}1731}else{1732$state->{opt}{$1} =undef;1733}1734}1735else1736{1737push@{$state->{args}},$arg;1738}1739}1740}1741else1742{1743my$mode=0;17441745foreachmy$value( @{$state->{arguments}} )1746{1747if($valueeq"--")1748{1749$mode++;1750next;1751}1752push@{$state->{args}},$valueif($mode==0);1753push@{$state->{files}},$valueif($mode==1);1754}1755}1756}17571758# This method uses $state->{directory} to populate $state->{args} with a list of filenames1759sub argsfromdir1760{1761my$updater=shift;17621763$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17641765return if(scalar( @{$state->{args}} ) >1);17661767my@gethead= @{$updater->gethead};17681769# push added files1770foreachmy$file(keys%{$state->{entries}}) {1771if(exists$state->{entries}{$file}{revision} &&1772$state->{entries}{$file}{revision} ==0)1773{1774push@gethead, { name =>$file, filehash =>'added'};1775}1776}17771778if(scalar(@{$state->{args}}) ==1)1779{1780my$arg=$state->{args}[0];1781$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17821783$log->info("Only one arg specified, checking for directory expansion on '$arg'");17841785foreachmy$file(@gethead)1786{1787next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1788next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1789push@{$state->{args}},$file->{name};1790}17911792shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1793}else{1794$log->info("Only one arg specified, populating file list automatically");17951796$state->{args} = [];17971798foreachmy$file(@gethead)1799{1800next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1801next unless($file->{name} =~s/^$state->{prependdir}//);1802push@{$state->{args}},$file->{name};1803}1804}1805}18061807# This method cleans up the $state variable after a command that uses arguments has run1808sub statecleanup1809{1810$state->{files} = [];1811$state->{args} = [];1812$state->{arguments} = [];1813$state->{entries} = {};1814}18151816sub revparse1817{1818my$filename=shift;18191820returnundefunless(defined($state->{entries}{$filename}{revision} ) );18211822return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1823return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);18241825returnundef;1826}18271828# This method takes a file hash and does a CVS "file transfer" which transmits the1829# size of the file, and then the file contents.1830# If a second argument $targetfile is given, the file is instead written out to1831# a file by the name of $targetfile1832sub transmitfile1833{1834my$filehash=shift;1835my$targetfile=shift;18361837if(defined($filehash)and$filehasheq"deleted")1838{1839$log->warn("filehash is 'deleted'");1840return;1841}18421843die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);18441845my$type=`git-cat-file -t$filehash`;1846 chomp$type;18471848 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );18491850 my$size= `git-cat-file -s $filehash`;1851chomp$size;18521853$log->debug("transmitfile($filehash) size=$size, type=$type");18541855if(open my$fh,'-|',"git-cat-file","blob",$filehash)1856{1857if(defined($targetfile) )1858{1859open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1860print NEWFILE $_while( <$fh> );1861close NEWFILE;1862}else{1863print"$size\n";1864printwhile( <$fh> );1865}1866close$fhor die("Couldn't close filehandle for transmitfile()");1867}else{1868die("Couldn't execute git-cat-file");1869}1870}18711872# This method takes a file name, and returns ( $dirpart, $filepart ) which1873# refers to the directory portion and the file portion of the filename1874# respectively1875sub filenamesplit1876{1877my$filename=shift;1878my$fixforlocaldir=shift;18791880my($filepart,$dirpart) = ($filename,".");1881($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1882$dirpart.="/";18831884if($fixforlocaldir)1885{1886$dirpart=~s/^$state->{prependdir}//;1887}18881889return($filepart,$dirpart);1890}18911892sub filecleanup1893{1894my$filename=shift;18951896returnundefunless(defined($filename));1897if($filename=~/^\// )1898{1899print"E absolute filenames '$filename' not supported by server\n";1900returnundef;1901}19021903$filename=~s/^\.\///g;1904$filename=$state->{prependdir} .$filename;1905return$filename;1906}19071908# Given a path, this function returns a string containing the kopts1909# that should go into that path's Entries line. For example, a binary1910# file should get -kb.1911sub kopts_from_path1912{1913my($path) =@_;19141915# Once it exists, the git attributes system should be used to look up1916# what attributes apply to this path.19171918# Until then, take the setting from the config file1919unless(defined($cfg->{gitcvs}{allbinary} )and$cfg->{gitcvs}{allbinary} =~/^\s*(1|true|yes)\s*$/i)1920{1921# Return "" to give no special treatment to any path1922return"";1923}else{1924# Alternatively, to have all files treated as if they are binary (which1925# is more like git itself), always return the "-kb" option1926return"-kb";1927}1928}19291930package GITCVS::log;19311932####1933#### Copyright The Open University UK - 2006.1934####1935#### Authors: Martyn Smith <martyn@catalyst.net.nz>1936#### Martin Langhoff <martin@catalyst.net.nz>1937####1938####19391940use strict;1941use warnings;19421943=head1 NAME19441945GITCVS::log19461947=head1 DESCRIPTION19481949This module provides very crude logging with a similar interface to1950Log::Log4perl19511952=head1 METHODS19531954=cut19551956=head2 new19571958Creates a new log object, optionally you can specify a filename here to1959indicate the file to log to. If no log file is specified, you can specify one1960later with method setfile, or indicate you no longer want logging with method1961nofile.19621963Until one of these methods is called, all log calls will buffer messages ready1964to write out.19651966=cut1967sub new1968{1969my$class=shift;1970my$filename=shift;19711972my$self= {};19731974bless$self,$class;19751976if(defined($filename) )1977{1978open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1979}19801981return$self;1982}19831984=head2 setfile19851986This methods takes a filename, and attempts to open that file as the log file.1987If successful, all buffered data is written out to the file, and any further1988logging is written directly to the file.19891990=cut1991sub setfile1992{1993my$self=shift;1994my$filename=shift;19951996if(defined($filename) )1997{1998open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1999}20002001return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");20022003while(my$line=shift@{$self->{buffer}} )2004{2005print{$self->{fh}}$line;2006}2007}20082009=head2 nofile20102011This method indicates no logging is going to be used. It flushes any entries in2012the internal buffer, and sets a flag to ensure no further data is put there.20132014=cut2015sub nofile2016{2017my$self=shift;20182019$self->{nolog} =1;20202021return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");20222023$self->{buffer} = [];2024}20252026=head2 _logopen20272028Internal method. Returns true if the log file is open, false otherwise.20292030=cut2031sub _logopen2032{2033my$self=shift;20342035return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");2036return0;2037}20382039=head2 debug info warn fatal20402041These four methods are wrappers to _log. They provide the actual interface for2042logging data.20432044=cut2045sub debug {my$self=shift;$self->_log("debug",@_); }2046sub info {my$self=shift;$self->_log("info",@_); }2047subwarn{my$self=shift;$self->_log("warn",@_); }2048sub fatal {my$self=shift;$self->_log("fatal",@_); }20492050=head2 _log20512052This is an internal method called by the logging functions. It generates a2053timestamp and pushes the logged line either to file, or internal buffer.20542055=cut2056sub _log2057{2058my$self=shift;2059my$level=shift;20602061return if($self->{nolog} );20622063my@time=localtime;2064my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2065$time[5] +1900,2066$time[4] +1,2067$time[3],2068$time[2],2069$time[1],2070$time[0],2071uc$level,2072);20732074if($self->_logopen)2075{2076print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2077}else{2078push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2079}2080}20812082=head2 DESTROY20832084This method simply closes the file handle if one is open20852086=cut2087sub DESTROY2088{2089my$self=shift;20902091if($self->_logopen)2092{2093close$self->{fh};2094}2095}20962097package GITCVS::updater;20982099####2100#### Copyright The Open University UK - 2006.2101####2102#### Authors: Martyn Smith <martyn@catalyst.net.nz>2103#### Martin Langhoff <martin@catalyst.net.nz>2104####2105####21062107use strict;2108use warnings;2109use DBI;21102111=head1 METHODS21122113=cut21142115=head2 new21162117=cut2118sub new2119{2120my$class=shift;2121my$config=shift;2122my$module=shift;2123my$log=shift;21242125die"Need to specify a git repository"unless(defined($config)and-d $config);2126die"Need to specify a module"unless(defined($module) );21272128$class=ref($class) ||$class;21292130my$self= {};21312132bless$self,$class;21332134$self->{dbdir} =$config."/";2135die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );21362137$self->{module} =$module;2138$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";21392140$self->{git_path} =$config."/";21412142$self->{log} =$log;21432144die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );21452146$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");21472148$self->{tables} = {};2149foreachmy$table($self->{dbh}->tables)2150{2151$table=~s/^"//;2152$table=~s/"$//;2153$self->{tables}{$table} =1;2154}21552156# Construct the revision table if required2157unless($self->{tables}{revision} )2158{2159$self->{dbh}->do("2160 CREATE TABLE revision (2161 name TEXT NOT NULL,2162 revision INTEGER NOT NULL,2163 filehash TEXT NOT NULL,2164 commithash TEXT NOT NULL,2165 author TEXT NOT NULL,2166 modified TEXT NOT NULL,2167 mode TEXT NOT NULL2168 )2169 ");2170$self->{dbh}->do("2171 CREATE INDEX revision_ix12172 ON revision (name,revision)2173 ");2174$self->{dbh}->do("2175 CREATE INDEX revision_ix22176 ON revision (name,commithash)2177 ");2178}21792180# Construct the head table if required2181unless($self->{tables}{head} )2182{2183$self->{dbh}->do("2184 CREATE TABLE head (2185 name TEXT NOT NULL,2186 revision INTEGER NOT NULL,2187 filehash TEXT NOT NULL,2188 commithash TEXT NOT NULL,2189 author TEXT NOT NULL,2190 modified TEXT NOT NULL,2191 mode TEXT NOT NULL2192 )2193 ");2194$self->{dbh}->do("2195 CREATE INDEX head_ix12196 ON head (name)2197 ");2198}21992200# Construct the properties table if required2201unless($self->{tables}{properties} )2202{2203$self->{dbh}->do("2204 CREATE TABLE properties (2205 key TEXT NOT NULL PRIMARY KEY,2206 value TEXT2207 )2208 ");2209}22102211# Construct the commitmsgs table if required2212unless($self->{tables}{commitmsgs} )2213{2214$self->{dbh}->do("2215 CREATE TABLE commitmsgs (2216 key TEXT NOT NULL PRIMARY KEY,2217 value TEXT2218 )2219 ");2220}22212222return$self;2223}22242225=head2 update22262227=cut2228sub update2229{2230my$self=shift;22312232# first lets get the commit list2233$ENV{GIT_DIR} =$self->{git_path};22342235my$commitsha1=`git rev-parse$self->{module}`;2236chomp$commitsha1;22372238my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2239unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2240{2241die("Invalid module '$self->{module}'");2242}224322442245my$git_log;2246my$lastcommit=$self->_get_prop("last_commit");22472248if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2249return1;2250}22512252# Start exclusive lock here...2253$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";22542255# TODO: log processing is memory bound2256# if we can parse into a 2nd file that is in reverse order2257# we can probably do something really efficient2258my@git_log_params= ('--pretty','--parents','--topo-order');22592260if(defined$lastcommit) {2261push@git_log_params,"$lastcommit..$self->{module}";2262}else{2263push@git_log_params,$self->{module};2264}2265# git-rev-list is the backend / plumbing version of git-log2266open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";22672268my@commits;22692270my%commit= ();22712272while( <GITLOG> )2273{2274chomp;2275if(m/^commit\s+(.*)$/) {2276# on ^commit lines put the just seen commit in the stack2277# and prime things for the next one2278if(keys%commit) {2279my%copy=%commit;2280unshift@commits, \%copy;2281%commit= ();2282}2283my@parents=split(m/\s+/,$1);2284$commit{hash} =shift@parents;2285$commit{parents} = \@parents;2286}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2287# on rfc822-like lines seen before we see any message,2288# lowercase the entry and put it in the hash as key-value2289$commit{lc($1)} =$2;2290}else{2291# message lines - skip initial empty line2292# and trim whitespace2293if(!exists($commit{message}) &&m/^\s*$/) {2294# define it to mark the end of headers2295$commit{message} ='';2296next;2297}2298s/^\s+//;s/\s+$//;# trim ws2299$commit{message} .=$_."\n";2300}2301}2302close GITLOG;23032304unshift@commits, \%commitif(keys%commit);23052306# Now all the commits are in the @commits bucket2307# ordered by time DESC. for each commit that needs processing,2308# determine whether it's following the last head we've seen or if2309# it's on its own branch, grab a file list, and add whatever's changed2310# NOTE: $lastcommit refers to the last commit from previous run2311# $lastpicked is the last commit we picked in this run2312my$lastpicked;2313my$head= {};2314if(defined$lastcommit) {2315$lastpicked=$lastcommit;2316}23172318my$committotal=scalar(@commits);2319my$commitcount=0;23202321# Load the head table into $head (for cached lookups during the update process)2322foreachmy$file( @{$self->gethead()} )2323{2324$head->{$file->{name}} =$file;2325}23262327foreachmy$commit(@commits)2328{2329$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2330if(defined$lastpicked)2331{2332if(!in_array($lastpicked, @{$commit->{parents}}))2333{2334# skip, we'll see this delta2335# as part of a merge later2336# warn "skipping off-track $commit->{hash}\n";2337next;2338}elsif(@{$commit->{parents}} >1) {2339# it is a merge commit, for each parent that is2340# not $lastpicked, see if we can get a log2341# from the merge-base to that parent to put it2342# in the message as a merge summary.2343my@parents= @{$commit->{parents}};2344foreachmy$parent(@parents) {2345# git-merge-base can potentially (but rarely) throw2346# several candidate merge bases. let's assume2347# that the first one is the best one.2348if($parenteq$lastpicked) {2349next;2350}2351open my$p,'git-merge-base '.$lastpicked.' '2352.$parent.'|';2353my@output= (<$p>);2354close$p;2355my$base=join('',@output);2356chomp$base;2357if($base) {2358my@merged;2359# print "want to log between $base $parent \n";2360open(GITLOG,'-|','git-log',"$base..$parent")2361or die"Cannot call git-log:$!";2362my$mergedhash;2363while(<GITLOG>) {2364chomp;2365if(!defined$mergedhash) {2366if(m/^commit\s+(.+)$/) {2367$mergedhash=$1;2368}else{2369next;2370}2371}else{2372# grab the first line that looks non-rfc8222373# aka has content after leading space2374if(m/^\s+(\S.*)$/) {2375my$title=$1;2376$title=substr($title,0,100);# truncate2377unshift@merged,"$mergedhash$title";2378undef$mergedhash;2379}2380}2381}2382close GITLOG;2383if(@merged) {2384$commit->{mergemsg} =$commit->{message};2385$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2386foreachmy$summary(@merged) {2387$commit->{mergemsg} .="\t$summary\n";2388}2389$commit->{mergemsg} .="\n\n";2390# print "Message for $commit->{hash} \n$commit->{mergemsg}";2391}2392}2393}2394}2395}23962397# convert the date to CVS-happy format2398$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);23992400if(defined($lastpicked) )2401{2402my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2403local($/) ="\0";2404while( <FILELIST> )2405{2406chomp;2407unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2408{2409die("Couldn't process git-diff-tree line :$_");2410}2411my($mode,$hash,$change) = ($1,$2,$3);2412my$name= <FILELIST>;2413chomp($name);24142415# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");24162417my$git_perms="";2418$git_perms.="r"if($mode&4);2419$git_perms.="w"if($mode&2);2420$git_perms.="x"if($mode&1);2421$git_perms="rw"if($git_permseq"");24222423if($changeeq"D")2424{2425#$log->debug("DELETE $name");2426$head->{$name} = {2427 name =>$name,2428 revision =>$head->{$name}{revision} +1,2429 filehash =>"deleted",2430 commithash =>$commit->{hash},2431 modified =>$commit->{date},2432 author =>$commit->{author},2433 mode =>$git_perms,2434};2435$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2436}2437elsif($changeeq"M")2438{2439#$log->debug("MODIFIED $name");2440$head->{$name} = {2441 name =>$name,2442 revision =>$head->{$name}{revision} +1,2443 filehash =>$hash,2444 commithash =>$commit->{hash},2445 modified =>$commit->{date},2446 author =>$commit->{author},2447 mode =>$git_perms,2448};2449$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2450}2451elsif($changeeq"A")2452{2453#$log->debug("ADDED $name");2454$head->{$name} = {2455 name =>$name,2456 revision =>1,2457 filehash =>$hash,2458 commithash =>$commit->{hash},2459 modified =>$commit->{date},2460 author =>$commit->{author},2461 mode =>$git_perms,2462};2463$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2464}2465else2466{2467$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2468die;2469}2470}2471close FILELIST;2472}else{2473# this is used to detect files removed from the repo2474my$seen_files= {};24752476my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2477local$/="\0";2478while( <FILELIST> )2479{2480chomp;2481unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2482{2483die("Couldn't process git-ls-tree line :$_");2484}24852486my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);24872488$seen_files->{$git_filename} =1;24892490my($oldhash,$oldrevision,$oldmode) = (2491$head->{$git_filename}{filehash},2492$head->{$git_filename}{revision},2493$head->{$git_filename}{mode}2494);24952496if($git_perms=~/^\d\d\d(\d)\d\d/o)2497{2498$git_perms="";2499$git_perms.="r"if($1&4);2500$git_perms.="w"if($1&2);2501$git_perms.="x"if($1&1);2502}else{2503$git_perms="rw";2504}25052506# unless the file exists with the same hash, we need to update it ...2507unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2508{2509my$newrevision= ($oldrevisionor0) +1;25102511$head->{$git_filename} = {2512 name =>$git_filename,2513 revision =>$newrevision,2514 filehash =>$git_hash,2515 commithash =>$commit->{hash},2516 modified =>$commit->{date},2517 author =>$commit->{author},2518 mode =>$git_perms,2519};252025212522$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2523}2524}2525close FILELIST;25262527# Detect deleted files2528foreachmy$file(keys%$head)2529{2530unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2531{2532$head->{$file}{revision}++;2533$head->{$file}{filehash} ="deleted";2534$head->{$file}{commithash} =$commit->{hash};2535$head->{$file}{modified} =$commit->{date};2536$head->{$file}{author} =$commit->{author};25372538$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2539}2540}2541# END : "Detect deleted files"2542}254325442545if(exists$commit->{mergemsg})2546{2547$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2548}25492550$lastpicked=$commit->{hash};25512552$self->_set_prop("last_commit",$commit->{hash});2553}25542555$self->delete_head();2556foreachmy$file(keys%$head)2557{2558$self->insert_head(2559$file,2560$head->{$file}{revision},2561$head->{$file}{filehash},2562$head->{$file}{commithash},2563$head->{$file}{modified},2564$head->{$file}{author},2565$head->{$file}{mode},2566);2567}2568# invalidate the gethead cache2569$self->{gethead_cache} =undef;257025712572# Ending exclusive lock here2573$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2574}25752576sub insert_rev2577{2578my$self=shift;2579my$name=shift;2580my$revision=shift;2581my$filehash=shift;2582my$commithash=shift;2583my$modified=shift;2584my$author=shift;2585my$mode=shift;25862587my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2588$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2589}25902591sub insert_mergelog2592{2593my$self=shift;2594my$key=shift;2595my$value=shift;25962597my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2598$insert_mergelog->execute($key,$value);2599}26002601sub delete_head2602{2603my$self=shift;26042605my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2606$delete_head->execute();2607}26082609sub insert_head2610{2611my$self=shift;2612my$name=shift;2613my$revision=shift;2614my$filehash=shift;2615my$commithash=shift;2616my$modified=shift;2617my$author=shift;2618my$mode=shift;26192620my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2621$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2622}26232624sub _headrev2625{2626my$self=shift;2627my$filename=shift;26282629my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2630$db_query->execute($filename);2631my($hash,$revision,$mode) =$db_query->fetchrow_array;26322633return($hash,$revision,$mode);2634}26352636sub _get_prop2637{2638my$self=shift;2639my$key=shift;26402641my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2642$db_query->execute($key);2643my($value) =$db_query->fetchrow_array;26442645return$value;2646}26472648sub _set_prop2649{2650my$self=shift;2651my$key=shift;2652my$value=shift;26532654my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2655$db_query->execute($value,$key);26562657unless($db_query->rows)2658{2659$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2660$db_query->execute($key,$value);2661}26622663return$value;2664}26652666=head2 gethead26672668=cut26692670sub gethead2671{2672my$self=shift;26732674return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );26752676my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2677$db_query->execute();26782679my$tree= [];2680while(my$file=$db_query->fetchrow_hashref)2681{2682push@$tree,$file;2683}26842685$self->{gethead_cache} =$tree;26862687return$tree;2688}26892690=head2 getlog26912692=cut26932694sub getlog2695{2696my$self=shift;2697my$filename=shift;26982699my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2700$db_query->execute($filename);27012702my$tree= [];2703while(my$file=$db_query->fetchrow_hashref)2704{2705push@$tree,$file;2706}27072708return$tree;2709}27102711=head2 getmeta27122713This function takes a filename (with path) argument and returns a hashref of2714metadata for that file.27152716=cut27172718sub getmeta2719{2720my$self=shift;2721my$filename=shift;2722my$revision=shift;27232724my$db_query;2725if(defined($revision)and$revision=~/^\d+$/)2726{2727$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2728$db_query->execute($filename,$revision);2729}2730elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2731{2732$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2733$db_query->execute($filename,$revision);2734}else{2735$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2736$db_query->execute($filename);2737}27382739return$db_query->fetchrow_hashref;2740}27412742=head2 commitmessage27432744this function takes a commithash and returns the commit message for that commit27452746=cut2747sub commitmessage2748{2749my$self=shift;2750my$commithash=shift;27512752die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);27532754my$db_query;2755$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2756$db_query->execute($commithash);27572758my($message) =$db_query->fetchrow_array;27592760if(defined($message) )2761{2762$message.=" "if($message=~/\n$/);2763return$message;2764}27652766my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2767shift@lineswhile($lines[0] =~/\S/);2768$message=join("",@lines);2769$message.=" "if($message=~/\n$/);2770return$message;2771}27722773=head2 gethistory27742775This function takes a filename (with path) argument and returns an arrayofarrays2776containing revision,filehash,commithash ordered by revision descending27772778=cut2779sub gethistory2780{2781my$self=shift;2782my$filename=shift;27832784my$db_query;2785$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2786$db_query->execute($filename);27872788return$db_query->fetchall_arrayref;2789}27902791=head2 gethistorydense27922793This function takes a filename (with path) argument and returns an arrayofarrays2794containing revision,filehash,commithash ordered by revision descending.27952796This version of gethistory skips deleted entries -- so it is useful for annotate.2797The 'dense' part is a reference to a '--dense' option available for git-rev-list2798and other git tools that depend on it.27992800=cut2801sub gethistorydense2802{2803my$self=shift;2804my$filename=shift;28052806my$db_query;2807$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2808$db_query->execute($filename);28092810return$db_query->fetchall_arrayref;2811}28122813=head2 in_array()28142815from Array::PAT - mimics the in_array() function2816found in PHP. Yuck but works for small arrays.28172818=cut2819sub in_array2820{2821my($check,@array) =@_;2822my$retval=0;2823foreachmy$test(@array){2824if($checkeq$test){2825$retval=1;2826}2827}2828return$retval;2829}28302831=head2 safe_pipe_capture28322833an alternative to `command` that allows input to be passed as an array2834to work around shell problems with weird characters in arguments28352836=cut2837sub safe_pipe_capture {28382839my@output;28402841if(my$pid=open my$child,'-|') {2842@output= (<$child>);2843close$childor die join(' ',@_).":$!$?";2844}else{2845exec(@_)or die"$!$?";# exec() can fail the executable can't be found2846}2847returnwantarray?@output:join('',@output);2848}2849285028511;