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= {}; 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 # TODO : Not quite sure how Argument and Argumentx differ, but I assume 551 # it's for multi-line arguments ... somehow ... 552 553$log->debug("$cmd:$data"); 554 555push@{$state->{arguments}},$data; 556} 557 558# expand-modules \n 559# Response expected: yes. Expand the modules which are specified in the 560# arguments. Returns the data in Module-expansion responses. Note that the 561# server can assume that this is checkout or export, not rtag or rdiff; the 562# latter do not access the working directory and thus have no need to 563# expand modules on the client side. Expand may not be the best word for 564# what this request does. It does not necessarily tell you all the files 565# contained in a module, for example. Basically it is a way of telling you 566# which working directories the server needs to know about in order to 567# handle a checkout of the specified modules. For example, suppose that the 568# server has a module defined by 569# aliasmodule -a 1dir 570# That is, one can check out aliasmodule and it will take 1dir in the 571# repository and check it out to 1dir in the working directory. Now suppose 572# the client already has this module checked out and is planning on using 573# the co request to update it. Without using expand-modules, the client 574# would have two bad choices: it could either send information about all 575# working directories under the current directory, which could be 576# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 577# stands for 1dir, and neglect to send information for 1dir, which would 578# lead to incorrect operation. With expand-modules, the client would first 579# ask for the module to be expanded: 580sub req_expandmodules 581{ 582my($cmd,$data) =@_; 583 584 argsplit(); 585 586$log->debug("req_expandmodules : ". (defined($data) ?$data:"[NULL]") ); 587 588unless(ref$state->{arguments}eq"ARRAY") 589{ 590print"ok\n"; 591return; 592} 593 594foreachmy$module( @{$state->{arguments}} ) 595{ 596$log->debug("SEND : Module-expansion$module"); 597print"Module-expansion$module\n"; 598} 599 600print"ok\n"; 601 statecleanup(); 602} 603 604# co \n 605# Response expected: yes. Get files from the repository. This uses any 606# previous Argument, Directory, Entry, or Modified requests, if they have 607# been sent. Arguments to this command are module names; the client cannot 608# know what directories they correspond to except by (1) just sending the 609# co request, and then seeing what directory names the server sends back in 610# its responses, and (2) the expand-modules request. 611sub req_co 612{ 613my($cmd,$data) =@_; 614 615 argsplit("co"); 616 617my$module=$state->{args}[0]; 618my$checkout_path=$module; 619 620# use the user specified directory if we're given it 621$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 622 623$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 624 625$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 626 627$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 628 629# Grab a handle to the SQLite db and do any necessary updates 630my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 631$updater->update(); 632 633$checkout_path=~ s|/$||;# get rid of trailing slashes 634 635# Eclipse seems to need the Clear-sticky command 636# to prepare the 'Entries' file for the new directory. 637print"Clear-sticky$checkout_path/\n"; 638print$state->{CVSROOT} ."/$module/\n"; 639print"Clear-static-directory$checkout_path/\n"; 640print$state->{CVSROOT} ."/$module/\n"; 641print"Clear-sticky$checkout_path/\n";# yes, twice 642print$state->{CVSROOT} ."/$module/\n"; 643print"Template$checkout_path/\n"; 644print$state->{CVSROOT} ."/$module/\n"; 645print"0\n"; 646 647# instruct the client that we're checking out to $checkout_path 648print"E cvs checkout: Updating$checkout_path\n"; 649 650my%seendirs= (); 651my$lastdir=''; 652 653# recursive 654sub prepdir { 655my($dir,$repodir,$remotedir,$seendirs) =@_; 656my$parent= dirname($dir); 657$dir=~ s|/+$||; 658$repodir=~ s|/+$||; 659$remotedir=~ s|/+$||; 660$parent=~ s|/+$||; 661$log->debug("announcedir$dir,$repodir,$remotedir"); 662 663if($parenteq'.'||$parenteq'./') { 664$parent=''; 665} 666# recurse to announce unseen parents first 667if(length($parent) && !exists($seendirs->{$parent})) { 668 prepdir($parent,$repodir,$remotedir,$seendirs); 669} 670# Announce that we are going to modify at the parent level 671if($parent) { 672print"E cvs checkout: Updating$remotedir/$parent\n"; 673}else{ 674print"E cvs checkout: Updating$remotedir\n"; 675} 676print"Clear-sticky$remotedir/$parent/\n"; 677print"$repodir/$parent/\n"; 678 679print"Clear-static-directory$remotedir/$dir/\n"; 680print"$repodir/$dir/\n"; 681print"Clear-sticky$remotedir/$parent/\n";# yes, twice 682print"$repodir/$parent/\n"; 683print"Template$remotedir/$dir/\n"; 684print"$repodir/$dir/\n"; 685print"0\n"; 686 687$seendirs->{$dir} =1; 688} 689 690foreachmy$git( @{$updater->gethead} ) 691{ 692# Don't want to check out deleted files 693next if($git->{filehash}eq"deleted"); 694 695($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 696 697if(length($git->{dir}) &&$git->{dir}ne'./' 698&&$git->{dir}ne$lastdir) { 699unless(exists($seendirs{$git->{dir}})) { 700 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 701$checkout_path, \%seendirs); 702$lastdir=$git->{dir}; 703$seendirs{$git->{dir}} =1; 704} 705print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 706} 707 708# modification time of this file 709print"Mod-time$git->{modified}\n"; 710 711# print some information to the client 712if(defined($git->{dir} )and$git->{dir}ne"./") 713{ 714print"M U$checkout_path/$git->{dir}$git->{name}\n"; 715}else{ 716print"M U$checkout_path/$git->{name}\n"; 717} 718 719# instruct client we're sending a file to put in this path 720print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 721 722print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 723 724# this is an "entries" line 725print"/$git->{name}/1.$git->{revision}///\n"; 726# permissions 727print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 728 729# transmit file 730 transmitfile($git->{filehash}); 731} 732 733print"ok\n"; 734 735 statecleanup(); 736} 737 738# update \n 739# Response expected: yes. Actually do a cvs update command. This uses any 740# previous Argument, Directory, Entry, or Modified requests, if they have 741# been sent. The last Directory sent specifies the working directory at the 742# time of the operation. The -I option is not used--files which the client 743# can decide whether to ignore are not mentioned and the client sends the 744# Questionable request for others. 745sub req_update 746{ 747my($cmd,$data) =@_; 748 749$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 750 751 argsplit("update"); 752 753# 754# It may just be a client exploring the available heads/modules 755# in that case, list them as top level directories and leave it 756# at that. Eclipse uses this technique to offer you a list of 757# projects (heads in this case) to checkout. 758# 759if($state->{module}eq'') { 760print"E cvs update: Updating .\n"; 761opendir HEADS,$state->{CVSROOT} .'/refs/heads'; 762while(my$head=readdir(HEADS)) { 763if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 764print"E cvs update: New directory `$head'\n"; 765} 766} 767closedir HEADS; 768print"ok\n"; 769return1; 770} 771 772 773# Grab a handle to the SQLite db and do any necessary updates 774my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 775 776$updater->update(); 777 778 argsfromdir($updater); 779 780#$log->debug("update state : " . Dumper($state)); 781 782# foreach file specified on the commandline ... 783foreachmy$filename( @{$state->{args}} ) 784{ 785$filename= filecleanup($filename); 786 787$log->debug("Processing file$filename"); 788 789# if we have a -C we should pretend we never saw modified stuff 790if(exists($state->{opt}{C} ) ) 791{ 792delete$state->{entries}{$filename}{modified_hash}; 793delete$state->{entries}{$filename}{modified_filename}; 794$state->{entries}{$filename}{unchanged} =1; 795} 796 797my$meta; 798if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 799{ 800$meta=$updater->getmeta($filename,$1); 801}else{ 802$meta=$updater->getmeta($filename); 803} 804 805next unless($meta->{revision} ); 806 807my$oldmeta=$meta; 808 809my$wrev= revparse($filename); 810 811# If the working copy is an old revision, lets get that version too for comparison. 812if(defined($wrev)and$wrev!=$meta->{revision} ) 813{ 814$oldmeta=$updater->getmeta($filename,$wrev); 815} 816 817#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 818 819# Files are up to date if the working copy and repo copy have the same revision, 820# and the working copy is unmodified _and_ the user hasn't specified -C 821next if(defined($wrev) 822and defined($meta->{revision}) 823and$wrev==$meta->{revision} 824and$state->{entries}{$filename}{unchanged} 825and not exists($state->{opt}{C} ) ); 826 827# If the working copy and repo copy have the same revision, 828# but the working copy is modified, tell the client it's modified 829if(defined($wrev) 830and defined($meta->{revision}) 831and$wrev==$meta->{revision} 832and not exists($state->{opt}{C} ) ) 833{ 834$log->info("Tell the client the file is modified"); 835print"MT text U\n"; 836print"MT fname$filename\n"; 837print"MT newline\n"; 838next; 839} 840 841if($meta->{filehash}eq"deleted") 842{ 843my($filepart,$dirpart) = filenamesplit($filename,1); 844 845$log->info("Removing '$filename' from working copy (no longer in the repo)"); 846 847print"E cvs update: `$filename' is no longer in the repository\n"; 848# Don't want to actually _DO_ the update if -n specified 849unless($state->{globaloptions}{-n} ) { 850print"Removed$dirpart\n"; 851print"$filepart\n"; 852} 853} 854elsif(not defined($state->{entries}{$filename}{modified_hash} ) 855or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) 856{ 857$log->info("Updating '$filename'"); 858# normal update, just send the new revision (either U=Update, or A=Add, or R=Remove) 859print"MT +updated\n"; 860print"MT text U\n"; 861print"MT fname$filename\n"; 862print"MT newline\n"; 863print"MT -updated\n"; 864 865my($filepart,$dirpart) = filenamesplit($filename,1); 866 867# Don't want to actually _DO_ the update if -n specified 868unless($state->{globaloptions}{-n} ) 869{ 870if(defined($wrev) ) 871{ 872# instruct client we're sending a file to put in this path as a replacement 873print"Update-existing$dirpart\n"; 874$log->debug("Updating existing file 'Update-existing$dirpart'"); 875}else{ 876# instruct client we're sending a file to put in this path as a new file 877print"Clear-static-directory$dirpart\n"; 878print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 879print"Clear-sticky$dirpart\n"; 880print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 881 882$log->debug("Creating new file 'Created$dirpart'"); 883print"Created$dirpart\n"; 884} 885print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 886 887# this is an "entries" line 888$log->debug("/$filepart/1.$meta->{revision}///"); 889print"/$filepart/1.$meta->{revision}///\n"; 890 891# permissions 892$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 893print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 894 895# transmit file 896 transmitfile($meta->{filehash}); 897} 898}else{ 899$log->info("Updating '$filename'"); 900my($filepart,$dirpart) = filenamesplit($meta->{name},1); 901 902my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/"; 903 904chdir$dir; 905my$file_local=$filepart.".mine"; 906system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local); 907my$file_old=$filepart.".".$oldmeta->{revision}; 908 transmitfile($oldmeta->{filehash},$file_old); 909my$file_new=$filepart.".".$meta->{revision}; 910 transmitfile($meta->{filehash},$file_new); 911 912# we need to merge with the local changes ( M=successful merge, C=conflict merge ) 913$log->info("Merging$file_local,$file_old,$file_new"); 914 915$log->debug("Temporary directory for merge is$dir"); 916 917my$return=system("merge",$file_local,$file_old,$file_new); 918$return>>=8; 919 920if($return==0) 921{ 922$log->info("Merged successfully"); 923print"M M$filename\n"; 924$log->debug("Update-existing$dirpart"); 925 926# Don't want to actually _DO_ the update if -n specified 927unless($state->{globaloptions}{-n} ) 928{ 929print"Update-existing$dirpart\n"; 930$log->debug($state->{CVSROOT} ."/$state->{module}/$filename"); 931print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 932$log->debug("/$filepart/1.$meta->{revision}///"); 933print"/$filepart/1.$meta->{revision}///\n"; 934} 935} 936elsif($return==1) 937{ 938$log->info("Merged with conflicts"); 939print"M C$filename\n"; 940 941# Don't want to actually _DO_ the update if -n specified 942unless($state->{globaloptions}{-n} ) 943{ 944print"Update-existing$dirpart\n"; 945print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 946print"/$filepart/1.$meta->{revision}/+//\n"; 947} 948} 949else 950{ 951$log->warn("Merge failed"); 952next; 953} 954 955# Don't want to actually _DO_ the update if -n specified 956unless($state->{globaloptions}{-n} ) 957{ 958# permissions 959$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 960print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 961 962# transmit file, format is single integer on a line by itself (file 963# size) followed by the file contents 964# TODO : we should copy files in blocks 965my$data=`cat$file_local`; 966$log->debug("File size : " . length($data)); 967 print length($data) . "\n"; 968 print$data; 969 } 970 971 chdir "/"; 972 } 973 974 } 975 976 print "ok\n"; 977} 978 979sub req_ci 980{ 981 my ($cmd,$data) =@_; 982 983 argsplit("ci"); 984 985 #$log->debug("State : " . Dumper($state)); 986 987$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" )); 988 989 if (@ARGV&&$ARGV[0] eq 'pserver') 990 { 991 print "error 1 pserver access cannot commit\n"; 992 exit; 993 } 994 995 if ( -e$state->{CVSROOT} . "/index" ) 996 { 997$log->warn("file 'index' already exists in the git repository"); 998 print "error 1 Index already exists in git repo\n"; 999 exit;1000 }10011002 my$lockfile= "$state->{CVSROOT}/refs/heads/$state->{module}.lock";1003 unless ( sysopen(LOCKFILE,$lockfile,O_EXCL|O_CREAT|O_WRONLY) )1004 {1005$log->warn("lockfile '$lockfile' already exists, please try again");1006 print "error 1 Lock file '$lockfile' already exists, please try again\n";1007 exit;1008 }10091010 # Grab a handle to the SQLite db and do any necessary updates1011 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1012$updater->update();10131014 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1015 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1016$log->info("Lock successful, basing commit on '$tmpdir', index file is '$file_index'");10171018$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1019$ENV{GIT_INDEX_FILE} =$file_index;10201021 chdir$tmpdir;10221023 # populate the temporary index based1024 system("git-read-tree",$state->{module});1025 unless ($?== 0)1026 {1027 die "Error running git-read-tree$state->{module}$file_index$!";1028 }1029$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");103010311032 my@committedfiles= ();10331034 # foreach file specified on the commandline ...1035 foreach my$filename( @{$state->{args}} )1036 {1037 my$committedfile=$filename;1038$filename= filecleanup($filename);10391040 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10411042 my$meta=$updater->getmeta($filename);10431044 my$wrev= revparse($filename);10451046 my ($filepart,$dirpart) = filenamesplit($filename);10471048 # do a checkout of the file if it part of this tree1049 if ($wrev) {1050 system('git-checkout-index', '-f', '-u',$filename);1051 unless ($?== 0) {1052 die "Error running git-checkout-index -f -u$filename:$!";1053 }1054 }10551056 my$addflag= 0;1057 my$rmflag= 0;1058$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1059$addflag= 1 unless ( -e$filename);10601061 # Do up to date checking1062 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1063 {1064 # fail everything if an up to date check fails1065 print "error 1 Up to date check failed for$filename\n";1066 close LOCKFILE;1067 unlink($lockfile);1068 chdir "/";1069 exit;1070 }10711072 push@committedfiles,$committedfile;1073$log->info("Committing$filename");10741075 system("mkdir","-p",$dirpart) unless ( -d$dirpart);10761077 unless ($rmflag)1078 {1079$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1080 rename$state->{entries}{$filename}{modified_filename},$filename;10811082 # Calculate modes to remove1083 my$invmode= "";1084 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }10851086$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1087 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1088 }10891090 if ($rmflag)1091 {1092$log->info("Removing file '$filename'");1093 unlink($filename);1094 system("git-update-index", "--remove",$filename);1095 }1096 elsif ($addflag)1097 {1098$log->info("Adding file '$filename'");1099 system("git-update-index", "--add",$filename);1100 } else {1101$log->info("Updating file '$filename'");1102 system("git-update-index",$filename);1103 }1104 }11051106 unless ( scalar(@committedfiles) > 0 )1107 {1108 print "E No files to commit\n";1109 print "ok\n";1110 close LOCKFILE;1111 unlink($lockfile);1112 chdir "/";1113 return;1114 }11151116 my$treehash= `git-write-tree`;1117 my$parenthash= `cat $ENV{GIT_DIR}refs/heads/$state->{module}`;1118 chomp$treehash;1119 chomp$parenthash;11201121$log->debug("Treehash :$treehash, Parenthash :$parenthash");11221123 # write our commit message out if we have one ...1124 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1125 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1126 print$msg_fh"\n\nvia git-CVS emulator\n";1127 close$msg_fh;11281129 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1130$log->info("Commit hash :$commithash");11311132unless($commithash=~/[a-zA-Z0-9]{40}/)1133{1134$log->warn("Commit failed (Invalid commit hash)");1135print"error 1 Commit failed (unknown reason)\n";1136close LOCKFILE;1137unlink($lockfile);1138chdir"/";1139exit;1140}11411142open FILE,">","$ENV{GIT_DIR}refs/heads/$state->{module}";1143print FILE $commithash;1144close FILE;11451146$updater->update();11471148# foreach file specified on the commandline ...1149foreachmy$filename(@committedfiles)1150{1151$filename= filecleanup($filename);11521153my$meta=$updater->getmeta($filename);11541155my($filepart,$dirpart) = filenamesplit($filename,1);11561157$log->debug("Checked-in$dirpart:$filename");11581159if($meta->{filehash}eq"deleted")1160{1161print"Remove-entry$dirpart\n";1162print"$filename\n";1163}else{1164print"Checked-in$dirpart\n";1165print"$filename\n";1166print"/$filepart/1.$meta->{revision}///\n";1167}1168}11691170close LOCKFILE;1171unlink($lockfile);1172chdir"/";11731174print"ok\n";1175}11761177sub req_status1178{1179my($cmd,$data) =@_;11801181 argsplit("status");11821183$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1184#$log->debug("status state : " . Dumper($state));11851186# Grab a handle to the SQLite db and do any necessary updates1187my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1188$updater->update();11891190# if no files were specified, we need to work out what files we should be providing status on ...1191 argsfromdir($updater);11921193# foreach file specified on the commandline ...1194foreachmy$filename( @{$state->{args}} )1195{1196$filename= filecleanup($filename);11971198my$meta=$updater->getmeta($filename);1199my$oldmeta=$meta;12001201my$wrev= revparse($filename);12021203# If the working copy is an old revision, lets get that version too for comparison.1204if(defined($wrev)and$wrev!=$meta->{revision} )1205{1206$oldmeta=$updater->getmeta($filename,$wrev);1207}12081209# TODO : All possible statuses aren't yet implemented1210my$status;1211# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1212$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1213and1214( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1215or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1216);12171218# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1219$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1220and1221($state->{entries}{$filename}{unchanged}1222or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1223);12241225# Need checkout if it exists in the repo but doesn't have a working copy1226$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12271228# Locally modified if working copy and repo copy have the same revision but there are local changes1229$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12301231# Needs Merge if working copy revision is less than repo copy and there are local changes1232$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12331234$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1235$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1236$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1237$status||="File had conflicts on merge"if(0);12381239$status||="Unknown";12401241print"M ===================================================================\n";1242print"M File:$filename\tStatus:$status\n";1243if(defined($state->{entries}{$filename}{revision}) )1244{1245print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1246}else{1247print"M Working revision:\tNo entry for$filename\n";1248}1249if(defined($meta->{revision}) )1250{1251print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{repository}/$filename,v\n";1252print"M Sticky Tag:\t\t(none)\n";1253print"M Sticky Date:\t\t(none)\n";1254print"M Sticky Options:\t\t(none)\n";1255}else{1256print"M Repository revision:\tNo revision control file\n";1257}1258print"M\n";1259}12601261print"ok\n";1262}12631264sub req_diff1265{1266my($cmd,$data) =@_;12671268 argsplit("diff");12691270$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1271#$log->debug("status state : " . Dumper($state));12721273my($revision1,$revision2);1274if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1275{1276$revision1=$state->{opt}{r}[0];1277$revision2=$state->{opt}{r}[1];1278}else{1279$revision1=$state->{opt}{r};1280}12811282$revision1=~s/^1\.//if(defined($revision1) );1283$revision2=~s/^1\.//if(defined($revision2) );12841285$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );12861287# Grab a handle to the SQLite db and do any necessary updates1288my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1289$updater->update();12901291# if no files were specified, we need to work out what files we should be providing status on ...1292 argsfromdir($updater);12931294# foreach file specified on the commandline ...1295foreachmy$filename( @{$state->{args}} )1296{1297$filename= filecleanup($filename);12981299my($fh,$file1,$file2,$meta1,$meta2,$filediff);13001301my$wrev= revparse($filename);13021303# We need _something_ to diff against1304next unless(defined($wrev) );13051306# if we have a -r switch, use it1307if(defined($revision1) )1308{1309(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1310$meta1=$updater->getmeta($filename,$revision1);1311unless(defined($meta1)and$meta1->{filehash}ne"deleted")1312{1313print"E File$filenameat revision 1.$revision1doesn't exist\n";1314next;1315}1316 transmitfile($meta1->{filehash},$file1);1317}1318# otherwise we just use the working copy revision1319else1320{1321(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1322$meta1=$updater->getmeta($filename,$wrev);1323 transmitfile($meta1->{filehash},$file1);1324}13251326# if we have a second -r switch, use it too1327if(defined($revision2) )1328{1329(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1330$meta2=$updater->getmeta($filename,$revision2);13311332unless(defined($meta2)and$meta2->{filehash}ne"deleted")1333{1334print"E File$filenameat revision 1.$revision2doesn't exist\n";1335next;1336}13371338 transmitfile($meta2->{filehash},$file2);1339}1340# otherwise we just use the working copy1341else1342{1343$file2=$state->{entries}{$filename}{modified_filename};1344}13451346# if we have been given -r, and we don't have a $file2 yet, lets get one1347if(defined($revision1)and not defined($file2) )1348{1349(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1350$meta2=$updater->getmeta($filename,$wrev);1351 transmitfile($meta2->{filehash},$file2);1352}13531354# We need to have retrieved something useful1355next unless(defined($meta1) );13561357# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1358next if(not defined($meta2)and$wrev==$meta1->{revision}1359and1360( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1361or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1362);13631364# Apparently we only show diffs for locally modified files1365next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );13661367print"M Index:$filename\n";1368print"M ===================================================================\n";1369print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1370print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1371print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1372print"M diff ";1373foreachmy$opt(keys%{$state->{opt}} )1374{1375if(ref$state->{opt}{$opt}eq"ARRAY")1376{1377foreachmy$value( @{$state->{opt}{$opt}} )1378{1379print"-$opt$value";1380}1381}else{1382print"-$opt";1383print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1384}1385}1386print"$filename\n";13871388$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));13891390($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);13911392if(exists$state->{opt}{u} )1393{1394system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1395}else{1396system("diff$file1$file2>$filediff");1397}13981399while( <$fh> )1400{1401print"M$_";1402}1403close$fh;1404}14051406print"ok\n";1407}14081409sub req_log1410{1411my($cmd,$data) =@_;14121413 argsplit("log");14141415$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1416#$log->debug("log state : " . Dumper($state));14171418my($minrev,$maxrev);1419if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1420{1421my$control=$2;1422$minrev=$1;1423$maxrev=$3;1424$minrev=~s/^1\.//if(defined($minrev) );1425$maxrev=~s/^1\.//if(defined($maxrev) );1426$minrev++if(defined($minrev)and$controleq"::");1427}14281429# Grab a handle to the SQLite db and do any necessary updates1430my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1431$updater->update();14321433# if no files were specified, we need to work out what files we should be providing status on ...1434 argsfromdir($updater);14351436# foreach file specified on the commandline ...1437foreachmy$filename( @{$state->{args}} )1438{1439$filename= filecleanup($filename);14401441my$headmeta=$updater->getmeta($filename);14421443my$revisions=$updater->getlog($filename);1444my$totalrevisions=scalar(@$revisions);14451446if(defined($minrev) )1447{1448$log->debug("Removing revisions less than$minrev");1449while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1450{1451pop@$revisions;1452}1453}1454if(defined($maxrev) )1455{1456$log->debug("Removing revisions greater than$maxrev");1457while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1458{1459shift@$revisions;1460}1461}14621463next unless(scalar(@$revisions) );14641465print"M\n";1466print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1467print"M Working file:$filename\n";1468print"M head: 1.$headmeta->{revision}\n";1469print"M branch:\n";1470print"M locks: strict\n";1471print"M access list:\n";1472print"M symbolic names:\n";1473print"M keyword substitution: kv\n";1474print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1475print"M description:\n";14761477foreachmy$revision(@$revisions)1478{1479print"M ----------------------------\n";1480print"M revision 1.$revision->{revision}\n";1481# reformat the date for log output1482$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}) );1483$revision->{author} =~s/\s+.*//;1484$revision->{author} =~s/^(.{8}).*/$1/;1485print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1486my$commitmessage=$updater->commitmessage($revision->{commithash});1487$commitmessage=~s/^/M /mg;1488print$commitmessage."\n";1489}1490print"M =============================================================================\n";1491}14921493print"ok\n";1494}14951496sub req_annotate1497{1498my($cmd,$data) =@_;14991500 argsplit("annotate");15011502$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1503#$log->debug("status state : " . Dumper($state));15041505# Grab a handle to the SQLite db and do any necessary updates1506my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1507$updater->update();15081509# if no files were specified, we need to work out what files we should be providing annotate on ...1510 argsfromdir($updater);15111512# we'll need a temporary checkout dir1513my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1514my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1515$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15161517$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1518$ENV{GIT_INDEX_FILE} =$file_index;15191520chdir$tmpdir;15211522# foreach file specified on the commandline ...1523foreachmy$filename( @{$state->{args}} )1524{1525$filename= filecleanup($filename);15261527my$meta=$updater->getmeta($filename);15281529next unless($meta->{revision} );15301531# get all the commits that this file was in1532# in dense format -- aka skip dead revisions1533my$revisions=$updater->gethistorydense($filename);1534my$lastseenin=$revisions->[0][2];15351536# populate the temporary index based on the latest commit were we saw1537# the file -- but do it cheaply without checking out any files1538# TODO: if we got a revision from the client, use that instead1539# to look up the commithash in sqlite (still good to default to1540# the current head as we do now)1541system("git-read-tree",$lastseenin);1542unless($?==0)1543{1544die"Error running git-read-tree$lastseenin$file_index$!";1545}1546$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");15471548# do a checkout of the file1549system('git-checkout-index','-f','-u',$filename);1550unless($?==0) {1551die"Error running git-checkout-index -f -u$filename:$!";1552}15531554$log->info("Annotate$filename");15551556# Prepare a file with the commits from the linearized1557# history that annotate should know about. This prevents1558# git-jsannotate telling us about commits we are hiding1559# from the client.15601561open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1562for(my$i=0;$i<@$revisions;$i++)1563{1564print ANNOTATEHINTS $revisions->[$i][2];1565if($i+1<@$revisions) {# have we got a parent?1566print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1567}1568print ANNOTATEHINTS "\n";1569}15701571print ANNOTATEHINTS "\n";1572close ANNOTATEHINTS;15731574my$annotatecmd='git-annotate';1575open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1576or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1577my$metadata= {};1578print"E Annotations for$filename\n";1579print"E ***************\n";1580while( <ANNOTATE> )1581{1582if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1583{1584my$commithash=$1;1585my$data=$2;1586unless(defined($metadata->{$commithash} ) )1587{1588$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1589$metadata->{$commithash}{author} =~s/\s+.*//;1590$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1591$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1592}1593printf("M 1.%-5d (%-8s%10s):%s\n",1594$metadata->{$commithash}{revision},1595$metadata->{$commithash}{author},1596$metadata->{$commithash}{modified},1597$data1598);1599}else{1600$log->warn("Error in annotate output! LINE:$_");1601print"E Annotate error\n";1602next;1603}1604}1605close ANNOTATE;1606}16071608# done; get out of the tempdir1609chdir"/";16101611print"ok\n";16121613}16141615# This method takes the state->{arguments} array and produces two new arrays.1616# The first is $state->{args} which is everything before the '--' argument, and1617# the second is $state->{files} which is everything after it.1618sub argsplit1619{1620return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16211622my$type=shift;16231624$state->{args} = [];1625$state->{files} = [];1626$state->{opt} = {};16271628if(defined($type) )1629{1630my$opt= {};1631$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");1632$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1633$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");1634$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1635$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1636$opt= { k =>1, m =>1}if($typeeq"add");1637$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1638$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");163916401641while(scalar( @{$state->{arguments}} ) >0)1642{1643my$arg=shift@{$state->{arguments}};16441645next if($argeq"--");1646next unless($arg=~/\S/);16471648# if the argument looks like a switch1649if($arg=~/^-(\w)(.*)/)1650{1651# if it's a switch that takes an argument1652if($opt->{$1} )1653{1654# If this switch has already been provided1655if($opt->{$1} >1and exists($state->{opt}{$1} ) )1656{1657$state->{opt}{$1} = [$state->{opt}{$1} ];1658if(length($2) >0)1659{1660push@{$state->{opt}{$1}},$2;1661}else{1662push@{$state->{opt}{$1}},shift@{$state->{arguments}};1663}1664}else{1665# if there's extra data in the arg, use that as the argument for the switch1666if(length($2) >0)1667{1668$state->{opt}{$1} =$2;1669}else{1670$state->{opt}{$1} =shift@{$state->{arguments}};1671}1672}1673}else{1674$state->{opt}{$1} =undef;1675}1676}1677else1678{1679push@{$state->{args}},$arg;1680}1681}1682}1683else1684{1685my$mode=0;16861687foreachmy$value( @{$state->{arguments}} )1688{1689if($valueeq"--")1690{1691$mode++;1692next;1693}1694push@{$state->{args}},$valueif($mode==0);1695push@{$state->{files}},$valueif($mode==1);1696}1697}1698}16991700# This method uses $state->{directory} to populate $state->{args} with a list of filenames1701sub argsfromdir1702{1703my$updater=shift;17041705$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17061707return if(scalar( @{$state->{args}} ) >1);17081709if(scalar(@{$state->{args}}) ==1)1710{1711my$arg=$state->{args}[0];1712$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17131714$log->info("Only one arg specified, checking for directory expansion on '$arg'");17151716foreachmy$file( @{$updater->gethead} )1717{1718next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1719next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1720push@{$state->{args}},$file->{name};1721}17221723shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1724}else{1725$log->info("Only one arg specified, populating file list automatically");17261727$state->{args} = [];17281729foreachmy$file( @{$updater->gethead} )1730{1731next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1732next unless($file->{name} =~s/^$state->{prependdir}//);1733push@{$state->{args}},$file->{name};1734}1735}1736}17371738# This method cleans up the $state variable after a command that uses arguments has run1739sub statecleanup1740{1741$state->{files} = [];1742$state->{args} = [];1743$state->{arguments} = [];1744$state->{entries} = {};1745}17461747sub revparse1748{1749my$filename=shift;17501751returnundefunless(defined($state->{entries}{$filename}{revision} ) );17521753return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1754return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);17551756returnundef;1757}17581759# This method takes a file hash and does a CVS "file transfer" which transmits the1760# size of the file, and then the file contents.1761# If a second argument $targetfile is given, the file is instead written out to1762# a file by the name of $targetfile1763sub transmitfile1764{1765my$filehash=shift;1766my$targetfile=shift;17671768if(defined($filehash)and$filehasheq"deleted")1769{1770$log->warn("filehash is 'deleted'");1771return;1772}17731774die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);17751776my$type=`git-cat-file -t$filehash`;1777 chomp$type;17781779 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );17801781 my$size= `git-cat-file -s $filehash`;1782chomp$size;17831784$log->debug("transmitfile($filehash) size=$size, type=$type");17851786if(open my$fh,'-|',"git-cat-file","blob",$filehash)1787{1788if(defined($targetfile) )1789{1790open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1791print NEWFILE $_while( <$fh> );1792close NEWFILE;1793}else{1794print"$size\n";1795printwhile( <$fh> );1796}1797close$fhor die("Couldn't close filehandle for transmitfile()");1798}else{1799die("Couldn't execute git-cat-file");1800}1801}18021803# This method takes a file name, and returns ( $dirpart, $filepart ) which1804# refers to the directory portion and the file portion of the filename1805# respectively1806sub filenamesplit1807{1808my$filename=shift;1809my$fixforlocaldir=shift;18101811my($filepart,$dirpart) = ($filename,".");1812($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1813$dirpart.="/";18141815if($fixforlocaldir)1816{1817$dirpart=~s/^$state->{prependdir}//;1818}18191820return($filepart,$dirpart);1821}18221823sub filecleanup1824{1825my$filename=shift;18261827returnundefunless(defined($filename));1828if($filename=~/^\// )1829{1830print"E absolute filenames '$filename' not supported by server\n";1831returnundef;1832}18331834$filename=~s/^\.\///g;1835$filename=$state->{prependdir} .$filename;1836return$filename;1837}18381839package GITCVS::log;18401841####1842#### Copyright The Open University UK - 2006.1843####1844#### Authors: Martyn Smith <martyn@catalyst.net.nz>1845#### Martin Langhoff <martin@catalyst.net.nz>1846####1847####18481849use strict;1850use warnings;18511852=head1 NAME18531854GITCVS::log18551856=head1 DESCRIPTION18571858This module provides very crude logging with a similar interface to1859Log::Log4perl18601861=head1 METHODS18621863=cut18641865=head2 new18661867Creates a new log object, optionally you can specify a filename here to1868indicate the file to log to. If no log file is specified, you can specify one1869later with method setfile, or indicate you no longer want logging with method1870nofile.18711872Until one of these methods is called, all log calls will buffer messages ready1873to write out.18741875=cut1876sub new1877{1878my$class=shift;1879my$filename=shift;18801881my$self= {};18821883bless$self,$class;18841885if(defined($filename) )1886{1887open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1888}18891890return$self;1891}18921893=head2 setfile18941895This methods takes a filename, and attempts to open that file as the log file.1896If successful, all buffered data is written out to the file, and any further1897logging is written directly to the file.18981899=cut1900sub setfile1901{1902my$self=shift;1903my$filename=shift;19041905if(defined($filename) )1906{1907open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1908}19091910return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19111912while(my$line=shift@{$self->{buffer}} )1913{1914print{$self->{fh}}$line;1915}1916}19171918=head2 nofile19191920This method indicates no logging is going to be used. It flushes any entries in1921the internal buffer, and sets a flag to ensure no further data is put there.19221923=cut1924sub nofile1925{1926my$self=shift;19271928$self->{nolog} =1;19291930return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19311932$self->{buffer} = [];1933}19341935=head2 _logopen19361937Internal method. Returns true if the log file is open, false otherwise.19381939=cut1940sub _logopen1941{1942my$self=shift;19431944return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");1945return0;1946}19471948=head2 debug info warn fatal19491950These four methods are wrappers to _log. They provide the actual interface for1951logging data.19521953=cut1954sub debug {my$self=shift;$self->_log("debug",@_); }1955sub info {my$self=shift;$self->_log("info",@_); }1956subwarn{my$self=shift;$self->_log("warn",@_); }1957sub fatal {my$self=shift;$self->_log("fatal",@_); }19581959=head2 _log19601961This is an internal method called by the logging functions. It generates a1962timestamp and pushes the logged line either to file, or internal buffer.19631964=cut1965sub _log1966{1967my$self=shift;1968my$level=shift;19691970return if($self->{nolog} );19711972my@time=localtime;1973my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",1974$time[5] +1900,1975$time[4] +1,1976$time[3],1977$time[2],1978$time[1],1979$time[0],1980uc$level,1981);19821983if($self->_logopen)1984{1985print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";1986}else{1987push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";1988}1989}19901991=head2 DESTROY19921993This method simply closes the file handle if one is open19941995=cut1996sub DESTROY1997{1998my$self=shift;19992000if($self->_logopen)2001{2002close$self->{fh};2003}2004}20052006package GITCVS::updater;20072008####2009#### Copyright The Open University UK - 2006.2010####2011#### Authors: Martyn Smith <martyn@catalyst.net.nz>2012#### Martin Langhoff <martin@catalyst.net.nz>2013####2014####20152016use strict;2017use warnings;2018use DBI;20192020=head1 METHODS20212022=cut20232024=head2 new20252026=cut2027sub new2028{2029my$class=shift;2030my$config=shift;2031my$module=shift;2032my$log=shift;20332034die"Need to specify a git repository"unless(defined($config)and-d $config);2035die"Need to specify a module"unless(defined($module) );20362037$class=ref($class) ||$class;20382039my$self= {};20402041bless$self,$class;20422043$self->{dbdir} =$config."/";2044die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );20452046$self->{module} =$module;2047$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";20482049$self->{git_path} =$config."/";20502051$self->{log} =$log;20522053die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );20542055$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");20562057$self->{tables} = {};2058foreachmy$table($self->{dbh}->tables)2059{2060$table=~s/^"//;2061$table=~s/"$//;2062$self->{tables}{$table} =1;2063}20642065# Construct the revision table if required2066unless($self->{tables}{revision} )2067{2068$self->{dbh}->do("2069 CREATE TABLE revision (2070 name TEXT NOT NULL,2071 revision INTEGER NOT NULL,2072 filehash TEXT NOT NULL,2073 commithash TEXT NOT NULL,2074 author TEXT NOT NULL,2075 modified TEXT NOT NULL,2076 mode TEXT NOT NULL2077 )2078 ");2079}20802081# Construct the revision table if required2082unless($self->{tables}{head} )2083{2084$self->{dbh}->do("2085 CREATE TABLE head (2086 name TEXT NOT NULL,2087 revision INTEGER NOT NULL,2088 filehash TEXT NOT NULL,2089 commithash TEXT NOT NULL,2090 author TEXT NOT NULL,2091 modified TEXT NOT NULL,2092 mode TEXT NOT NULL2093 )2094 ");2095}20962097# Construct the properties table if required2098unless($self->{tables}{properties} )2099{2100$self->{dbh}->do("2101 CREATE TABLE properties (2102 key TEXT NOT NULL PRIMARY KEY,2103 value TEXT2104 )2105 ");2106}21072108# Construct the commitmsgs table if required2109unless($self->{tables}{commitmsgs} )2110{2111$self->{dbh}->do("2112 CREATE TABLE commitmsgs (2113 key TEXT NOT NULL PRIMARY KEY,2114 value TEXT2115 )2116 ");2117}21182119return$self;2120}21212122=head2 update21232124=cut2125sub update2126{2127my$self=shift;21282129# first lets get the commit list2130$ENV{GIT_DIR} =$self->{git_path};21312132# prepare database queries2133my$db_insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2134my$db_insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2135my$db_delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2136my$db_insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);21372138my$commitinfo=`git-cat-file commit$self->{module} 2>&1`;2139unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2140{2141die("Invalid module '$self->{module}'");2142}214321442145my$git_log;2146my$lastcommit=$self->_get_prop("last_commit");21472148# Start exclusive lock here...2149$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";21502151# TODO: log processing is memory bound2152# if we can parse into a 2nd file that is in reverse order2153# we can probably do something really efficient2154my@git_log_params= ('--pretty','--parents','--topo-order');21552156if(defined$lastcommit) {2157push@git_log_params,"$lastcommit..$self->{module}";2158}else{2159push@git_log_params,$self->{module};2160}2161# git-rev-list is the backend / plumbing version of git-log2162open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";21632164my@commits;21652166my%commit= ();21672168while( <GITLOG> )2169{2170chomp;2171if(m/^commit\s+(.*)$/) {2172# on ^commit lines put the just seen commit in the stack2173# and prime things for the next one2174if(keys%commit) {2175my%copy=%commit;2176unshift@commits, \%copy;2177%commit= ();2178}2179my@parents=split(m/\s+/,$1);2180$commit{hash} =shift@parents;2181$commit{parents} = \@parents;2182}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2183# on rfc822-like lines seen before we see any message,2184# lowercase the entry and put it in the hash as key-value2185$commit{lc($1)} =$2;2186}else{2187# message lines - skip initial empty line2188# and trim whitespace2189if(!exists($commit{message}) &&m/^\s*$/) {2190# define it to mark the end of headers2191$commit{message} ='';2192next;2193}2194s/^\s+//;s/\s+$//;# trim ws2195$commit{message} .=$_."\n";2196}2197}2198close GITLOG;21992200unshift@commits, \%commitif(keys%commit);22012202# Now all the commits are in the @commits bucket2203# ordered by time DESC. for each commit that needs processing,2204# determine whether it's following the last head we've seen or if2205# it's on its own branch, grab a file list, and add whatever's changed2206# NOTE: $lastcommit refers to the last commit from previous run2207# $lastpicked is the last commit we picked in this run2208my$lastpicked;2209my$head= {};2210if(defined$lastcommit) {2211$lastpicked=$lastcommit;2212}22132214my$committotal=scalar(@commits);2215my$commitcount=0;22162217# Load the head table into $head (for cached lookups during the update process)2218foreachmy$file( @{$self->gethead()} )2219{2220$head->{$file->{name}} =$file;2221}22222223foreachmy$commit(@commits)2224{2225$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2226if(defined$lastpicked)2227{2228if(!in_array($lastpicked, @{$commit->{parents}}))2229{2230# skip, we'll see this delta2231# as part of a merge later2232# warn "skipping off-track $commit->{hash}\n";2233next;2234}elsif(@{$commit->{parents}} >1) {2235# it is a merge commit, for each parent that is2236# not $lastpicked, see if we can get a log2237# from the merge-base to that parent to put it2238# in the message as a merge summary.2239my@parents= @{$commit->{parents}};2240foreachmy$parent(@parents) {2241# git-merge-base can potentially (but rarely) throw2242# several candidate merge bases. let's assume2243# that the first one is the best one.2244if($parenteq$lastpicked) {2245next;2246}2247open my$p,'git-merge-base '.$lastpicked.' '2248.$parent.'|';2249my@output= (<$p>);2250close$p;2251my$base=join('',@output);2252chomp$base;2253if($base) {2254my@merged;2255# print "want to log between $base $parent \n";2256open(GITLOG,'-|','git-log',"$base..$parent")2257or die"Cannot call git-log:$!";2258my$mergedhash;2259while(<GITLOG>) {2260chomp;2261if(!defined$mergedhash) {2262if(m/^commit\s+(.+)$/) {2263$mergedhash=$1;2264}else{2265next;2266}2267}else{2268# grab the first line that looks non-rfc8222269# aka has content after leading space2270if(m/^\s+(\S.*)$/) {2271my$title=$1;2272$title=substr($title,0,100);# truncate2273unshift@merged,"$mergedhash$title";2274undef$mergedhash;2275}2276}2277}2278close GITLOG;2279if(@merged) {2280$commit->{mergemsg} =$commit->{message};2281$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2282foreachmy$summary(@merged) {2283$commit->{mergemsg} .="\t$summary\n";2284}2285$commit->{mergemsg} .="\n\n";2286# print "Message for $commit->{hash} \n$commit->{mergemsg}";2287}2288}2289}2290}2291}22922293# convert the date to CVS-happy format2294$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);22952296if(defined($lastpicked) )2297{2298my$filepipe=open(FILELIST,'-|','git-diff-tree','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2299while( <FILELIST> )2300{2301unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)\s+(.*)$/o)2302{2303die("Couldn't process git-diff-tree line :$_");2304}23052306# $log->debug("File mode=$1, hash=$2, change=$3, name=$4");23072308my$git_perms="";2309$git_perms.="r"if($1&4);2310$git_perms.="w"if($1&2);2311$git_perms.="x"if($1&1);2312$git_perms="rw"if($git_permseq"");23132314if($3eq"D")2315{2316#$log->debug("DELETE $4");2317$head->{$4} = {2318 name =>$4,2319 revision =>$head->{$4}{revision} +1,2320 filehash =>"deleted",2321 commithash =>$commit->{hash},2322 modified =>$commit->{date},2323 author =>$commit->{author},2324 mode =>$git_perms,2325};2326$db_insert_rev->execute($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2327}2328elsif($3eq"M")2329{2330#$log->debug("MODIFIED $4");2331$head->{$4} = {2332 name =>$4,2333 revision =>$head->{$4}{revision} +1,2334 filehash =>$2,2335 commithash =>$commit->{hash},2336 modified =>$commit->{date},2337 author =>$commit->{author},2338 mode =>$git_perms,2339};2340$db_insert_rev->execute($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2341}2342elsif($3eq"A")2343{2344#$log->debug("ADDED $4");2345$head->{$4} = {2346 name =>$4,2347 revision =>1,2348 filehash =>$2,2349 commithash =>$commit->{hash},2350 modified =>$commit->{date},2351 author =>$commit->{author},2352 mode =>$git_perms,2353};2354$db_insert_rev->execute($4,$head->{$4}{revision},$2,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2355}2356else2357{2358$log->warn("UNKNOWN FILE CHANGE mode=$1, hash=$2, change=$3, name=$4");2359die;2360}2361}2362close FILELIST;2363}else{2364# this is used to detect files removed from the repo2365my$seen_files= {};23662367my$filepipe=open(FILELIST,'-|','git-ls-tree','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2368while( <FILELIST> )2369{2370unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\s+(.*)$/o)2371{2372die("Couldn't process git-ls-tree line :$_");2373}23742375my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);23762377$seen_files->{$git_filename} =1;23782379my($oldhash,$oldrevision,$oldmode) = (2380$head->{$git_filename}{filehash},2381$head->{$git_filename}{revision},2382$head->{$git_filename}{mode}2383);23842385if($git_perms=~/^\d\d\d(\d)\d\d/o)2386{2387$git_perms="";2388$git_perms.="r"if($1&4);2389$git_perms.="w"if($1&2);2390$git_perms.="x"if($1&1);2391}else{2392$git_perms="rw";2393}23942395# unless the file exists with the same hash, we need to update it ...2396unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2397{2398my$newrevision= ($oldrevisionor0) +1;23992400$head->{$git_filename} = {2401 name =>$git_filename,2402 revision =>$newrevision,2403 filehash =>$git_hash,2404 commithash =>$commit->{hash},2405 modified =>$commit->{date},2406 author =>$commit->{author},2407 mode =>$git_perms,2408};240924102411$db_insert_rev->execute($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2412}2413}2414close FILELIST;24152416# Detect deleted files2417foreachmy$file(keys%$head)2418{2419unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2420{2421$head->{$file}{revision}++;2422$head->{$file}{filehash} ="deleted";2423$head->{$file}{commithash} =$commit->{hash};2424$head->{$file}{modified} =$commit->{date};2425$head->{$file}{author} =$commit->{author};24262427$db_insert_rev->execute($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2428}2429}2430# END : "Detect deleted files"2431}243224332434if(exists$commit->{mergemsg})2435{2436$db_insert_mergelog->execute($commit->{hash},$commit->{mergemsg});2437}24382439$lastpicked=$commit->{hash};24402441$self->_set_prop("last_commit",$commit->{hash});2442}24432444$db_delete_head->execute();2445foreachmy$file(keys%$head)2446{2447$db_insert_head->execute(2448$file,2449$head->{$file}{revision},2450$head->{$file}{filehash},2451$head->{$file}{commithash},2452$head->{$file}{modified},2453$head->{$file}{author},2454$head->{$file}{mode},2455);2456}2457# invalidate the gethead cache2458$self->{gethead_cache} =undef;245924602461# Ending exclusive lock here2462$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2463}24642465sub _headrev2466{2467my$self=shift;2468my$filename=shift;24692470my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2471$db_query->execute($filename);2472my($hash,$revision,$mode) =$db_query->fetchrow_array;24732474return($hash,$revision,$mode);2475}24762477sub _get_prop2478{2479my$self=shift;2480my$key=shift;24812482my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2483$db_query->execute($key);2484my($value) =$db_query->fetchrow_array;24852486return$value;2487}24882489sub _set_prop2490{2491my$self=shift;2492my$key=shift;2493my$value=shift;24942495my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2496$db_query->execute($value,$key);24972498unless($db_query->rows)2499{2500$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2501$db_query->execute($key,$value);2502}25032504return$value;2505}25062507=head2 gethead25082509=cut25102511sub gethead2512{2513my$self=shift;25142515return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );25162517my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2518$db_query->execute();25192520my$tree= [];2521while(my$file=$db_query->fetchrow_hashref)2522{2523push@$tree,$file;2524}25252526$self->{gethead_cache} =$tree;25272528return$tree;2529}25302531=head2 getlog25322533=cut25342535sub getlog2536{2537my$self=shift;2538my$filename=shift;25392540my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2541$db_query->execute($filename);25422543my$tree= [];2544while(my$file=$db_query->fetchrow_hashref)2545{2546push@$tree,$file;2547}25482549return$tree;2550}25512552=head2 getmeta25532554This function takes a filename (with path) argument and returns a hashref of2555metadata for that file.25562557=cut25582559sub getmeta2560{2561my$self=shift;2562my$filename=shift;2563my$revision=shift;25642565my$db_query;2566if(defined($revision)and$revision=~/^\d+$/)2567{2568$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2569$db_query->execute($filename,$revision);2570}2571elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2572{2573$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2574$db_query->execute($filename,$revision);2575}else{2576$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2577$db_query->execute($filename);2578}25792580return$db_query->fetchrow_hashref;2581}25822583=head2 commitmessage25842585this function takes a commithash and returns the commit message for that commit25862587=cut2588sub commitmessage2589{2590my$self=shift;2591my$commithash=shift;25922593die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);25942595my$db_query;2596$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2597$db_query->execute($commithash);25982599my($message) =$db_query->fetchrow_array;26002601if(defined($message) )2602{2603$message.=" "if($message=~/\n$/);2604return$message;2605}26062607my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2608shift@lineswhile($lines[0] =~/\S/);2609$message=join("",@lines);2610$message.=" "if($message=~/\n$/);2611return$message;2612}26132614=head2 gethistory26152616This function takes a filename (with path) argument and returns an arrayofarrays2617containing revision,filehash,commithash ordered by revision descending26182619=cut2620sub gethistory2621{2622my$self=shift;2623my$filename=shift;26242625my$db_query;2626$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2627$db_query->execute($filename);26282629return$db_query->fetchall_arrayref;2630}26312632=head2 gethistorydense26332634This function takes a filename (with path) argument and returns an arrayofarrays2635containing revision,filehash,commithash ordered by revision descending.26362637This version of gethistory skips deleted entries -- so it is useful for annotate.2638The 'dense' part is a reference to a '--dense' option available for git-rev-list2639and other git tools that depend on it.26402641=cut2642sub gethistorydense2643{2644my$self=shift;2645my$filename=shift;26462647my$db_query;2648$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2649$db_query->execute($filename);26502651return$db_query->fetchall_arrayref;2652}26532654=head2 in_array()26552656from Array::PAT - mimics the in_array() function2657found in PHP. Yuck but works for small arrays.26582659=cut2660sub in_array2661{2662my($check,@array) =@_;2663my$retval=0;2664foreachmy$test(@array){2665if($checkeq$test){2666$retval=1;2667}2668}2669return$retval;2670}26712672=head2 safe_pipe_capture26732674an alternative to `command` that allows input to be passed as an array2675to work around shell problems with weird characters in arguments26762677=cut2678sub safe_pipe_capture {26792680my@output;26812682if(my$pid=open my$child,'-|') {2683@output= (<$child>);2684close$childor die join(' ',@_).":$!$?";2685}else{2686exec(@_)or die"$!$?";# exec() can fail the executable can't be found2687}2688returnwantarray?@output:join('',@output);2689}2690269126921;