Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # Write a directory to the Git index.
- # Prints the directory's SHA-1 to stdout.
- #
- # Copyright 2013 Lars Buitinck / University of Amsterdam.
- # Copyright 2016 Jakub Łopuszański.
- # License: MIT (http://opensource.org/licenses/MIT)
- import os
- from os.path import split
- from posixpath import join
- from subprocess import check_output, Popen, PIPE
- import sys
- def hash_file(path):
- """Write file at path to Git index, return its SHA1 as a string."""
- return check_output(["git", "hash-object", "--", path]).strip()
- def _lstree(files, dirs):
- """Make git ls-tree like output."""
- entries = sorted(
- [ (f,"100644",sha1) for f,sha1 in files] +
- [ (d, "40000",sha1) for d,sha1 in dirs],
- key = lambda x : x[0]
- )
- return ["{} {}\0{}".format(mode,name,sha1.decode('hex')) for name,mode,sha1 in entries]
- def _mktree(files, dirs):
- mkt = Popen(['git','hash-object','--stdin','-t','tree'],stdin=PIPE, stdout=PIPE)
- return mkt.communicate("".join(_lstree(files, dirs)))[0].strip()
- def hash_dir(path):
- """Write directory at path to Git index, return its SHA1 as a string."""
- dir_hash = {}
- for root, dirs, files in os.walk(path, topdown=False):
- f_hash = ((f, hash_file(join(root, f))) for f in files)
- d_hash = ((d, dir_hash[join(root, d)]) for d in dirs)
- # split+join normalizes paths on Windows (note the imports)
- dir_hash[join(*split(root))] = _mktree(f_hash, d_hash)
- return dir_hash[path]
- if __name__ == "__main__":
- print(hash_dir(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement