Advertisement
Guest User

Git Tree Hash

a guest
Jul 19th, 2016
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Write a directory to the Git index.
  4. # Prints the directory's SHA-1 to stdout.
  5. #
  6. # Copyright 2013 Lars Buitinck / University of Amsterdam.
  7. # Copyright 2016 Jakub Łopuszański.
  8. # License: MIT (http://opensource.org/licenses/MIT)
  9.  
  10. import os
  11. from os.path import split
  12. from posixpath import join
  13. from subprocess import check_output, Popen, PIPE
  14. import sys
  15.  
  16.  
  17. def hash_file(path):
  18.     """Write file at path to Git index, return its SHA1 as a string."""
  19.     return check_output(["git", "hash-object", "--", path]).strip()
  20.  
  21.  
  22. def _lstree(files, dirs):
  23.     """Make git ls-tree like output."""
  24.     entries = sorted(
  25.         [ (f,"100644",sha1) for f,sha1 in files] +
  26.         [ (d, "40000",sha1) for d,sha1 in dirs],
  27.         key = lambda x : x[0]
  28.     )
  29.     return ["{} {}\0{}".format(mode,name,sha1.decode('hex')) for name,mode,sha1 in entries]
  30.  
  31. def _mktree(files, dirs):
  32.     mkt = Popen(['git','hash-object','--stdin','-t','tree'],stdin=PIPE, stdout=PIPE)
  33.     return mkt.communicate("".join(_lstree(files, dirs)))[0].strip()
  34.  
  35.  
  36. def hash_dir(path):
  37.     """Write directory at path to Git index, return its SHA1 as a string."""
  38.     dir_hash = {}
  39.  
  40.     for root, dirs, files in os.walk(path, topdown=False):
  41.         f_hash = ((f, hash_file(join(root, f))) for f in files)
  42.         d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
  43.         # split+join normalizes paths on Windows (note the imports)
  44.         dir_hash[join(*split(root))] = _mktree(f_hash, d_hash)
  45.  
  46.     return dir_hash[path]
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     print(hash_dir(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement