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-repo-config -l`; 176if($?) { 177print"E problems executing git-repo-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-repo-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) 880{ 881$log->info("Tell the client the file will be added"); 882print"MT text A\n"; 883print"MT fname$filename\n"; 884print"MT newline\n"; 885next; 886 887} 888else{ 889$log->info("Updating '$filename'$wrev"); 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 my$lockfile= "$state->{CVSROOT}/refs/heads/$state->{module}.lock";1035 unless ( sysopen(LOCKFILE,$lockfile,O_EXCL|O_CREAT|O_WRONLY) )1036 {1037$log->warn("lockfile '$lockfile' already exists, please try again");1038 print "error 1 Lock file '$lockfile' already exists, please try again\n";1039 exit;1040 }10411042 # Grab a handle to the SQLite db and do any necessary updates1043 my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1044$updater->update();10451046 my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1047 my ( undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN => 0 );1048$log->info("Lock successful, basing commit on '$tmpdir', index file is '$file_index'");10491050$ENV{GIT_DIR} =$state->{CVSROOT} . "/";1051$ENV{GIT_INDEX_FILE} =$file_index;10521053 chdir$tmpdir;10541055 # populate the temporary index based1056 system("git-read-tree",$state->{module});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$?");106210631064 my@committedfiles= ();10651066 # foreach file specified on the command line ...1067 foreach my$filename( @{$state->{args}} )1068 {1069 my$committedfile=$filename;1070$filename= filecleanup($filename);10711072 next unless ( exists$state->{entries}{$filename}{modified_filename} or not$state->{entries}{$filename}{unchanged} );10731074 my$meta=$updater->getmeta($filename);10751076 my$wrev= revparse($filename);10771078 my ($filepart,$dirpart) = filenamesplit($filename);10791080 # do a checkout of the file if it part of this tree1081 if ($wrev) {1082 system('git-checkout-index', '-f', '-u',$filename);1083 unless ($?== 0) {1084 die "Error running git-checkout-index -f -u$filename:$!";1085 }1086 }10871088 my$addflag= 0;1089 my$rmflag= 0;1090$rmflag= 1 if ( defined($wrev) and$wrev< 0 );1091$addflag= 1 unless ( -e$filename);10921093 # Do up to date checking1094 unless ($addflagor$wrev==$meta->{revision} or ($rmflagand -$wrev==$meta->{revision} ) )1095 {1096 # fail everything if an up to date check fails1097 print "error 1 Up to date check failed for$filename\n";1098 close LOCKFILE;1099 unlink($lockfile);1100 chdir "/";1101 exit;1102 }11031104 push@committedfiles,$committedfile;1105$log->info("Committing$filename");11061107 system("mkdir","-p",$dirpart) unless ( -d$dirpart);11081109 unless ($rmflag)1110 {1111$log->debug("rename$state->{entries}{$filename}{modified_filename}$filename");1112 rename$state->{entries}{$filename}{modified_filename},$filename;11131114 # Calculate modes to remove1115 my$invmode= "";1116 foreach ( qw (r w x) ) {$invmode.=$_unless ($state->{entries}{$filename}{modified_mode} =~ /$_/); }11171118$log->debug("chmod u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode. "$filename");1119 system("chmod","u+" .$state->{entries}{$filename}{modified_mode} . "-" .$invmode,$filename);1120 }11211122 if ($rmflag)1123 {1124$log->info("Removing file '$filename'");1125 unlink($filename);1126 system("git-update-index", "--remove",$filename);1127 }1128 elsif ($addflag)1129 {1130$log->info("Adding file '$filename'");1131 system("git-update-index", "--add",$filename);1132 } else {1133$log->info("Updating file '$filename'");1134 system("git-update-index",$filename);1135 }1136 }11371138 unless ( scalar(@committedfiles) > 0 )1139 {1140 print "E No files to commit\n";1141 print "ok\n";1142 close LOCKFILE;1143 unlink($lockfile);1144 chdir "/";1145 return;1146 }11471148 my$treehash= `git-write-tree`;1149 my$parenthash= `cat $ENV{GIT_DIR}refs/heads/$state->{module}`;1150 chomp$treehash;1151 chomp$parenthash;11521153$log->debug("Treehash :$treehash, Parenthash :$parenthash");11541155 # write our commit message out if we have one ...1156 my ($msg_fh,$msg_filename) = tempfile( DIR =>$TEMP_DIR);1157 print$msg_fh$state->{opt}{m};# if ( exists ($state->{opt}{m} ) );1158 print$msg_fh"\n\nvia git-CVS emulator\n";1159 close$msg_fh;11601161 my$commithash= `git-commit-tree $treehash-p $parenthash<$msg_filename`;1162$log->info("Commit hash :$commithash");11631164unless($commithash=~/[a-zA-Z0-9]{40}/)1165{1166$log->warn("Commit failed (Invalid commit hash)");1167print"error 1 Commit failed (unknown reason)\n";1168close LOCKFILE;1169unlink($lockfile);1170chdir"/";1171exit;1172}11731174print LOCKFILE $commithash;11751176$updater->update();11771178# foreach file specified on the command line ...1179foreachmy$filename(@committedfiles)1180{1181$filename= filecleanup($filename);11821183my$meta=$updater->getmeta($filename);1184unless(defined$meta->{revision}) {1185$meta->{revision} =1;1186}11871188my($filepart,$dirpart) = filenamesplit($filename,1);11891190$log->debug("Checked-in$dirpart:$filename");11911192if(defined$meta->{filehash} &&$meta->{filehash}eq"deleted")1193{1194print"Remove-entry$dirpart\n";1195print"$filename\n";1196}else{1197print"Checked-in$dirpart\n";1198print"$filename\n";1199print"/$filepart/1.$meta->{revision}///\n";1200}1201}12021203close LOCKFILE;1204my$reffile="$ENV{GIT_DIR}refs/heads/$state->{module}";1205unlink($reffile);1206rename($lockfile,$reffile);1207chdir"/";12081209print"ok\n";1210}12111212sub req_status1213{1214my($cmd,$data) =@_;12151216 argsplit("status");12171218$log->info("req_status : ". (defined($data) ?$data:"[NULL]"));1219#$log->debug("status state : " . Dumper($state));12201221# Grab a handle to the SQLite db and do any necessary updates1222my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1223$updater->update();12241225# if no files were specified, we need to work out what files we should be providing status on ...1226 argsfromdir($updater);12271228# foreach file specified on the command line ...1229foreachmy$filename( @{$state->{args}} )1230{1231$filename= filecleanup($filename);12321233my$meta=$updater->getmeta($filename);1234my$oldmeta=$meta;12351236my$wrev= revparse($filename);12371238# If the working copy is an old revision, lets get that version too for comparison.1239if(defined($wrev)and$wrev!=$meta->{revision} )1240{1241$oldmeta=$updater->getmeta($filename,$wrev);1242}12431244# TODO : All possible statuses aren't yet implemented1245my$status;1246# Files are up to date if the working copy and repo copy have the same revision, and the working copy is unmodified1247$status="Up-to-date"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}1248and1249( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1250or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta->{filehash} ) )1251);12521253# Need checkout if the working copy has an older revision than the repo copy, and the working copy is unmodified1254$status||="Needs Checkout"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrev1255and1256($state->{entries}{$filename}{unchanged}1257or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$oldmeta->{filehash} ) )1258);12591260# Need checkout if it exists in the repo but doesn't have a working copy1261$status||="Needs Checkout"if(not defined($wrev)and defined($meta->{revision} ) );12621263# Locally modified if working copy and repo copy have the same revision but there are local changes1264$status||="Locally Modified"if(defined($wrev)and defined($meta->{revision})and$wrev==$meta->{revision}and$state->{entries}{$filename}{modified_filename} );12651266# Needs Merge if working copy revision is less than repo copy and there are local changes1267$status||="Needs Merge"if(defined($wrev)and defined($meta->{revision} )and$meta->{revision} >$wrevand$state->{entries}{$filename}{modified_filename} );12681269$status||="Locally Added"if(defined($state->{entries}{$filename}{revision} )and not defined($meta->{revision} ) );1270$status||="Locally Removed"if(defined($wrev)and defined($meta->{revision} )and-$wrev==$meta->{revision} );1271$status||="Unresolved Conflict"if(defined($state->{entries}{$filename}{conflict} )and$state->{entries}{$filename}{conflict} =~/^\+=/);1272$status||="File had conflicts on merge"if(0);12731274$status||="Unknown";12751276print"M ===================================================================\n";1277print"M File:$filename\tStatus:$status\n";1278if(defined($state->{entries}{$filename}{revision}) )1279{1280print"M Working revision:\t".$state->{entries}{$filename}{revision} ."\n";1281}else{1282print"M Working revision:\tNo entry for$filename\n";1283}1284if(defined($meta->{revision}) )1285{1286print"M Repository revision:\t1.".$meta->{revision} ."\t$state->{repository}/$filename,v\n";1287print"M Sticky Tag:\t\t(none)\n";1288print"M Sticky Date:\t\t(none)\n";1289print"M Sticky Options:\t\t(none)\n";1290}else{1291print"M Repository revision:\tNo revision control file\n";1292}1293print"M\n";1294}12951296print"ok\n";1297}12981299sub req_diff1300{1301my($cmd,$data) =@_;13021303 argsplit("diff");13041305$log->debug("req_diff : ". (defined($data) ?$data:"[NULL]"));1306#$log->debug("status state : " . Dumper($state));13071308my($revision1,$revision2);1309if(defined($state->{opt}{r} )and ref$state->{opt}{r}eq"ARRAY")1310{1311$revision1=$state->{opt}{r}[0];1312$revision2=$state->{opt}{r}[1];1313}else{1314$revision1=$state->{opt}{r};1315}13161317$revision1=~s/^1\.//if(defined($revision1) );1318$revision2=~s/^1\.//if(defined($revision2) );13191320$log->debug("Diffing revisions ". (defined($revision1) ?$revision1:"[NULL]") ." and ". (defined($revision2) ?$revision2:"[NULL]") );13211322# Grab a handle to the SQLite db and do any necessary updates1323my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1324$updater->update();13251326# if no files were specified, we need to work out what files we should be providing status on ...1327 argsfromdir($updater);13281329# foreach file specified on the command line ...1330foreachmy$filename( @{$state->{args}} )1331{1332$filename= filecleanup($filename);13331334my($fh,$file1,$file2,$meta1,$meta2,$filediff);13351336my$wrev= revparse($filename);13371338# We need _something_ to diff against1339next unless(defined($wrev) );13401341# if we have a -r switch, use it1342if(defined($revision1) )1343{1344(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1345$meta1=$updater->getmeta($filename,$revision1);1346unless(defined($meta1)and$meta1->{filehash}ne"deleted")1347{1348print"E File$filenameat revision 1.$revision1doesn't exist\n";1349next;1350}1351 transmitfile($meta1->{filehash},$file1);1352}1353# otherwise we just use the working copy revision1354else1355{1356(undef,$file1) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1357$meta1=$updater->getmeta($filename,$wrev);1358 transmitfile($meta1->{filehash},$file1);1359}13601361# if we have a second -r switch, use it too1362if(defined($revision2) )1363{1364(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1365$meta2=$updater->getmeta($filename,$revision2);13661367unless(defined($meta2)and$meta2->{filehash}ne"deleted")1368{1369print"E File$filenameat revision 1.$revision2doesn't exist\n";1370next;1371}13721373 transmitfile($meta2->{filehash},$file2);1374}1375# otherwise we just use the working copy1376else1377{1378$file2=$state->{entries}{$filename}{modified_filename};1379}13801381# if we have been given -r, and we don't have a $file2 yet, lets get one1382if(defined($revision1)and not defined($file2) )1383{1384(undef,$file2) = tempfile( DIR =>$TEMP_DIR, OPEN =>0);1385$meta2=$updater->getmeta($filename,$wrev);1386 transmitfile($meta2->{filehash},$file2);1387}13881389# We need to have retrieved something useful1390next unless(defined($meta1) );13911392# Files to date if the working copy and repo copy have the same revision, and the working copy is unmodified1393next if(not defined($meta2)and$wrev==$meta1->{revision}1394and1395( ($state->{entries}{$filename}{unchanged}and(not defined($state->{entries}{$filename}{conflict} )or$state->{entries}{$filename}{conflict} !~/^\+=/) )1396or(defined($state->{entries}{$filename}{modified_hash})and$state->{entries}{$filename}{modified_hash}eq$meta1->{filehash} ) )1397);13981399# Apparently we only show diffs for locally modified files1400next unless(defined($meta2)or defined($state->{entries}{$filename}{modified_filename} ) );14011402print"M Index:$filename\n";1403print"M ===================================================================\n";1404print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1405print"M retrieving revision 1.$meta1->{revision}\n"if(defined($meta1) );1406print"M retrieving revision 1.$meta2->{revision}\n"if(defined($meta2) );1407print"M diff ";1408foreachmy$opt(keys%{$state->{opt}} )1409{1410if(ref$state->{opt}{$opt}eq"ARRAY")1411{1412foreachmy$value( @{$state->{opt}{$opt}} )1413{1414print"-$opt$value";1415}1416}else{1417print"-$opt";1418print"$state->{opt}{$opt} "if(defined($state->{opt}{$opt} ) );1419}1420}1421print"$filename\n";14221423$log->info("Diffing$filename-r$meta1->{revision} -r ". ($meta2->{revision}or"workingcopy"));14241425($fh,$filediff) = tempfile ( DIR =>$TEMP_DIR);14261427if(exists$state->{opt}{u} )1428{1429system("diff -u -L '$filenamerevision 1.$meta1->{revision}' -L '$filename". (defined($meta2->{revision}) ?"revision 1.$meta2->{revision}":"working copy") ."'$file1$file2>$filediff");1430}else{1431system("diff$file1$file2>$filediff");1432}14331434while( <$fh> )1435{1436print"M$_";1437}1438close$fh;1439}14401441print"ok\n";1442}14431444sub req_log1445{1446my($cmd,$data) =@_;14471448 argsplit("log");14491450$log->debug("req_log : ". (defined($data) ?$data:"[NULL]"));1451#$log->debug("log state : " . Dumper($state));14521453my($minrev,$maxrev);1454if(defined($state->{opt}{r} )and$state->{opt}{r} =~/([\d.]+)?(::?)([\d.]+)?/)1455{1456my$control=$2;1457$minrev=$1;1458$maxrev=$3;1459$minrev=~s/^1\.//if(defined($minrev) );1460$maxrev=~s/^1\.//if(defined($maxrev) );1461$minrev++if(defined($minrev)and$controleq"::");1462}14631464# Grab a handle to the SQLite db and do any necessary updates1465my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1466$updater->update();14671468# if no files were specified, we need to work out what files we should be providing status on ...1469 argsfromdir($updater);14701471# foreach file specified on the command line ...1472foreachmy$filename( @{$state->{args}} )1473{1474$filename= filecleanup($filename);14751476my$headmeta=$updater->getmeta($filename);14771478my$revisions=$updater->getlog($filename);1479my$totalrevisions=scalar(@$revisions);14801481if(defined($minrev) )1482{1483$log->debug("Removing revisions less than$minrev");1484while(scalar(@$revisions) >0and$revisions->[-1]{revision} <$minrev)1485{1486pop@$revisions;1487}1488}1489if(defined($maxrev) )1490{1491$log->debug("Removing revisions greater than$maxrev");1492while(scalar(@$revisions) >0and$revisions->[0]{revision} >$maxrev)1493{1494shift@$revisions;1495}1496}14971498next unless(scalar(@$revisions) );14991500print"M\n";1501print"M RCS file:$state->{CVSROOT}/$state->{module}/$filename,v\n";1502print"M Working file:$filename\n";1503print"M head: 1.$headmeta->{revision}\n";1504print"M branch:\n";1505print"M locks: strict\n";1506print"M access list:\n";1507print"M symbolic names:\n";1508print"M keyword substitution: kv\n";1509print"M total revisions:$totalrevisions;\tselected revisions: ".scalar(@$revisions) ."\n";1510print"M description:\n";15111512foreachmy$revision(@$revisions)1513{1514print"M ----------------------------\n";1515print"M revision 1.$revision->{revision}\n";1516# reformat the date for log output1517$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}) );1518$revision->{author} =~s/\s+.*//;1519$revision->{author} =~s/^(.{8}).*/$1/;1520print"M date:$revision->{modified}; author:$revision->{author}; state: ". ($revision->{filehash}eq"deleted"?"dead":"Exp") ."; lines: +2 -3\n";1521my$commitmessage=$updater->commitmessage($revision->{commithash});1522$commitmessage=~s/^/M /mg;1523print$commitmessage."\n";1524}1525print"M =============================================================================\n";1526}15271528print"ok\n";1529}15301531sub req_annotate1532{1533my($cmd,$data) =@_;15341535 argsplit("annotate");15361537$log->info("req_annotate : ". (defined($data) ?$data:"[NULL]"));1538#$log->debug("status state : " . Dumper($state));15391540# Grab a handle to the SQLite db and do any necessary updates1541my$updater= GITCVS::updater->new($state->{CVSROOT},$state->{module},$log);1542$updater->update();15431544# if no files were specified, we need to work out what files we should be providing annotate on ...1545 argsfromdir($updater);15461547# we'll need a temporary checkout dir1548my$tmpdir= tempdir ( DIR =>$TEMP_DIR);1549my(undef,$file_index) = tempfile ( DIR =>$TEMP_DIR, OPEN =>0);1550$log->info("Temp checkoutdir creation successful, basing annotate session work on '$tmpdir', index file is '$file_index'");15511552$ENV{GIT_DIR} =$state->{CVSROOT} ."/";1553$ENV{GIT_INDEX_FILE} =$file_index;15541555chdir$tmpdir;15561557# foreach file specified on the command line ...1558foreachmy$filename( @{$state->{args}} )1559{1560$filename= filecleanup($filename);15611562my$meta=$updater->getmeta($filename);15631564next unless($meta->{revision} );15651566# get all the commits that this file was in1567# in dense format -- aka skip dead revisions1568my$revisions=$updater->gethistorydense($filename);1569my$lastseenin=$revisions->[0][2];15701571# populate the temporary index based on the latest commit were we saw1572# the file -- but do it cheaply without checking out any files1573# TODO: if we got a revision from the client, use that instead1574# to look up the commithash in sqlite (still good to default to1575# the current head as we do now)1576system("git-read-tree",$lastseenin);1577unless($?==0)1578{1579die"Error running git-read-tree$lastseenin$file_index$!";1580}1581$log->info("Created index '$file_index' with commit$lastseenin- exit status$?");15821583# do a checkout of the file1584system('git-checkout-index','-f','-u',$filename);1585unless($?==0) {1586die"Error running git-checkout-index -f -u$filename:$!";1587}15881589$log->info("Annotate$filename");15901591# Prepare a file with the commits from the linearized1592# history that annotate should know about. This prevents1593# git-jsannotate telling us about commits we are hiding1594# from the client.15951596open(ANNOTATEHINTS,">$tmpdir/.annotate_hints")or die"Error opening >$tmpdir/.annotate_hints$!";1597for(my$i=0;$i<@$revisions;$i++)1598{1599print ANNOTATEHINTS $revisions->[$i][2];1600if($i+1<@$revisions) {# have we got a parent?1601print ANNOTATEHINTS ' '.$revisions->[$i+1][2];1602}1603print ANNOTATEHINTS "\n";1604}16051606print ANNOTATEHINTS "\n";1607close ANNOTATEHINTS;16081609my$annotatecmd='git-annotate';1610open(ANNOTATE,"-|",$annotatecmd,'-l','-S',"$tmpdir/.annotate_hints",$filename)1611or die"Error invoking$annotatecmd-l -S$tmpdir/.annotate_hints$filename:$!";1612my$metadata= {};1613print"E Annotations for$filename\n";1614print"E ***************\n";1615while( <ANNOTATE> )1616{1617if(m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)1618{1619my$commithash=$1;1620my$data=$2;1621unless(defined($metadata->{$commithash} ) )1622{1623$metadata->{$commithash} =$updater->getmeta($filename,$commithash);1624$metadata->{$commithash}{author} =~s/\s+.*//;1625$metadata->{$commithash}{author} =~s/^(.{8}).*/$1/;1626$metadata->{$commithash}{modified} =sprintf("%02d-%s-%02d",$1,$2,$3)if($metadata->{$commithash}{modified} =~/^(\d+)\s(\w+)\s\d\d(\d\d)/);1627}1628printf("M 1.%-5d (%-8s%10s):%s\n",1629$metadata->{$commithash}{revision},1630$metadata->{$commithash}{author},1631$metadata->{$commithash}{modified},1632$data1633);1634}else{1635$log->warn("Error in annotate output! LINE:$_");1636print"E Annotate error\n";1637next;1638}1639}1640close ANNOTATE;1641}16421643# done; get out of the tempdir1644chdir"/";16451646print"ok\n";16471648}16491650# This method takes the state->{arguments} array and produces two new arrays.1651# The first is $state->{args} which is everything before the '--' argument, and1652# the second is $state->{files} which is everything after it.1653sub argsplit1654{1655return unless(defined($state->{arguments})and ref$state->{arguments}eq"ARRAY");16561657my$type=shift;16581659$state->{args} = [];1660$state->{files} = [];1661$state->{opt} = {};16621663if(defined($type) )1664{1665my$opt= {};1666$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");1667$opt= { v =>0, l =>0, R =>0}if($typeeq"status");1668$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");1669$opt= { l =>0, R =>0, k =>1, D =>1, D =>1, r =>2}if($typeeq"diff");1670$opt= { c =>0, R =>0, l =>0, f =>0, F =>1, m =>1, r =>1}if($typeeq"ci");1671$opt= { k =>1, m =>1}if($typeeq"add");1672$opt= { f =>0, l =>0, R =>0}if($typeeq"remove");1673$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");167416751676while(scalar( @{$state->{arguments}} ) >0)1677{1678my$arg=shift@{$state->{arguments}};16791680next if($argeq"--");1681next unless($arg=~/\S/);16821683# if the argument looks like a switch1684if($arg=~/^-(\w)(.*)/)1685{1686# if it's a switch that takes an argument1687if($opt->{$1} )1688{1689# If this switch has already been provided1690if($opt->{$1} >1and exists($state->{opt}{$1} ) )1691{1692$state->{opt}{$1} = [$state->{opt}{$1} ];1693if(length($2) >0)1694{1695push@{$state->{opt}{$1}},$2;1696}else{1697push@{$state->{opt}{$1}},shift@{$state->{arguments}};1698}1699}else{1700# if there's extra data in the arg, use that as the argument for the switch1701if(length($2) >0)1702{1703$state->{opt}{$1} =$2;1704}else{1705$state->{opt}{$1} =shift@{$state->{arguments}};1706}1707}1708}else{1709$state->{opt}{$1} =undef;1710}1711}1712else1713{1714push@{$state->{args}},$arg;1715}1716}1717}1718else1719{1720my$mode=0;17211722foreachmy$value( @{$state->{arguments}} )1723{1724if($valueeq"--")1725{1726$mode++;1727next;1728}1729push@{$state->{args}},$valueif($mode==0);1730push@{$state->{files}},$valueif($mode==1);1731}1732}1733}17341735# This method uses $state->{directory} to populate $state->{args} with a list of filenames1736sub argsfromdir1737{1738my$updater=shift;17391740$state->{args} = []if(scalar(@{$state->{args}}) ==1and$state->{args}[0]eq".");17411742return if(scalar( @{$state->{args}} ) >1);17431744my@gethead= @{$updater->gethead};17451746# push added files1747foreachmy$file(keys%{$state->{entries}}) {1748if(exists$state->{entries}{$file}{revision} &&1749$state->{entries}{$file}{revision} ==0)1750{1751push@gethead, { name =>$file, filehash =>'added'};1752}1753}17541755if(scalar(@{$state->{args}}) ==1)1756{1757my$arg=$state->{args}[0];1758$arg.=$state->{prependdir}if(defined($state->{prependdir} ) );17591760$log->info("Only one arg specified, checking for directory expansion on '$arg'");17611762foreachmy$file(@gethead)1763{1764next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1765next unless($file->{name} =~/^$arg\//or$file->{name}eq$arg);1766push@{$state->{args}},$file->{name};1767}17681769shift@{$state->{args}}if(scalar(@{$state->{args}}) >1);1770}else{1771$log->info("Only one arg specified, populating file list automatically");17721773$state->{args} = [];17741775foreachmy$file(@gethead)1776{1777next if($file->{filehash}eq"deleted"and not defined($state->{entries}{$file->{name}} ) );1778next unless($file->{name} =~s/^$state->{prependdir}//);1779push@{$state->{args}},$file->{name};1780}1781}1782}17831784# This method cleans up the $state variable after a command that uses arguments has run1785sub statecleanup1786{1787$state->{files} = [];1788$state->{args} = [];1789$state->{arguments} = [];1790$state->{entries} = {};1791}17921793sub revparse1794{1795my$filename=shift;17961797returnundefunless(defined($state->{entries}{$filename}{revision} ) );17981799return$1if($state->{entries}{$filename}{revision} =~/^1\.(\d+)/);1800return-$1if($state->{entries}{$filename}{revision} =~/^-1\.(\d+)/);18011802returnundef;1803}18041805# This method takes a file hash and does a CVS "file transfer" which transmits the1806# size of the file, and then the file contents.1807# If a second argument $targetfile is given, the file is instead written out to1808# a file by the name of $targetfile1809sub transmitfile1810{1811my$filehash=shift;1812my$targetfile=shift;18131814if(defined($filehash)and$filehasheq"deleted")1815{1816$log->warn("filehash is 'deleted'");1817return;1818}18191820die"Need filehash"unless(defined($filehash)and$filehash=~/^[a-zA-Z0-9]{40}$/);18211822my$type=`git-cat-file -t$filehash`;1823 chomp$type;18241825 die ( "Invalid type '$type' (expected 'blob')" ) unless ( defined ($type) and$typeeq "blob" );18261827 my$size= `git-cat-file -s $filehash`;1828chomp$size;18291830$log->debug("transmitfile($filehash) size=$size, type=$type");18311832if(open my$fh,'-|',"git-cat-file","blob",$filehash)1833{1834if(defined($targetfile) )1835{1836open NEWFILE,">",$targetfileor die("Couldn't open '$targetfile' for writing :$!");1837print NEWFILE $_while( <$fh> );1838close NEWFILE;1839}else{1840print"$size\n";1841printwhile( <$fh> );1842}1843close$fhor die("Couldn't close filehandle for transmitfile()");1844}else{1845die("Couldn't execute git-cat-file");1846}1847}18481849# This method takes a file name, and returns ( $dirpart, $filepart ) which1850# refers to the directory portion and the file portion of the filename1851# respectively1852sub filenamesplit1853{1854my$filename=shift;1855my$fixforlocaldir=shift;18561857my($filepart,$dirpart) = ($filename,".");1858($filepart,$dirpart) = ($2,$1)if($filename=~/(.*)\/(.*)/ );1859$dirpart.="/";18601861if($fixforlocaldir)1862{1863$dirpart=~s/^$state->{prependdir}//;1864}18651866return($filepart,$dirpart);1867}18681869sub filecleanup1870{1871my$filename=shift;18721873returnundefunless(defined($filename));1874if($filename=~/^\// )1875{1876print"E absolute filenames '$filename' not supported by server\n";1877returnundef;1878}18791880$filename=~s/^\.\///g;1881$filename=$state->{prependdir} .$filename;1882return$filename;1883}18841885package GITCVS::log;18861887####1888#### Copyright The Open University UK - 2006.1889####1890#### Authors: Martyn Smith <martyn@catalyst.net.nz>1891#### Martin Langhoff <martin@catalyst.net.nz>1892####1893####18941895use strict;1896use warnings;18971898=head1 NAME18991900GITCVS::log19011902=head1 DESCRIPTION19031904This module provides very crude logging with a similar interface to1905Log::Log4perl19061907=head1 METHODS19081909=cut19101911=head2 new19121913Creates a new log object, optionally you can specify a filename here to1914indicate the file to log to. If no log file is specified, you can specify one1915later with method setfile, or indicate you no longer want logging with method1916nofile.19171918Until one of these methods is called, all log calls will buffer messages ready1919to write out.19201921=cut1922sub new1923{1924my$class=shift;1925my$filename=shift;19261927my$self= {};19281929bless$self,$class;19301931if(defined($filename) )1932{1933open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1934}19351936return$self;1937}19381939=head2 setfile19401941This methods takes a filename, and attempts to open that file as the log file.1942If successful, all buffered data is written out to the file, and any further1943logging is written directly to the file.19441945=cut1946sub setfile1947{1948my$self=shift;1949my$filename=shift;19501951if(defined($filename) )1952{1953open$self->{fh},">>",$filenameor die("Couldn't open '$filename' for writing :$!");1954}19551956return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19571958while(my$line=shift@{$self->{buffer}} )1959{1960print{$self->{fh}}$line;1961}1962}19631964=head2 nofile19651966This method indicates no logging is going to be used. It flushes any entries in1967the internal buffer, and sets a flag to ensure no further data is put there.19681969=cut1970sub nofile1971{1972my$self=shift;19731974$self->{nolog} =1;19751976return unless(defined($self->{buffer} )and ref$self->{buffer}eq"ARRAY");19771978$self->{buffer} = [];1979}19801981=head2 _logopen19821983Internal method. Returns true if the log file is open, false otherwise.19841985=cut1986sub _logopen1987{1988my$self=shift;19891990return1if(defined($self->{fh} )and ref$self->{fh}eq"GLOB");1991return0;1992}19931994=head2 debug info warn fatal19951996These four methods are wrappers to _log. They provide the actual interface for1997logging data.19981999=cut2000sub debug {my$self=shift;$self->_log("debug",@_); }2001sub info {my$self=shift;$self->_log("info",@_); }2002subwarn{my$self=shift;$self->_log("warn",@_); }2003sub fatal {my$self=shift;$self->_log("fatal",@_); }20042005=head2 _log20062007This is an internal method called by the logging functions. It generates a2008timestamp and pushes the logged line either to file, or internal buffer.20092010=cut2011sub _log2012{2013my$self=shift;2014my$level=shift;20152016return if($self->{nolog} );20172018my@time=localtime;2019my$timestring=sprintf("%4d-%02d-%02d%02d:%02d:%02d: %-5s",2020$time[5] +1900,2021$time[4] +1,2022$time[3],2023$time[2],2024$time[1],2025$time[0],2026uc$level,2027);20282029if($self->_logopen)2030{2031print{$self->{fh}}$timestring." - ".join(" ",@_) ."\n";2032}else{2033push@{$self->{buffer}},$timestring." - ".join(" ",@_) ."\n";2034}2035}20362037=head2 DESTROY20382039This method simply closes the file handle if one is open20402041=cut2042sub DESTROY2043{2044my$self=shift;20452046if($self->_logopen)2047{2048close$self->{fh};2049}2050}20512052package GITCVS::updater;20532054####2055#### Copyright The Open University UK - 2006.2056####2057#### Authors: Martyn Smith <martyn@catalyst.net.nz>2058#### Martin Langhoff <martin@catalyst.net.nz>2059####2060####20612062use strict;2063use warnings;2064use DBI;20652066=head1 METHODS20672068=cut20692070=head2 new20712072=cut2073sub new2074{2075my$class=shift;2076my$config=shift;2077my$module=shift;2078my$log=shift;20792080die"Need to specify a git repository"unless(defined($config)and-d $config);2081die"Need to specify a module"unless(defined($module) );20822083$class=ref($class) ||$class;20842085my$self= {};20862087bless$self,$class;20882089$self->{dbdir} =$config."/";2090die"Database dir '$self->{dbdir}' isn't a directory"unless(defined($self->{dbdir})and-d $self->{dbdir} );20912092$self->{module} =$module;2093$self->{file} =$self->{dbdir} ."/gitcvs.$module.sqlite";20942095$self->{git_path} =$config."/";20962097$self->{log} =$log;20982099die"Git repo '$self->{git_path}' doesn't exist"unless( -d $self->{git_path} );21002101$self->{dbh} = DBI->connect("dbi:SQLite:dbname=".$self->{file},"","");21022103$self->{tables} = {};2104foreachmy$table($self->{dbh}->tables)2105{2106$table=~s/^"//;2107$table=~s/"$//;2108$self->{tables}{$table} =1;2109}21102111# Construct the revision table if required2112unless($self->{tables}{revision} )2113{2114$self->{dbh}->do("2115 CREATE TABLE revision (2116 name TEXT NOT NULL,2117 revision INTEGER NOT NULL,2118 filehash TEXT NOT NULL,2119 commithash TEXT NOT NULL,2120 author TEXT NOT NULL,2121 modified TEXT NOT NULL,2122 mode TEXT NOT NULL2123 )2124 ");2125$self->{dbh}->do("2126 CREATE INDEX revision_ix12127 ON revision (name,revision)2128 ");2129$self->{dbh}->do("2130 CREATE INDEX revision_ix22131 ON revision (name,commithash)2132 ");2133}21342135# Construct the head table if required2136unless($self->{tables}{head} )2137{2138$self->{dbh}->do("2139 CREATE TABLE head (2140 name TEXT NOT NULL,2141 revision INTEGER NOT NULL,2142 filehash TEXT NOT NULL,2143 commithash TEXT NOT NULL,2144 author TEXT NOT NULL,2145 modified TEXT NOT NULL,2146 mode TEXT NOT NULL2147 )2148 ");2149$self->{dbh}->do("2150 CREATE INDEX head_ix12151 ON head (name)2152 ");2153}21542155# Construct the properties table if required2156unless($self->{tables}{properties} )2157{2158$self->{dbh}->do("2159 CREATE TABLE properties (2160 key TEXT NOT NULL PRIMARY KEY,2161 value TEXT2162 )2163 ");2164}21652166# Construct the commitmsgs table if required2167unless($self->{tables}{commitmsgs} )2168{2169$self->{dbh}->do("2170 CREATE TABLE commitmsgs (2171 key TEXT NOT NULL PRIMARY KEY,2172 value TEXT2173 )2174 ");2175}21762177return$self;2178}21792180=head2 update21812182=cut2183sub update2184{2185my$self=shift;21862187# first lets get the commit list2188$ENV{GIT_DIR} =$self->{git_path};21892190my$commitsha1=`git rev-parse$self->{module}`;2191chomp$commitsha1;21922193my$commitinfo=`git cat-file commit$self->{module} 2>&1`;2194unless($commitinfo=~/tree\s+[a-zA-Z0-9]{40}/)2195{2196die("Invalid module '$self->{module}'");2197}219821992200my$git_log;2201my$lastcommit=$self->_get_prop("last_commit");22022203if(defined$lastcommit&&$lastcommiteq$commitsha1) {# up-to-date2204return1;2205}22062207# Start exclusive lock here...2208$self->{dbh}->begin_work()or die"Cannot lock database for BEGIN";22092210# TODO: log processing is memory bound2211# if we can parse into a 2nd file that is in reverse order2212# we can probably do something really efficient2213my@git_log_params= ('--pretty','--parents','--topo-order');22142215if(defined$lastcommit) {2216push@git_log_params,"$lastcommit..$self->{module}";2217}else{2218push@git_log_params,$self->{module};2219}2220# git-rev-list is the backend / plumbing version of git-log2221open(GITLOG,'-|','git-rev-list',@git_log_params)or die"Cannot call git-rev-list:$!";22222223my@commits;22242225my%commit= ();22262227while( <GITLOG> )2228{2229chomp;2230if(m/^commit\s+(.*)$/) {2231# on ^commit lines put the just seen commit in the stack2232# and prime things for the next one2233if(keys%commit) {2234my%copy=%commit;2235unshift@commits, \%copy;2236%commit= ();2237}2238my@parents=split(m/\s+/,$1);2239$commit{hash} =shift@parents;2240$commit{parents} = \@parents;2241}elsif(m/^(\w+?):\s+(.*)$/&& !exists($commit{message})) {2242# on rfc822-like lines seen before we see any message,2243# lowercase the entry and put it in the hash as key-value2244$commit{lc($1)} =$2;2245}else{2246# message lines - skip initial empty line2247# and trim whitespace2248if(!exists($commit{message}) &&m/^\s*$/) {2249# define it to mark the end of headers2250$commit{message} ='';2251next;2252}2253s/^\s+//;s/\s+$//;# trim ws2254$commit{message} .=$_."\n";2255}2256}2257close GITLOG;22582259unshift@commits, \%commitif(keys%commit);22602261# Now all the commits are in the @commits bucket2262# ordered by time DESC. for each commit that needs processing,2263# determine whether it's following the last head we've seen or if2264# it's on its own branch, grab a file list, and add whatever's changed2265# NOTE: $lastcommit refers to the last commit from previous run2266# $lastpicked is the last commit we picked in this run2267my$lastpicked;2268my$head= {};2269if(defined$lastcommit) {2270$lastpicked=$lastcommit;2271}22722273my$committotal=scalar(@commits);2274my$commitcount=0;22752276# Load the head table into $head (for cached lookups during the update process)2277foreachmy$file( @{$self->gethead()} )2278{2279$head->{$file->{name}} =$file;2280}22812282foreachmy$commit(@commits)2283{2284$self->{log}->debug("GITCVS::updater - Processing commit$commit->{hash} (". (++$commitcount) ." of$committotal)");2285if(defined$lastpicked)2286{2287if(!in_array($lastpicked, @{$commit->{parents}}))2288{2289# skip, we'll see this delta2290# as part of a merge later2291# warn "skipping off-track $commit->{hash}\n";2292next;2293}elsif(@{$commit->{parents}} >1) {2294# it is a merge commit, for each parent that is2295# not $lastpicked, see if we can get a log2296# from the merge-base to that parent to put it2297# in the message as a merge summary.2298my@parents= @{$commit->{parents}};2299foreachmy$parent(@parents) {2300# git-merge-base can potentially (but rarely) throw2301# several candidate merge bases. let's assume2302# that the first one is the best one.2303if($parenteq$lastpicked) {2304next;2305}2306open my$p,'git-merge-base '.$lastpicked.' '2307.$parent.'|';2308my@output= (<$p>);2309close$p;2310my$base=join('',@output);2311chomp$base;2312if($base) {2313my@merged;2314# print "want to log between $base $parent \n";2315open(GITLOG,'-|','git-log',"$base..$parent")2316or die"Cannot call git-log:$!";2317my$mergedhash;2318while(<GITLOG>) {2319chomp;2320if(!defined$mergedhash) {2321if(m/^commit\s+(.+)$/) {2322$mergedhash=$1;2323}else{2324next;2325}2326}else{2327# grab the first line that looks non-rfc8222328# aka has content after leading space2329if(m/^\s+(\S.*)$/) {2330my$title=$1;2331$title=substr($title,0,100);# truncate2332unshift@merged,"$mergedhash$title";2333undef$mergedhash;2334}2335}2336}2337close GITLOG;2338if(@merged) {2339$commit->{mergemsg} =$commit->{message};2340$commit->{mergemsg} .="\nSummary of merged commits:\n\n";2341foreachmy$summary(@merged) {2342$commit->{mergemsg} .="\t$summary\n";2343}2344$commit->{mergemsg} .="\n\n";2345# print "Message for $commit->{hash} \n$commit->{mergemsg}";2346}2347}2348}2349}2350}23512352# convert the date to CVS-happy format2353$commit->{date} ="$2$1$4$3$5"if($commit->{date} =~/^\w+\s+(\w+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)\s+([+-]\d+)$/);23542355if(defined($lastpicked) )2356{2357my$filepipe=open(FILELIST,'-|','git-diff-tree','-z','-r',$lastpicked,$commit->{hash})or die("Cannot call git-diff-tree :$!");2358local($/) ="\0";2359while( <FILELIST> )2360{2361chomp;2362unless(/^:\d{6}\s+\d{3}(\d)\d{2}\s+[a-zA-Z0-9]{40}\s+([a-zA-Z0-9]{40})\s+(\w)$/o)2363{2364die("Couldn't process git-diff-tree line :$_");2365}2366my($mode,$hash,$change) = ($1,$2,$3);2367my$name= <FILELIST>;2368chomp($name);23692370# $log->debug("File mode=$mode, hash=$hash, change=$change, name=$name");23712372my$git_perms="";2373$git_perms.="r"if($mode&4);2374$git_perms.="w"if($mode&2);2375$git_perms.="x"if($mode&1);2376$git_perms="rw"if($git_permseq"");23772378if($changeeq"D")2379{2380#$log->debug("DELETE $name");2381$head->{$name} = {2382 name =>$name,2383 revision =>$head->{$name}{revision} +1,2384 filehash =>"deleted",2385 commithash =>$commit->{hash},2386 modified =>$commit->{date},2387 author =>$commit->{author},2388 mode =>$git_perms,2389};2390$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2391}2392elsif($changeeq"M")2393{2394#$log->debug("MODIFIED $name");2395$head->{$name} = {2396 name =>$name,2397 revision =>$head->{$name}{revision} +1,2398 filehash =>$hash,2399 commithash =>$commit->{hash},2400 modified =>$commit->{date},2401 author =>$commit->{author},2402 mode =>$git_perms,2403};2404$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2405}2406elsif($changeeq"A")2407{2408#$log->debug("ADDED $name");2409$head->{$name} = {2410 name =>$name,2411 revision =>1,2412 filehash =>$hash,2413 commithash =>$commit->{hash},2414 modified =>$commit->{date},2415 author =>$commit->{author},2416 mode =>$git_perms,2417};2418$self->insert_rev($name,$head->{$name}{revision},$hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2419}2420else2421{2422$log->warn("UNKNOWN FILE CHANGE mode=$mode, hash=$hash, change=$change, name=$name");2423die;2424}2425}2426close FILELIST;2427}else{2428# this is used to detect files removed from the repo2429my$seen_files= {};24302431my$filepipe=open(FILELIST,'-|','git-ls-tree','-z','-r',$commit->{hash})or die("Cannot call git-ls-tree :$!");2432local$/="\0";2433while( <FILELIST> )2434{2435chomp;2436unless(/^(\d+)\s+(\w+)\s+([a-zA-Z0-9]+)\t(.*)$/o)2437{2438die("Couldn't process git-ls-tree line :$_");2439}24402441my($git_perms,$git_type,$git_hash,$git_filename) = ($1,$2,$3,$4);24422443$seen_files->{$git_filename} =1;24442445my($oldhash,$oldrevision,$oldmode) = (2446$head->{$git_filename}{filehash},2447$head->{$git_filename}{revision},2448$head->{$git_filename}{mode}2449);24502451if($git_perms=~/^\d\d\d(\d)\d\d/o)2452{2453$git_perms="";2454$git_perms.="r"if($1&4);2455$git_perms.="w"if($1&2);2456$git_perms.="x"if($1&1);2457}else{2458$git_perms="rw";2459}24602461# unless the file exists with the same hash, we need to update it ...2462unless(defined($oldhash)and$oldhasheq$git_hashand defined($oldmode)and$oldmodeeq$git_perms)2463{2464my$newrevision= ($oldrevisionor0) +1;24652466$head->{$git_filename} = {2467 name =>$git_filename,2468 revision =>$newrevision,2469 filehash =>$git_hash,2470 commithash =>$commit->{hash},2471 modified =>$commit->{date},2472 author =>$commit->{author},2473 mode =>$git_perms,2474};247524762477$self->insert_rev($git_filename,$newrevision,$git_hash,$commit->{hash},$commit->{date},$commit->{author},$git_perms);2478}2479}2480close FILELIST;24812482# Detect deleted files2483foreachmy$file(keys%$head)2484{2485unless(exists$seen_files->{$file}or$head->{$file}{filehash}eq"deleted")2486{2487$head->{$file}{revision}++;2488$head->{$file}{filehash} ="deleted";2489$head->{$file}{commithash} =$commit->{hash};2490$head->{$file}{modified} =$commit->{date};2491$head->{$file}{author} =$commit->{author};24922493$self->insert_rev($file,$head->{$file}{revision},$head->{$file}{filehash},$commit->{hash},$commit->{date},$commit->{author},$head->{$file}{mode});2494}2495}2496# END : "Detect deleted files"2497}249824992500if(exists$commit->{mergemsg})2501{2502$self->insert_mergelog($commit->{hash},$commit->{mergemsg});2503}25042505$lastpicked=$commit->{hash};25062507$self->_set_prop("last_commit",$commit->{hash});2508}25092510$self->delete_head();2511foreachmy$file(keys%$head)2512{2513$self->insert_head(2514$file,2515$head->{$file}{revision},2516$head->{$file}{filehash},2517$head->{$file}{commithash},2518$head->{$file}{modified},2519$head->{$file}{author},2520$head->{$file}{mode},2521);2522}2523# invalidate the gethead cache2524$self->{gethead_cache} =undef;252525262527# Ending exclusive lock here2528$self->{dbh}->commit()or die"Failed to commit changes to SQLite";2529}25302531sub insert_rev2532{2533my$self=shift;2534my$name=shift;2535my$revision=shift;2536my$filehash=shift;2537my$commithash=shift;2538my$modified=shift;2539my$author=shift;2540my$mode=shift;25412542my$insert_rev=$self->{dbh}->prepare_cached("INSERT INTO revision (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2543$insert_rev->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2544}25452546sub insert_mergelog2547{2548my$self=shift;2549my$key=shift;2550my$value=shift;25512552my$insert_mergelog=$self->{dbh}->prepare_cached("INSERT INTO commitmsgs (key, value) VALUES (?,?)",{},1);2553$insert_mergelog->execute($key,$value);2554}25552556sub delete_head2557{2558my$self=shift;25592560my$delete_head=$self->{dbh}->prepare_cached("DELETE FROM head",{},1);2561$delete_head->execute();2562}25632564sub insert_head2565{2566my$self=shift;2567my$name=shift;2568my$revision=shift;2569my$filehash=shift;2570my$commithash=shift;2571my$modified=shift;2572my$author=shift;2573my$mode=shift;25742575my$insert_head=$self->{dbh}->prepare_cached("INSERT INTO head (name, revision, filehash, commithash, modified, author, mode) VALUES (?,?,?,?,?,?,?)",{},1);2576$insert_head->execute($name,$revision,$filehash,$commithash,$modified,$author,$mode);2577}25782579sub _headrev2580{2581my$self=shift;2582my$filename=shift;25832584my$db_query=$self->{dbh}->prepare_cached("SELECT filehash, revision, mode FROM head WHERE name=?",{},1);2585$db_query->execute($filename);2586my($hash,$revision,$mode) =$db_query->fetchrow_array;25872588return($hash,$revision,$mode);2589}25902591sub _get_prop2592{2593my$self=shift;2594my$key=shift;25952596my$db_query=$self->{dbh}->prepare_cached("SELECT value FROM properties WHERE key=?",{},1);2597$db_query->execute($key);2598my($value) =$db_query->fetchrow_array;25992600return$value;2601}26022603sub _set_prop2604{2605my$self=shift;2606my$key=shift;2607my$value=shift;26082609my$db_query=$self->{dbh}->prepare_cached("UPDATE properties SET value=? WHERE key=?",{},1);2610$db_query->execute($value,$key);26112612unless($db_query->rows)2613{2614$db_query=$self->{dbh}->prepare_cached("INSERT INTO properties (key, value) VALUES (?,?)",{},1);2615$db_query->execute($key,$value);2616}26172618return$value;2619}26202621=head2 gethead26222623=cut26242625sub gethead2626{2627my$self=shift;26282629return$self->{gethead_cache}if(defined($self->{gethead_cache} ) );26302631my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, mode, revision, modified, commithash, author FROM head ORDER BY name ASC",{},1);2632$db_query->execute();26332634my$tree= [];2635while(my$file=$db_query->fetchrow_hashref)2636{2637push@$tree,$file;2638}26392640$self->{gethead_cache} =$tree;26412642return$tree;2643}26442645=head2 getlog26462647=cut26482649sub getlog2650{2651my$self=shift;2652my$filename=shift;26532654my$db_query=$self->{dbh}->prepare_cached("SELECT name, filehash, author, mode, revision, modified, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2655$db_query->execute($filename);26562657my$tree= [];2658while(my$file=$db_query->fetchrow_hashref)2659{2660push@$tree,$file;2661}26622663return$tree;2664}26652666=head2 getmeta26672668This function takes a filename (with path) argument and returns a hashref of2669metadata for that file.26702671=cut26722673sub getmeta2674{2675my$self=shift;2676my$filename=shift;2677my$revision=shift;26782679my$db_query;2680if(defined($revision)and$revision=~/^\d+$/)2681{2682$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND revision=?",{},1);2683$db_query->execute($filename,$revision);2684}2685elsif(defined($revision)and$revision=~/^[a-zA-Z0-9]{40}$/)2686{2687$db_query=$self->{dbh}->prepare_cached("SELECT * FROM revision WHERE name=? AND commithash=?",{},1);2688$db_query->execute($filename,$revision);2689}else{2690$db_query=$self->{dbh}->prepare_cached("SELECT * FROM head WHERE name=?",{},1);2691$db_query->execute($filename);2692}26932694return$db_query->fetchrow_hashref;2695}26962697=head2 commitmessage26982699this function takes a commithash and returns the commit message for that commit27002701=cut2702sub commitmessage2703{2704my$self=shift;2705my$commithash=shift;27062707die("Need commithash")unless(defined($commithash)and$commithash=~/^[a-zA-Z0-9]{40}$/);27082709my$db_query;2710$db_query=$self->{dbh}->prepare_cached("SELECT value FROM commitmsgs WHERE key=?",{},1);2711$db_query->execute($commithash);27122713my($message) =$db_query->fetchrow_array;27142715if(defined($message) )2716{2717$message.=" "if($message=~/\n$/);2718return$message;2719}27202721my@lines= safe_pipe_capture("git-cat-file","commit",$commithash);2722shift@lineswhile($lines[0] =~/\S/);2723$message=join("",@lines);2724$message.=" "if($message=~/\n$/);2725return$message;2726}27272728=head2 gethistory27292730This function takes a filename (with path) argument and returns an arrayofarrays2731containing revision,filehash,commithash ordered by revision descending27322733=cut2734sub gethistory2735{2736my$self=shift;2737my$filename=shift;27382739my$db_query;2740$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? ORDER BY revision DESC",{},1);2741$db_query->execute($filename);27422743return$db_query->fetchall_arrayref;2744}27452746=head2 gethistorydense27472748This function takes a filename (with path) argument and returns an arrayofarrays2749containing revision,filehash,commithash ordered by revision descending.27502751This version of gethistory skips deleted entries -- so it is useful for annotate.2752The 'dense' part is a reference to a '--dense' option available for git-rev-list2753and other git tools that depend on it.27542755=cut2756sub gethistorydense2757{2758my$self=shift;2759my$filename=shift;27602761my$db_query;2762$db_query=$self->{dbh}->prepare_cached("SELECT revision, filehash, commithash FROM revision WHERE name=? AND filehash!='deleted' ORDER BY revision DESC",{},1);2763$db_query->execute($filename);27642765return$db_query->fetchall_arrayref;2766}27672768=head2 in_array()27692770from Array::PAT - mimics the in_array() function2771found in PHP. Yuck but works for small arrays.27722773=cut2774sub in_array2775{2776my($check,@array) =@_;2777my$retval=0;2778foreachmy$test(@array){2779if($checkeq$test){2780$retval=1;2781}2782}2783return$retval;2784}27852786=head2 safe_pipe_capture27872788an alternative to `command` that allows input to be passed as an array2789to work around shell problems with weird characters in arguments27902791=cut2792sub safe_pipe_capture {27932794my@output;27952796if(my$pid=open my$child,'-|') {2797@output= (<$child>);2798close$childor die join(' ',@_).":$!$?";2799}else{2800exec(@_)or die"$!$?";# exec() can fail the executable can't be found2801}2802returnwantarray?@output:join('',@output);2803}2804280528061;