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; 20 21use Fcntl; 22use File::Temp qw/tempdir tempfile/; 23use File::Basename; 24 25my$log= GITCVS::log->new(); 26my$cfg; 27 28my$DATE_LIST= { 29 Jan =>"01", 30 Feb =>"02", 31 Mar =>"03", 32 Apr =>"04", 33 May =>"05", 34 Jun =>"06", 35 Jul =>"07", 36 Aug =>"08", 37 Sep =>"09", 38 Oct =>"10", 39 Nov =>"11", 40 Dec =>"12", 41}; 42 43# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 44$| =1; 45 46#### Definition and mappings of functions #### 47 48my$methods= { 49'Root'=> \&req_Root, 50'Valid-responses'=> \&req_Validresponses, 51'valid-requests'=> \&req_validrequests, 52'Directory'=> \&req_Directory, 53'Entry'=> \&req_Entry, 54'Modified'=> \&req_Modified, 55'Unchanged'=> \&req_Unchanged, 56'Questionable'=> \&req_Questionable, 57'Argument'=> \&req_Argument, 58'Argumentx'=> \&req_Argument, 59'expand-modules'=> \&req_expandmodules, 60'add'=> \&req_add, 61'remove'=> \&req_remove, 62'co'=> \&req_co, 63'update'=> \&req_update, 64'ci'=> \&req_ci, 65'diff'=> \&req_diff, 66'log'=> \&req_log, 67'rlog'=> \&req_log, 68'tag'=> \&req_CATCHALL, 69'status'=> \&req_status, 70'admin'=> \&req_CATCHALL, 71'history'=> \&req_CATCHALL, 72'watchers'=> \&req_CATCHALL, 73'editors'=> \&req_CATCHALL, 74'annotate'=> \&req_annotate, 75'Global_option'=> \&req_Globaloption, 76#'annotate' => \&req_CATCHALL, 77}; 78 79############################################## 80 81 82# $state holds all the bits of information the clients sends us that could 83# potentially be useful when it comes to actually _doing_ something. 84my$state= { prependdir =>''}; 85$log->info("--------------- STARTING -----------------"); 86 87my$TEMP_DIR= tempdir( CLEANUP =>1); 88$log->debug("Temporary directory is '$TEMP_DIR'"); 89 90# if we are called with a pserver argument, 91# deal with the authentication cat before entering the 92# main loop 93if(@ARGV&&$ARGV[0]eq'pserver') { 94my$line= <STDIN>;chomp$line; 95unless($lineeq'BEGIN AUTH REQUEST') { 96die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 97} 98$line= <STDIN>;chomp$line; 99 req_Root('root',$line)# reuse Root 100or die"E Invalid root$line\n"; 101$line= <STDIN>;chomp$line; 102unless($lineeq'anonymous') { 103print"E Only anonymous user allowed via pserver\n"; 104print"I HATE YOU\n"; 105} 106$line= <STDIN>;chomp$line;# validate the password? 107$line= <STDIN>;chomp$line; 108unless($lineeq'END AUTH REQUEST') { 109die"E Do not understand$line-- expecting END AUTH REQUEST\n"; 110} 111print"I LOVE YOU\n"; 112# and now back to our regular programme... 113} 114 115# Keep going until the client closes the connection 116while(<STDIN>) 117{ 118chomp; 119 120# Check to see if we've seen this method, and call appropriate function. 121if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 122{ 123# use the $methods hash to call the appropriate sub for this command 124#$log->info("Method : $1"); 125&{$methods->{$1}}($1,$2); 126}else{ 127# log fatal because we don't understand this function. If this happens 128# we're fairly screwed because we don't know if the client is expecting 129# a response. If it is, the client will hang, we'll hang, and the whole 130# thing will be custard. 131$log->fatal("Don't understand command$_\n"); 132die("Unknown command$_"); 133} 134} 135 136$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 137$log->info("--------------- FINISH -----------------"); 138 139# Magic catchall method. 140# This is the method that will handle all commands we haven't yet 141# implemented. It simply sends a warning to the log file indicating a 142# command that hasn't been implemented has been invoked. 143sub req_CATCHALL 144{ 145my($cmd,$data) =@_; 146$log->warn("Unhandled command : req_$cmd:$data"); 147} 148 149 150# Root pathname \n 151# Response expected: no. Tell the server which CVSROOT to use. Note that 152# pathname is a local directory and not a fully qualified CVSROOT variable. 153# pathname must already exist; if creating a new root, use the init 154# request, not Root. pathname does not include the hostname of the server, 155# how to access the server, etc.; by the time the CVS protocol is in use, 156# connection, authentication, etc., are already taken care of. The Root 157# request must be sent only once, and it must be sent before any requests 158# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 159sub req_Root 160{ 161my($cmd,$data) =@_; 162$log->debug("req_Root :$data"); 163 164$state->{CVSROOT} =$data; 165 166$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 167unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 168print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 169print"E\n"; 170print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 171return0; 172} 173 174my@gitvars=`git-repo-config -l`; 175if($?) { 176print"E problems executing git-repo-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 177print"E\n"; 178print"error 1 - problem executing git-repo-config\n"; 179return0; 180} 181foreachmy$line(@gitvars) 182{ 183next unless($line=~/^(.*?)\.(.*?)=(.*)$/); 184$cfg->{$1}{$2} =$3; 185} 186 187unless(defined($cfg->{gitcvs}{enabled} )and$cfg->{gitcvs}{enabled} =~/^\s*(1|true|yes)\s*$/i) 188{ 189print"E GITCVS emulation needs to be enabled on this repo\n"; 190print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 191print"E\n"; 192print"error 1 GITCVS emulation disabled\n"; 193return0; 194} 195 196if(defined($cfg->{gitcvs}{logfile} ) ) 197{ 198$log->setfile($cfg->{gitcvs}{logfile}); 199}else{ 200$log->nofile(); 201} 202 203return1; 204} 205 206# Global_option option \n 207# Response expected: no. Transmit one of the global options `-q', `-Q', 208# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 209# variations (such as combining of options) are allowed. For graceful 210# handling of valid-requests, it is probably better to make new global 211# options separate requests, rather than trying to add them to this 212# request. 213sub req_Globaloption 214{ 215my($cmd,$data) =@_; 216$log->debug("req_Globaloption :$data"); 217$state->{globaloptions}{$data} =1; 218} 219 220# Valid-responses request-list \n 221# Response expected: no. Tell the server what responses the client will 222# accept. request-list is a space separated list of tokens. 223sub req_Validresponses 224{ 225my($cmd,$data) =@_; 226$log->debug("req_Validresponses :$data"); 227 228# TODO : re-enable this, currently it's not particularly useful 229#$state->{validresponses} = [ split /\s+/, $data ]; 230} 231 232# valid-requests \n 233# Response expected: yes. Ask the server to send back a Valid-requests 234# response. 235sub req_validrequests 236{ 237my($cmd,$data) =@_; 238 239$log->debug("req_validrequests"); 240 241$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 242$log->debug("SEND : ok"); 243 244print"Valid-requests ".join(" ",keys%$methods) ."\n"; 245print"ok\n"; 246} 247 248# Directory local-directory \n 249# Additional data: repository \n. Response expected: no. Tell the server 250# what directory to use. The repository should be a directory name from a 251# previous server response. Note that this both gives a default for Entry 252# and Modified and also for ci and the other commands; normal usage is to 253# send Directory for each directory in which there will be an Entry or 254# Modified, and then a final Directory for the original directory, then the 255# command. The local-directory is relative to the top level at which the 256# command is occurring (i.e. the last Directory which is sent before the 257# command); to indicate that top level, `.' should be sent for 258# local-directory. 259sub req_Directory 260{ 261my($cmd,$data) =@_; 262 263my$repository= <STDIN>; 264chomp$repository; 265 266 267$state->{localdir} =$data; 268$state->{repository} =$repository; 269$state->{path} =$repository; 270$state->{path} =~s/^$state->{CVSROOT}\///; 271$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 272$state->{path} .="/"if($state->{path} =~ /\S/ ); 273 274$state->{directory} =$state->{localdir}; 275$state->{directory} =""if($state->{directory}eq"."); 276$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 277 278if(not defined($state->{prependdir})and$state->{localdir}eq"."and$state->{path} =~/\S/) 279{ 280$log->info("Setting prepend to '$state->{path}'"); 281$state->{prependdir} =$state->{path}; 282foreachmy$entry(keys%{$state->{entries}} ) 283{ 284$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 285delete$state->{entries}{$entry}; 286} 287} 288 289if(defined($state->{prependdir} ) ) 290{ 291$log->debug("Prepending '$state->{prependdir}' to state|directory"); 292$state->{directory} =$state->{prependdir} .$state->{directory} 293} 294$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 295} 296 297# Entry entry-line \n 298# Response expected: no. Tell the server what version of a file is on the 299# local machine. The name in entry-line is a name relative to the directory 300# most recently specified with Directory. If the user is operating on only 301# some files in a directory, Entry requests for only those files need be 302# included. If an Entry request is sent without Modified, Is-modified, or 303# Unchanged, it means the file is lost (does not exist in the working 304# directory). If both Entry and one of Modified, Is-modified, or Unchanged 305# are sent for the same file, Entry must be sent first. For a given file, 306# one can send Modified, Is-modified, or Unchanged, but not more than one 307# of these three. 308sub req_Entry 309{ 310my($cmd,$data) =@_; 311 312#$log->debug("req_Entry : $data"); 313 314my@data=split(/\//,$data); 315 316$state->{entries}{$state->{directory}.$data[1]} = { 317 revision =>$data[2], 318 conflict =>$data[3], 319 options =>$data[4], 320 tag_or_date =>$data[5], 321}; 322 323$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 324} 325 326# Questionable filename \n 327# Response expected: no. Additional data: no. Tell the server to check 328# whether filename should be ignored, and if not, next time the server 329# sends responses, send (in a M response) `?' followed by the directory and 330# filename. filename must not contain `/'; it needs to be a file in the 331# directory named by the most recent Directory request. 332sub req_Questionable 333{ 334my($cmd,$data) =@_; 335 336$log->debug("req_Questionable :$data"); 337$state->{entries}{$state->{directory}.$data}{questionable} =1; 338} 339 340# add \n 341# Response expected: yes. Add a file or directory. This uses any previous 342# Argument, Directory, Entry, or Modified requests, if they have been sent. 343# The last Directory sent specifies the working directory at the time of 344# the operation. To add a directory, send the directory to be added using 345# Directory and Argument requests. 346sub req_add 347{ 348my($cmd,$data) =@_; 349 350 argsplit("add"); 351 352my$addcount=0; 353 354foreachmy$filename( @{$state->{args}} ) 355{ 356$filename= filecleanup($filename); 357 358unless(defined($state->{entries}{$filename}{modified_filename} ) ) 359{ 360print"E cvs add: nothing known about `$filename'\n"; 361next; 362} 363# TODO : check we're not squashing an already existing file 364if(defined($state->{entries}{$filename}{revision} ) ) 365{ 366print"E cvs add: `$filename' has already been entered\n"; 367next; 368} 369 370my($filepart,$dirpart) = filenamesplit($filename,1); 371 372print"E cvs add: scheduling file `$filename' for addition\n"; 373 374print"Checked-in$dirpart\n"; 375print"$filename\n"; 376print"/$filepart/0///\n"; 377 378$addcount++; 379} 380 381if($addcount==1) 382{ 383print"E cvs add: use `cvs commit' to add this file permanently\n"; 384} 385elsif($addcount>1) 386{ 387print"E cvs add: use `cvs commit' to add these files permanently\n"; 388} 389 390print"ok\n"; 391} 392 393# remove \n 394# Response expected: yes. Remove a file. This uses any previous Argument, 395# Directory, Entry, or Modified requests, if they have been sent. The last 396# Directory sent specifies the working directory at the time of the 397# operation. Note that this request does not actually do anything to the 398# repository; the only effect of a successful remove request is to supply 399# the client with a new entries line containing `-' to indicate a removed 400# file. In fact, the client probably could perform this operation without 401# contacting the server, although using remove may cause the server to 402# perform a few more checks. The client sends a subsequent ci request to 403# actually record the removal in the repository. 404sub req_remove 405{ 406my($cmd,$data) =@_; 407 408 argsplit("remove"); 409 410# Grab a handle to the SQLite db and do any necessary updates 411my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 412$updater->update(); 413 414#$log->debug("add state : " . Dumper($state)); 415 416my$rmcount=0; 417 418foreachmy$filename( @{$state->{args}} ) 419{ 420$filename= filecleanup($filename); 421 422if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 423{ 424print"E cvs remove: file `$filename' still in working directory\n"; 425next; 426} 427 428my$meta=$updater->getmeta($filename); 429my$wrev= revparse($filename); 430 431unless(defined($wrev) ) 432{ 433print"E cvs remove: nothing known about `$filename'\n"; 434next; 435} 436 437if(defined($wrev)and$wrev<0) 438{ 439print"E cvs remove: file `$filename' already scheduled for removal\n"; 440next; 441} 442 443unless($wrev==$meta->{revision} ) 444{ 445# TODO : not sure if the format of this message is quite correct. 446print"E cvs remove: Up to date check failed for `$filename'\n"; 447next; 448} 449 450 451my($filepart,$dirpart) = filenamesplit($filename,1); 452 453print"E cvs remove: scheduling `$filename' for removal\n"; 454 455print"Checked-in$dirpart\n"; 456print"$filename\n"; 457print"/$filepart/-1.$wrev///\n"; 458 459$rmcount++; 460} 461 462if($rmcount==1) 463{ 464print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 465} 466elsif($rmcount>1) 467{ 468print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 469} 470 471print"ok\n"; 472} 473 474# Modified filename \n 475# Response expected: no. Additional data: mode, \n, file transmission. Send 476# the server a copy of one locally modified file. filename is a file within 477# the most recent directory sent with Directory; it must not contain `/'. 478# If the user is operating on only some files in a directory, only those 479# files need to be included. This can also be sent without Entry, if there 480# is no entry for the file. 481sub req_Modified 482{ 483my($cmd,$data) =@_; 484 485my$mode= <STDIN>; 486chomp$mode; 487my$size= <STDIN>; 488chomp$size; 489 490# Grab config information 491my$blocksize=8192; 492my$bytesleft=$size; 493my$tmp; 494 495# Get a filehandle/name to write it to 496my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 497 498# Loop over file data writing out to temporary file. 499while($bytesleft) 500{ 501$blocksize=$bytesleftif($bytesleft<$blocksize); 502read STDIN,$tmp,$blocksize; 503print$fh $tmp; 504$bytesleft-=$blocksize; 505} 506 507close$fh; 508 509# Ensure we have something sensible for the file mode 510if($mode=~/u=(\w+)/) 511{ 512$mode=$1; 513}else{ 514$mode="rw"; 515} 516 517# Save the file data in $state 518$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 519$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 520$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 521$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 522 523 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 524} 525 526# Unchanged filename\n 527# Response expected: no. Tell the server that filename has not been 528# modified in the checked out directory. The filename is a file within the 529# most recent directory sent with Directory; it must not contain `/'. 530sub req_Unchanged 531{ 532 my ($cmd,$data) =@_; 533 534$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 535 536 #$log->debug("req_Unchanged :$data"); 537} 538 539# Argument text\n 540# Response expected: no. Save argument for use in a subsequent command. 541# Arguments accumulate until an argument-using command is given, at which 542# point they are forgotten. 543# Argumentx text\n 544# Response expected: no. Append\nfollowed by text to the current argument 545# being saved. 546sub req_Argument 547{ 548 my ($cmd,$data) =@_; 549 550 # Argumentx means: append to last Argument (with a newline in front) 551 552$log->debug("$cmd:$data"); 553 554 if ($cmdeq 'Argumentx') { 555 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 556 } else { 557 push @{$state->{arguments}},$data; 558 } 559} 560 561# expand-modules\n 562# Response expected: yes. Expand the modules which are specified in the 563# arguments. Returns the data in Module-expansion responses. Note that the 564# server can assume that this is checkout or export, not rtag or rdiff; the 565# latter do not access the working directory and thus have no need to 566# expand modules on the client side. Expand may not be the best word for 567# what this request does. It does not necessarily tell you all the files 568# contained in a module, for example. Basically it is a way of telling you 569# which working directories the server needs to know about in order to 570# handle a checkout of the specified modules. For example, suppose that the 571# server has a module defined by 572# aliasmodule -a 1dir 573# That is, one can check out aliasmodule and it will take 1dir in the 574# repository and check it out to 1dir in the working directory. Now suppose 575# the client already has this module checked out and is planning on using 576# the co request to update it. Without using expand-modules, the client 577# would have two bad choices: it could either send information about all 578# working directories under the current directory, which could be 579# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 580# stands for 1dir, and neglect to send information for 1dir, which would 581# lead to incorrect operation. With expand-modules, the client would first 582# ask for the module to be expanded: 583sub req_expandmodules 584{ 585 my ($cmd,$data) =@_; 586 587 argsplit(); 588 589$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 590 591 unless ( ref$state->{arguments} eq "ARRAY" ) 592 { 593 print "ok\n"; 594 return; 595 } 596 597 foreach my$module( @{$state->{arguments}} ) 598 { 599$log->debug("SEND : Module-expansion$module"); 600 print "Module-expansion$module\n"; 601 } 602 603 print "ok\n"; 604 statecleanup(); 605} 606 607# co\n 608# Response expected: yes. Get files from the repository. This uses any 609# previous Argument, Directory, Entry, or Modified requests, if they have 610# been sent. Arguments to this command are module names; the client cannot 611# know what directories they correspond to except by (1) just sending the 612# co request, and then seeing what directory names the server sends back in 613# its responses, and (2) the expand-modules request. 614sub req_co 615{ 616 my ($cmd,$data) =@_; 617 618 argsplit("co"); 619 620 my$module=$state->{args}[0]; 621 my$checkout_path=$module; 622 623 # use the user specified directory if we're given it 624$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 625 626$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 627 628$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 629 630$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 631 632# Grab a handle to the SQLite db and do any necessary updates 633my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 634$updater->update(); 635 636$checkout_path=~ s|/$||;# get rid of trailing slashes 637 638# Eclipse seems to need the Clear-sticky command 639# to prepare the 'Entries' file for the new directory. 640print"Clear-sticky$checkout_path/\n"; 641print$state->{CVSROOT} ."/$module/\n"; 642print"Clear-static-directory$checkout_path/\n"; 643print$state->{CVSROOT} ."/$module/\n"; 644print"Clear-sticky$checkout_path/\n";# yes, twice 645print$state->{CVSROOT} ."/$module/\n"; 646print"Template$checkout_path/\n"; 647print$state->{CVSROOT} ."/$module/\n"; 648print"0\n"; 649 650# instruct the client that we're checking out to $checkout_path 651print"E cvs checkout: Updating$checkout_path\n"; 652 653my%seendirs= (); 654my$lastdir=''; 655 656# recursive 657sub prepdir { 658my($dir,$repodir,$remotedir,$seendirs) =@_; 659my$parent= dirname($dir); 660$dir=~ s|/+$||; 661$repodir=~ s|/+$||; 662$remotedir=~ s|/+$||; 663$parent=~ s|/+$||; 664$log->debug("announcedir$dir,$repodir,$remotedir"); 665 666if($parenteq'.'||$parenteq'./') { 667$parent=''; 668} 669# recurse to announce unseen parents first 670if(length($parent) && !exists($seendirs->{$parent})) { 671 prepdir($parent,$repodir,$remotedir,$seendirs); 672} 673# Announce that we are going to modify at the parent level 674if($parent) { 675print"E cvs checkout: Updating$remotedir/$parent\n"; 676}else{ 677print"E cvs checkout: Updating$remotedir\n"; 678} 679print"Clear-sticky$remotedir/$parent/\n"; 680print"$repodir/$parent/\n"; 681 682print"Clear-static-directory$remotedir/$dir/\n"; 683print"$repodir/$dir/\n"; 684print"Clear-sticky$remotedir/$parent/\n";# yes, twice 685print"$repodir/$parent/\n"; 686print"Template$remotedir/$dir/\n"; 687print"$repodir/$dir/\n"; 688print"0\n"; 689 690$seendirs->{$dir} =1; 691} 692 693foreachmy$git( @{$updater->gethead} ) 694{ 695# Don't want to check out deleted files 696next if($git->{filehash}eq"deleted"); 697 698($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 699 700if(length($git->{dir}) &&$git->{dir}ne'./' 701&&$git->{dir}ne$lastdir) { 702unless(exists($seendirs{$git->{dir}})) { 703 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 704$checkout_path, \%seendirs); 705$lastdir=$git->{dir}; 706$seendirs{$git->{dir}} =1; 707} 708print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 709} 710 711# modification time of this file 712print"Mod-time$git->{modified}\n"; 713 714# print some information to the client 715if(defined($git->{dir} )and$git->{dir}ne"./") 716{ 717print"M U$checkout_path/$git->{dir}$git->{name}\n"; 718}else{ 719print"M U$checkout_path/$git->{name}\n"; 720} 721 722# instruct client we're sending a file to put in this path 723print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 724 725print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 726 727# this is an "entries" line 728print"/$git->{name}/1.$git->{revision}///\n"; 729# permissions 730print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 731 732# transmit file 733 transmitfile($git->{filehash}); 734} 735 736print"ok\n"; 737 738 statecleanup(); 739} 740 741# update \n 742# Response expected: yes. Actually do a cvs update command. This uses any 743# previous Argument, Directory, Entry, or Modified requests, if they have 744# been sent. The last Directory sent specifies the working directory at the 745# time of the operation. The -I option is not used--files which the client 746# can decide whether to ignore are not mentioned and the client sends the 747# Questionable request for others. 748sub req_update 749{ 750my($cmd,$data) =@_; 751 752$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 753 754 argsplit("update"); 755 756# 757# It may just be a client exploring the available heads/modules 758# in that case, list them as top level directories and leave it 759# at that. Eclipse uses this technique to offer you a list of 760# projects (heads in this case) to checkout. 761# 762if($state->{module}eq'') { 763print"E cvs update: Updating .\n"; 764opendir HEADS,$state->{CVSROOT} .'/refs/heads'; 765while(my$head=readdir(HEADS)) { 766if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 767print"E cvs update: New directory `$head'\n"; 768} 769} 770closedir HEADS; 771print"ok\n"; 772return1; 773} 774 775 776# Grab a handle to the SQLite db and do any necessary updates 777my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 778 779$updater->update(); 780 781 argsfromdir($updater); 782 783#$log->debug("update state : " . Dumper($state)); 784 785# foreach file specified on the command line ... 786foreachmy$filename( @{$state->{args}} ) 787{ 788$filename= filecleanup($filename); 789 790$log->debug("Processing file$filename"); 791 792# if we have a -C we should pretend we never saw modified stuff 793if(exists($state->{opt}{C} ) ) 794{ 795delete$state->{entries}{$filename}{modified_hash}; 796delete$state->{entries}{$filename}{modified_filename}; 797$state->{entries}{$filename}{unchanged} =1; 798} 799 800my$meta; 801if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 802{ 803$meta=$updater->getmeta($filename,$1); 804}else{ 805$meta=$updater->getmeta($filename); 806} 807 808next unless($meta->{revision} ); 809 810my$oldmeta=$meta; 811 812my$wrev= revparse($filename); 813 814# If the working copy is an old revision, lets get that version too for comparison. 815if(defined($wrev)and$wrev!=$meta->{revision} ) 816{ 817$oldmeta=$updater->getmeta($filename,$wrev); 818} 819 820#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 821 822# Files are up to date if the working copy and repo copy have the same revision, 823# and the working copy is unmodified _and_ the user hasn't specified -C 824next if(defined($wrev) 825and defined($meta->{revision}) 826and$wrev==$meta->{revision} 827and$state->{entries}{$filename}{unchanged} 828and not exists($state->{opt}{C} ) ); 829 830# If the working copy and repo copy have the same revision, 831# but the working copy is modified, tell the client it's modified 832if(defined($wrev) 833and defined($meta->{revision}) 834and$wrev==$meta->{revision} 835and not exists($state->{opt}{C} ) ) 836{ 837$log->info("Tell the client the file is modified"); 838print"MT text U\n"; 839print"MT fname$filename\n"; 840print"MT newline\n"; 841next; 842} 843 844if($meta->{filehash}eq"deleted") 845{ 846my($filepart,$dirpart) = filenamesplit($filename,1); 847 848$log->info("Removing '$filename' from working copy (no longer in the repo)"); 849 850print"E cvs update: `$filename' is no longer in the repository\n"; 851# Don't want to actually _DO_ the update if -n specified 852unless($state->{globaloptions}{-n} ) { 853print"Removed$dirpart\n"; 854print"$filepart\n"; 855} 856} 857elsif(not defined($state->{entries}{$filename}{modified_hash} ) 858or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) 859{ 860$log->info("Updating '$filename'"); 861# normal update, just send the new revision (either U=Update, or A=Add, or R=Remove) 862print"MT +updated\n"; 863print"MT text U\n"; 864print"MT fname$filename\n"; 865print"MT newline\n"; 866print"MT -updated\n"; 867 868my($filepart,$dirpart) = filenamesplit($filename,1); 869 870# Don't want to actually _DO_ the update if -n specified 871unless($state->{globaloptions}{-n} ) 872{ 873if(defined($wrev) ) 874{ 875# instruct client we're sending a file to put in this path as a replacement 876print"Update-existing$dirpart\n"; 877$log->debug("Updating existing file 'Update-existing$dirpart'"); 878}else{ 879# instruct client we're sending a file to put in this path as a new file 880print"Clear-static-directory$dirpart\n"; 881print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 882print"Clear-sticky$dirpart\n"; 883print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 884 885$log->debug("Creating new file 'Created$dirpart'"); 886print"Created$dirpart\n"; 887} 888print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 889 890# this is an "entries" line 891$log->debug("/$filepart/1.$meta->{revision}///"); 892print"/$filepart/1.$meta->{revision}///\n"; 893 894# permissions 895$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 896print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 897 898# transmit file 899 transmitfile($meta->{filehash}); 900} 901}else{ 902$log->info("Updating '$filename'"); 903my($filepart,$dirpart) = filenamesplit($meta->{name},1); 904 905my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/"; 906 907chdir$dir; 908my$file_local=$filepart.".mine"; 909system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local); 910my$file_old=$filepart.".".$oldmeta->{revision}; 911 transmitfile($oldmeta->{filehash},$file_old); 912my$file_new=$filepart.".".$meta->{revision}; 913 transmitfile($meta->{filehash},$file_new); 914 915# we need to merge with the local changes ( M=successful merge, C=conflict merge ) 916$log->info("Merging$file_local,$file_old,$file_new"); 917 918$log->debug("Temporary directory for merge is$dir"); 919 920my$return=system("merge",$file_local,$file_old,$file_new); 921$return>>=8; 922 923if($return==0) 924{ 925$log->info("Merged successfully"); 926print"M M$filename\n"; 927$log->debug("Update-existing$dirpart"); 928 929# Don't want to actually _DO_ the update if -n specified 930unless($state->{globaloptions}{-n} ) 931{ 932print"Update-existing$dirpart\n"; 933$log->debug($state->{CVSROOT} ."/$state->{module}/$filename"); 934print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 935$log->debug("/$filepart/1.$meta->{revision}///"); 936print"/$filepart/1.$meta->{revision}///\n"; 937} 938} 939elsif($return==1) 940{ 941$log->info("Merged with conflicts"); 942print"M C$filename\n"; 943 944# Don't want to actually _DO_ the update if -n specified 945unless($state->{globaloptions}{-n} ) 946{ 947print"Update-existing$dirpart\n"; 948print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 949print"/$filepart/1.$meta->{revision}/+//\n"; 950} 951} 952else 953{ 954$log->warn("Merge failed"); 955next; 956} 957 958# Don't want to actually _DO_ the update if -n specified 959unless($state->{globaloptions}{-n} ) 960{ 961# permissions 962$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 963print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 964 965# transmit file, format is single integer on a line by itself (file 966# size) followed by the file contents 967# TODO : we should copy files in blocks 968my$data=`cat$file_local`; 969$log->debug("File size : " . length($data)); 970 print length($data) . "\n"; 971 print$data; 972 } 973 974 chdir "/"; 975 } 976 977 } 978 979 print "ok\n"; 980} 981 982sub req_ci 983{ 984 my ($cmd,$data) =@_; 985 986 argsplit("ci"); 987 988 #$log->debug("State : " . Dumper($state)); 989 990$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" )); 991 992 if (@ARGV&&$ARGV[0] eq 'pserver') 993 { 994 print "error 1 pserver access cannot commit\n"; 995 exit; 996 } 997 998 if ( -e$state->{CVSROOT} . "/index" ) 999 {1000$log->warn("file 'index' already exists in the git repository");1001 print "error 1 Index already exists in git repo\n";1002 exit;1003 }10041005 my$lockfile= "$state->{CVSROOT}/refs/heads/$state->{module}.lock";1006 unless ( sysopen(LOCKFILE,$lockfile,O_EXCL|O_CREAT|O_WRONLY) )1007 {1008$log->warn("lockfile '$lockfile' already exists, please try again");1009 print "error 1 Lock file '$lockfile' already exists, please try again\n";1010 exit;1011 }10121013 # Grab a handle to the SQLite db and do any necessary updates1014 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1015$updater->update();10161017 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1018 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1019$log->info("Lock successful, basing commit on '$tmpdir', index file is '$file_index'");10201021$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1022$ENV{GIT_INDEX_FILE} =$file_index;10231024 chdir$tmpdir;10251026 # populate the temporary index based1027 system("git-read-tree",$state->{module});1028 unless ($?== 0)1029 {1030 die "Error running git-read-tree$state->{module}$file_index$!";1031 }1032$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");103310341035 my@committedfiles= ();10361037 # foreach file specified on the command line ...1038 foreach my$filename( @{$state->{args}} )1039 {1040 my$committedfile=$filename;1041$filename= filecleanup($filename);10421043 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10441045 my$meta=$updater->getmeta($filename);10461047 my$wrev= revparse($filename);10481049 my ($filepart,$dirpart) = filenamesplit($filename);10501051 # do a checkout of the file if it part of this tree1052 if ($wrev) {1053 system('git-checkout-index', '-f', '-u',$filename);1054 unless ($?== 0) {1055 die "Error running git-checkout-index -f -u$filename:$!";1056 }1057 }10581059 my$addflag= 0;1060 my$rmflag= 0;1061$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1062$addflag= 1 unless ( -e$filename);10631064 # Do up to date checking1065 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1066 {1067 # fail everything if an up to date check fails1068 print "error 1 Up to date check failed for$filename\n";1069 close LOCKFILE;1070 unlink($lockfile);1071 chdir "/";1072 exit;1073 }10741075 push@committedfiles,$committedfile;1076$log->info("Committing$filename");10771078 system("mkdir","-p",$dirpart) unless ( -d$dirpart);10791080 unless ($rmflag)1081 {1082$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1083 rename$state->{entries}{$filename}{modified_filename},$filename;10841085 # Calculate modes to remove1086 my$invmode= "";1087 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }10881089$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1090 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1091 }10921093 if ($rmflag)1094 {1095$log->info("Removing file '$filename'");1096 unlink($filename);1097 system("git-update-index", "--remove",$filename);1098 }1099 elsif ($addflag)1100 {1101$log->info("Adding file '$filename'");1102 system("git-update-index", "--add",$filename);1103 } else {1104$log->info("Updating file '$filename'");1105 system("git-update-index",$filename);1106 }1107 }11081109 unless ( scalar(@committedfiles) > 0 )1110 {1111 print "E No files to commit\n";1112 print "ok\n";1113 close LOCKFILE;1114 unlink($lockfile);1115 chdir "/";1116 return;1117 }11181119 my$treehash= `git-write-tree`;1120 my$parenthash= `cat $ENV{GIT_DIR}refs/heads/$state->{module}`;1121 chomp$treehash;1122 chomp$parenthash;11231124$log->debug("Treehash :$treehash, Parenthash :$parenthash");11251126 # write our commit message out if we have one ...1127 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1128 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1129 print$msg_fh"\n\nvia git-CVS emulator\n";1130 close$msg_fh;11311132 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1133$log->info("Commit hash :$commithash");11341135unless($commithash=~/[a-zA-Z0-9]{40}/)1136{1137$log->warn("Commit failed (Invalid commit hash)");1138print"error 1 Commit failed (unknown reason)\n";1139close LOCKFILE;1140unlink($lockfile);1141chdir"/";1142exit;1143}11441145print LOCKFILE $commithash;11461147$updater->update();11481149# foreach file specified on the command line ...1150foreachmy$filename(@committedfiles)1151{1152$filename= filecleanup($filename);11531154my$meta=$updater->getmeta($filename);11551156my($filepart,$dirpart) = filenamesplit($filename,1);11571158$log->debug("Checked-in$dirpart:$filename");11591160if($meta->{filehash}eq"deleted")1161{1162print"Remove-entry$dirpart\n";1163print"$filename\n";1164}else{1165print"Checked-in$dirpart\n";1166print"$filename\n";1167print"/$filepart/1.$meta->{revision}///\n";1168}1169}11701171close LOCKFILE;1172my$reffile="$ENV{GIT_DIR}refs/heads/$state->{module}";1173unlink($reffile);1174rename($lockfile,$reffile);1175chdir"/";11761177print"ok\n";1178}11791180sub req_status1181{1182my($cmd,$data) =@_;11831184 argsplit("status");11851186$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1187#$log->debug("status state : " . Dumper($state));11881189# Grab a handle to the SQLite db and do any necessary updates1190my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1191$updater->update();11921193# if no files were specified, we need to work out what files we should be providing status on ...1194 argsfromdir($updater);11951196# foreach file specified on the command line ...1197foreachmy$filename( @{$state->{args}} )1198{1199$filename= filecleanup($filename);12001201my$meta=$updater->getmeta($filename);1202my$oldmeta=$meta;12031204my$wrev= revparse($filename);12051206# If the working copy is an old revision, lets get that version too for comparison.1207if(defined($wrev)and$wrev!=$meta->{revision} )1208{1209$oldmeta=$updater->getmeta($filename,$wrev);1210}12111212# TODO : All possible statuses aren't yet implemented1213my$status;1214# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1215$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1216and1217( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1218or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1219);12201221# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1222$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1223and1224($state->{entries}{$filename}{unchanged}1225or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1226);12271228# Need checkout if it exists in the repo but doesn't have a working copy1229$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12301231# Locally modified if working copy and repo copy have the same revision but there are local changes1232$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12331234# Needs Merge if working copy revision is less than repo copy and there are local changes1235$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12361237$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1238$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1239$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1240$status||="File had conflicts on merge"if(0);12411242$status||="Unknown";12431244print"M ===================================================================\n";1245print"M File:$filename\tStatus:$status\n";1246if(defined($state->{entries}{$filename}{revision}) )1247{1248print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1249}else{1250print"M Working revision:\tNo entry for$filename\n";1251}1252if(defined($meta->{revision}) )1253{1254print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{repository}/$filename,v\n";1255print"M Sticky Tag:\t\t(none)\n";1256print"M Sticky Date:\t\t(none)\n";1257print"M Sticky Options:\t\t(none)\n";1258}else{1259print"M Repository revision:\tNo revision control file\n";1260}1261print"M\n";1262}12631264print"ok\n";1265}12661267sub req_diff1268{1269my($cmd,$data) =@_;12701271 argsplit("diff");12721273$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1274#$log->debug("status state : " . Dumper($state));12751276my($revision1,$revision2);1277if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1278{1279$revision1=$state->{opt}{r}[0];1280$revision2=$state->{opt}{r}[1];1281}else{1282$revision1=$state->{opt}{r};1283}12841285$revision1=~s/^1\.//if(defined($revision1) );1286$revision2=~s/^1\.//if(defined($revision2) );12871288$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );12891290# Grab a handle to the SQLite db and do any necessary updates1291my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1292$updater->update();12931294# if no files were specified, we need to work out what files we should be providing status on ...1295 argsfromdir($updater);12961297# foreach file specified on the command line ...1298foreachmy$filename( @{$state->{args}} )1299{1300$filename= filecleanup($filename);13011302my($fh,$file1,$file2,$meta1,$meta2,$filediff);13031304my$wrev= revparse($filename);13051306# We need _something_ to diff against1307next unless(defined($wrev) );13081309# if we have a -r switch, use it1310if(defined($revision1) )1311{1312(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1313$meta1=$updater->getmeta($filename,$revision1);1314unless(defined($meta1)and$meta1->{filehash}ne"deleted")1315{1316print"E File$filenameat revision 1.$revision1doesn't exist\n";1317next;1318}1319 transmitfile($meta1->{filehash},$file1);1320}1321# otherwise we just use the working copy revision1322else1323{1324(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1325$meta1=$updater->getmeta($filename,$wrev);1326 transmitfile($meta1->{filehash},$file1);1327}13281329# if we have a second -r switch, use it too1330if(defined($revision2) )1331{1332(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1333$meta2=$updater->getmeta($filename,$revision2);13341335unless(defined($meta2)and$meta2->{filehash}ne"deleted")1336{1337print"E File$filenameat revision 1.$revision2doesn't exist\n";1338next;1339}13401341 transmitfile($meta2->{filehash},$file2);1342}1343# otherwise we just use the working copy1344else1345{1346$file2=$state->{entries}{$filename}{modified_filename};1347}13481349# if we have been given -r, and we don't have a $file2 yet, lets get one1350if(defined($revision1)and not defined($file2) )1351{1352(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1353$meta2=$updater->getmeta($filename,$wrev);1354 transmitfile($meta2->{filehash},$file2);1355}13561357# We need to have retrieved something useful1358next unless(defined($meta1) );13591360# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1361next if(not defined($meta2)and$wrev==$meta1->{revision}1362and1363( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1364or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1365);13661367# Apparently we only show diffs for locally modified files1368next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );13691370print"M Index:$filename\n";1371print"M ===================================================================\n";1372print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1373print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1374print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1375print"M diff ";1376foreachmy$opt(keys%{$state->{opt}} )1377{1378if(ref$state->{opt}{$opt}eq"ARRAY")1379{1380foreachmy$value( @{$state->{opt}{$opt}} )1381{1382print"-$opt$value";1383}1384}else{1385print"-$opt";1386print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1387}1388}1389print"$filename\n";13901391$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));13921393($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);13941395if(exists$state->{opt}{u} )1396{1397system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1398}else{1399system("diff$file1$file2>$filediff");1400}14011402while( <$fh> )1403{1404print"M$_";1405}1406close$fh;1407}14081409print"ok\n";1410}14111412sub req_log1413{1414my($cmd,$data) =@_;14151416 argsplit("log");14171418$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1419#$log->debug("log state : " . Dumper($state));14201421my($minrev,$maxrev);1422if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1423{1424my$control=$2;1425$minrev=$1;1426$maxrev=$3;1427$minrev=~s/^1\.//if(defined($minrev) );1428$maxrev=~s/^1\.//if(defined($maxrev) );1429$minrev++if(defined($minrev)and$controleq"::");1430}14311432# Grab a handle to the SQLite db and do any necessary updates1433my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1434$updater->update();14351436# if no files were specified, we need to work out what files we should be providing status on ...1437 argsfromdir($updater);14381439# foreach file specified on the command line ...1440foreachmy$filename( @{$state->{args}} )1441{1442$filename= filecleanup($filename);14431444my$headmeta=$updater->getmeta($filename);14451446my$revisions=$updater->getlog($filename);1447my$totalrevisions=scalar(@$revisions);14481449if(defined($minrev) )1450{1451$log->debug("Removing revisions less than$minrev");1452while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1453{1454pop@$revisions;1455}1456}1457if(defined($maxrev) )1458{1459$log->debug("Removing revisions greater than$maxrev");1460while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1461{1462shift@$revisions;1463}1464}14651466next unless(scalar(@$revisions) );14671468print"M\n";1469print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1470print"M Working file:$filename\n";1471print"M head: 1.$headmeta->{revision}\n";1472print"M branch:\n";1473print"M locks: strict\n";1474print"M access list:\n";1475print"M symbolic names:\n";1476print"M keyword substitution: kv\n";1477print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1478print"M description:\n";14791480foreachmy$revision(@$revisions)1481{1482print"M ----------------------------\n";1483print"M revision 1.$revision->{revision}\n";1484# reformat the date for log output1485$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}) );1486$revision->{author} =~s/\s+.*//;1487$revision->{author} =~s/^(.{8}).*/$1/;1488print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1489my$commitmessage=$updater->commitmessage($revision->{commithash});1490$commitmessage=~s/^/M /mg;1491print$commitmessage."\n";1492}1493print"M =============================================================================\n";1494}14951496print"ok\n";1497}14981499sub req_annotate1500{1501my($cmd,$data) =@_;15021503 argsplit("annotate");15041505$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1506#$log->debug("status state : " . Dumper($state));15071508# Grab a handle to the SQLite db and do any necessary updates1509my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1510$updater->update();15111512# if no files were specified, we need to work out what files we should be providing annotate on ...1513 argsfromdir($updater);15141515# we'll need a temporary checkout dir1516my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1517my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1518$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15191520$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1521$ENV{GIT_INDEX_FILE} =$file_index;15221523chdir$tmpdir;15241525# foreach file specified on the command line ...1526foreachmy$filename( @{$state->{args}} )1527{1528$filename= filecleanup($filename);15291530my$meta=$updater->getmeta($filename);15311532next unless($meta->{revision} );15331534# get all the commits that this file was in1535# in dense format -- aka skip dead revisions1536my$revisions=$updater->gethistorydense($filename);1537my$lastseenin=$revisions->[0][2];15381539# populate the temporary index based on the latest commit were we saw1540# the file -- but do it cheaply without checking out any files1541# TODO: if we got a revision from the client, use that instead1542# to look up the commithash in sqlite (still good to default to1543# the current head as we do now)1544system("git-read-tree",$lastseenin);1545unless($?==0)1546{1547die"Error running git-read-tree$lastseenin$file_index$!";1548}1549$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");15501551# do a checkout of the file1552system('git-checkout-index','-f','-u',$filename);1553unless($?==0) {1554die"Error running git-checkout-index -f -u$filename:$!";1555}15561557$log->info("Annotate$filename");15581559# Prepare a file with the commits from the linearized1560# history that annotate should know about. This prevents1561# git-jsannotate telling us about commits we are hiding1562# from the client.15631564open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1565for(my$i=0;$i<@$revisions;$i++)1566{1567print ANNOTATEHINTS $revisions->[$i][2];1568if($i+1<@$revisions) {# have we got a parent?1569print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1570}1571print ANNOTATEHINTS "\n";1572}15731574print ANNOTATEHINTS "\n";1575close ANNOTATEHINTS;15761577my$annotatecmd='git-annotate';1578open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1579or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1580my$metadata= {};1581print"E Annotations for$filename\n";1582print"E ***************\n";1583while( <ANNOTATE> )1584{1585if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1586{1587my$commithash=$1;1588my$data=$2;1589unless(defined($metadata->{$commithash} ) )1590{1591$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1592$metadata->{$commithash}{author} =~s/\s+.*//;1593$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1594$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1595}1596printf("M 1.%-5d (%-8s%10s):%s\n",1597$metadata->{$commithash}{revision},1598$metadata->{$commithash}{author},1599$metadata->{$commithash}{modified},1600$data1601);1602}else{1603$log->warn("Error in annotate output! LINE:$_");1604print"E Annotate error\n";1605next;1606}1607}1608close ANNOTATE;1609}16101611# done; get out of the tempdir1612chdir"/";16131614print"ok\n";16151616}16171618# This method takes the state->{arguments} array and produces two new arrays.1619# The first is $state->{args} which is everything before the '--' argument, and1620# the second is $state->{files} which is everything after it.1621sub argsplit1622{1623return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16241625my$type=shift;16261627$state->{args} = [];1628$state->{files} = [];1629$state->{opt} = {};16301631if(defined($type) )1632{1633my$opt= {};1634$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");1635$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1636$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");1637$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1638$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1639$opt= { k =>1, m =>1}if($typeeq"add");1640$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1641$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");164216431644while(scalar( @{$state->{arguments}} ) >0)1645{1646my$arg=shift@{$state->{arguments}};16471648next if($argeq"--");1649next unless($arg=~/\S/);16501651# if the argument looks like a switch1652if($arg=~/^-(\w)(.*)/)1653{1654# if it's a switch that takes an argument1655if($opt->{$1} )1656{1657# If this switch has already been provided1658if($opt->{$1} >1and exists($state->{opt}{$1} ) )1659{1660$state->{opt}{$1} = [$state->{opt}{$1} ];1661if(length($2) >0)1662{1663push@{$state->{opt}{$1}},$2;1664}else{1665push@{$state->{opt}{$1}},shift@{$state->{arguments}};1666}1667}else{1668# if there's extra data in the arg, use that as the argument for the switch1669if(length($2) >0)1670{1671$state->{opt}{$1} =$2;1672}else{1673$state->{opt}{$1} =shift@{$state->{arguments}};1674}1675}1676}else{1677$state->{opt}{$1} =undef;1678}1679}1680else1681{1682push@{$state->{args}},$arg;1683}1684}1685}1686else1687{1688my$mode=0;16891690foreachmy$value( @{$state->{arguments}} )1691{1692if($valueeq"--")1693{1694$mode++;1695next;1696}1697push@{$state->{args}},$valueif($mode==0);1698push@{$state->{files}},$valueif($mode==1);1699}1700}1701}17021703# This method uses $state->{directory} to populate $state->{args} with a list of filenames1704sub argsfromdir1705{1706my$updater=shift;17071708$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17091710return if(scalar( @{$state->{args}} ) >1);17111712if(scalar(@{$state->{args}}) ==1)1713{1714my$arg=$state->{args}[0];1715$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17161717$log->info("Only one arg specified, checking for directory expansion on '$arg'");17181719foreachmy$file( @{$updater->gethead} )1720{1721next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1722next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1723push@{$state->{args}},$file->{name};1724}17251726shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1727}else{1728$log->info("Only one arg specified, populating file list automatically");17291730$state->{args} = [];17311732foreachmy$file( @{$updater->gethead} )1733{1734next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1735next unless($file->{name} =~s/^$state->{prependdir}//);1736push@{$state->{args}},$file->{name};1737}1738}1739}17401741# This method cleans up the $state variable after a command that uses arguments has run1742sub statecleanup1743{1744$state->{files} = [];1745$state->{args} = [];1746$state->{arguments} = [];1747$state->{entries} = {};1748}17491750sub revparse1751{1752my$filename=shift;17531754returnundefunless(defined($state->{entries}{$filename}{revision} ) );17551756return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1757return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);17581759returnundef;1760}17611762# This method takes a file hash and does a CVS "file transfer" which transmits the1763# size of the file, and then the file contents.1764# If a second argument $targetfile is given, the file is instead written out to1765# a file by the name of $targetfile1766sub transmitfile1767{1768my$filehash=shift;1769my$targetfile=shift;17701771if(defined($filehash)and$filehasheq"deleted")1772{1773$log->warn("filehash is 'deleted'");1774return;1775}17761777die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);17781779my$type=`git-cat-file -t$filehash`;1780 chomp$type;17811782 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );17831784 my$size= `git-cat-file -s $filehash`;1785chomp$size;17861787$log->debug("transmitfile($filehash) size=$size, type=$type");17881789if(open my$fh,'-|',"git-cat-file","blob",$filehash)1790{1791if(defined($targetfile) )1792{1793open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1794print NEWFILE $_while( <$fh> );1795close NEWFILE;1796}else{1797print"$size\n";1798printwhile( <$fh> );1799}1800close$fhor die("Couldn't close filehandle for transmitfile()");1801}else{1802die("Couldn't execute git-cat-file");1803}1804}18051806# This method takes a file name, and returns ( $dirpart, $filepart ) which1807# refers to the directory portion and the file portion of the filename1808# respectively1809sub filenamesplit1810{1811my$filename=shift;1812my$fixforlocaldir=shift;18131814my($filepart,$dirpart) = ($filename,".");1815($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1816$dirpart.="/";18171818if($fixforlocaldir)1819{1820$dirpart=~s/^$state->{prependdir}//;1821}18221823return($filepart,$dirpart);1824}18251826sub filecleanup1827{1828my$filename=shift;18291830returnundefunless(defined($filename));1831if($filename=~/^\// )1832{1833print"E absolute filenames '$filename' not supported by server\n";1834returnundef;1835}18361837$filename=~s/^\.\///g;1838$filename=$state->{prependdir} .$filename;1839return$filename;1840}18411842package GITCVS::log;18431844####1845#### Copyright The Open University UK - 2006.1846####1847#### Authors: Martyn Smith <martyn@catalyst.net.nz>1848#### Martin Langhoff <martin@catalyst.net.nz>1849####1850####18511852use strict;1853use warnings;18541855=head1 NAME18561857GITCVS::log18581859=head1 DESCRIPTION18601861This module provides very crude logging with a similar interface to1862Log::Log4perl18631864=head1 METHODS18651866=cut18671868=head2 new18691870Creates a new log object, optionally you can specify a filename here to1871indicate the file to log to. If no log file is specified, you can specify one1872later with method setfile, or indicate you no longer want logging with method1873nofile.18741875Until one of these methods is called, all log calls will buffer messages ready1876to write out.18771878=cut1879sub new1880{1881my$class=shift;1882my$filename=shift;18831884my$self= {};18851886bless$self,$class;18871888if(defined($filename) )1889{1890open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1891}18921893return$self;1894}18951896=head2 setfile18971898This methods takes a filename, and attempts to open that file as the log file.1899If successful, all buffered data is written out to the file, and any further1900logging is written directly to the file.19011902=cut1903sub setfile1904{1905my$self=shift;1906my$filename=shift;19071908if(defined($filename) )1909{1910open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1911}19121913return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19141915while(my$line=shift@{$self->{buffer}} )1916{1917print{$self->{fh}}$line;1918}1919}19201921=head2 nofile19221923This method indicates no logging is going to be used. It flushes any entries in1924the internal buffer, and sets a flag to ensure no further data is put there.19251926=cut1927sub nofile1928{1929my$self=shift;19301931$self->{nolog} =1;19321933return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19341935$self->{buffer} = [];1936}19371938=head2 _logopen19391940Internal method. Returns true if the log file is open, false otherwise.19411942=cut1943sub _logopen1944{1945my$self=shift;19461947return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");1948return0;1949}19501951=head2 debug info warn fatal19521953These four methods are wrappers to _log. They provide the actual interface for1954logging data.19551956=cut1957sub debug {my$self=shift;$self->_log("debug",@_); }1958sub info {my$self=shift;$self->_log("info",@_); }1959subwarn{my$self=shift;$self->_log("warn",@_); }1960sub fatal {my$self=shift;$self->_log("fatal",@_); }19611962=head2 _log19631964This is an internal method called by the logging functions. It generates a1965timestamp and pushes the logged line either to file, or internal buffer.19661967=cut1968sub _log1969{1970my$self=shift;1971my$level=shift;19721973return if($self->{nolog} );19741975my@time=localtime;1976my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",1977$time[5] +1900,1978$time[4] +1,1979$time[3],1980$time[2],1981$time[1],1982$time[0],1983uc$level,1984);19851986if($self->_logopen)1987{1988print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";1989}else{1990push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";1991}1992}19931994=head2 DESTROY19951996This method simply closes the file handle if one is open19971998=cut1999sub DESTROY2000{2001my$self=shift;20022003if($self->_logopen)2004{2005close$self->{fh};2006}2007}20082009package GITCVS::updater;20102011####2012#### Copyright The Open University UK - 2006.2013####2014#### Authors: Martyn Smith <martyn@catalyst.net.nz>2015#### Martin Langhoff <martin@catalyst.net.nz>2016####2017####20182019use strict;2020use warnings;2021use DBI;20222023=head1 METHODS20242025=cut20262027=head2 new20282029=cut2030sub new2031{2032my$class=shift;2033my$config=shift;2034my$module=shift;2035my$log=shift;20362037die"Need to specify a git repository"unless(defined($config)and-d $config);2038die"Need to specify a module"unless(defined($module) );20392040$class=ref($class) ||$class;20412042my$self= {};20432044bless$self,$class;20452046$self->{dbdir} =$config."/";2047die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );20482049$self->{module} =$module;2050$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";20512052$self->{git_path} =$config."/";20532054$self->{log} =$log;20552056die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );20572058$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");20592060$self->{tables} = {};2061foreachmy$table($self->{dbh}->tables)2062{2063$table=~s/^"//;2064$table=~s/"$//;2065$self->{tables}{$table} =1;2066}20672068# Construct the revision table if required2069unless($self->{tables}{revision} )2070{2071$self->{dbh}->do("2072 CREATE TABLE revision (2073 name TEXT NOT NULL,2074 revision INTEGER NOT NULL,2075 filehash TEXT NOT NULL,2076 commithash TEXT NOT NULL,2077 author TEXT NOT NULL,2078 modified TEXT NOT NULL,2079 mode TEXT NOT NULL2080 )2081 ");2082}20832084# Construct the revision table if required2085unless($self->{tables}{head} )2086{2087$self->{dbh}->do("2088 CREATE TABLE head (2089 name TEXT NOT NULL,2090 revision INTEGER NOT NULL,2091 filehash TEXT NOT NULL,2092 commithash TEXT NOT NULL,2093 author TEXT NOT NULL,2094 modified TEXT NOT NULL,2095 mode TEXT NOT NULL2096 )2097 ");2098}20992100# Construct the properties table if required2101unless($self->{tables}{properties} )2102{2103$self->{dbh}->do("2104 CREATE TABLE properties (2105 key TEXT NOT NULL PRIMARY KEY,2106 value TEXT2107 )2108 ");2109}21102111# Construct the commitmsgs table if required2112unless($self->{tables}{commitmsgs} )2113{2114$self->{dbh}->do("2115 CREATE TABLE commitmsgs (2116 key TEXT NOT NULL PRIMARY KEY,2117 value TEXT2118 )2119 ");2120}21212122return$self;2123}21242125=head2 update21262127=cut2128sub update2129{2130my$self=shift;21312132# first lets get the commit list2133$ENV{GIT_DIR} =$self->{git_path};21342135my$commitinfo=`git-cat-file commit$self->{module} 2>&1`;2136unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2137{2138die("Invalid module '$self->{module}'");2139}214021412142my$git_log;2143my$lastcommit=$self->_get_prop("last_commit");21442145# Start exclusive lock here...2146$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";21472148# TODO: log processing is memory bound2149# if we can parse into a 2nd file that is in reverse order2150# we can probably do something really efficient2151my@git_log_params= ('--pretty','--parents','--topo-order');21522153if(defined$lastcommit) {2154push@git_log_params,"$lastcommit..$self->{module}";2155}else{2156push@git_log_params,$self->{module};2157}2158# git-rev-list is the backend / plumbing version of git-log2159open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";21602161my@commits;21622163my%commit= ();21642165while( <GITLOG> )2166{2167chomp;2168if(m/^commit\s+(.*)$/) {2169# on ^commit lines put the just seen commit in the stack2170# and prime things for the next one2171if(keys%commit) {2172my%copy=%commit;2173unshift@commits, \%copy;2174%commit= ();2175}2176my@parents=split(m/\s+/,$1);2177$commit{hash} =shift@parents;2178$commit{parents} = \@parents;2179}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2180# on rfc822-like lines seen before we see any message,2181# lowercase the entry and put it in the hash as key-value2182$commit{lc($1)} =$2;2183}else{2184# message lines - skip initial empty line2185# and trim whitespace2186if(!exists($commit{message}) &&m/^\s*$/) {2187# define it to mark the end of headers2188$commit{message} ='';2189next;2190}2191s/^\s+//;s/\s+$//;# trim ws2192$commit{message} .=$_."\n";2193}2194}2195close GITLOG;21962197unshift@commits, \%commitif(keys%commit);21982199# Now all the commits are in the @commits bucket2200# ordered by time DESC. for each commit that needs processing,2201# determine whether it's following the last head we've seen or if2202# it's on its own branch, grab a file list, and add whatever's changed2203# NOTE: $lastcommit refers to the last commit from previous run2204# $lastpicked is the last commit we picked in this run2205my$lastpicked;2206my$head= {};2207if(defined$lastcommit) {2208$lastpicked=$lastcommit;2209}22102211my$committotal=scalar(@commits);2212my$commitcount=0;22132214# Load the head table into $head (for cached lookups during the update process)2215foreachmy$file( @{$self->gethead()} )2216{2217$head->{$file->{name}} =$file;2218}22192220foreachmy$commit(@commits)2221{2222$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2223if(defined$lastpicked)2224{2225if(!in_array($lastpicked, @{$commit->{parents}}))2226{2227# skip, we'll see this delta2228# as part of a merge later2229# warn "skipping off-track $commit->{hash}\n";2230next;2231}elsif(@{$commit->{parents}} >1) {2232# it is a merge commit, for each parent that is2233# not $lastpicked, see if we can get a log2234# from the merge-base to that parent to put it2235# in the message as a merge summary.2236my@parents= @{$commit->{parents}};2237foreachmy$parent(@parents) {2238# git-merge-base can potentially (but rarely) throw2239# several candidate merge bases. let's assume2240# that the first one is the best one.2241if($parenteq$lastpicked) {2242next;2243}2244open my$p,'git-merge-base '.$lastpicked.' '2245.$parent.'|';2246my@output= (<$p>);2247close$p;2248my$base=join('',@output);2249chomp$base;2250if($base) {2251my@merged;2252# print "want to log between $base $parent \n";2253open(GITLOG,'-|','git-log',"$base..$parent")2254or die"Cannot call git-log:$!";2255my$mergedhash;2256while(<GITLOG>) {2257chomp;2258if(!defined$mergedhash) {2259if(m/^commit\s+(.+)$/) {2260$mergedhash=$1;2261}else{2262next;2263}2264}else{2265# grab the first line that looks non-rfc8222266# aka has content after leading space2267if(m/^\s+(\S.*)$/) {2268my$title=$1;2269$title=substr($title,0,100);# truncate2270unshift@merged,"$mergedhash$title";2271undef$mergedhash;2272}2273}2274}2275close GITLOG;2276if(@merged) {2277$commit->{mergemsg} =$commit->{message};2278$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2279foreachmy$summary(@merged) {2280$commit->{mergemsg} .="\t$summary\n";2281}2282$commit->{mergemsg} .="\n\n";2283# print "Message for $commit->{hash} \n$commit->{mergemsg}";2284}2285}2286}2287}2288}22892290# convert the date to CVS-happy format2291$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);22922293if(defined($lastpicked) )2294{2295my$filepipe=open(FILELIST,'-|','git-diff-tree','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2296while( <FILELIST> )2297{2298unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)\s+(.*)$/o)2299{2300die("Couldn't process git-diff-tree line :$_");2301}23022303# $log->debug("File mode=$1, hash=$2, change=$3, name=$4");23042305my$git_perms="";2306$git_perms.="r"if($1&4);2307$git_perms.="w"if($1&2);2308$git_perms.="x"if($1&1);2309$git_perms="rw"if($git_permseq"");23102311if($3eq"D")2312{2313#$log->debug("DELETE $4");2314$head->{$4} = {2315 name =>$4,2316 revision =>$head->{$4}{revision} +1,2317 filehash =>"deleted",2318 commithash =>$commit->{hash},2319 modified =>$commit->{date},2320 author =>$commit->{author},2321 mode =>$git_perms,2322};2323$self->insert_rev($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2324}2325elsif($3eq"M")2326{2327#$log->debug("MODIFIED $4");2328$head->{$4} = {2329 name =>$4,2330 revision =>$head->{$4}{revision} +1,2331 filehash =>$2,2332 commithash =>$commit->{hash},2333 modified =>$commit->{date},2334 author =>$commit->{author},2335 mode =>$git_perms,2336};2337$self->insert_rev($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2338}2339elsif($3eq"A")2340{2341#$log->debug("ADDED $4");2342$head->{$4} = {2343 name =>$4,2344 revision =>1,2345 filehash =>$2,2346 commithash =>$commit->{hash},2347 modified =>$commit->{date},2348 author =>$commit->{author},2349 mode =>$git_perms,2350};2351$self->insert_rev($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2352}2353else2354{2355$log->warn("UNKNOWN FILE CHANGE mode=$1, hash=$2, change=$3, name=$4");2356die;2357}2358}2359close FILELIST;2360}else{2361# this is used to detect files removed from the repo2362my$seen_files= {};23632364my$filepipe=open(FILELIST,'-|','git-ls-tree','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2365while( <FILELIST> )2366{2367unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\s+(.*)$/o)2368{2369die("Couldn't process git-ls-tree line :$_");2370}23712372my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);23732374$seen_files->{$git_filename} =1;23752376my($oldhash,$oldrevision,$oldmode) = (2377$head->{$git_filename}{filehash},2378$head->{$git_filename}{revision},2379$head->{$git_filename}{mode}2380);23812382if($git_perms=~/^\d\d\d(\d)\d\d/o)2383{2384$git_perms="";2385$git_perms.="r"if($1&4);2386$git_perms.="w"if($1&2);2387$git_perms.="x"if($1&1);2388}else{2389$git_perms="rw";2390}23912392# unless the file exists with the same hash, we need to update it ...2393unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2394{2395my$newrevision= ($oldrevisionor0) +1;23962397$head->{$git_filename} = {2398 name =>$git_filename,2399 revision =>$newrevision,2400 filehash =>$git_hash,2401 commithash =>$commit->{hash},2402 modified =>$commit->{date},2403 author =>$commit->{author},2404 mode =>$git_perms,2405};240624072408$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2409}2410}2411close FILELIST;24122413# Detect deleted files2414foreachmy$file(keys%$head)2415{2416unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2417{2418$head->{$file}{revision}++;2419$head->{$file}{filehash} ="deleted";2420$head->{$file}{commithash} =$commit->{hash};2421$head->{$file}{modified} =$commit->{date};2422$head->{$file}{author} =$commit->{author};24232424$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2425}2426}2427# END : "Detect deleted files"2428}242924302431if(exists$commit->{mergemsg})2432{2433$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2434}24352436$lastpicked=$commit->{hash};24372438$self->_set_prop("last_commit",$commit->{hash});2439}24402441$self->delete_head();2442foreachmy$file(keys%$head)2443{2444$self->insert_head(2445$file,2446$head->{$file}{revision},2447$head->{$file}{filehash},2448$head->{$file}{commithash},2449$head->{$file}{modified},2450$head->{$file}{author},2451$head->{$file}{mode},2452);2453}2454# invalidate the gethead cache2455$self->{gethead_cache} =undef;245624572458# Ending exclusive lock here2459$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2460}24612462sub insert_rev2463{2464my$self=shift;2465my$name=shift;2466my$revision=shift;2467my$filehash=shift;2468my$commithash=shift;2469my$modified=shift;2470my$author=shift;2471my$mode=shift;24722473my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2474$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2475}24762477sub insert_mergelog2478{2479my$self=shift;2480my$key=shift;2481my$value=shift;24822483my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2484$insert_mergelog->execute($key,$value);2485}24862487sub delete_head2488{2489my$self=shift;24902491my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2492$delete_head->execute();2493}24942495sub insert_head2496{2497my$self=shift;2498my$name=shift;2499my$revision=shift;2500my$filehash=shift;2501my$commithash=shift;2502my$modified=shift;2503my$author=shift;2504my$mode=shift;25052506my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2507$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2508}25092510sub _headrev2511{2512my$self=shift;2513my$filename=shift;25142515my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2516$db_query->execute($filename);2517my($hash,$revision,$mode) =$db_query->fetchrow_array;25182519return($hash,$revision,$mode);2520}25212522sub _get_prop2523{2524my$self=shift;2525my$key=shift;25262527my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2528$db_query->execute($key);2529my($value) =$db_query->fetchrow_array;25302531return$value;2532}25332534sub _set_prop2535{2536my$self=shift;2537my$key=shift;2538my$value=shift;25392540my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2541$db_query->execute($value,$key);25422543unless($db_query->rows)2544{2545$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2546$db_query->execute($key,$value);2547}25482549return$value;2550}25512552=head2 gethead25532554=cut25552556sub gethead2557{2558my$self=shift;25592560return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );25612562my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2563$db_query->execute();25642565my$tree= [];2566while(my$file=$db_query->fetchrow_hashref)2567{2568push@$tree,$file;2569}25702571$self->{gethead_cache} =$tree;25722573return$tree;2574}25752576=head2 getlog25772578=cut25792580sub getlog2581{2582my$self=shift;2583my$filename=shift;25842585my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2586$db_query->execute($filename);25872588my$tree= [];2589while(my$file=$db_query->fetchrow_hashref)2590{2591push@$tree,$file;2592}25932594return$tree;2595}25962597=head2 getmeta25982599This function takes a filename (with path) argument and returns a hashref of2600metadata for that file.26012602=cut26032604sub getmeta2605{2606my$self=shift;2607my$filename=shift;2608my$revision=shift;26092610my$db_query;2611if(defined($revision)and$revision=~/^\d+$/)2612{2613$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2614$db_query->execute($filename,$revision);2615}2616elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2617{2618$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2619$db_query->execute($filename,$revision);2620}else{2621$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2622$db_query->execute($filename);2623}26242625return$db_query->fetchrow_hashref;2626}26272628=head2 commitmessage26292630this function takes a commithash and returns the commit message for that commit26312632=cut2633sub commitmessage2634{2635my$self=shift;2636my$commithash=shift;26372638die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);26392640my$db_query;2641$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2642$db_query->execute($commithash);26432644my($message) =$db_query->fetchrow_array;26452646if(defined($message) )2647{2648$message.=" "if($message=~/\n$/);2649return$message;2650}26512652my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2653shift@lineswhile($lines[0] =~/\S/);2654$message=join("",@lines);2655$message.=" "if($message=~/\n$/);2656return$message;2657}26582659=head2 gethistory26602661This function takes a filename (with path) argument and returns an arrayofarrays2662containing revision,filehash,commithash ordered by revision descending26632664=cut2665sub gethistory2666{2667my$self=shift;2668my$filename=shift;26692670my$db_query;2671$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2672$db_query->execute($filename);26732674return$db_query->fetchall_arrayref;2675}26762677=head2 gethistorydense26782679This function takes a filename (with path) argument and returns an arrayofarrays2680containing revision,filehash,commithash ordered by revision descending.26812682This version of gethistory skips deleted entries -- so it is useful for annotate.2683The 'dense' part is a reference to a '--dense' option available for git-rev-list2684and other git tools that depend on it.26852686=cut2687sub gethistorydense2688{2689my$self=shift;2690my$filename=shift;26912692my$db_query;2693$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2694$db_query->execute($filename);26952696return$db_query->fetchall_arrayref;2697}26982699=head2 in_array()27002701from Array::PAT - mimics the in_array() function2702found in PHP. Yuck but works for small arrays.27032704=cut2705sub in_array2706{2707my($check,@array) =@_;2708my$retval=0;2709foreachmy$test(@array){2710if($checkeq$test){2711$retval=1;2712}2713}2714return$retval;2715}27162717=head2 safe_pipe_capture27182719an alternative to `command` that allows input to be passed as an array2720to work around shell problems with weird characters in arguments27212722=cut2723sub safe_pipe_capture {27242725my@output;27262727if(my$pid=open my$child,'-|') {2728@output= (<$child>);2729close$childor die join(' ',@_).":$!$?";2730}else{2731exec(@_)or die"$!$?";# exec() can fail the executable can't be found2732}2733returnwantarray?@output:join('',@output);2734}2735273627371;