我想提取git存储库中保存的文件的最新版本的副本,并将其传递到脚本中进行某些处理。使用svn或hg时,我只使用“ cat”命令:
按指定版本打印指定文件。如果未给出修订,则使用工作目录的父目录;如果未签出任何修订,则提示。
(来自hg文档中对hg cat的描述)
用git执行此操作的等效命令是什么?
我想提取git存储库中保存的文件的最新版本的副本,并将其传递到脚本中进行某些处理。使用svn或hg时,我只使用“ cat”命令:
按指定版本打印指定文件。如果未给出修订,则使用工作目录的父目录;如果未签出任何修订,则提示。
(来自hg文档中对hg cat的描述)
用git执行此操作的等效命令是什么?
Answers:
git show
是您要查找的命令。从文档中:
git show next~10:Documentation/README
Shows the contents of the file Documentation/README as they were
current in the 10th last commit of the branch next.
没有一个git show
建议真正令人满意,因为(我可能会尝试),我找不到不从输出顶部获取元数据数据的方法。cat(1)的精神只是为了显示内容。这(下面)带有一个文件名和一个可选数字。该数字是您要返回的提交方式。(更改该文件的提交。不计算不更改目标文件的提交。)
gitcat.pl filename.txt
gitcat.pl -3 filename.txt
显示截至filename.txt的最新提交为止的filename.txt的内容,以及之前的3次提交的内容。
#!/usr/bin/perl -w
use strict;
use warnings;
use FileHandle;
use Cwd;
# Have I mentioned lately how much I despise git?
(my $prog = $0) =~ s!.*/!!;
my $usage = "Usage: $prog [revisions-ago] filename\n";
die( $usage ) if( ! @ARGV );
my( $revision, $fname ) = @ARGV;
if( ! $fname && -f $revision ) {
( $fname, $revision ) = ( $revision, 0 );
}
gitcat( $fname, $revision );
sub gitcat {
my( $fname, $revision ) = @_;
my $rev = $revision;
my $file = FileHandle->new( "git log --format=oneline '$fname' |" );
# Get the $revisionth line from the log.
my $line;
for( 0..$revision ) {
$line = $file->getline();
}
die( "Could not get line $revision from the log for $fname.\n" )
if( ! $line );
# Get the hash from that.
my $hash = substr( $line, 0, 40 );
if( ! $hash =~ m/ ^ ( [0-9a-fA-F]{40} )/x ) {
die( "The commit hash does not look a hash.\n" );
}
# Git needs the path from the root of the repo to the file because it can
# not work out the path itself.
my $path = pathhere();
if( ! $path ) {
die( "Could not find the git repository.\n" );
}
exec( "git cat-file blob $hash:$path/'$fname'" );
}
# Get the path from the git repo to the current dir.
sub pathhere {
my $cwd = getcwd();
my @cwd = split( '/', $cwd );
my @path;
while( ! -d "$cwd/.git" ) {
my $path = pop( @cwd );
unshift( @path, $path );
if( ! @cwd ) {
die( "Did not find .git in or above your pwd.\n" );
}
$cwd = join( '/', @cwd );
}
return join( '/', map { "'$_'"; } @path );
}
对于使用bash的用户,以下是有用的功能:
gcat () { if [ $# -lt 1 ]; then echo "Usage: $FUNCNAME [rev] file"; elif [ $# -lt 2 ]; then git show HEAD:./$*; else git show $1:./$2; fi }
将其放在.bashrc
文件中(您可以使用任何其他喜欢的名称gcat
。
用法示例:
> gcat
Usage: gcat [rev] file
要么
> gcat subdirectory/file.ext
要么
> gcat rev subdirectory/file.ext