Alec the Geek

Reflections on software and related things from an older geek

Handy Hack: Calculating Git SHA1 on files without Git installed

Posted by Alec The Geek on 17 March 2010

If you are not a Git geek this will be of limited interest and I suggest you go and surf whatever inappropriate material uses up your bandwidth.

Updated after tips from Randal Schwartz and Charles Bailey

Still here? OK. As you will know every file stored in a Git repo is identified by a SHA1 hexadecimal string (as explained in the Pro Git book, it’s the hash of the concatenation of the  file contents and a Git specific header). You can calculate the Git SHA1 of any file with the command

git hash-object $file

assuming you have Git installed

If you do not have access to Git, but do have access to a UNIX style shell or Perl you have a couple of options (the Pro Git book also shows a Ruby solution and Stackoverflow has examples in Python and #F))

On Cygwin or Linux

(printf  "blob %s\00" $(wc -c < $file);cat $file)|sha1sum -b | cut -d " " -f 1

On Solaris

(printf  "blob %s\00" $(wc -c < $file);cat $file)|digest -a sha1 | cut -d " " -f 1

In Perl

# See also Git::PurePerl at http://search.cpan.org/dist/Git-PurePerl/

use strict;
use warnings;
use Digest::SHA1;

my @input = <>;

my $content = join("", @input);

my $git_blob = 'blob' . ' ' . length($content) . "\0" . $content;

my $sha1 = Digest::SHA1->new();

$sha1->add($git_blob);

print $sha1->hexdigest();
About these ads

2 Responses to “Handy Hack: Calculating Git SHA1 on files without Git installed”

  1. realmerlyn said

    Lovely useless use of cat. Consider “wc -c <$file" instead of your cat-pipe.

Sorry, the comment form is closed at this time.

 
Follow

Get every new post delivered to your Inbox.

Join 272 other followers

%d bloggers like this: