1#!/usr/bin/perl 2 3#### 4#### This application is a CVS emulation layer for git. 5#### It is intended for clients to connect over SSH. 6#### See the documentation for more details. 7#### 8#### Copyright The Open University UK - 2006. 9#### 10#### Authors: Martyn Smith <martyn@catalyst.net.nz> 11#### Martin Langhoff <martin@catalyst.net.nz> 12#### 13#### 14#### Released under the GNU Public License, version 2. 15#### 16#### 17 18use strict; 19use warnings; 20use bytes; 21 22use Fcntl; 23use File::Temp qw/tempdir tempfile/; 24use File::Basename; 25 26my$log= GITCVS::log->new(); 27my$cfg; 28 29my$DATE_LIST= { 30 Jan =>"01", 31 Feb =>"02", 32 Mar =>"03", 33 Apr =>"04", 34 May =>"05", 35 Jun =>"06", 36 Jul =>"07", 37 Aug =>"08", 38 Sep =>"09", 39 Oct =>"10", 40 Nov =>"11", 41 Dec =>"12", 42}; 43 44# Enable autoflush for STDOUT (otherwise the whole thing falls apart) 45$| =1; 46 47#### Definition and mappings of functions #### 48 49my$methods= { 50'Root'=> \&req_Root, 51'Valid-responses'=> \&req_Validresponses, 52'valid-requests'=> \&req_validrequests, 53'Directory'=> \&req_Directory, 54'Entry'=> \&req_Entry, 55'Modified'=> \&req_Modified, 56'Unchanged'=> \&req_Unchanged, 57'Questionable'=> \&req_Questionable, 58'Argument'=> \&req_Argument, 59'Argumentx'=> \&req_Argument, 60'expand-modules'=> \&req_expandmodules, 61'add'=> \&req_add, 62'remove'=> \&req_remove, 63'co'=> \&req_co, 64'update'=> \&req_update, 65'ci'=> \&req_ci, 66'diff'=> \&req_diff, 67'log'=> \&req_log, 68'rlog'=> \&req_log, 69'tag'=> \&req_CATCHALL, 70'status'=> \&req_status, 71'admin'=> \&req_CATCHALL, 72'history'=> \&req_CATCHALL, 73'watchers'=> \&req_CATCHALL, 74'editors'=> \&req_CATCHALL, 75'annotate'=> \&req_annotate, 76'Global_option'=> \&req_Globaloption, 77#'annotate' => \&req_CATCHALL, 78}; 79 80############################################## 81 82 83# $state holds all the bits of information the clients sends us that could 84# potentially be useful when it comes to actually _doing_ something. 85my$state= { prependdir =>''}; 86$log->info("--------------- STARTING -----------------"); 87 88my$TEMP_DIR= tempdir( CLEANUP =>1); 89$log->debug("Temporary directory is '$TEMP_DIR'"); 90 91# if we are called with a pserver argument, 92# deal with the authentication cat before entering the 93# main loop 94if(@ARGV&&$ARGV[0]eq'pserver') { 95my$line= <STDIN>;chomp$line; 96unless($lineeq'BEGIN AUTH REQUEST') { 97die"E Do not understand$line- expecting BEGIN AUTH REQUEST\n"; 98} 99$line= <STDIN>;chomp$line; 100 req_Root('root',$line)# reuse Root 101or die"E Invalid root$line\n"; 102$line= <STDIN>;chomp$line; 103unless($lineeq'anonymous') { 104print"E Only anonymous user allowed via pserver\n"; 105print"I HATE YOU\n"; 106} 107$line= <STDIN>;chomp$line;# validate the password? 108$line= <STDIN>;chomp$line; 109unless($lineeq'END AUTH REQUEST') { 110die"E Do not understand$line-- expecting END AUTH REQUEST\n"; 111} 112print"I LOVE YOU\n"; 113# and now back to our regular programme... 114} 115 116# Keep going until the client closes the connection 117while(<STDIN>) 118{ 119chomp; 120 121# Check to see if we've seen this method, and call appropriate function. 122if(/^([\w-]+)(?:\s+(.*))?$/and defined($methods->{$1}) ) 123{ 124# use the $methods hash to call the appropriate sub for this command 125#$log->info("Method : $1"); 126&{$methods->{$1}}($1,$2); 127}else{ 128# log fatal because we don't understand this function. If this happens 129# we're fairly screwed because we don't know if the client is expecting 130# a response. If it is, the client will hang, we'll hang, and the whole 131# thing will be custard. 132$log->fatal("Don't understand command$_\n"); 133die("Unknown command$_"); 134} 135} 136 137$log->debug("Processing time : user=". (times)[0] ." system=". (times)[1]); 138$log->info("--------------- FINISH -----------------"); 139 140# Magic catchall method. 141# This is the method that will handle all commands we haven't yet 142# implemented. It simply sends a warning to the log file indicating a 143# command that hasn't been implemented has been invoked. 144sub req_CATCHALL 145{ 146my($cmd,$data) =@_; 147$log->warn("Unhandled command : req_$cmd:$data"); 148} 149 150 151# Root pathname \n 152# Response expected: no. Tell the server which CVSROOT to use. Note that 153# pathname is a local directory and not a fully qualified CVSROOT variable. 154# pathname must already exist; if creating a new root, use the init 155# request, not Root. pathname does not include the hostname of the server, 156# how to access the server, etc.; by the time the CVS protocol is in use, 157# connection, authentication, etc., are already taken care of. The Root 158# request must be sent only once, and it must be sent before any requests 159# other than Valid-responses, valid-requests, UseUnchanged, Set or init. 160sub req_Root 161{ 162my($cmd,$data) =@_; 163$log->debug("req_Root :$data"); 164 165$state->{CVSROOT} =$data; 166 167$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 168unless(-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') { 169print"E$ENV{GIT_DIR} does not seem to be a valid GIT repository\n"; 170print"E\n"; 171print"error 1$ENV{GIT_DIR} is not a valid repository\n"; 172return0; 173} 174 175my@gitvars=`git-config -l`; 176if($?) { 177print"E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n"; 178print"E\n"; 179print"error 1 - problem executing git-config\n"; 180return0; 181} 182foreachmy$line(@gitvars) 183{ 184next unless($line=~/^(.*?)\.(.*?)=(.*)$/); 185$cfg->{$1}{$2} =$3; 186} 187 188unless(defined($cfg->{gitcvs}{enabled} )and$cfg->{gitcvs}{enabled} =~/^\s*(1|true|yes)\s*$/i) 189{ 190print"E GITCVS emulation needs to be enabled on this repo\n"; 191print"E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n"; 192print"E\n"; 193print"error 1 GITCVS emulation disabled\n"; 194return0; 195} 196 197if(defined($cfg->{gitcvs}{logfile} ) ) 198{ 199$log->setfile($cfg->{gitcvs}{logfile}); 200}else{ 201$log->nofile(); 202} 203 204return1; 205} 206 207# Global_option option \n 208# Response expected: no. Transmit one of the global options `-q', `-Q', 209# `-l', `-t', `-r', or `-n'. option must be one of those strings, no 210# variations (such as combining of options) are allowed. For graceful 211# handling of valid-requests, it is probably better to make new global 212# options separate requests, rather than trying to add them to this 213# request. 214sub req_Globaloption 215{ 216my($cmd,$data) =@_; 217$log->debug("req_Globaloption :$data"); 218$state->{globaloptions}{$data} =1; 219} 220 221# Valid-responses request-list \n 222# Response expected: no. Tell the server what responses the client will 223# accept. request-list is a space separated list of tokens. 224sub req_Validresponses 225{ 226my($cmd,$data) =@_; 227$log->debug("req_Validresponses :$data"); 228 229# TODO : re-enable this, currently it's not particularly useful 230#$state->{validresponses} = [ split /\s+/, $data ]; 231} 232 233# valid-requests \n 234# Response expected: yes. Ask the server to send back a Valid-requests 235# response. 236sub req_validrequests 237{ 238my($cmd,$data) =@_; 239 240$log->debug("req_validrequests"); 241 242$log->debug("SEND : Valid-requests ".join(" ",keys%$methods)); 243$log->debug("SEND : ok"); 244 245print"Valid-requests ".join(" ",keys%$methods) ."\n"; 246print"ok\n"; 247} 248 249# Directory local-directory \n 250# Additional data: repository \n. Response expected: no. Tell the server 251# what directory to use. The repository should be a directory name from a 252# previous server response. Note that this both gives a default for Entry 253# and Modified and also for ci and the other commands; normal usage is to 254# send Directory for each directory in which there will be an Entry or 255# Modified, and then a final Directory for the original directory, then the 256# command. The local-directory is relative to the top level at which the 257# command is occurring (i.e. the last Directory which is sent before the 258# command); to indicate that top level, `.' should be sent for 259# local-directory. 260sub req_Directory 261{ 262my($cmd,$data) =@_; 263 264my$repository= <STDIN>; 265chomp$repository; 266 267 268$state->{localdir} =$data; 269$state->{repository} =$repository; 270$state->{path} =$repository; 271$state->{path} =~s/^$state->{CVSROOT}\///; 272$state->{module} =$1if($state->{path} =~s/^(.*?)(\/|$)//); 273$state->{path} .="/"if($state->{path} =~ /\S/ ); 274 275$state->{directory} =$state->{localdir}; 276$state->{directory} =""if($state->{directory}eq"."); 277$state->{directory} .="/"if($state->{directory} =~ /\S/ ); 278 279if( (not defined($state->{prependdir})or$state->{prependdir}eq'')and$state->{localdir}eq"."and$state->{path} =~/\S/) 280{ 281$log->info("Setting prepend to '$state->{path}'"); 282$state->{prependdir} =$state->{path}; 283foreachmy$entry(keys%{$state->{entries}} ) 284{ 285$state->{entries}{$state->{prependdir} .$entry} =$state->{entries}{$entry}; 286delete$state->{entries}{$entry}; 287} 288} 289 290if(defined($state->{prependdir} ) ) 291{ 292$log->debug("Prepending '$state->{prependdir}' to state|directory"); 293$state->{directory} =$state->{prependdir} .$state->{directory} 294} 295$log->debug("req_Directory : localdir=$datarepository=$repositorypath=$state->{path} directory=$state->{directory} module=$state->{module}"); 296} 297 298# Entry entry-line \n 299# Response expected: no. Tell the server what version of a file is on the 300# local machine. The name in entry-line is a name relative to the directory 301# most recently specified with Directory. If the user is operating on only 302# some files in a directory, Entry requests for only those files need be 303# included. If an Entry request is sent without Modified, Is-modified, or 304# Unchanged, it means the file is lost (does not exist in the working 305# directory). If both Entry and one of Modified, Is-modified, or Unchanged 306# are sent for the same file, Entry must be sent first. For a given file, 307# one can send Modified, Is-modified, or Unchanged, but not more than one 308# of these three. 309sub req_Entry 310{ 311my($cmd,$data) =@_; 312 313#$log->debug("req_Entry : $data"); 314 315my@data=split(/\//,$data); 316 317$state->{entries}{$state->{directory}.$data[1]} = { 318 revision =>$data[2], 319 conflict =>$data[3], 320 options =>$data[4], 321 tag_or_date =>$data[5], 322}; 323 324$log->info("Received entry line '$data' => '".$state->{directory} .$data[1] ."'"); 325} 326 327# Questionable filename \n 328# Response expected: no. Additional data: no. Tell the server to check 329# whether filename should be ignored, and if not, next time the server 330# sends responses, send (in a M response) `?' followed by the directory and 331# filename. filename must not contain `/'; it needs to be a file in the 332# directory named by the most recent Directory request. 333sub req_Questionable 334{ 335my($cmd,$data) =@_; 336 337$log->debug("req_Questionable :$data"); 338$state->{entries}{$state->{directory}.$data}{questionable} =1; 339} 340 341# add \n 342# Response expected: yes. Add a file or directory. This uses any previous 343# Argument, Directory, Entry, or Modified requests, if they have been sent. 344# The last Directory sent specifies the working directory at the time of 345# the operation. To add a directory, send the directory to be added using 346# Directory and Argument requests. 347sub req_add 348{ 349my($cmd,$data) =@_; 350 351 argsplit("add"); 352 353my$addcount=0; 354 355foreachmy$filename( @{$state->{args}} ) 356{ 357$filename= filecleanup($filename); 358 359unless(defined($state->{entries}{$filename}{modified_filename} ) ) 360{ 361print"E cvs add: nothing known about `$filename'\n"; 362next; 363} 364# TODO : check we're not squashing an already existing file 365if(defined($state->{entries}{$filename}{revision} ) ) 366{ 367print"E cvs add: `$filename' has already been entered\n"; 368next; 369} 370 371my($filepart,$dirpart) = filenamesplit($filename,1); 372 373print"E cvs add: scheduling file `$filename' for addition\n"; 374 375print"Checked-in$dirpart\n"; 376print"$filename\n"; 377print"/$filepart/0///\n"; 378 379$addcount++; 380} 381 382if($addcount==1) 383{ 384print"E cvs add: use `cvs commit' to add this file permanently\n"; 385} 386elsif($addcount>1) 387{ 388print"E cvs add: use `cvs commit' to add these files permanently\n"; 389} 390 391print"ok\n"; 392} 393 394# remove \n 395# Response expected: yes. Remove a file. This uses any previous Argument, 396# Directory, Entry, or Modified requests, if they have been sent. The last 397# Directory sent specifies the working directory at the time of the 398# operation. Note that this request does not actually do anything to the 399# repository; the only effect of a successful remove request is to supply 400# the client with a new entries line containing `-' to indicate a removed 401# file. In fact, the client probably could perform this operation without 402# contacting the server, although using remove may cause the server to 403# perform a few more checks. The client sends a subsequent ci request to 404# actually record the removal in the repository. 405sub req_remove 406{ 407my($cmd,$data) =@_; 408 409 argsplit("remove"); 410 411# Grab a handle to the SQLite db and do any necessary updates 412my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 413$updater->update(); 414 415#$log->debug("add state : " . Dumper($state)); 416 417my$rmcount=0; 418 419foreachmy$filename( @{$state->{args}} ) 420{ 421$filename= filecleanup($filename); 422 423if(defined($state->{entries}{$filename}{unchanged} )or defined($state->{entries}{$filename}{modified_filename} ) ) 424{ 425print"E cvs remove: file `$filename' still in working directory\n"; 426next; 427} 428 429my$meta=$updater->getmeta($filename); 430my$wrev= revparse($filename); 431 432unless(defined($wrev) ) 433{ 434print"E cvs remove: nothing known about `$filename'\n"; 435next; 436} 437 438if(defined($wrev)and$wrev<0) 439{ 440print"E cvs remove: file `$filename' already scheduled for removal\n"; 441next; 442} 443 444unless($wrev==$meta->{revision} ) 445{ 446# TODO : not sure if the format of this message is quite correct. 447print"E cvs remove: Up to date check failed for `$filename'\n"; 448next; 449} 450 451 452my($filepart,$dirpart) = filenamesplit($filename,1); 453 454print"E cvs remove: scheduling `$filename' for removal\n"; 455 456print"Checked-in$dirpart\n"; 457print"$filename\n"; 458print"/$filepart/-1.$wrev///\n"; 459 460$rmcount++; 461} 462 463if($rmcount==1) 464{ 465print"E cvs remove: use `cvs commit' to remove this file permanently\n"; 466} 467elsif($rmcount>1) 468{ 469print"E cvs remove: use `cvs commit' to remove these files permanently\n"; 470} 471 472print"ok\n"; 473} 474 475# Modified filename \n 476# Response expected: no. Additional data: mode, \n, file transmission. Send 477# the server a copy of one locally modified file. filename is a file within 478# the most recent directory sent with Directory; it must not contain `/'. 479# If the user is operating on only some files in a directory, only those 480# files need to be included. This can also be sent without Entry, if there 481# is no entry for the file. 482sub req_Modified 483{ 484my($cmd,$data) =@_; 485 486my$mode= <STDIN>; 487chomp$mode; 488my$size= <STDIN>; 489chomp$size; 490 491# Grab config information 492my$blocksize=8192; 493my$bytesleft=$size; 494my$tmp; 495 496# Get a filehandle/name to write it to 497my($fh,$filename) = tempfile( DIR =>$TEMP_DIR); 498 499# Loop over file data writing out to temporary file. 500while($bytesleft) 501{ 502$blocksize=$bytesleftif($bytesleft<$blocksize); 503read STDIN,$tmp,$blocksize; 504print$fh $tmp; 505$bytesleft-=$blocksize; 506} 507 508close$fh; 509 510# Ensure we have something sensible for the file mode 511if($mode=~/u=(\w+)/) 512{ 513$mode=$1; 514}else{ 515$mode="rw"; 516} 517 518# Save the file data in $state 519$state->{entries}{$state->{directory}.$data}{modified_filename} =$filename; 520$state->{entries}{$state->{directory}.$data}{modified_mode} =$mode; 521$state->{entries}{$state->{directory}.$data}{modified_hash} =`git-hash-object$filename`; 522$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s; 523 524 #$log->debug("req_Modified : file=$datamode=$modesize=$size"); 525} 526 527# Unchanged filename\n 528# Response expected: no. Tell the server that filename has not been 529# modified in the checked out directory. The filename is a file within the 530# most recent directory sent with Directory; it must not contain `/'. 531sub req_Unchanged 532{ 533 my ($cmd,$data) =@_; 534 535$state->{entries}{$state->{directory}.$data}{unchanged} = 1; 536 537 #$log->debug("req_Unchanged :$data"); 538} 539 540# Argument text\n 541# Response expected: no. Save argument for use in a subsequent command. 542# Arguments accumulate until an argument-using command is given, at which 543# point they are forgotten. 544# Argumentx text\n 545# Response expected: no. Append\nfollowed by text to the current argument 546# being saved. 547sub req_Argument 548{ 549 my ($cmd,$data) =@_; 550 551 # Argumentx means: append to last Argument (with a newline in front) 552 553$log->debug("$cmd:$data"); 554 555 if ($cmdeq 'Argumentx') { 556 ${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" .$data; 557 } else { 558 push @{$state->{arguments}},$data; 559 } 560} 561 562# expand-modules\n 563# Response expected: yes. Expand the modules which are specified in the 564# arguments. Returns the data in Module-expansion responses. Note that the 565# server can assume that this is checkout or export, not rtag or rdiff; the 566# latter do not access the working directory and thus have no need to 567# expand modules on the client side. Expand may not be the best word for 568# what this request does. It does not necessarily tell you all the files 569# contained in a module, for example. Basically it is a way of telling you 570# which working directories the server needs to know about in order to 571# handle a checkout of the specified modules. For example, suppose that the 572# server has a module defined by 573# aliasmodule -a 1dir 574# That is, one can check out aliasmodule and it will take 1dir in the 575# repository and check it out to 1dir in the working directory. Now suppose 576# the client already has this module checked out and is planning on using 577# the co request to update it. Without using expand-modules, the client 578# would have two bad choices: it could either send information about all 579# working directories under the current directory, which could be 580# unnecessarily slow, or it could be ignorant of the fact that aliasmodule 581# stands for 1dir, and neglect to send information for 1dir, which would 582# lead to incorrect operation. With expand-modules, the client would first 583# ask for the module to be expanded: 584sub req_expandmodules 585{ 586 my ($cmd,$data) =@_; 587 588 argsplit(); 589 590$log->debug("req_expandmodules : " . ( defined($data) ?$data: "[NULL]" ) ); 591 592 unless ( ref$state->{arguments} eq "ARRAY" ) 593 { 594 print "ok\n"; 595 return; 596 } 597 598 foreach my$module( @{$state->{arguments}} ) 599 { 600$log->debug("SEND : Module-expansion$module"); 601 print "Module-expansion$module\n"; 602 } 603 604 print "ok\n"; 605 statecleanup(); 606} 607 608# co\n 609# Response expected: yes. Get files from the repository. This uses any 610# previous Argument, Directory, Entry, or Modified requests, if they have 611# been sent. Arguments to this command are module names; the client cannot 612# know what directories they correspond to except by (1) just sending the 613# co request, and then seeing what directory names the server sends back in 614# its responses, and (2) the expand-modules request. 615sub req_co 616{ 617 my ($cmd,$data) =@_; 618 619 argsplit("co"); 620 621 my$module=$state->{args}[0]; 622 my$checkout_path=$module; 623 624 # use the user specified directory if we're given it 625$checkout_path=$state->{opt}{d}if(exists($state->{opt}{d} ) ); 626 627$log->debug("req_co : ". (defined($data) ?$data:"[NULL]") ); 628 629$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'"); 630 631$ENV{GIT_DIR} =$state->{CVSROOT} ."/"; 632 633# Grab a handle to the SQLite db and do any necessary updates 634my$updater= GITCVS::updater->new($state->{CVSROOT},$module,$log); 635$updater->update(); 636 637$checkout_path=~ s|/$||;# get rid of trailing slashes 638 639# Eclipse seems to need the Clear-sticky command 640# to prepare the 'Entries' file for the new directory. 641print"Clear-sticky$checkout_path/\n"; 642print$state->{CVSROOT} ."/$module/\n"; 643print"Clear-static-directory$checkout_path/\n"; 644print$state->{CVSROOT} ."/$module/\n"; 645print"Clear-sticky$checkout_path/\n";# yes, twice 646print$state->{CVSROOT} ."/$module/\n"; 647print"Template$checkout_path/\n"; 648print$state->{CVSROOT} ."/$module/\n"; 649print"0\n"; 650 651# instruct the client that we're checking out to $checkout_path 652print"E cvs checkout: Updating$checkout_path\n"; 653 654my%seendirs= (); 655my$lastdir=''; 656 657# recursive 658sub prepdir { 659my($dir,$repodir,$remotedir,$seendirs) =@_; 660my$parent= dirname($dir); 661$dir=~ s|/+$||; 662$repodir=~ s|/+$||; 663$remotedir=~ s|/+$||; 664$parent=~ s|/+$||; 665$log->debug("announcedir$dir,$repodir,$remotedir"); 666 667if($parenteq'.'||$parenteq'./') { 668$parent=''; 669} 670# recurse to announce unseen parents first 671if(length($parent) && !exists($seendirs->{$parent})) { 672 prepdir($parent,$repodir,$remotedir,$seendirs); 673} 674# Announce that we are going to modify at the parent level 675if($parent) { 676print"E cvs checkout: Updating$remotedir/$parent\n"; 677}else{ 678print"E cvs checkout: Updating$remotedir\n"; 679} 680print"Clear-sticky$remotedir/$parent/\n"; 681print"$repodir/$parent/\n"; 682 683print"Clear-static-directory$remotedir/$dir/\n"; 684print"$repodir/$dir/\n"; 685print"Clear-sticky$remotedir/$parent/\n";# yes, twice 686print"$repodir/$parent/\n"; 687print"Template$remotedir/$dir/\n"; 688print"$repodir/$dir/\n"; 689print"0\n"; 690 691$seendirs->{$dir} =1; 692} 693 694foreachmy$git( @{$updater->gethead} ) 695{ 696# Don't want to check out deleted files 697next if($git->{filehash}eq"deleted"); 698 699($git->{name},$git->{dir} ) = filenamesplit($git->{name}); 700 701if(length($git->{dir}) &&$git->{dir}ne'./' 702&&$git->{dir}ne$lastdir) { 703unless(exists($seendirs{$git->{dir}})) { 704 prepdir($git->{dir},$state->{CVSROOT} ."/$module/", 705$checkout_path, \%seendirs); 706$lastdir=$git->{dir}; 707$seendirs{$git->{dir}} =1; 708} 709print"E cvs checkout: Updating /$checkout_path/$git->{dir}\n"; 710} 711 712# modification time of this file 713print"Mod-time$git->{modified}\n"; 714 715# print some information to the client 716if(defined($git->{dir} )and$git->{dir}ne"./") 717{ 718print"M U$checkout_path/$git->{dir}$git->{name}\n"; 719}else{ 720print"M U$checkout_path/$git->{name}\n"; 721} 722 723# instruct client we're sending a file to put in this path 724print"Created$checkout_path/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."\n"; 725 726print$state->{CVSROOT} ."/$module/". (defined($git->{dir} )and$git->{dir}ne"./"?$git->{dir} ."/":"") ."$git->{name}\n"; 727 728# this is an "entries" line 729print"/$git->{name}/1.$git->{revision}///\n"; 730# permissions 731print"u=$git->{mode},g=$git->{mode},o=$git->{mode}\n"; 732 733# transmit file 734 transmitfile($git->{filehash}); 735} 736 737print"ok\n"; 738 739 statecleanup(); 740} 741 742# update \n 743# Response expected: yes. Actually do a cvs update command. This uses any 744# previous Argument, Directory, Entry, or Modified requests, if they have 745# been sent. The last Directory sent specifies the working directory at the 746# time of the operation. The -I option is not used--files which the client 747# can decide whether to ignore are not mentioned and the client sends the 748# Questionable request for others. 749sub req_update 750{ 751my($cmd,$data) =@_; 752 753$log->debug("req_update : ". (defined($data) ?$data:"[NULL]")); 754 755 argsplit("update"); 756 757# 758# It may just be a client exploring the available heads/modules 759# in that case, list them as top level directories and leave it 760# at that. Eclipse uses this technique to offer you a list of 761# projects (heads in this case) to checkout. 762# 763if($state->{module}eq'') { 764print"E cvs update: Updating .\n"; 765opendir HEADS,$state->{CVSROOT} .'/refs/heads'; 766while(my$head=readdir(HEADS)) { 767if(-f $state->{CVSROOT} .'/refs/heads/'.$head) { 768print"E cvs update: New directory `$head'\n"; 769} 770} 771closedir HEADS; 772print"ok\n"; 773return1; 774} 775 776 777# Grab a handle to the SQLite db and do any necessary updates 778my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log); 779 780$updater->update(); 781 782 argsfromdir($updater); 783 784#$log->debug("update state : " . Dumper($state)); 785 786# foreach file specified on the command line ... 787foreachmy$filename( @{$state->{args}} ) 788{ 789$filename= filecleanup($filename); 790 791$log->debug("Processing file$filename"); 792 793# if we have a -C we should pretend we never saw modified stuff 794if(exists($state->{opt}{C} ) ) 795{ 796delete$state->{entries}{$filename}{modified_hash}; 797delete$state->{entries}{$filename}{modified_filename}; 798$state->{entries}{$filename}{unchanged} =1; 799} 800 801my$meta; 802if(defined($state->{opt}{r})and$state->{opt}{r} =~/^1\.(\d+)/) 803{ 804$meta=$updater->getmeta($filename,$1); 805}else{ 806$meta=$updater->getmeta($filename); 807} 808 809if( !defined$meta) 810{ 811$meta= { 812 name =>$filename, 813 revision =>0, 814 filehash =>'added' 815}; 816} 817 818my$oldmeta=$meta; 819 820my$wrev= revparse($filename); 821 822# If the working copy is an old revision, lets get that version too for comparison. 823if(defined($wrev)and$wrev!=$meta->{revision} ) 824{ 825$oldmeta=$updater->getmeta($filename,$wrev); 826} 827 828#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev"); 829 830# Files are up to date if the working copy and repo copy have the same revision, 831# and the working copy is unmodified _and_ the user hasn't specified -C 832next if(defined($wrev) 833and defined($meta->{revision}) 834and$wrev==$meta->{revision} 835and$state->{entries}{$filename}{unchanged} 836and not exists($state->{opt}{C} ) ); 837 838# If the working copy and repo copy have the same revision, 839# but the working copy is modified, tell the client it's modified 840if(defined($wrev) 841and defined($meta->{revision}) 842and$wrev==$meta->{revision} 843and not exists($state->{opt}{C} ) ) 844{ 845$log->info("Tell the client the file is modified"); 846print"MT text M\n"; 847print"MT fname$filename\n"; 848print"MT newline\n"; 849next; 850} 851 852if($meta->{filehash}eq"deleted") 853{ 854my($filepart,$dirpart) = filenamesplit($filename,1); 855 856$log->info("Removing '$filename' from working copy (no longer in the repo)"); 857 858print"E cvs update: `$filename' is no longer in the repository\n"; 859# Don't want to actually _DO_ the update if -n specified 860unless($state->{globaloptions}{-n} ) { 861print"Removed$dirpart\n"; 862print"$filepart\n"; 863} 864} 865elsif(not defined($state->{entries}{$filename}{modified_hash} ) 866or$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} 867or$meta->{filehash}eq'added') 868{ 869# normal update, just send the new revision (either U=Update, 870# or A=Add, or R=Remove) 871if(defined($wrev) &&$wrev<0) 872{ 873$log->info("Tell the client the file is scheduled for removal"); 874print"MT text R\n"; 875print"MT fname$filename\n"; 876print"MT newline\n"; 877next; 878} 879elsif( (!defined($wrev) ||$wrev==0) && (!defined($meta->{revision}) ||$meta->{revision} ==0) ) 880{ 881$log->info("Tell the client the file is scheduled for addition"); 882print"MT text A\n"; 883print"MT fname$filename\n"; 884print"MT newline\n"; 885next; 886 887} 888else{ 889$log->info("Updating '$filename' to ".$meta->{revision}); 890print"MT +updated\n"; 891print"MT text U\n"; 892print"MT fname$filename\n"; 893print"MT newline\n"; 894print"MT -updated\n"; 895} 896 897my($filepart,$dirpart) = filenamesplit($filename,1); 898 899# Don't want to actually _DO_ the update if -n specified 900unless($state->{globaloptions}{-n} ) 901{ 902if(defined($wrev) ) 903{ 904# instruct client we're sending a file to put in this path as a replacement 905print"Update-existing$dirpart\n"; 906$log->debug("Updating existing file 'Update-existing$dirpart'"); 907}else{ 908# instruct client we're sending a file to put in this path as a new file 909print"Clear-static-directory$dirpart\n"; 910print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 911print"Clear-sticky$dirpart\n"; 912print$state->{CVSROOT} ."/$state->{module}/$dirpart\n"; 913 914$log->debug("Creating new file 'Created$dirpart'"); 915print"Created$dirpart\n"; 916} 917print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 918 919# this is an "entries" line 920$log->debug("/$filepart/1.$meta->{revision}///"); 921print"/$filepart/1.$meta->{revision}///\n"; 922 923# permissions 924$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 925print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 926 927# transmit file 928 transmitfile($meta->{filehash}); 929} 930}else{ 931$log->info("Updating '$filename'"); 932my($filepart,$dirpart) = filenamesplit($meta->{name},1); 933 934my$dir= tempdir( DIR =>$TEMP_DIR, CLEANUP =>1) ."/"; 935 936chdir$dir; 937my$file_local=$filepart.".mine"; 938system("ln","-s",$state->{entries}{$filename}{modified_filename},$file_local); 939my$file_old=$filepart.".".$oldmeta->{revision}; 940 transmitfile($oldmeta->{filehash},$file_old); 941my$file_new=$filepart.".".$meta->{revision}; 942 transmitfile($meta->{filehash},$file_new); 943 944# we need to merge with the local changes ( M=successful merge, C=conflict merge ) 945$log->info("Merging$file_local,$file_old,$file_new"); 946 947$log->debug("Temporary directory for merge is$dir"); 948 949my$return=system("git","merge-file",$file_local,$file_old,$file_new); 950$return>>=8; 951 952if($return==0) 953{ 954$log->info("Merged successfully"); 955print"M M$filename\n"; 956$log->debug("Update-existing$dirpart"); 957 958# Don't want to actually _DO_ the update if -n specified 959unless($state->{globaloptions}{-n} ) 960{ 961print"Update-existing$dirpart\n"; 962$log->debug($state->{CVSROOT} ."/$state->{module}/$filename"); 963print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 964$log->debug("/$filepart/1.$meta->{revision}///"); 965print"/$filepart/1.$meta->{revision}///\n"; 966} 967} 968elsif($return==1) 969{ 970$log->info("Merged with conflicts"); 971print"M C$filename\n"; 972 973# Don't want to actually _DO_ the update if -n specified 974unless($state->{globaloptions}{-n} ) 975{ 976print"Update-existing$dirpart\n"; 977print$state->{CVSROOT} ."/$state->{module}/$filename\n"; 978print"/$filepart/1.$meta->{revision}/+//\n"; 979} 980} 981else 982{ 983$log->warn("Merge failed"); 984next; 985} 986 987# Don't want to actually _DO_ the update if -n specified 988unless($state->{globaloptions}{-n} ) 989{ 990# permissions 991$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}"); 992print"u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n"; 993 994# transmit file, format is single integer on a line by itself (file 995# size) followed by the file contents 996# TODO : we should copy files in blocks 997my$data=`cat$file_local`; 998$log->debug("File size : " . length($data)); 999 print length($data) . "\n";1000 print$data;1001 }10021003 chdir "/";1004 }10051006 }10071008 print "ok\n";1009}10101011sub req_ci1012{1013 my ($cmd,$data) =@_;10141015 argsplit("ci");10161017 #$log->debug("State : " . Dumper($state));10181019$log->info("req_ci : " . ( defined($data) ?$data: "[NULL]" ));10201021 if (@ARGV&&$ARGV[0] eq 'pserver')1022 {1023 print "error 1 pserver access cannot commit\n";1024 exit;1025 }10261027 if ( -e$state->{CVSROOT} . "/index" )1028 {1029$log->warn("file 'index' already exists in the git repository");1030 print "error 1 Index already exists in git repo\n";1031 exit;1032 }10331034 # Grab a handle to the SQLite db and do any necessary updates1035 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1036$updater->update();10371038 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1039 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1040$log->info("Lockless commit start, basing commit on '$tmpdir', index file is '$file_index'");10411042$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1043$ENV{GIT_INDEX_FILE} =$file_index;10441045 # Remember where the head was at the beginning.1046 my$parenthash= `git show-ref -s refs/heads/$state->{module}`;1047 chomp$parenthash;1048 if ($parenthash!~ /^[0-9a-f]{40}$/) {1049 print "error 1 pserver cannot find the current HEAD of module";1050 exit;1051 }10521053 chdir$tmpdir;10541055 # populate the temporary index based1056 system("git-read-tree",$parenthash);1057 unless ($?== 0)1058 {1059 die "Error running git-read-tree$state->{module}$file_index$!";1060 }1061$log->info("Created index '$file_index' with for head$state->{module} - exit status$?");10621063 my@committedfiles= ();10641065 # foreach file specified on the command line ...1066 foreach my$filename( @{$state->{args}} )1067 {1068 my$committedfile=$filename;1069$filename= filecleanup($filename);10701071 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10721073 my$meta=$updater->getmeta($filename);10741075 my$wrev= revparse($filename);10761077 my ($filepart,$dirpart) = filenamesplit($filename);10781079 # do a checkout of the file if it part of this tree1080 if ($wrev) {1081 system('git-checkout-index', '-f', '-u',$filename);1082 unless ($?== 0) {1083 die "Error running git-checkout-index -f -u$filename:$!";1084 }1085 }10861087 my$addflag= 0;1088 my$rmflag= 0;1089$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1090$addflag= 1 unless ( -e$filename);10911092 # Do up to date checking1093 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1094 {1095 # fail everything if an up to date check fails1096 print "error 1 Up to date check failed for$filename\n";1097 chdir "/";1098 exit;1099 }11001101 push@committedfiles,$committedfile;1102$log->info("Committing$filename");11031104 system("mkdir","-p",$dirpart) unless ( -d$dirpart);11051106 unless ($rmflag)1107 {1108$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1109 rename$state->{entries}{$filename}{modified_filename},$filename;11101111 # Calculate modes to remove1112 my$invmode= "";1113 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }11141115$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1116 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1117 }11181119 if ($rmflag)1120 {1121$log->info("Removing file '$filename'");1122 unlink($filename);1123 system("git-update-index", "--remove",$filename);1124 }1125 elsif ($addflag)1126 {1127$log->info("Adding file '$filename'");1128 system("git-update-index", "--add",$filename);1129 } else {1130$log->info("Updating file '$filename'");1131 system("git-update-index",$filename);1132 }1133 }11341135 unless ( scalar(@committedfiles) > 0 )1136 {1137 print "E No files to commit\n";1138 print "ok\n";1139 chdir "/";1140 return;1141 }11421143 my$treehash= `git-write-tree`;1144 chomp$treehash;11451146$log->debug("Treehash :$treehash, Parenthash :$parenthash");11471148 # write our commit message out if we have one ...1149 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1150 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1151 print$msg_fh"\n\nvia git-CVS emulator\n";1152 close$msg_fh;11531154 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1155chomp($commithash);1156$log->info("Commit hash :$commithash");11571158unless($commithash=~/[a-zA-Z0-9]{40}/)1159{1160$log->warn("Commit failed (Invalid commit hash)");1161print"error 1 Commit failed (unknown reason)\n";1162chdir"/";1163exit;1164}11651166# Check that this is allowed, just as we would with a receive-pack1167my@cmd= ($ENV{GIT_DIR}.'hooks/update',"refs/heads/$state->{module}",1168$parenthash,$commithash);1169if( -x $cmd[0] ) {1170unless(system(@cmd) ==0)1171{1172$log->warn("Commit failed (update hook declined to update ref)");1173print"error 1 Commit failed (update hook declined)\n";1174chdir"/";1175exit;1176}1177}11781179if(system(qw(git update-ref -m),"cvsserver ci",1180"refs/heads/$state->{module}",$commithash,$parenthash)) {1181$log->warn("update-ref for$state->{module} failed.");1182print"error 1 Cannot commit -- update first\n";1183exit;1184}11851186$updater->update();11871188# foreach file specified on the command line ...1189foreachmy$filename(@committedfiles)1190{1191$filename= filecleanup($filename);11921193my$meta=$updater->getmeta($filename);1194unless(defined$meta->{revision}) {1195$meta->{revision} =1;1196}11971198my($filepart,$dirpart) = filenamesplit($filename,1);11991200$log->debug("Checked-in$dirpart:$filename");12011202if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1203{1204print"Remove-entry$dirpart\n";1205print"$filename\n";1206}else{1207print"Checked-in$dirpart\n";1208print"$filename\n";1209print"/$filepart/1.$meta->{revision}///\n";1210}1211}12121213chdir"/";1214print"ok\n";1215}12161217sub req_status1218{1219my($cmd,$data) =@_;12201221 argsplit("status");12221223$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1224#$log->debug("status state : " . Dumper($state));12251226# Grab a handle to the SQLite db and do any necessary updates1227my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1228$updater->update();12291230# if no files were specified, we need to work out what files we should be providing status on ...1231 argsfromdir($updater);12321233# foreach file specified on the command line ...1234foreachmy$filename( @{$state->{args}} )1235{1236$filename= filecleanup($filename);12371238my$meta=$updater->getmeta($filename);1239my$oldmeta=$meta;12401241my$wrev= revparse($filename);12421243# If the working copy is an old revision, lets get that version too for comparison.1244if(defined($wrev)and$wrev!=$meta->{revision} )1245{1246$oldmeta=$updater->getmeta($filename,$wrev);1247}12481249# TODO : All possible statuses aren't yet implemented1250my$status;1251# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1252$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1253and1254( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1255or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1256);12571258# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1259$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1260and1261($state->{entries}{$filename}{unchanged}1262or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1263);12641265# Need checkout if it exists in the repo but doesn't have a working copy1266$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12671268# Locally modified if working copy and repo copy have the same revision but there are local changes1269$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12701271# Needs Merge if working copy revision is less than repo copy and there are local changes1272$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12731274$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1275$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1276$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1277$status||="File had conflicts on merge"if(0);12781279$status||="Unknown";12801281print"M ===================================================================\n";1282print"M File:$filename\tStatus:$status\n";1283if(defined($state->{entries}{$filename}{revision}) )1284{1285print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1286}else{1287print"M Working revision:\tNo entry for$filename\n";1288}1289if(defined($meta->{revision}) )1290{1291print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{repository}/$filename,v\n";1292print"M Sticky Tag:\t\t(none)\n";1293print"M Sticky Date:\t\t(none)\n";1294print"M Sticky Options:\t\t(none)\n";1295}else{1296print"M Repository revision:\tNo revision control file\n";1297}1298print"M\n";1299}13001301print"ok\n";1302}13031304sub req_diff1305{1306my($cmd,$data) =@_;13071308 argsplit("diff");13091310$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1311#$log->debug("status state : " . Dumper($state));13121313my($revision1,$revision2);1314if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1315{1316$revision1=$state->{opt}{r}[0];1317$revision2=$state->{opt}{r}[1];1318}else{1319$revision1=$state->{opt}{r};1320}13211322$revision1=~s/^1\.//if(defined($revision1) );1323$revision2=~s/^1\.//if(defined($revision2) );13241325$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );13261327# Grab a handle to the SQLite db and do any necessary updates1328my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1329$updater->update();13301331# if no files were specified, we need to work out what files we should be providing status on ...1332 argsfromdir($updater);13331334# foreach file specified on the command line ...1335foreachmy$filename( @{$state->{args}} )1336{1337$filename= filecleanup($filename);13381339my($fh,$file1,$file2,$meta1,$meta2,$filediff);13401341my$wrev= revparse($filename);13421343# We need _something_ to diff against1344next unless(defined($wrev) );13451346# if we have a -r switch, use it1347if(defined($revision1) )1348{1349(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1350$meta1=$updater->getmeta($filename,$revision1);1351unless(defined($meta1)and$meta1->{filehash}ne"deleted")1352{1353print"E File$filenameat revision 1.$revision1doesn't exist\n";1354next;1355}1356 transmitfile($meta1->{filehash},$file1);1357}1358# otherwise we just use the working copy revision1359else1360{1361(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1362$meta1=$updater->getmeta($filename,$wrev);1363 transmitfile($meta1->{filehash},$file1);1364}13651366# if we have a second -r switch, use it too1367if(defined($revision2) )1368{1369(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1370$meta2=$updater->getmeta($filename,$revision2);13711372unless(defined($meta2)and$meta2->{filehash}ne"deleted")1373{1374print"E File$filenameat revision 1.$revision2doesn't exist\n";1375next;1376}13771378 transmitfile($meta2->{filehash},$file2);1379}1380# otherwise we just use the working copy1381else1382{1383$file2=$state->{entries}{$filename}{modified_filename};1384}13851386# if we have been given -r, and we don't have a $file2 yet, lets get one1387if(defined($revision1)and not defined($file2) )1388{1389(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1390$meta2=$updater->getmeta($filename,$wrev);1391 transmitfile($meta2->{filehash},$file2);1392}13931394# We need to have retrieved something useful1395next unless(defined($meta1) );13961397# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1398next if(not defined($meta2)and$wrev==$meta1->{revision}1399and1400( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1401or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1402);14031404# Apparently we only show diffs for locally modified files1405next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );14061407print"M Index:$filename\n";1408print"M ===================================================================\n";1409print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1410print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1411print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1412print"M diff ";1413foreachmy$opt(keys%{$state->{opt}} )1414{1415if(ref$state->{opt}{$opt}eq"ARRAY")1416{1417foreachmy$value( @{$state->{opt}{$opt}} )1418{1419print"-$opt$value";1420}1421}else{1422print"-$opt";1423print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1424}1425}1426print"$filename\n";14271428$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));14291430($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);14311432if(exists$state->{opt}{u} )1433{1434system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1435}else{1436system("diff$file1$file2>$filediff");1437}14381439while( <$fh> )1440{1441print"M$_";1442}1443close$fh;1444}14451446print"ok\n";1447}14481449sub req_log1450{1451my($cmd,$data) =@_;14521453 argsplit("log");14541455$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1456#$log->debug("log state : " . Dumper($state));14571458my($minrev,$maxrev);1459if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1460{1461my$control=$2;1462$minrev=$1;1463$maxrev=$3;1464$minrev=~s/^1\.//if(defined($minrev) );1465$maxrev=~s/^1\.//if(defined($maxrev) );1466$minrev++if(defined($minrev)and$controleq"::");1467}14681469# Grab a handle to the SQLite db and do any necessary updates1470my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1471$updater->update();14721473# if no files were specified, we need to work out what files we should be providing status on ...1474 argsfromdir($updater);14751476# foreach file specified on the command line ...1477foreachmy$filename( @{$state->{args}} )1478{1479$filename= filecleanup($filename);14801481my$headmeta=$updater->getmeta($filename);14821483my$revisions=$updater->getlog($filename);1484my$totalrevisions=scalar(@$revisions);14851486if(defined($minrev) )1487{1488$log->debug("Removing revisions less than$minrev");1489while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1490{1491pop@$revisions;1492}1493}1494if(defined($maxrev) )1495{1496$log->debug("Removing revisions greater than$maxrev");1497while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1498{1499shift@$revisions;1500}1501}15021503next unless(scalar(@$revisions) );15041505print"M\n";1506print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1507print"M Working file:$filename\n";1508print"M head: 1.$headmeta->{revision}\n";1509print"M branch:\n";1510print"M locks: strict\n";1511print"M access list:\n";1512print"M symbolic names:\n";1513print"M keyword substitution: kv\n";1514print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1515print"M description:\n";15161517foreachmy$revision(@$revisions)1518{1519print"M ----------------------------\n";1520print"M revision 1.$revision->{revision}\n";1521# reformat the date for log output1522$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}) );1523$revision->{author} =~s/\s+.*//;1524$revision->{author} =~s/^(.{8}).*/$1/;1525print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1526my$commitmessage=$updater->commitmessage($revision->{commithash});1527$commitmessage=~s/^/M /mg;1528print$commitmessage."\n";1529}1530print"M =============================================================================\n";1531}15321533print"ok\n";1534}15351536sub req_annotate1537{1538my($cmd,$data) =@_;15391540 argsplit("annotate");15411542$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1543#$log->debug("status state : " . Dumper($state));15441545# Grab a handle to the SQLite db and do any necessary updates1546my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1547$updater->update();15481549# if no files were specified, we need to work out what files we should be providing annotate on ...1550 argsfromdir($updater);15511552# we'll need a temporary checkout dir1553my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1554my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1555$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15561557$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1558$ENV{GIT_INDEX_FILE} =$file_index;15591560chdir$tmpdir;15611562# foreach file specified on the command line ...1563foreachmy$filename( @{$state->{args}} )1564{1565$filename= filecleanup($filename);15661567my$meta=$updater->getmeta($filename);15681569next unless($meta->{revision} );15701571# get all the commits that this file was in1572# in dense format -- aka skip dead revisions1573my$revisions=$updater->gethistorydense($filename);1574my$lastseenin=$revisions->[0][2];15751576# populate the temporary index based on the latest commit were we saw1577# the file -- but do it cheaply without checking out any files1578# TODO: if we got a revision from the client, use that instead1579# to look up the commithash in sqlite (still good to default to1580# the current head as we do now)1581system("git-read-tree",$lastseenin);1582unless($?==0)1583{1584die"Error running git-read-tree$lastseenin$file_index$!";1585}1586$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");15871588# do a checkout of the file1589system('git-checkout-index','-f','-u',$filename);1590unless($?==0) {1591die"Error running git-checkout-index -f -u$filename:$!";1592}15931594$log->info("Annotate$filename");15951596# Prepare a file with the commits from the linearized1597# history that annotate should know about. This prevents1598# git-jsannotate telling us about commits we are hiding1599# from the client.16001601open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1602for(my$i=0;$i<@$revisions;$i++)1603{1604print ANNOTATEHINTS $revisions->[$i][2];1605if($i+1<@$revisions) {# have we got a parent?1606print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1607}1608print ANNOTATEHINTS "\n";1609}16101611print ANNOTATEHINTS "\n";1612close ANNOTATEHINTS;16131614my$annotatecmd='git-annotate';1615open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1616or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1617my$metadata= {};1618print"E Annotations for$filename\n";1619print"E ***************\n";1620while( <ANNOTATE> )1621{1622if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1623{1624my$commithash=$1;1625my$data=$2;1626unless(defined($metadata->{$commithash} ) )1627{1628$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1629$metadata->{$commithash}{author} =~s/\s+.*//;1630$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1631$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1632}1633printf("M 1.%-5d (%-8s%10s):%s\n",1634$metadata->{$commithash}{revision},1635$metadata->{$commithash}{author},1636$metadata->{$commithash}{modified},1637$data1638);1639}else{1640$log->warn("Error in annotate output! LINE:$_");1641print"E Annotate error\n";1642next;1643}1644}1645close ANNOTATE;1646}16471648# done; get out of the tempdir1649chdir"/";16501651print"ok\n";16521653}16541655# This method takes the state->{arguments} array and produces two new arrays.1656# The first is $state->{args} which is everything before the '--' argument, and1657# the second is $state->{files} which is everything after it.1658sub argsplit1659{1660return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16611662my$type=shift;16631664$state->{args} = [];1665$state->{files} = [];1666$state->{opt} = {};16671668if(defined($type) )1669{1670my$opt= {};1671$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");1672$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1673$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");1674$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1675$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1676$opt= { k =>1, m =>1}if($typeeq"add");1677$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1678$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");167916801681while(scalar( @{$state->{arguments}} ) >0)1682{1683my$arg=shift@{$state->{arguments}};16841685next if($argeq"--");1686next unless($arg=~/\S/);16871688# if the argument looks like a switch1689if($arg=~/^-(\w)(.*)/)1690{1691# if it's a switch that takes an argument1692if($opt->{$1} )1693{1694# If this switch has already been provided1695if($opt->{$1} >1and exists($state->{opt}{$1} ) )1696{1697$state->{opt}{$1} = [$state->{opt}{$1} ];1698if(length($2) >0)1699{1700push@{$state->{opt}{$1}},$2;1701}else{1702push@{$state->{opt}{$1}},shift@{$state->{arguments}};1703}1704}else{1705# if there's extra data in the arg, use that as the argument for the switch1706if(length($2) >0)1707{1708$state->{opt}{$1} =$2;1709}else{1710$state->{opt}{$1} =shift@{$state->{arguments}};1711}1712}1713}else{1714$state->{opt}{$1} =undef;1715}1716}1717else1718{1719push@{$state->{args}},$arg;1720}1721}1722}1723else1724{1725my$mode=0;17261727foreachmy$value( @{$state->{arguments}} )1728{1729if($valueeq"--")1730{1731$mode++;1732next;1733}1734push@{$state->{args}},$valueif($mode==0);1735push@{$state->{files}},$valueif($mode==1);1736}1737}1738}17391740# This method uses $state->{directory} to populate $state->{args} with a list of filenames1741sub argsfromdir1742{1743my$updater=shift;17441745$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17461747return if(scalar( @{$state->{args}} ) >1);17481749my@gethead= @{$updater->gethead};17501751# push added files1752foreachmy$file(keys%{$state->{entries}}) {1753if(exists$state->{entries}{$file}{revision} &&1754$state->{entries}{$file}{revision} ==0)1755{1756push@gethead, { name =>$file, filehash =>'added'};1757}1758}17591760if(scalar(@{$state->{args}}) ==1)1761{1762my$arg=$state->{args}[0];1763$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17641765$log->info("Only one arg specified, checking for directory expansion on '$arg'");17661767foreachmy$file(@gethead)1768{1769next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1770next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1771push@{$state->{args}},$file->{name};1772}17731774shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1775}else{1776$log->info("Only one arg specified, populating file list automatically");17771778$state->{args} = [];17791780foreachmy$file(@gethead)1781{1782next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1783next unless($file->{name} =~s/^$state->{prependdir}//);1784push@{$state->{args}},$file->{name};1785}1786}1787}17881789# This method cleans up the $state variable after a command that uses arguments has run1790sub statecleanup1791{1792$state->{files} = [];1793$state->{args} = [];1794$state->{arguments} = [];1795$state->{entries} = {};1796}17971798sub revparse1799{1800my$filename=shift;18011802returnundefunless(defined($state->{entries}{$filename}{revision} ) );18031804return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1805return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);18061807returnundef;1808}18091810# This method takes a file hash and does a CVS "file transfer" which transmits the1811# size of the file, and then the file contents.1812# If a second argument $targetfile is given, the file is instead written out to1813# a file by the name of $targetfile1814sub transmitfile1815{1816my$filehash=shift;1817my$targetfile=shift;18181819if(defined($filehash)and$filehasheq"deleted")1820{1821$log->warn("filehash is 'deleted'");1822return;1823}18241825die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);18261827my$type=`git-cat-file -t$filehash`;1828 chomp$type;18291830 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );18311832 my$size= `git-cat-file -s $filehash`;1833chomp$size;18341835$log->debug("transmitfile($filehash) size=$size, type=$type");18361837if(open my$fh,'-|',"git-cat-file","blob",$filehash)1838{1839if(defined($targetfile) )1840{1841open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1842print NEWFILE $_while( <$fh> );1843close NEWFILE;1844}else{1845print"$size\n";1846printwhile( <$fh> );1847}1848close$fhor die("Couldn't close filehandle for transmitfile()");1849}else{1850die("Couldn't execute git-cat-file");1851}1852}18531854# This method takes a file name, and returns ( $dirpart, $filepart ) which1855# refers to the directory portion and the file portion of the filename1856# respectively1857sub filenamesplit1858{1859my$filename=shift;1860my$fixforlocaldir=shift;18611862my($filepart,$dirpart) = ($filename,".");1863($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1864$dirpart.="/";18651866if($fixforlocaldir)1867{1868$dirpart=~s/^$state->{prependdir}//;1869}18701871return($filepart,$dirpart);1872}18731874sub filecleanup1875{1876my$filename=shift;18771878returnundefunless(defined($filename));1879if($filename=~/^\// )1880{1881print"E absolute filenames '$filename' not supported by server\n";1882returnundef;1883}18841885$filename=~s/^\.\///g;1886$filename=$state->{prependdir} .$filename;1887return$filename;1888}18891890package GITCVS::log;18911892####1893#### Copyright The Open University UK - 2006.1894####1895#### Authors: Martyn Smith <martyn@catalyst.net.nz>1896#### Martin Langhoff <martin@catalyst.net.nz>1897####1898####18991900use strict;1901use warnings;19021903=head1 NAME19041905GITCVS::log19061907=head1 DESCRIPTION19081909This module provides very crude logging with a similar interface to1910Log::Log4perl19111912=head1 METHODS19131914=cut19151916=head2 new19171918Creates a new log object, optionally you can specify a filename here to1919indicate the file to log to. If no log file is specified, you can specify one1920later with method setfile, or indicate you no longer want logging with method1921nofile.19221923Until one of these methods is called, all log calls will buffer messages ready1924to write out.19251926=cut1927sub new1928{1929my$class=shift;1930my$filename=shift;19311932my$self= {};19331934bless$self,$class;19351936if(defined($filename) )1937{1938open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1939}19401941return$self;1942}19431944=head2 setfile19451946This methods takes a filename, and attempts to open that file as the log file.1947If successful, all buffered data is written out to the file, and any further1948logging is written directly to the file.19491950=cut1951sub setfile1952{1953my$self=shift;1954my$filename=shift;19551956if(defined($filename) )1957{1958open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1959}19601961return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19621963while(my$line=shift@{$self->{buffer}} )1964{1965print{$self->{fh}}$line;1966}1967}19681969=head2 nofile19701971This method indicates no logging is going to be used. It flushes any entries in1972the internal buffer, and sets a flag to ensure no further data is put there.19731974=cut1975sub nofile1976{1977my$self=shift;19781979$self->{nolog} =1;19801981return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19821983$self->{buffer} = [];1984}19851986=head2 _logopen19871988Internal method. Returns true if the log file is open, false otherwise.19891990=cut1991sub _logopen1992{1993my$self=shift;19941995return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");1996return0;1997}19981999=head2 debug info warn fatal20002001These four methods are wrappers to _log. They provide the actual interface for2002logging data.20032004=cut2005sub debug {my$self=shift;$self->_log("debug",@_); }2006sub info {my$self=shift;$self->_log("info",@_); }2007subwarn{my$self=shift;$self->_log("warn",@_); }2008sub fatal {my$self=shift;$self->_log("fatal",@_); }20092010=head2 _log20112012This is an internal method called by the logging functions. It generates a2013timestamp and pushes the logged line either to file, or internal buffer.20142015=cut2016sub _log2017{2018my$self=shift;2019my$level=shift;20202021return if($self->{nolog} );20222023my@time=localtime;2024my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2025$time[5] +1900,2026$time[4] +1,2027$time[3],2028$time[2],2029$time[1],2030$time[0],2031uc$level,2032);20332034if($self->_logopen)2035{2036print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2037}else{2038push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2039}2040}20412042=head2 DESTROY20432044This method simply closes the file handle if one is open20452046=cut2047sub DESTROY2048{2049my$self=shift;20502051if($self->_logopen)2052{2053close$self->{fh};2054}2055}20562057package GITCVS::updater;20582059####2060#### Copyright The Open University UK - 2006.2061####2062#### Authors: Martyn Smith <martyn@catalyst.net.nz>2063#### Martin Langhoff <martin@catalyst.net.nz>2064####2065####20662067use strict;2068use warnings;2069use DBI;20702071=head1 METHODS20722073=cut20742075=head2 new20762077=cut2078sub new2079{2080my$class=shift;2081my$config=shift;2082my$module=shift;2083my$log=shift;20842085die"Need to specify a git repository"unless(defined($config)and-d $config);2086die"Need to specify a module"unless(defined($module) );20872088$class=ref($class) ||$class;20892090my$self= {};20912092bless$self,$class;20932094$self->{dbdir} =$config."/";2095die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );20962097$self->{module} =$module;2098$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";20992100$self->{git_path} =$config."/";21012102$self->{log} =$log;21032104die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );21052106$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");21072108$self->{tables} = {};2109foreachmy$table($self->{dbh}->tables)2110{2111$table=~s/^"//;2112$table=~s/"$//;2113$self->{tables}{$table} =1;2114}21152116# Construct the revision table if required2117unless($self->{tables}{revision} )2118{2119$self->{dbh}->do("2120 CREATE TABLE revision (2121 name TEXT NOT NULL,2122 revision INTEGER NOT NULL,2123 filehash TEXT NOT NULL,2124 commithash TEXT NOT NULL,2125 author TEXT NOT NULL,2126 modified TEXT NOT NULL,2127 mode TEXT NOT NULL2128 )2129 ");2130$self->{dbh}->do("2131 CREATE INDEX revision_ix12132 ON revision (name,revision)2133 ");2134$self->{dbh}->do("2135 CREATE INDEX revision_ix22136 ON revision (name,commithash)2137 ");2138}21392140# Construct the head table if required2141unless($self->{tables}{head} )2142{2143$self->{dbh}->do("2144 CREATE TABLE head (2145 name TEXT NOT NULL,2146 revision INTEGER NOT NULL,2147 filehash TEXT NOT NULL,2148 commithash TEXT NOT NULL,2149 author TEXT NOT NULL,2150 modified TEXT NOT NULL,2151 mode TEXT NOT NULL2152 )2153 ");2154$self->{dbh}->do("2155 CREATE INDEX head_ix12156 ON head (name)2157 ");2158}21592160# Construct the properties table if required2161unless($self->{tables}{properties} )2162{2163$self->{dbh}->do("2164 CREATE TABLE properties (2165 key TEXT NOT NULL PRIMARY KEY,2166 value TEXT2167 )2168 ");2169}21702171# Construct the commitmsgs table if required2172unless($self->{tables}{commitmsgs} )2173{2174$self->{dbh}->do("2175 CREATE TABLE commitmsgs (2176 key TEXT NOT NULL PRIMARY KEY,2177 value TEXT2178 )2179 ");2180}21812182return$self;2183}21842185=head2 update21862187=cut2188sub update2189{2190my$self=shift;21912192# first lets get the commit list2193$ENV{GIT_DIR} =$self->{git_path};21942195my$commitsha1=`git rev-parse$self->{module}`;2196chomp$commitsha1;21972198my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2199unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2200{2201die("Invalid module '$self->{module}'");2202}220322042205my$git_log;2206my$lastcommit=$self->_get_prop("last_commit");22072208if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2209return1;2210}22112212# Start exclusive lock here...2213$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";22142215# TODO: log processing is memory bound2216# if we can parse into a 2nd file that is in reverse order2217# we can probably do something really efficient2218my@git_log_params= ('--pretty','--parents','--topo-order');22192220if(defined$lastcommit) {2221push@git_log_params,"$lastcommit..$self->{module}";2222}else{2223push@git_log_params,$self->{module};2224}2225# git-rev-list is the backend / plumbing version of git-log2226open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";22272228my@commits;22292230my%commit= ();22312232while( <GITLOG> )2233{2234chomp;2235if(m/^commit\s+(.*)$/) {2236# on ^commit lines put the just seen commit in the stack2237# and prime things for the next one2238if(keys%commit) {2239my%copy=%commit;2240unshift@commits, \%copy;2241%commit= ();2242}2243my@parents=split(m/\s+/,$1);2244$commit{hash} =shift@parents;2245$commit{parents} = \@parents;2246}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2247# on rfc822-like lines seen before we see any message,2248# lowercase the entry and put it in the hash as key-value2249$commit{lc($1)} =$2;2250}else{2251# message lines - skip initial empty line2252# and trim whitespace2253if(!exists($commit{message}) &&m/^\s*$/) {2254# define it to mark the end of headers2255$commit{message} ='';2256next;2257}2258s/^\s+//;s/\s+$//;# trim ws2259$commit{message} .=$_."\n";2260}2261}2262close GITLOG;22632264unshift@commits, \%commitif(keys%commit);22652266# Now all the commits are in the @commits bucket2267# ordered by time DESC. for each commit that needs processing,2268# determine whether it's following the last head we've seen or if2269# it's on its own branch, grab a file list, and add whatever's changed2270# NOTE: $lastcommit refers to the last commit from previous run2271# $lastpicked is the last commit we picked in this run2272my$lastpicked;2273my$head= {};2274if(defined$lastcommit) {2275$lastpicked=$lastcommit;2276}22772278my$committotal=scalar(@commits);2279my$commitcount=0;22802281# Load the head table into $head (for cached lookups during the update process)2282foreachmy$file( @{$self->gethead()} )2283{2284$head->{$file->{name}} =$file;2285}22862287foreachmy$commit(@commits)2288{2289$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2290if(defined$lastpicked)2291{2292if(!in_array($lastpicked, @{$commit->{parents}}))2293{2294# skip, we'll see this delta2295# as part of a merge later2296# warn "skipping off-track $commit->{hash}\n";2297next;2298}elsif(@{$commit->{parents}} >1) {2299# it is a merge commit, for each parent that is2300# not $lastpicked, see if we can get a log2301# from the merge-base to that parent to put it2302# in the message as a merge summary.2303my@parents= @{$commit->{parents}};2304foreachmy$parent(@parents) {2305# git-merge-base can potentially (but rarely) throw2306# several candidate merge bases. let's assume2307# that the first one is the best one.2308if($parenteq$lastpicked) {2309next;2310}2311open my$p,'git-merge-base '.$lastpicked.' '2312.$parent.'|';2313my@output= (<$p>);2314close$p;2315my$base=join('',@output);2316chomp$base;2317if($base) {2318my@merged;2319# print "want to log between $base $parent \n";2320open(GITLOG,'-|','git-log',"$base..$parent")2321or die"Cannot call git-log:$!";2322my$mergedhash;2323while(<GITLOG>) {2324chomp;2325if(!defined$mergedhash) {2326if(m/^commit\s+(.+)$/) {2327$mergedhash=$1;2328}else{2329next;2330}2331}else{2332# grab the first line that looks non-rfc8222333# aka has content after leading space2334if(m/^\s+(\S.*)$/) {2335my$title=$1;2336$title=substr($title,0,100);# truncate2337unshift@merged,"$mergedhash$title";2338undef$mergedhash;2339}2340}2341}2342close GITLOG;2343if(@merged) {2344$commit->{mergemsg} =$commit->{message};2345$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2346foreachmy$summary(@merged) {2347$commit->{mergemsg} .="\t$summary\n";2348}2349$commit->{mergemsg} .="\n\n";2350# print "Message for $commit->{hash} \n$commit->{mergemsg}";2351}2352}2353}2354}2355}23562357# convert the date to CVS-happy format2358$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);23592360if(defined($lastpicked) )2361{2362my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2363local($/) ="\0";2364while( <FILELIST> )2365{2366chomp;2367unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2368{2369die("Couldn't process git-diff-tree line :$_");2370}2371my($mode,$hash,$change) = ($1,$2,$3);2372my$name= <FILELIST>;2373chomp($name);23742375# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");23762377my$git_perms="";2378$git_perms.="r"if($mode&4);2379$git_perms.="w"if($mode&2);2380$git_perms.="x"if($mode&1);2381$git_perms="rw"if($git_permseq"");23822383if($changeeq"D")2384{2385#$log->debug("DELETE $name");2386$head->{$name} = {2387 name =>$name,2388 revision =>$head->{$name}{revision} +1,2389 filehash =>"deleted",2390 commithash =>$commit->{hash},2391 modified =>$commit->{date},2392 author =>$commit->{author},2393 mode =>$git_perms,2394};2395$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2396}2397elsif($changeeq"M")2398{2399#$log->debug("MODIFIED $name");2400$head->{$name} = {2401 name =>$name,2402 revision =>$head->{$name}{revision} +1,2403 filehash =>$hash,2404 commithash =>$commit->{hash},2405 modified =>$commit->{date},2406 author =>$commit->{author},2407 mode =>$git_perms,2408};2409$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2410}2411elsif($changeeq"A")2412{2413#$log->debug("ADDED $name");2414$head->{$name} = {2415 name =>$name,2416 revision =>1,2417 filehash =>$hash,2418 commithash =>$commit->{hash},2419 modified =>$commit->{date},2420 author =>$commit->{author},2421 mode =>$git_perms,2422};2423$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2424}2425else2426{2427$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2428die;2429}2430}2431close FILELIST;2432}else{2433# this is used to detect files removed from the repo2434my$seen_files= {};24352436my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2437local$/="\0";2438while( <FILELIST> )2439{2440chomp;2441unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2442{2443die("Couldn't process git-ls-tree line :$_");2444}24452446my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);24472448$seen_files->{$git_filename} =1;24492450my($oldhash,$oldrevision,$oldmode) = (2451$head->{$git_filename}{filehash},2452$head->{$git_filename}{revision},2453$head->{$git_filename}{mode}2454);24552456if($git_perms=~/^\d\d\d(\d)\d\d/o)2457{2458$git_perms="";2459$git_perms.="r"if($1&4);2460$git_perms.="w"if($1&2);2461$git_perms.="x"if($1&1);2462}else{2463$git_perms="rw";2464}24652466# unless the file exists with the same hash, we need to update it ...2467unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2468{2469my$newrevision= ($oldrevisionor0) +1;24702471$head->{$git_filename} = {2472 name =>$git_filename,2473 revision =>$newrevision,2474 filehash =>$git_hash,2475 commithash =>$commit->{hash},2476 modified =>$commit->{date},2477 author =>$commit->{author},2478 mode =>$git_perms,2479};248024812482$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2483}2484}2485close FILELIST;24862487# Detect deleted files2488foreachmy$file(keys%$head)2489{2490unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2491{2492$head->{$file}{revision}++;2493$head->{$file}{filehash} ="deleted";2494$head->{$file}{commithash} =$commit->{hash};2495$head->{$file}{modified} =$commit->{date};2496$head->{$file}{author} =$commit->{author};24972498$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2499}2500}2501# END : "Detect deleted files"2502}250325042505if(exists$commit->{mergemsg})2506{2507$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2508}25092510$lastpicked=$commit->{hash};25112512$self->_set_prop("last_commit",$commit->{hash});2513}25142515$self->delete_head();2516foreachmy$file(keys%$head)2517{2518$self->insert_head(2519$file,2520$head->{$file}{revision},2521$head->{$file}{filehash},2522$head->{$file}{commithash},2523$head->{$file}{modified},2524$head->{$file}{author},2525$head->{$file}{mode},2526);2527}2528# invalidate the gethead cache2529$self->{gethead_cache} =undef;253025312532# Ending exclusive lock here2533$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2534}25352536sub insert_rev2537{2538my$self=shift;2539my$name=shift;2540my$revision=shift;2541my$filehash=shift;2542my$commithash=shift;2543my$modified=shift;2544my$author=shift;2545my$mode=shift;25462547my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2548$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2549}25502551sub insert_mergelog2552{2553my$self=shift;2554my$key=shift;2555my$value=shift;25562557my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2558$insert_mergelog->execute($key,$value);2559}25602561sub delete_head2562{2563my$self=shift;25642565my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2566$delete_head->execute();2567}25682569sub insert_head2570{2571my$self=shift;2572my$name=shift;2573my$revision=shift;2574my$filehash=shift;2575my$commithash=shift;2576my$modified=shift;2577my$author=shift;2578my$mode=shift;25792580my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2581$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2582}25832584sub _headrev2585{2586my$self=shift;2587my$filename=shift;25882589my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2590$db_query->execute($filename);2591my($hash,$revision,$mode) =$db_query->fetchrow_array;25922593return($hash,$revision,$mode);2594}25952596sub _get_prop2597{2598my$self=shift;2599my$key=shift;26002601my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2602$db_query->execute($key);2603my($value) =$db_query->fetchrow_array;26042605return$value;2606}26072608sub _set_prop2609{2610my$self=shift;2611my$key=shift;2612my$value=shift;26132614my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2615$db_query->execute($value,$key);26162617unless($db_query->rows)2618{2619$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2620$db_query->execute($key,$value);2621}26222623return$value;2624}26252626=head2 gethead26272628=cut26292630sub gethead2631{2632my$self=shift;26332634return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );26352636my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2637$db_query->execute();26382639my$tree= [];2640while(my$file=$db_query->fetchrow_hashref)2641{2642push@$tree,$file;2643}26442645$self->{gethead_cache} =$tree;26462647return$tree;2648}26492650=head2 getlog26512652=cut26532654sub getlog2655{2656my$self=shift;2657my$filename=shift;26582659my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2660$db_query->execute($filename);26612662my$tree= [];2663while(my$file=$db_query->fetchrow_hashref)2664{2665push@$tree,$file;2666}26672668return$tree;2669}26702671=head2 getmeta26722673This function takes a filename (with path) argument and returns a hashref of2674metadata for that file.26752676=cut26772678sub getmeta2679{2680my$self=shift;2681my$filename=shift;2682my$revision=shift;26832684my$db_query;2685if(defined($revision)and$revision=~/^\d+$/)2686{2687$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2688$db_query->execute($filename,$revision);2689}2690elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2691{2692$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2693$db_query->execute($filename,$revision);2694}else{2695$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2696$db_query->execute($filename);2697}26982699return$db_query->fetchrow_hashref;2700}27012702=head2 commitmessage27032704this function takes a commithash and returns the commit message for that commit27052706=cut2707sub commitmessage2708{2709my$self=shift;2710my$commithash=shift;27112712die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);27132714my$db_query;2715$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2716$db_query->execute($commithash);27172718my($message) =$db_query->fetchrow_array;27192720if(defined($message) )2721{2722$message.=" "if($message=~/\n$/);2723return$message;2724}27252726my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2727shift@lineswhile($lines[0] =~/\S/);2728$message=join("",@lines);2729$message.=" "if($message=~/\n$/);2730return$message;2731}27322733=head2 gethistory27342735This function takes a filename (with path) argument and returns an arrayofarrays2736containing revision,filehash,commithash ordered by revision descending27372738=cut2739sub gethistory2740{2741my$self=shift;2742my$filename=shift;27432744my$db_query;2745$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2746$db_query->execute($filename);27472748return$db_query->fetchall_arrayref;2749}27502751=head2 gethistorydense27522753This function takes a filename (with path) argument and returns an arrayofarrays2754containing revision,filehash,commithash ordered by revision descending.27552756This version of gethistory skips deleted entries -- so it is useful for annotate.2757The 'dense' part is a reference to a '--dense' option available for git-rev-list2758and other git tools that depend on it.27592760=cut2761sub gethistorydense2762{2763my$self=shift;2764my$filename=shift;27652766my$db_query;2767$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2768$db_query->execute($filename);27692770return$db_query->fetchall_arrayref;2771}27722773=head2 in_array()27742775from Array::PAT - mimics the in_array() function2776found in PHP. Yuck but works for small arrays.27772778=cut2779sub in_array2780{2781my($check,@array) =@_;2782my$retval=0;2783foreachmy$test(@array){2784if($checkeq$test){2785$retval=1;2786}2787}2788return$retval;2789}27902791=head2 safe_pipe_capture27922793an alternative to `command` that allows input to be passed as an array2794to work around shell problems with weird characters in arguments27952796=cut2797sub safe_pipe_capture {27982799my@output;28002801if(my$pid=open my$child,'-|') {2802@output= (<$child>);2803close$childor die join(' ',@_).":$!$?";2804}else{2805exec(@_)or die"$!$?";# exec() can fail the executable can't be found2806}2807returnwantarray?@output:join('',@output);2808}2809281028111;