Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 5109 lines (4361 sloc) 162.359 kB
#!/usr/bin/perl
####
#### This application is a CVS emulation layer for git.
#### It is intended for clients to connect over SSH.
#### See the documentation for more details.
####
#### Copyright The Open University UK - 2006.
####
#### Authors: Martyn Smith <martyn@catalyst.net.nz>
#### Martin Langhoff <martin@laptop.org>
####
####
#### Released under the GNU Public License, version 2.
####
####
use 5.008;
use strict;
use warnings;
use bytes;
use Fcntl;
use File::Temp qw/tempdir tempfile/;
use File::Path qw/rmtree/;
use File::Basename;
use Getopt::Long qw(:config require_order no_ignore_case);
my $VERSION = '@@GIT_VERSION@@';
my $log = GITCVS::log->new();
my $cfg;
my $DATE_LIST = {
Jan => "01",
Feb => "02",
Mar => "03",
Apr => "04",
May => "05",
Jun => "06",
Jul => "07",
Aug => "08",
Sep => "09",
Oct => "10",
Nov => "11",
Dec => "12",
};
# Enable autoflush for STDOUT (otherwise the whole thing falls apart)
$| = 1;
#### Definition and mappings of functions ####
# NOTE: Despite the existence of req_CATCHALL and req_EMPTY unimplemented
# requests, this list is incomplete. It is missing many rarer/optional
# requests. Perhaps some clients require a claim of support for
# these specific requests for main functionality to work?
my $methods = {
'Root' => \&req_Root,
'Valid-responses' => \&req_Validresponses,
'valid-requests' => \&req_validrequests,
'Directory' => \&req_Directory,
'Sticky' => \&req_Sticky,
'Entry' => \&req_Entry,
'Modified' => \&req_Modified,
'Unchanged' => \&req_Unchanged,
'Questionable' => \&req_Questionable,
'Argument' => \&req_Argument,
'Argumentx' => \&req_Argument,
'expand-modules' => \&req_expandmodules,
'add' => \&req_add,
'remove' => \&req_remove,
'co' => \&req_co,
'update' => \&req_update,
'ci' => \&req_ci,
'diff' => \&req_diff,
'log' => \&req_log,
'rlog' => \&req_log,
'tag' => \&req_CATCHALL,
'status' => \&req_status,
'admin' => \&req_CATCHALL,
'history' => \&req_CATCHALL,
'watchers' => \&req_EMPTY,
'editors' => \&req_EMPTY,
'noop' => \&req_EMPTY,
'annotate' => \&req_annotate,
'Global_option' => \&req_Globaloption,
};
##############################################
# $state holds all the bits of information the clients sends us that could
# potentially be useful when it comes to actually _doing_ something.
my $state = { prependdir => '' };
# Work is for managing temporary working directory
my $work =
{
state => undef, # undef, 1 (empty), 2 (with stuff)
workDir => undef,
index => undef,
emptyDir => undef,
tmpDir => undef
};
$log->info("--------------- STARTING -----------------");
my $usage =
"usage: git cvsserver [options] [pserver|server] [<directory> ...]\n".
" --base-path <path> : Prepend to requested CVSROOT\n".
" Can be read from GIT_CVSSERVER_BASE_PATH\n".
" --strict-paths : Don't allow recursing into subdirectories\n".
" --export-all : Don't check for gitcvs.enabled in config\n".
" --version, -V : Print version information and exit\n".
" -h, -H : Print usage information and exit\n".
"\n".
"<directory> ... is a list of allowed directories. If no directories\n".
"are given, all are allowed. This is an additional restriction, gitcvs\n".
"access still needs to be enabled by the gitcvs.enabled config option.\n".
"Alternately, one directory may be specified in GIT_CVSSERVER_ROOT.\n";
my @opts = ( 'h|H', 'version|V',
'base-path=s', 'strict-paths', 'export-all' );
GetOptions( $state, @opts )
or die $usage;
if ($state->{version}) {
print "git-cvsserver version $VERSION\n";
exit;
}
if ($state->{help}) {
print $usage;
exit;
}
my $TEMP_DIR = tempdir( CLEANUP => 1 );
$log->debug("Temporary directory is '$TEMP_DIR'");
$state->{method} = 'ext';
if (@ARGV) {
if ($ARGV[0] eq 'pserver') {
$state->{method} = 'pserver';
shift @ARGV;
} elsif ($ARGV[0] eq 'server') {
shift @ARGV;
}
}
# everything else is a directory
$state->{allowed_roots} = [ @ARGV ];
# don't export the whole system unless the users requests it
if ($state->{'export-all'} && !@{$state->{allowed_roots}}) {
die "--export-all can only be used together with an explicit whitelist\n";
}
# Environment handling for running under git-shell
if (exists $ENV{GIT_CVSSERVER_BASE_PATH}) {
if ($state->{'base-path'}) {
die "Cannot specify base path both ways.\n";
}
my $base_path = $ENV{GIT_CVSSERVER_BASE_PATH};
$state->{'base-path'} = $base_path;
$log->debug("Picked up base path '$base_path' from environment.\n");
}
if (exists $ENV{GIT_CVSSERVER_ROOT}) {
if (@{$state->{allowed_roots}}) {
die "Cannot specify roots both ways: @ARGV\n";
}
my $allowed_root = $ENV{GIT_CVSSERVER_ROOT};
$state->{allowed_roots} = [ $allowed_root ];
$log->debug("Picked up allowed root '$allowed_root' from environment.\n");
}
# if we are called with a pserver argument,
# deal with the authentication cat before entering the
# main loop
if ($state->{method} eq 'pserver') {
my $line = <STDIN>; chomp $line;
unless( $line =~ /^BEGIN (AUTH|VERIFICATION) REQUEST$/) {
die "E Do not understand $line - expecting BEGIN AUTH REQUEST\n";
}
my $request = $1;
$line = <STDIN>; chomp $line;
unless (req_Root('root', $line)) { # reuse Root
print "E Invalid root $line \n";
exit 1;
}
$line = <STDIN>; chomp $line;
my $user = $line;
$line = <STDIN>; chomp $line;
my $password = $line;
if ($user eq 'anonymous') {
# "A" will be 1 byte, use length instead in case the
# encryption method ever changes (yeah, right!)
if (length($password) > 1 ) {
print "E Don't supply a password for the `anonymous' user\n";
print "I HATE YOU\n";
exit 1;
}
# Fall through to LOVE
} else {
# Trying to authenticate a user
if (not exists $cfg->{gitcvs}->{authdb}) {
print "E the repo config file needs a [gitcvs] section with an 'authdb' parameter set to the filename of the authentication database\n";
print "I HATE YOU\n";
exit 1;
}
my $authdb = $cfg->{gitcvs}->{authdb};
unless (-e $authdb) {
print "E The authentication database specified in [gitcvs.authdb] does not exist\n";
print "I HATE YOU\n";
exit 1;
}
my $auth_ok;
open my $passwd, "<", $authdb or die $!;
while (<$passwd>) {
if (m{^\Q$user\E:(.*)}) {
if (crypt($user, descramble($password)) eq $1) {
$auth_ok = 1;
}
};
}
close $passwd;
unless ($auth_ok) {
print "I HATE YOU\n";
exit 1;
}
# Fall through to LOVE
}
# For checking whether the user is anonymous on commit
$state->{user} = $user;
$line = <STDIN>; chomp $line;
unless ($line eq "END $request REQUEST") {
die "E Do not understand $line -- expecting END $request REQUEST\n";
}
print "I LOVE YOU\n";
exit if $request eq 'VERIFICATION'; # cvs login
# and now back to our regular programme...
}
# Keep going until the client closes the connection
while (<STDIN>)
{
chomp;
# Check to see if we've seen this method, and call appropriate function.
if ( /^([\w-]+)(?:\s+(.*))?$/ and defined($methods->{$1}) )
{
# use the $methods hash to call the appropriate sub for this command
#$log->info("Method : $1");
&{$methods->{$1}}($1,$2);
} else {
# log fatal because we don't understand this function. If this happens
# we're fairly screwed because we don't know if the client is expecting
# a response. If it is, the client will hang, we'll hang, and the whole
# thing will be custard.
$log->fatal("Don't understand command $_\n");
die("Unknown command $_");
}
}
$log->debug("Processing time : user=" . (times)[0] . " system=" . (times)[1]);
$log->info("--------------- FINISH -----------------");
chdir '/';
exit 0;
# Magic catchall method.
# This is the method that will handle all commands we haven't yet
# implemented. It simply sends a warning to the log file indicating a
# command that hasn't been implemented has been invoked.
sub req_CATCHALL
{
my ( $cmd, $data ) = @_;
$log->warn("Unhandled command : req_$cmd : $data");
}
# This method invariably succeeds with an empty response.
sub req_EMPTY
{
print "ok\n";
}
# Root pathname \n
# Response expected: no. Tell the server which CVSROOT to use. Note that
# pathname is a local directory and not a fully qualified CVSROOT variable.
# pathname must already exist; if creating a new root, use the init
# request, not Root. pathname does not include the hostname of the server,
# how to access the server, etc.; by the time the CVS protocol is in use,
# connection, authentication, etc., are already taken care of. The Root
# request must be sent only once, and it must be sent before any requests
# other than Valid-responses, valid-requests, UseUnchanged, Set or init.
sub req_Root
{
my ( $cmd, $data ) = @_;
$log->debug("req_Root : $data");
unless ($data =~ m#^/#) {
print "error 1 Root must be an absolute pathname\n";
return 0;
}
my $cvsroot = $state->{'base-path'} || '';
$cvsroot =~ s#/+$##;
$cvsroot .= $data;
if ($state->{CVSROOT}
&& ($state->{CVSROOT} ne $cvsroot)) {
print "error 1 Conflicting roots specified\n";
return 0;
}
$state->{CVSROOT} = $cvsroot;
$ENV{GIT_DIR} = $state->{CVSROOT} . "/";
if (@{$state->{allowed_roots}}) {
my $allowed = 0;
foreach my $dir (@{$state->{allowed_roots}}) {
next unless $dir =~ m#^/#;
$dir =~ s#/+$##;
if ($state->{'strict-paths'}) {
if ($ENV{GIT_DIR} =~ m#^\Q$dir\E/?$#) {
$allowed = 1;
last;
}
} elsif ($ENV{GIT_DIR} =~ m#^\Q$dir\E(/?$|/)#) {
$allowed = 1;
last;
}
}
unless ($allowed) {
print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
print "E \n";
print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
return 0;
}
}
unless (-d $ENV{GIT_DIR} && -e $ENV{GIT_DIR}.'HEAD') {
print "E $ENV{GIT_DIR} does not seem to be a valid GIT repository\n";
print "E \n";
print "error 1 $ENV{GIT_DIR} is not a valid repository\n";
return 0;
}
my @gitvars = `git config -l`;
if ($?) {
print "E problems executing git-config on the server -- this is not a git repository or the PATH is not set correctly.\n";
print "E \n";
print "error 1 - problem executing git-config\n";
return 0;
}
foreach my $line ( @gitvars )
{
next unless ( $line =~ /^(gitcvs)\.(?:(ext|pserver)\.)?([\w-]+)=(.*)$/ );
unless ($2) {
$cfg->{$1}{$3} = $4;
} else {
$cfg->{$1}{$2}{$3} = $4;
}
}
my $enabled = ($cfg->{gitcvs}{$state->{method}}{enabled}
|| $cfg->{gitcvs}{enabled});
unless ($state->{'export-all'} ||
($enabled && $enabled =~ /^\s*(1|true|yes)\s*$/i)) {
print "E GITCVS emulation needs to be enabled on this repo\n";
print "E the repo config file needs a [gitcvs] section added, and the parameter 'enabled' set to 1\n";
print "E \n";
print "error 1 GITCVS emulation disabled\n";
return 0;
}
my $logfile = $cfg->{gitcvs}{$state->{method}}{logfile} || $cfg->{gitcvs}{logfile};
if ( $logfile )
{
$log->setfile($logfile);
} else {
$log->nofile();
}
return 1;
}
# Global_option option \n
# Response expected: no. Transmit one of the global options `-q', `-Q',
# `-l', `-t', `-r', or `-n'. option must be one of those strings, no
# variations (such as combining of options) are allowed. For graceful
# handling of valid-requests, it is probably better to make new global
# options separate requests, rather than trying to add them to this
# request.
sub req_Globaloption
{
my ( $cmd, $data ) = @_;
$log->debug("req_Globaloption : $data");
$state->{globaloptions}{$data} = 1;
}
# Valid-responses request-list \n
# Response expected: no. Tell the server what responses the client will
# accept. request-list is a space separated list of tokens.
sub req_Validresponses
{
my ( $cmd, $data ) = @_;
$log->debug("req_Validresponses : $data");
# TODO : re-enable this, currently it's not particularly useful
#$state->{validresponses} = [ split /\s+/, $data ];
}
# valid-requests \n
# Response expected: yes. Ask the server to send back a Valid-requests
# response.
sub req_validrequests
{
my ( $cmd, $data ) = @_;
$log->debug("req_validrequests");
$log->debug("SEND : Valid-requests " . join(" ",sort keys %$methods));
$log->debug("SEND : ok");
print "Valid-requests " . join(" ",sort keys %$methods) . "\n";
print "ok\n";
}
# Directory local-directory \n
# Additional data: repository \n. Response expected: no. Tell the server
# what directory to use. The repository should be a directory name from a
# previous server response. Note that this both gives a default for Entry
# and Modified and also for ci and the other commands; normal usage is to
# send Directory for each directory in which there will be an Entry or
# Modified, and then a final Directory for the original directory, then the
# command. The local-directory is relative to the top level at which the
# command is occurring (i.e. the last Directory which is sent before the
# command); to indicate that top level, `.' should be sent for
# local-directory.
sub req_Directory
{
my ( $cmd, $data ) = @_;
my $repository = <STDIN>;
chomp $repository;
$state->{localdir} = $data;
$state->{repository} = $repository;
$state->{path} = $repository;
$state->{path} =~ s/^\Q$state->{CVSROOT}\E\///;
$state->{module} = $1 if ($state->{path} =~ s/^(.*?)(\/|$)//);
$state->{path} .= "/" if ( $state->{path} =~ /\S/ );
$state->{directory} = $state->{localdir};
$state->{directory} = "" if ( $state->{directory} eq "." );
$state->{directory} .= "/" if ( $state->{directory} =~ /\S/ );
if ( (not defined($state->{prependdir}) or $state->{prependdir} eq '') and $state->{localdir} eq "." and $state->{path} =~ /\S/ )
{
$log->info("Setting prepend to '$state->{path}'");
$state->{prependdir} = $state->{path};
my %entries;
foreach my $entry ( keys %{$state->{entries}} )
{
$entries{$state->{prependdir} . $entry} = $state->{entries}{$entry};
}
$state->{entries}=\%entries;
my %dirMap;
foreach my $dir ( keys %{$state->{dirMap}} )
{
$dirMap{$state->{prependdir} . $dir} = $state->{dirMap}{$dir};
}
$state->{dirMap}=\%dirMap;
}
if ( defined ( $state->{prependdir} ) )
{
$log->debug("Prepending '$state->{prependdir}' to state|directory");
$state->{directory} = $state->{prependdir} . $state->{directory}
}
if ( ! defined($state->{dirMap}{$state->{directory}}) )
{
$state->{dirMap}{$state->{directory}} =
{
'names' => {}
#'tagspec' => undef
};
}
$log->debug("req_Directory : localdir=$data repository=$repository path=$state->{path} directory=$state->{directory} module=$state->{module}");
}
# Sticky tagspec \n
# Response expected: no. Tell the server that the directory most
# recently specified with Directory has a sticky tag or date
# tagspec. The first character of tagspec is T for a tag, D for
# a date, or some other character supplied by a Set-sticky
# response from a previous request to the server. The remainder
# of tagspec contains the actual tag or date, again as supplied
# by Set-sticky.
# The server should remember Static-directory and Sticky requests
# for a particular directory; the client need not resend them each
# time it sends a Directory request for a given directory. However,
# the server is not obliged to remember them beyond the context
# of a single command.
sub req_Sticky
{
my ( $cmd, $tagspec ) = @_;
my ( $stickyInfo );
if($tagspec eq "")
{
# nothing
}
elsif($tagspec=~/^T([^ ]+)\s*$/)
{
$stickyInfo = { 'tag' => $1 };
}
elsif($tagspec=~/^D([0-9.]+)\s*$/)
{
$stickyInfo= { 'date' => $1 };
}
else
{
die "Unknown tag_or_date format\n";
}
$state->{dirMap}{$state->{directory}}{stickyInfo}=$stickyInfo;
$log->debug("req_Sticky : tagspec=$tagspec repository=$state->{repository}"
. " path=$state->{path} directory=$state->{directory}"
. " module=$state->{module}");
}
# Entry entry-line \n
# Response expected: no. Tell the server what version of a file is on the
# local machine. The name in entry-line is a name relative to the directory
# most recently specified with Directory. If the user is operating on only
# some files in a directory, Entry requests for only those files need be
# included. If an Entry request is sent without Modified, Is-modified, or
# Unchanged, it means the file is lost (does not exist in the working
# directory). If both Entry and one of Modified, Is-modified, or Unchanged
# are sent for the same file, Entry must be sent first. For a given file,
# one can send Modified, Is-modified, or Unchanged, but not more than one
# of these three.
sub req_Entry
{
my ( $cmd, $data ) = @_;
#$log->debug("req_Entry : $data");
my @data = split(/\//, $data, -1);
$state->{entries}{$state->{directory}.$data[1]} = {
revision => $data[2],
conflict => $data[3],
options => $data[4],
tag_or_date => $data[5],
};
$state->{dirMap}{$state->{directory}}{names}{$data[1]} = 'F';
$log->info("Received entry line '$data' => '" . $state->{directory} . $data[1] . "'");
}
# Questionable filename \n
# Response expected: no. Additional data: no. Tell the server to check
# whether filename should be ignored, and if not, next time the server
# sends responses, send (in a M response) `?' followed by the directory and
# filename. filename must not contain `/'; it needs to be a file in the
# directory named by the most recent Directory request.
sub req_Questionable
{
my ( $cmd, $data ) = @_;
$log->debug("req_Questionable : $data");
$state->{entries}{$state->{directory}.$data}{questionable} = 1;
}
# add \n
# Response expected: yes. Add a file or directory. This uses any previous
# Argument, Directory, Entry, or Modified requests, if they have been sent.
# The last Directory sent specifies the working directory at the time of
# the operation. To add a directory, send the directory to be added using
# Directory and Argument requests.
sub req_add
{
my ( $cmd, $data ) = @_;
argsplit("add");
my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
my $addcount = 0;
foreach my $filename ( @{$state->{args}} )
{
$filename = filecleanup($filename);
# no -r, -A, or -D with add
my $stickyInfo = resolveStickyInfo($filename);
my $meta = $updater->getmeta($filename,$stickyInfo);
my $wrev = revparse($filename);
if ($wrev && $meta && ($wrev=~/^-/))
{
# previously removed file, add back
$log->info("added file $filename was previously removed, send $meta->{revision}");
print "MT +updated\n";
print "MT text U \n";
print "MT fname $filename\n";
print "MT newline\n";
print "MT -updated\n";
unless ( $state->{globaloptions}{-n} )
{
my ( $filepart, $dirpart ) = filenamesplit($filename,1);
print "Created $dirpart\n";
print $state->{CVSROOT} . "/$state->{module}/$filename\n";
# this is an "entries" line
my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
my $entryLine = "/$filepart/$meta->{revision}//$kopts/";
$entryLine .= getStickyTagOrDate($stickyInfo);
$log->debug($entryLine);
print "$entryLine\n";
# permissions
$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
# transmit file
transmitfile($meta->{filehash});
}
next;
}
unless ( defined ( $state->{entries}{$filename}{modified_filename} ) )
{
print "E cvs add: nothing known about `$filename'\n";
next;
}
# TODO : check we're not squashing an already existing file
if ( defined ( $state->{entries}{$filename}{revision} ) )
{
print "E cvs add: `$filename' has already been entered\n";
next;
}
my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
print "E cvs add: scheduling file `$filename' for addition\n";
print "Checked-in $dirpart\n";
print "$filename\n";
my $kopts = kopts_from_path($filename,"file",
$state->{entries}{$filename}{modified_filename});
print "/$filepart/0//$kopts/" .
getStickyTagOrDate($stickyInfo) . "\n";
my $requestedKopts = $state->{opt}{k};
if(defined($requestedKopts))
{
$requestedKopts = "-k$requestedKopts";
}
else
{
$requestedKopts = "";
}
if( $kopts ne $requestedKopts )
{
$log->warn("Ignoring requested -k='$requestedKopts'"
. " for '$filename'; detected -k='$kopts' instead");
#TODO: Also have option to send warning to user?
}
$addcount++;
}
if ( $addcount == 1 )
{
print "E cvs add: use `cvs commit' to add this file permanently\n";
}
elsif ( $addcount > 1 )
{
print "E cvs add: use `cvs commit' to add these files permanently\n";
}
print "ok\n";
}
# remove \n
# Response expected: yes. Remove a file. This uses any previous Argument,
# Directory, Entry, or Modified requests, if they have been sent. The last
# Directory sent specifies the working directory at the time of the
# operation. Note that this request does not actually do anything to the
# repository; the only effect of a successful remove request is to supply
# the client with a new entries line containing `-' to indicate a removed
# file. In fact, the client probably could perform this operation without
# contacting the server, although using remove may cause the server to
# perform a few more checks. The client sends a subsequent ci request to
# actually record the removal in the repository.
sub req_remove
{
my ( $cmd, $data ) = @_;
argsplit("remove");
# Grab a handle to the SQLite db and do any necessary updates
my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
#$log->debug("add state : " . Dumper($state));
my $rmcount = 0;
foreach my $filename ( @{$state->{args}} )
{
$filename = filecleanup($filename);
if ( defined ( $state->{entries}{$filename}{unchanged} ) or defined ( $state->{entries}{$filename}{modified_filename} ) )
{
print "E cvs remove: file `$filename' still in working directory\n";
next;
}
# only from entries
my $stickyInfo = resolveStickyInfo($filename);
my $meta = $updater->getmeta($filename,$stickyInfo);
my $wrev = revparse($filename);
unless ( defined ( $wrev ) )
{
print "E cvs remove: nothing known about `$filename'\n";
next;
}
if ( defined($wrev) and ($wrev=~/^-/) )
{
print "E cvs remove: file `$filename' already scheduled for removal\n";
next;
}
unless ( $wrev eq $meta->{revision} )
{
# TODO : not sure if the format of this message is quite correct.
print "E cvs remove: Up to date check failed for `$filename'\n";
next;
}
my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
print "E cvs remove: scheduling `$filename' for removal\n";
print "Checked-in $dirpart\n";
print "$filename\n";
my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
print "/$filepart/-$wrev//$kopts/" . getStickyTagOrDate($stickyInfo) . "\n";
$rmcount++;
}
if ( $rmcount == 1 )
{
print "E cvs remove: use `cvs commit' to remove this file permanently\n";
}
elsif ( $rmcount > 1 )
{
print "E cvs remove: use `cvs commit' to remove these files permanently\n";
}
print "ok\n";
}
# Modified filename \n
# Response expected: no. Additional data: mode, \n, file transmission. Send
# the server a copy of one locally modified file. filename is a file within
# the most recent directory sent with Directory; it must not contain `/'.
# If the user is operating on only some files in a directory, only those
# files need to be included. This can also be sent without Entry, if there
# is no entry for the file.
sub req_Modified
{
my ( $cmd, $data ) = @_;
my $mode = <STDIN>;
defined $mode
or (print "E end of file reading mode for $data\n"), return;
chomp $mode;
my $size = <STDIN>;
defined $size
or (print "E end of file reading size of $data\n"), return;
chomp $size;
# Grab config information
my $blocksize = 8192;
my $bytesleft = $size;
my $tmp;
# Get a filehandle/name to write it to
my ( $fh, $filename ) = tempfile( DIR => $TEMP_DIR );
# Loop over file data writing out to temporary file.
while ( $bytesleft )
{
$blocksize = $bytesleft if ( $bytesleft < $blocksize );
read STDIN, $tmp, $blocksize;
print $fh $tmp;
$bytesleft -= $blocksize;
}
close $fh
or (print "E failed to write temporary, $filename: $!\n"), return;
# Ensure we have something sensible for the file mode
if ( $mode =~ /u=(\w+)/ )
{
$mode = $1;
} else {
$mode = "rw";
}
# Save the file data in $state
$state->{entries}{$state->{directory}.$data}{modified_filename} = $filename;
$state->{entries}{$state->{directory}.$data}{modified_mode} = $mode;
$state->{entries}{$state->{directory}.$data}{modified_hash} = `git hash-object $filename`;
$state->{entries}{$state->{directory}.$data}{modified_hash} =~ s/\s.*$//s;
#$log->debug("req_Modified : file=$data mode=$mode size=$size");
}
# Unchanged filename \n
# Response expected: no. Tell the server that filename has not been
# modified in the checked out directory. The filename is a file within the
# most recent directory sent with Directory; it must not contain `/'.
sub req_Unchanged
{
my ( $cmd, $data ) = @_;
$state->{entries}{$state->{directory}.$data}{unchanged} = 1;
#$log->debug("req_Unchanged : $data");
}
# Argument text \n
# Response expected: no. Save argument for use in a subsequent command.
# Arguments accumulate until an argument-using command is given, at which
# point they are forgotten.
# Argumentx text \n
# Response expected: no. Append \n followed by text to the current argument
# being saved.
sub req_Argument
{
my ( $cmd, $data ) = @_;
# Argumentx means: append to last Argument (with a newline in front)
$log->debug("$cmd : $data");
if ( $cmd eq 'Argumentx') {
${$state->{arguments}}[$#{$state->{arguments}}] .= "\n" . $data;
} else {
push @{$state->{arguments}}, $data;
}
}
# expand-modules \n
# Response expected: yes. Expand the modules which are specified in the
# arguments. Returns the data in Module-expansion responses. Note that the
# server can assume that this is checkout or export, not rtag or rdiff; the
# latter do not access the working directory and thus have no need to
# expand modules on the client side. Expand may not be the best word for
# what this request does. It does not necessarily tell you all the files
# contained in a module, for example. Basically it is a way of telling you
# which working directories the server needs to know about in order to
# handle a checkout of the specified modules. For example, suppose that the
# server has a module defined by
# aliasmodule -a 1dir
# That is, one can check out aliasmodule and it will take 1dir in the
# repository and check it out to 1dir in the working directory. Now suppose
# the client already has this module checked out and is planning on using
# the co request to update it. Without using expand-modules, the client
# would have two bad choices: it could either send information about all
# working directories under the current directory, which could be
# unnecessarily slow, or it could be ignorant of the fact that aliasmodule
# stands for 1dir, and neglect to send information for 1dir, which would
# lead to incorrect operation. With expand-modules, the client would first
# ask for the module to be expanded:
sub req_expandmodules
{
my ( $cmd, $data ) = @_;
argsplit();
$log->debug("req_expandmodules : " . ( defined($data) ? $data : "[NULL]" ) );
unless ( ref $state->{arguments} eq "ARRAY" )
{
print "ok\n";
return;
}
foreach my $module ( @{$state->{arguments}} )
{
$log->debug("SEND : Module-expansion $module");
print "Module-expansion $module\n";
}
print "ok\n";
statecleanup();
}
# co \n
# Response expected: yes. Get files from the repository. This uses any
# previous Argument, Directory, Entry, or Modified requests, if they have
# been sent. Arguments to this command are module names; the client cannot
# know what directories they correspond to except by (1) just sending the
# co request, and then seeing what directory names the server sends back in
# its responses, and (2) the expand-modules request.
sub req_co
{
my ( $cmd, $data ) = @_;
argsplit("co");
# Provide list of modules, if -c was used.
if (exists $state->{opt}{c}) {
my $showref = `git show-ref --heads`;
for my $line (split '\n', $showref) {
if ( $line =~ m% refs/heads/(.*)$% ) {
print "M $1\t$1\n";
}
}
print "ok\n";
return 1;
}
my $stickyInfo = { 'tag' => $state->{opt}{r},
'date' => $state->{opt}{D} };
my $module = $state->{args}[0];
$state->{module} = $module;
my $checkout_path = $module;
# use the user specified directory if we're given it
$checkout_path = $state->{opt}{d} if ( exists ( $state->{opt}{d} ) );
$log->debug("req_co : " . ( defined($data) ? $data : "[NULL]" ) );
$log->info("Checking out module '$module' ($state->{CVSROOT}) to '$checkout_path'");
$ENV{GIT_DIR} = $state->{CVSROOT} . "/";
# Grab a handle to the SQLite db and do any necessary updates
my $updater = GITCVS::updater->new($state->{CVSROOT}, $module, $log);
$updater->update();
my $headHash;
if( defined($stickyInfo) && defined($stickyInfo->{tag}) )
{
$headHash = $updater->lookupCommitRef($stickyInfo->{tag});
if( !defined($headHash) )
{
print "error 1 no such tag `$stickyInfo->{tag}'\n";
cleanupWorkTree();
exit;
}
}
$checkout_path =~ s|/$||; # get rid of trailing slashes
my %seendirs = ();
my $lastdir ='';
prepDirForOutput(
".",
$state->{CVSROOT} . "/$module",
$checkout_path,
\%seendirs,
'checkout',
$state->{dirArgs} );
foreach my $git ( @{$updater->getAnyHead($headHash)} )
{
# Don't want to check out deleted files
next if ( $git->{filehash} eq "deleted" );
my $fullName = $git->{name};
( $git->{name}, $git->{dir} ) = filenamesplit($git->{name});
unless (exists($seendirs{$git->{dir}})) {
prepDirForOutput($git->{dir}, $state->{CVSROOT} . "/$module/",
$checkout_path, \%seendirs, 'checkout',
$state->{dirArgs} );
$lastdir = $git->{dir};
$seendirs{$git->{dir}} = 1;
}
# modification time of this file
print "Mod-time $git->{modified}\n";
# print some information to the client
if ( defined ( $git->{dir} ) and $git->{dir} ne "./" )
{
print "M U $checkout_path/$git->{dir}$git->{name}\n";
} else {
print "M U $checkout_path/$git->{name}\n";
}
# instruct client we're sending a file to put in this path
print "Created $checkout_path/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "\n";
print $state->{CVSROOT} . "/$module/" . ( defined ( $git->{dir} ) and $git->{dir} ne "./" ? $git->{dir} . "/" : "" ) . "$git->{name}\n";
# this is an "entries" line
my $kopts = kopts_from_path($fullName,"sha1",$git->{filehash});
print "/$git->{name}/$git->{revision}//$kopts/" .
getStickyTagOrDate($stickyInfo) . "\n";
# permissions
print "u=$git->{mode},g=$git->{mode},o=$git->{mode}\n";
# transmit file
transmitfile($git->{filehash});
}
print "ok\n";
statecleanup();
}
# used by req_co and req_update to set up directories for files
# recursively handles parents
sub prepDirForOutput
{
my ($dir, $repodir, $remotedir, $seendirs, $request, $dirArgs) = @_;
my $parent = dirname($dir);
$dir =~ s|/+$||;
$repodir =~ s|/+$||;
$remotedir =~ s|/+$||;
$parent =~ s|/+$||;
if ($parent eq '.' || $parent eq './')
{
$parent = '';
}
# recurse to announce unseen parents first
if( length($parent) &&
!exists($seendirs->{$parent}) &&
( $request eq "checkout" ||
exists($dirArgs->{$parent}) ) )
{
prepDirForOutput($parent, $repodir, $remotedir,
$seendirs, $request, $dirArgs);
}
# Announce that we are going to modify at the parent level
if ($dir eq '.' || $dir eq './')
{
$dir = '';
}
if(exists($seendirs->{$dir}))
{
return;
}
$log->debug("announcedir $dir, $repodir, $remotedir" );
my($thisRemoteDir,$thisRepoDir);
if ($dir ne "")
{
$thisRepoDir="$repodir/$dir";
if($remotedir eq ".")
{
$thisRemoteDir=$dir;
}
else
{
$thisRemoteDir="$remotedir/$dir";
}
}
else
{
$thisRepoDir=$repodir;
$thisRemoteDir=$remotedir;
}
unless ( $state->{globaloptions}{-Q} || $state->{globaloptions}{-q} )
{
print "E cvs $request: Updating $thisRemoteDir\n";
}
my ($opt_r)=$state->{opt}{r};
my $stickyInfo;
if(exists($state->{opt}{A}))
{
# $stickyInfo=undef;
}
elsif( defined($opt_r) && $opt_r ne "" )
# || ( defined($state->{opt}{D}) && $state->{opt}{D} ne "" ) # TODO
{
$stickyInfo={ 'tag' => (defined($opt_r)?$opt_r:undef) };
# TODO: Convert -D value into the form 2011.04.10.04.46.57,
# similar to an entry line's sticky date, without the D prefix.
# It sometimes (always?) arrives as something more like
# '10 Apr 2011 04:46:57 -0000'...
# $stickyInfo={ 'date' => (defined($stickyDate)?$stickyDate:undef) };
}
else
{
$stickyInfo=getDirStickyInfo($state->{prependdir} . $dir);
}
my $stickyResponse;
if(defined($stickyInfo))
{
$stickyResponse = "Set-sticky $thisRemoteDir/\n" .
"$thisRepoDir/\n" .
getStickyTagOrDate($stickyInfo) . "\n";
}
else
{
$stickyResponse = "Clear-sticky $thisRemoteDir/\n" .
"$thisRepoDir/\n";
}
unless ( $state->{globaloptions}{-n} )
{
print $stickyResponse;
print "Clear-static-directory $thisRemoteDir/\n";
print "$thisRepoDir/\n";
print $stickyResponse; # yes, twice
print "Template $thisRemoteDir/\n";
print "$thisRepoDir/\n";
print "0\n";
}
$seendirs->{$dir} = 1;
# FUTURE: This would more accurately emulate CVS by sending
# another copy of sticky after processing the files in that
# directory. Or intermediate: perhaps send all sticky's for
# $seendirs after after processing all files.
}
# update \n
# Response expected: yes. Actually do a cvs update command. This uses any
# previous Argument, Directory, Entry, or Modified requests, if they have
# been sent. The last Directory sent specifies the working directory at the
# time of the operation. The -I option is not used--files which the client
# can decide whether to ignore are not mentioned and the client sends the
# Questionable request for others.
sub req_update
{
my ( $cmd, $data ) = @_;
$log->debug("req_update : " . ( defined($data) ? $data : "[NULL]" ));
argsplit("update");
#
# It may just be a client exploring the available heads/modules
# in that case, list them as top level directories and leave it
# at that. Eclipse uses this technique to offer you a list of
# projects (heads in this case) to checkout.
#
if ($state->{module} eq '') {
my $showref = `git show-ref --heads`;
print "E cvs update: Updating .\n";
for my $line (split '\n', $showref) {
if ( $line =~ m% refs/heads/(.*)$% ) {
print "E cvs update: New directory `$1'\n";
}
}
print "ok\n";
return 1;
}
# Grab a handle to the SQLite db and do any necessary updates
my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
argsfromdir($updater);
#$log->debug("update state : " . Dumper($state));
my($repoDir);
$repoDir=$state->{CVSROOT} . "/$state->{module}/$state->{prependdir}";
my %seendirs = ();
# foreach file specified on the command line ...
foreach my $argsFilename ( @{$state->{args}} )
{
my $filename;
$filename = filecleanup($argsFilename);
$log->debug("Processing file $filename");
# if we have a -C we should pretend we never saw modified stuff
if ( exists ( $state->{opt}{C} ) )
{
delete $state->{entries}{$filename}{modified_hash};
delete $state->{entries}{$filename}{modified_filename};
$state->{entries}{$filename}{unchanged} = 1;
}
my $stickyInfo = resolveStickyInfo($filename,
$state->{opt}{r},
$state->{opt}{D},
exists($state->{opt}{A}));
my $meta = $updater->getmeta($filename, $stickyInfo);
# If -p was given, "print" the contents of the requested revision.
if ( exists ( $state->{opt}{p} ) ) {
if ( defined ( $meta->{revision} ) ) {
$log->info("Printing '$filename' revision " . $meta->{revision});
transmitfile($meta->{filehash}, { print => 1 });
}
next;
}
# Directories:
prepDirForOutput(
dirname($argsFilename),
$repoDir,
".",
\%seendirs,
"update",
$state->{dirArgs} );
my $wrev = revparse($filename);
if ( ! defined $meta )
{
$meta = {
name => $filename,
revision => '0',
filehash => 'added'
};
if($wrev ne "0")
{
$meta->{filehash}='deleted';
}
}
my $oldmeta = $meta;
# If the working copy is an old revision, lets get that version too for comparison.
my $oldWrev=$wrev;
if(defined($oldWrev))
{
$oldWrev=~s/^-//;
if($oldWrev ne $meta->{revision})
{
$oldmeta = $updater->getmeta($filename, $oldWrev);
}
}
#$log->debug("Target revision is $meta->{revision}, current working revision is $wrev");
# Files are up to date if the working copy and repo copy have the same revision,
# and the working copy is unmodified _and_ the user hasn't specified -C
next if ( defined ( $wrev )
and defined($meta->{revision})
and $wrev eq $meta->{revision}
and $state->{entries}{$filename}{unchanged}
and not exists ( $state->{opt}{C} ) );
# If the working copy and repo copy have the same revision,
# but the working copy is modified, tell the client it's modified
if ( defined ( $wrev )
and defined($meta->{revision})
and $wrev eq $meta->{revision}
and $wrev ne "0"
and defined($state->{entries}{$filename}{modified_hash})
and not exists ( $state->{opt}{C} ) )
{
$log->info("Tell the client the file is modified");
print "MT text M \n";
print "MT fname $filename\n";
print "MT newline\n";
next;
}
if ( $meta->{filehash} eq "deleted" && $wrev ne "0" )
{
# TODO: If it has been modified in the sandbox, error out
# with the appropriate message, rather than deleting a modified
# file.
my ( $filepart, $dirpart ) = filenamesplit($filename,1);
$log->info("Removing '$filename' from working copy (no longer in the repo)");
print "E cvs update: `$filename' is no longer in the repository\n";
# Don't want to actually _DO_ the update if -n specified
unless ( $state->{globaloptions}{-n} ) {
print "Removed $dirpart\n";
print "$filepart\n";
}
}
elsif ( not defined ( $state->{entries}{$filename}{modified_hash} )
or $state->{entries}{$filename}{modified_hash} eq $oldmeta->{filehash}
or $meta->{filehash} eq 'added' )
{
# normal update, just send the new revision (either U=Update,
# or A=Add, or R=Remove)
if ( defined($wrev) && ($wrev=~/^-/) )
{
$log->info("Tell the client the file is scheduled for removal");
print "MT text R \n";
print "MT fname $filename\n";
print "MT newline\n";
next;
}
elsif ( (!defined($wrev) || $wrev eq '0') &&
(!defined($meta->{revision}) || $meta->{revision} eq '0') )
{
$log->info("Tell the client the file is scheduled for addition");
print "MT text A \n";
print "MT fname $filename\n";
print "MT newline\n";
next;
}
else {
$log->info("UpdatingX3 '$filename' to ".$meta->{revision});
print "MT +updated\n";
print "MT text U \n";
print "MT fname $filename\n";
print "MT newline\n";
print "MT -updated\n";
}
my ( $filepart, $dirpart ) = filenamesplit($filename,1);
# Don't want to actually _DO_ the update if -n specified
unless ( $state->{globaloptions}{-n} )
{
if ( defined ( $wrev ) )
{
# instruct client we're sending a file to put in this path as a replacement
print "Update-existing $dirpart\n";
$log->debug("Updating existing file 'Update-existing $dirpart'");
} else {
# instruct client we're sending a file to put in this path as a new file
$log->debug("Creating new file 'Created $dirpart'");
print "Created $dirpart\n";
}
print $state->{CVSROOT} . "/$state->{module}/$filename\n";
# this is an "entries" line
my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
my $entriesLine = "/$filepart/$meta->{revision}//$kopts/";
$entriesLine .= getStickyTagOrDate($stickyInfo);
$log->debug($entriesLine);
print "$entriesLine\n";
# permissions
$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
# transmit file
transmitfile($meta->{filehash});
}
} else {
my ( $filepart, $dirpart ) = filenamesplit($meta->{name},1);
my $mergeDir = setupTmpDir();
my $file_local = $filepart . ".mine";
my $mergedFile = "$mergeDir/$file_local";
system("ln","-s",$state->{entries}{$filename}{modified_filename}, $file_local);
my $file_old = $filepart . "." . $oldmeta->{revision};
transmitfile($oldmeta->{filehash}, { targetfile => $file_old });
my $file_new = $filepart . "." . $meta->{revision};
transmitfile($meta->{filehash}, { targetfile => $file_new });
# we need to merge with the local changes ( M=successful merge, C=conflict merge )
$log->info("Merging $file_local, $file_old, $file_new");
print "M Merging differences between $oldmeta->{revision} and $meta->{revision} into $filename\n";
$log->debug("Temporary directory for merge is $mergeDir");
my $return = system("git", "merge-file", $file_local, $file_old, $file_new);
$return >>= 8;
cleanupTmpDir();
if ( $return == 0 )
{
$log->info("Merged successfully");
print "M M $filename\n";
$log->debug("Merged $dirpart");
# Don't want to actually _DO_ the update if -n specified
unless ( $state->{globaloptions}{-n} )
{
print "Merged $dirpart\n";
$log->debug($state->{CVSROOT} . "/$state->{module}/$filename");
print $state->{CVSROOT} . "/$state->{module}/$filename\n";
my $kopts = kopts_from_path("$dirpart/$filepart",
"file",$mergedFile);
$log->debug("/$filepart/$meta->{revision}//$kopts/");
my $entriesLine="/$filepart/$meta->{revision}//$kopts/";
$entriesLine .= getStickyTagOrDate($stickyInfo);
print "$entriesLine\n";
}
}
elsif ( $return == 1 )
{
$log->info("Merged with conflicts");
print "E cvs update: conflicts found in $filename\n";
print "M C $filename\n";
# Don't want to actually _DO_ the update if -n specified
unless ( $state->{globaloptions}{-n} )
{
print "Merged $dirpart\n";
print $state->{CVSROOT} . "/$state->{module}/$filename\n";
my $kopts = kopts_from_path("$dirpart/$filepart",
"file",$mergedFile);
my $entriesLine = "/$filepart/$meta->{revision}/+/$kopts/";
$entriesLine .= getStickyTagOrDate($stickyInfo);
print "$entriesLine\n";
}
}
else
{
$log->warn("Merge failed");
next;
}
# Don't want to actually _DO_ the update if -n specified
unless ( $state->{globaloptions}{-n} )
{
# permissions
$log->debug("SEND : u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}");
print "u=$meta->{mode},g=$meta->{mode},o=$meta->{mode}\n";
# transmit file, format is single integer on a line by itself (file
# size) followed by the file contents
# TODO : we should copy files in blocks
my $data = `cat $mergedFile`;
$log->debug("File size : " . length($data));
print length($data) . "\n";
print $data;
}
}
}
# prepDirForOutput() any other existing directories unless they already
# have the right sticky tag:
unless ( $state->{globaloptions}{n} )
{
my $dir;
foreach $dir (keys(%{$state->{dirMap}}))
{
if( ! $seendirs{$dir} &&
exists($state->{dirArgs}{$dir}) )
{
my($oldTag);
$oldTag=$state->{dirMap}{$dir}{tagspec};
unless( ( exists($state->{opt}{A}) &&
defined($oldTag) ) ||
( defined($state->{opt}{r}) &&
( !defined($oldTag) ||
$state->{opt}{r} ne $oldTag ) ) )
# TODO?: OR sticky dir is different...
{
next;
}
prepDirForOutput(
$dir,
$repoDir,
".",
\%seendirs,
'update',
$state->{dirArgs} );
}
# TODO?: Consider sending a final duplicate Sticky response
# to more closely mimic real CVS.
}
}
print "ok\n";
}
sub req_ci
{
my ( $cmd, $data ) = @_;
argsplit("ci");
#$log->debug("State : " . Dumper($state));
$log->info("req_ci : " . ( defined($data) ? $data : "[NULL]" ));
if ( $state->{method} eq 'pserver' and $state->{user} eq 'anonymous' )
{
print "error 1 anonymous user cannot commit via pserver\n";
cleanupWorkTree();
exit;
}
if ( -e $state->{CVSROOT} . "/index" )
{
$log->warn("file 'index' already exists in the git repository");
print "error 1 Index already exists in git repo\n";
cleanupWorkTree();
exit;
}
# Grab a handle to the SQLite db and do any necessary updates
my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
my @committedfiles = ();
my %oldmeta;
my $stickyInfo;
my $branchRef;
my $parenthash;
# foreach file specified on the command line ...
foreach my $filename ( @{$state->{args}} )
{
my $committedfile = $filename;
$filename = filecleanup($filename);
next unless ( exists $state->{entries}{$filename}{modified_filename} or not $state->{entries}{$filename}{unchanged} );
#####
# Figure out which branch and parenthash we are committing
# to, and setup worktree:
# should always come from entries:
my $fileStickyInfo = resolveStickyInfo($filename);
if( !defined($branchRef) )
{
$stickyInfo = $fileStickyInfo;
if( defined($stickyInfo) &&
( defined($stickyInfo->{date}) ||
!defined($stickyInfo->{tag}) ) )
{
print "error 1 cannot commit with sticky date for file `$filename'\n";
cleanupWorkTree();
exit;
}
$branchRef = "refs/heads/$state->{module}";
if ( defined($stickyInfo) && defined($stickyInfo->{tag}) )
{
$branchRef = "refs/heads/$stickyInfo->{tag}";
}
$parenthash = `git show-ref -s $branchRef`;
chomp $parenthash;
if ($parenthash !~ /^[0-9a-f]{40}$/)
{
if ( defined($stickyInfo) && defined($stickyInfo->{tag}) )
{
print "error 1 sticky tag `$stickyInfo->{tag}' for file `$filename' is not a branch\n";
}
else
{
print "error 1 pserver cannot find the current HEAD of module";
}
cleanupWorkTree();
exit;
}
setupWorkTree($parenthash);
$log->info("Lockless commit start, basing commit on '$work->{workDir}', index file is '$work->{index}'");
$log->info("Created index '$work->{index}' for head $state->{module} - exit status $?");
}
elsif( !refHashEqual($stickyInfo,$fileStickyInfo) )
{
#TODO: We could split the cvs commit into multiple
# git commits by distinct stickyTag values, but that
# is lowish priority.
print "error 1 Committing different files to different"
. " branches is not currently supported\n";
cleanupWorkTree();
exit;
}
#####
# Process this file:
my $meta = $updater->getmeta($filename,$stickyInfo);
$oldmeta{$filename} = $meta;
my $wrev = revparse($filename);
my ( $filepart, $dirpart ) = filenamesplit($filename);
# do a checkout of the file if it is part of this tree
if ($wrev) {
system('git', 'checkout-index', '-f', '-u', $filename);
unless ($? == 0) {
die "Error running git-checkout-index -f -u $filename : $!";
}
}
my $addflag = 0;
my $rmflag = 0;
$rmflag = 1 if ( defined($wrev) and ($wrev=~/^-/) );
$addflag = 1 unless ( -e $filename );
# Do up to date checking
unless ( $addflag or $wrev eq $meta->{revision} or
( $rmflag and $wrev eq "-$meta->{revision}" ) )
{
# fail everything if an up to date check fails
print "error 1 Up to date check failed for $filename\n";
cleanupWorkTree();
exit;
}
push @committedfiles, $committedfile;
$log->info("Committing $filename");
system("mkdir","-p",$dirpart) unless ( -d $dirpart );
unless ( $rmflag )
{
$log->debug("rename $state->{entries}{$filename}{modified_filename} $filename");
rename $state->{entries}{$filename}{modified_filename},$filename;
# Calculate modes to remove
my $invmode = "";
foreach ( qw (r w x) ) { $invmode .= $_ unless ( $state->{entries}{$filename}{modified_mode} =~ /$_/ ); }
$log->debug("chmod u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode . " $filename");
system("chmod","u+" . $state->{entries}{$filename}{modified_mode} . "-" . $invmode, $filename);
}
if ( $rmflag )
{
$log->info("Removing file '$filename'");
unlink($filename);
system("git", "update-index", "--remove", $filename);
}
elsif ( $addflag )
{
$log->info("Adding file '$filename'");
system("git", "update-index", "--add", $filename);
} else {
$log->info("UpdatingX2 file '$filename'");
system("git", "update-index", $filename);
}
}
unless ( scalar(@committedfiles) > 0 )
{
print "E No files to commit\n";
print "ok\n";
cleanupWorkTree();
return;
}
my $treehash = `git write-tree`;
chomp $treehash;
$log->debug("Treehash : $treehash, Parenthash : $parenthash");
# write our commit message out if we have one ...
my ( $msg_fh, $msg_filename ) = tempfile( DIR => $TEMP_DIR );
print $msg_fh $state->{opt}{m};# if ( exists ( $state->{opt}{m} ) );
if ( defined ( $cfg->{gitcvs}{commitmsgannotation} ) ) {
if ($cfg->{gitcvs}{commitmsgannotation} !~ /^\s*$/ ) {
print $msg_fh "\n\n".$cfg->{gitcvs}{commitmsgannotation}."\n"
}
} else {
print $msg_fh "\n\nvia git-CVS emulator\n";
}
close $msg_fh;
my $commithash = `git commit-tree $treehash -p $parenthash < $msg_filename`;
chomp($commithash);
$log->info("Commit hash : $commithash");
unless ( $commithash =~ /[a-zA-Z0-9]{40}/ )
{
$log->warn("Commit failed (Invalid commit hash)");
print "error 1 Commit failed (unknown reason)\n";
cleanupWorkTree();
exit;
}
### Emulate git-receive-pack by running hooks/update
my @hook = ( $ENV{GIT_DIR}.'hooks/update', $branchRef,
$parenthash, $commithash );
if( -x $hook[0] ) {
unless( system( @hook ) == 0 )
{
$log->warn("Commit failed (update hook declined to update ref)");
print "error 1 Commit failed (update hook declined)\n";
cleanupWorkTree();
exit;
}
}
### Update the ref
if (system(qw(git update-ref -m), "cvsserver ci",
$branchRef, $commithash, $parenthash)) {
$log->warn("update-ref for $state->{module} failed.");
print "error 1 Cannot commit -- update first\n";
cleanupWorkTree();
exit;
}
### Emulate git-receive-pack by running hooks/post-receive
my $hook = $ENV{GIT_DIR}.'hooks/post-receive';
if( -x $hook ) {
open(my $pipe, "| $hook") || die "can't fork $!";
local $SIG{PIPE} = sub { die 'pipe broke' };
print $pipe "$parenthash $commithash $branchRef\n";
close $pipe || die "bad pipe: $! $?";
}
$updater->update();
### Then hooks/post-update
$hook = $ENV{GIT_DIR}.'hooks/post-update';
if (-x $hook) {
system($hook, $branchRef);
}
# foreach file specified on the command line ...
foreach my $filename ( @committedfiles )
{
$filename = filecleanup($filename);
my $meta = $updater->getmeta($filename,$stickyInfo);
unless (defined $meta->{revision}) {
$meta->{revision} = "1.1";
}
my ( $filepart, $dirpart ) = filenamesplit($filename, 1);
$log->debug("Checked-in $dirpart : $filename");
print "M $state->{CVSROOT}/$state->{module}/$filename,v <-- $dirpart$filepart\n";
if ( defined $meta->{filehash} && $meta->{filehash} eq "deleted" )
{
print "M new revision: delete; previous revision: $oldmeta{$filename}{revision}\n";
print "Remove-entry $dirpart\n";
print "$filename\n";
} else {
if ($meta->{revision} eq "1.1") {
print "M initial revision: 1.1\n";
} else {
print "M new revision: $meta->{revision}; previous revision: $oldmeta{$filename}{revision}\n";
}
print "Checked-in $dirpart\n";
print "$filename\n";
my $kopts = kopts_from_path($filename,"sha1",$meta->{filehash});
print "/$filepart/$meta->{revision}//$kopts/" .
getStickyTagOrDate($stickyInfo) . "\n";
}
}
cleanupWorkTree();
print "ok\n";
}
sub req_status
{
my ( $cmd, $data ) = @_;
argsplit("status");
$log->info("req_status : " . ( defined($data) ? $data : "[NULL]" ));
#$log->debug("status state : " . Dumper($state));
# Grab a handle to the SQLite db and do any necessary updates
my $updater;
$updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
# if no files were specified, we need to work out what files we should
# be providing status on ...
argsfromdir($updater);
# foreach file specified on the command line ...
foreach my $filename ( @{$state->{args}} )
{
$filename = filecleanup($filename);
if ( exists($state->{opt}{l}) &&
index($filename, '/', length($state->{prependdir})) >= 0 )
{
next;
}
my $wrev = revparse($filename);
my $stickyInfo = resolveStickyInfo($filename);
my $meta = $updater->getmeta($filename,$stickyInfo);
my $oldmeta = $meta;
# If the working copy is an old revision, lets get that
# version too for comparison.
if ( defined($wrev) and $wrev ne $meta->{revision} )
{
my($rmRev)=$wrev;
$rmRev=~s/^-//;
$oldmeta = $updater->getmeta($filename, $rmRev);
}
# TODO : All possible statuses aren't yet implemented
my $status;
# Files are up to date if the working copy and repo copy have
# the same revision, and the working copy is unmodified
if ( defined ( $wrev ) and defined($meta->{revision}) and
$wrev eq $meta->{revision} and
( ( $state->{entries}{$filename}{unchanged} and
( not defined ( $state->{entries}{$filename}{conflict} ) or
$state->{entries}{$filename}{conflict} !~ /^\+=/ ) ) or
( defined($state->{entries}{$filename}{modified_hash}) and
$state->{entries}{$filename}{modified_hash} eq
$meta->{filehash} ) ) )
{
$status = "Up-to-date"
}
# Need checkout if the working copy has a different (usually
# older) revision than the repo copy, and the working copy is
# unmodified
if ( defined ( $wrev ) and defined ( $meta->{revision} ) and
$meta->{revision} ne $wrev and
( $state->{entries}{$filename}{unchanged} or
( defined($state->{entries}{$filename}{modified_hash}) and
$state->{entries}{$filename}{modified_hash} eq
$oldmeta->{filehash} ) ) )
{
$status ||= "Needs Checkout";
}
# Need checkout if it exists in the repo but doesn't have a working
# copy
if ( not defined ( $wrev ) and defined ( $meta->{revision} ) )
{
$status ||= "Needs Checkout";
}
# Locally modified if working copy and repo copy have the
# same revision but there are local changes
if ( defined ( $wrev ) and defined($meta->{revision}) and
$wrev eq $meta->{revision} and
$wrev ne "0" and
$state->{entries}{$filename}{modified_filename} )
{
$status ||= "Locally Modified";
}
# Needs Merge if working copy revision is different
# (usually older) than repo copy and there are local changes
if ( defined ( $wrev ) and defined ( $meta->{revision} ) and
$meta->{revision} ne $wrev and
$state->{entries}{$filename}{modified_filename} )
{
$status ||= "Needs Merge";
}
if ( defined ( $state->{entries}{$filename}{revision} ) and
( !defined($meta->{revision}) ||
$meta->{revision} eq "0" ) )
{
$status ||= "Locally Added";
}
if ( defined ( $wrev ) and defined ( $meta->{revision} ) and
$wrev eq "-$meta->{revision}" )
{
$status ||= "Locally Removed";
}
if ( defined ( $state->{entries}{$filename}{conflict} ) and
$state->{entries}{$filename}{conflict} =~ /^\+=/ )
{
$status ||= "Unresolved Conflict";
}
if ( 0 )
{
$status ||= "File had conflicts on merge";
}
$status ||= "Unknown";
my ($filepart) = filenamesplit($filename);
print "M =======" . ( "=" x 60 ) . "\n";
print "M File: $filepart\tStatus: $status\n";
if ( defined($state->{entries}{$filename}{revision}) )
{
print "M Working revision:\t" .
$state->{entries}{$filename}{revision} . "\n";
} else {
print "M Working revision:\tNo entry for $filename\n";
}
if ( defined($meta->{revision}) )
{
print "M Repository revision:\t" .
$meta->{revision} .
"\t$state->{CVSROOT}/$state->{module}/$filename,v\n";
my($tagOrDate)=$state->{entries}{$filename}{tag_or_date};
my($tag)=($tagOrDate=~m/^T(.+)$/);
if( !defined($tag) )
{
$tag="(none)";
}
print "M Sticky Tag:\t\t$tag\n";
my($date)=($tagOrDate=~m/^D(.+)$/);
if( !defined($date) )
{
$date="(none)";
}
print "M Sticky Date:\t\t$date\n";
my($options)=$state->{entries}{$filename}{options};
if( $options eq "" )
{
$options="(none)";
}
print "M Sticky Options:\t\t$options\n";
} else {
print "M Repository revision:\tNo revision control file\n";
}
print "M\n";
}
print "ok\n";
}
sub req_diff
{
my ( $cmd, $data ) = @_;
argsplit("diff");
$log->debug("req_diff : " . ( defined($data) ? $data : "[NULL]" ));
#$log->debug("status state : " . Dumper($state));
my ($revision1, $revision2);
if ( defined ( $state->{opt}{r} ) and ref $state->{opt}{r} eq "ARRAY" )
{
$revision1 = $state->{opt}{r}[0];
$revision2 = $state->{opt}{r}[1];
} else {
$revision1 = $state->{opt}{r};
}
$log->debug("Diffing revisions " .
( defined($revision1) ? $revision1 : "[NULL]" ) .
" and " . ( defined($revision2) ? $revision2 : "[NULL]" ) );
# Grab a handle to the SQLite db and do any necessary updates
my $updater;
$updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
# if no files were specified, we need to work out what files we should
# be providing status on ...
argsfromdir($updater);
my($foundDiff);
# foreach file specified on the command line ...
foreach my $argFilename ( @{$state->{args}} )
{
my($filename) = filecleanup($argFilename);
my ( $fh, $file1, $file2, $meta1, $meta2, $filediff );
my $wrev = revparse($filename);
# Priority for revision1:
# 1. First -r (missing file: check -N)
# 2. wrev from client's Entry line
# - missing line/file: check -N
# - "0": added file not committed (empty contents for rev1)
# - Prefixed with dash (to be removed): check -N
if ( defined ( $revision1 ) )
{
$meta1 = $updater->getmeta($filename, $revision1);
}
elsif( defined($wrev) && $wrev ne "0" )
{
my($rmRev)=$wrev;
$rmRev=~s/^-//;
$meta1 = $updater->getmeta($filename, $rmRev);
}
if ( !defined($meta1) ||
$meta1->{filehash} eq "deleted" )
{
if( !exists($state->{opt}{N}) )
{
if(!defined($revision1))
{
print "E File $filename at revision $revision1 doesn't exist\n";
}
next;
}
elsif( !defined($meta1) )
{
$meta1 = {
name => $filename,
revision => '0',
filehash => 'deleted'
};
}
}
# Priority for revision2:
# 1. Second -r (missing file: check -N)
# 2. Modified file contents from client
# 3. wrev from client's Entry line
# - missing line/file: check -N
# - Prefixed with dash (to be removed): check -N
# if we have a second -r switch, use it too
if ( defined ( $revision2 ) )
{
$meta2 = $updater->getmeta($filename, $revision2);
}
elsif(defined($state->{entries}{$filename}{modified_filename}))
{
$file2 = $state->{entries}{$filename}{modified_filename};
$meta2 = {
name => $filename,
revision => '0',
filehash => 'modified'
};
}
elsif( defined($wrev) && ($wrev!~/^-/) )
{
if(!defined($revision1)) # no revision and no modifications:
{
next;
}
$meta2 = $updater->getmeta($filename, $wrev);
}
if(!defined($file2))
{
if ( !defined($meta2) ||
$meta2->{filehash} eq "deleted" )
{
if( !exists($state->{opt}{N}) )
{
if(!defined($revision2))
{
print "E File $filename at revision $revision2 doesn't exist\n";
}
next;
}
elsif( !defined($meta2) )
{
$meta2 = {
name => $filename,
revision => '0',
filehash => 'deleted'
};
}
}
}
if( $meta1->{filehash} eq $meta2->{filehash} )
{
$log->info("unchanged $filename");
next;
}
# Retrieve revision contents:
( undef, $file1 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
transmitfile($meta1->{filehash}, { targetfile => $file1 });
if(!defined($file2))
{
( undef, $file2 ) = tempfile( DIR => $TEMP_DIR, OPEN => 0 );
transmitfile($meta2->{filehash}, { targetfile => $file2 });
}
# Generate the actual diff:
print "M Index: $argFilename\n";
print "M =======" . ( "=" x 60 ) . "\n";
print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
if ( defined ( $meta1 ) && $meta1->{revision} ne "0" )
{
print "M retrieving revision $meta1->{revision}\n"
}
if ( defined ( $meta2 ) && $meta2->{revision} ne "0" )
{
print "M retrieving revision $meta2->{revision}\n"
}
print "M diff ";
foreach my $opt ( sort keys %{$state->{opt}} )
{
if ( ref $state->{opt}{$opt} eq "ARRAY" )
{
foreach my $value ( @{$state->{opt}{$opt}} )
{
print "-$opt $value ";
}
} else {
print "-$opt ";
if ( defined ( $state->{opt}{$opt} ) )
{
print "$state->{opt}{$opt} "
}
}
}
print "$argFilename\n";
$log->info("Diffing $filename -r $meta1->{revision} -r " .
( $meta2->{revision} or "workingcopy" ));
# TODO: Use --label instead of -L because -L is no longer
# documented and may go away someday. Not sure if there there are
# versions that only support -L, which would make this change risky?
# http://osdir.com/ml/bug-gnu-utils-gnu/2010-12/msg00060.html
# ("man diff" should actually document the best migration strategy,
# [current behavior, future changes, old compatibility issues
# or lack thereof, etc], not just stop mentioning the option...)
# TODO: Real CVS seems to include a date in the label, before
# the revision part, without the keyword "revision". The following
# has minimal changes compared to original versions of
# git-cvsserver.perl. (Mostly tab vs space after filename.)
my (@diffCmd) = ( 'diff' );
if ( exists($state->{opt}{N}) )
{
push @diffCmd,"-N";
}
if ( exists $state->{opt}{u} )
{
push @diffCmd,("-u","-L");
if( $meta1->{filehash} eq "deleted" )
{
push @diffCmd,"/dev/null";
} else {
push @diffCmd,("$argFilename\trevision $meta1->{revision}");
}
if( defined($meta2->{filehash}) )
{
if( $meta2->{filehash} eq "deleted" )
{
push @diffCmd,("-L","/dev/null");
} else {
push @diffCmd,("-L",
"$argFilename\trevision $meta2->{revision}");
}
} else {
push @diffCmd,("-L","$argFilename\tworking copy");
}
}
push @diffCmd,($file1,$file2);
if(!open(DIFF,"-|",@diffCmd))
{
$log->warn("Unable to run diff: $!");
}
my($diffLine);
while(defined($diffLine=<DIFF>))
{
print "M $diffLine";
$foundDiff=1;
}
close(DIFF);
}
if($foundDiff)
{
print "error \n";
}
else
{
print "ok\n";
}
}
sub req_log
{
my ( $cmd, $data ) = @_;
argsplit("log");
$log->debug("req_log : " . ( defined($data) ? $data : "[NULL]" ));
#$log->debug("log state : " . Dumper($state));
my ( $revFilter );
if ( defined ( $state->{opt}{r} ) )
{
$revFilter = $state->{opt}{r};
}
# Grab a handle to the SQLite db and do any necessary updates
my $updater;
$updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
# if no files were specified, we need to work out what files we
# should be providing status on ...
argsfromdir($updater);
# foreach file specified on the command line ...
foreach my $filename ( @{$state->{args}} )
{
$filename = filecleanup($filename);
my $headmeta = $updater->getmeta($filename);
my ($revisions,$totalrevisions) = $updater->getlog($filename,
$revFilter);
next unless ( scalar(@$revisions) );
print "M \n";
print "M RCS file: $state->{CVSROOT}/$state->{module}/$filename,v\n";
print "M Working file: $filename\n";
print "M head: $headmeta->{revision}\n";
print "M branch:\n";
print "M locks: strict\n";
print "M access list:\n";
print "M symbolic names:\n";
print "M keyword substitution: kv\n";
print "M total revisions: $totalrevisions;\tselected revisions: " .
scalar(@$revisions) . "\n";
print "M description:\n";
foreach my $revision ( @$revisions )
{
print "M ----------------------------\n";
print "M revision $revision->{revision}\n";
# reformat the date for log output
if ( $revision->{modified} =~ /(\d+)\s+(\w+)\s+(\d+)\s+(\S+)/ and
defined($DATE_LIST->{$2}) )
{
$revision->{modified} = sprintf('%04d/%02d/%02d %s',
$3, $DATE_LIST->{$2}, $1, $4 );
}
$revision->{author} = cvs_author($revision->{author});
print "M date: $revision->{modified};" .
" author: $revision->{author}; state: " .
( $revision->{filehash} eq "deleted" ? "dead" : "Exp" ) .
"; lines: +2 -3\n";
my $commitmessage;
$commitmessage = $updater->commitmessage($revision->{commithash});
$commitmessage =~ s/^/M /mg;
print $commitmessage . "\n";
}
print "M =======" . ( "=" x 70 ) . "\n";
}
print "ok\n";
}
sub req_annotate
{
my ( $cmd, $data ) = @_;
argsplit("annotate");
$log->info("req_annotate : " . ( defined($data) ? $data : "[NULL]" ));
#$log->debug("status state : " . Dumper($state));
# Grab a handle to the SQLite db and do any necessary updates
my $updater = GITCVS::updater->new($state->{CVSROOT}, $state->{module}, $log);
$updater->update();
# if no files were specified, we need to work out what files we should be providing annotate on ...
argsfromdir($updater);
# we'll need a temporary checkout dir
setupWorkTree();
$log->info("Temp checkoutdir creation successful, basing annotate session work on '$work->{workDir}', index file is '$ENV{GIT_INDEX_FILE}'");
# foreach file specified on the command line ...
foreach my $filename ( @{$state->{args}} )
{
$filename = filecleanup($filename);
my $meta = $updater->getmeta($filename);
next unless ( $meta->{revision} );
# get all the commits that this file was in
# in dense format -- aka skip dead revisions
my $revisions = $updater->gethistorydense($filename);
my $lastseenin = $revisions->[0][2];
# populate the temporary index based on the latest commit were we saw
# the file -- but do it cheaply without checking out any files
# TODO: if we got a revision from the client, use that instead
# to look up the commithash in sqlite (still good to default to
# the current head as we do now)
system("git", "read-tree", $lastseenin);
unless ($? == 0)
{
print "E error running git-read-tree $lastseenin $ENV{GIT_INDEX_FILE} $!\n";
return;
}
$log->info("Created index '$ENV{GIT_INDEX_FILE}' with commit $lastseenin - exit status $?");
# do a checkout of the file
system('git', 'checkout-index', '-f', '-u', $filename);
unless ($? == 0) {
print "E error running git-checkout-index -f -u $filename : $!\n";
return;
}
$log->info("Annotate $filename");
# Prepare a file with the commits from the linearized
# history that annotate should know about. This prevents
# git-jsannotate telling us about commits we are hiding
# from the client.
my $a_hints = "$work->{workDir}/.annotate_hints";
if (!open(ANNOTATEHINTS, '>', $a_hints)) {
print "E failed to open '$a_hints' for writing: $!\n";
return;
}
for (my $i=0; $i < @$revisions; $i++)
{
print ANNOTATEHINTS $revisions->[$i][2];
if ($i+1 < @$revisions) { # have we got a parent?
print ANNOTATEHINTS ' ' . $revisions->[$i+1][2];
}
print ANNOTATEHINTS "\n";
}
print ANNOTATEHINTS "\n";
close ANNOTATEHINTS
or (print "E failed to write $a_hints: $!\n"), return;
my @cmd = (qw(git annotate -l -S), $a_hints, $filename);
if (!open(ANNOTATE, "-|", @cmd)) {
print "E error invoking ". join(' ',@cmd) .": $!\n";
return;
}
my $metadata = {};
print "E Annotations for $filename\n";
print "E ***************\n";
while ( <ANNOTATE> )
{
if (m/^([a-zA-Z0-9]{40})\t\([^\)]*\)(.*)$/i)
{
my $commithash = $1;
my $data = $2;
unless ( defined ( $metadata->{$commithash} ) )
{
$metadata->{$commithash} = $updater->getmeta($filename, $commithash);
$metadata->{$commithash}{author} = cvs_author($metadata->{$commithash}{author});
$metadata->{$commithash}{modified} = sprintf("%02d-%s-%02d", $1, $2, $3) if ( $metadata->{$commithash}{modified} =~ /^(\d+)\s(\w+)\s\d\d(\d\d)/ );
}
printf("M %-7s (%-8s %10s): %s\n",
$metadata->{$commithash}{revision},
$metadata->{$commithash}{author},
$metadata->{$commithash}{modified},
$data
);
} else {
$log->warn("Error in annotate output! LINE: $_");
print "E Annotate error \n";
next;
}
}
close ANNOTATE;
}
# done; get out of the tempdir
cleanupWorkTree();
print "ok\n";
}
# This method takes the state->{arguments} array and produces two new arrays.
# The first is $state->{args} which is everything before the '--' argument, and
# the second is $state->{files} which is everything after it.
sub argsplit
{
$state->{args} = [];
$state->{files} = [];
$state->{opt} = {};
return unless( defined($state->{arguments}) and ref $state->{arguments} eq "ARRAY" );
my $type = shift;
if ( defined($type) )
{
my $opt = {};
$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 ( $type eq "co" );
$opt = { v => 0, l => 0, R => 0 } if ( $type eq "status" );
$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 ( $type eq "update" );
$opt = { l => 0, R => 0, k => 1, D => 1, D => 1, r => 2, N => 0 } if ( $type eq "diff" );
$opt = { c => 0, R => 0, l => 0, f => 0, F => 1, m => 1, r => 1 } if ( $type eq "ci" );
$opt = { k => 1, m => 1 } if ( $type eq "add" );
$opt = { f => 0, l => 0, R => 0 } if ( $type eq "remove" );
$opt = { l => 0, b => 0, h => 0, R => 0, t => 0, N => 0, S => 0, r => 1, d => 1, s => 1, w => 1 } if ( $type eq "log" );
while ( scalar ( @{$state->{arguments}} ) > 0 )
{
my $arg = shift @{$state->{arguments}};
next if ( $arg eq "--" );