hash.py (1606B)
1 # This Source Code Form is subject to the terms of the Mozilla Public 2 # License, v. 2.0. If a copy of the MPL was not distributed with this 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 5 import hashlib 6 7 import mozpack.path as mozpath 8 from mozbuild.util import memoize 9 from mozversioncontrol import get_repository_object 10 11 12 @memoize 13 def hash_path(path): 14 """Hash a single file. 15 16 Returns the SHA-256 hash in hex form. 17 """ 18 with open(path, mode="rb") as fh: 19 return hashlib.sha256(fh.read()).hexdigest() 20 21 22 @memoize 23 def get_file_finder(base_path): 24 return get_repository_object(base_path).get_tracked_files_finder(base_path) 25 26 27 def hash_paths(base_path, patterns): 28 """ 29 Give a list of path patterns, return a digest of the contents of all 30 the corresponding files, similarly to git tree objects or mercurial 31 manifests. 32 33 Each file is hashed. The list of all hashes and file paths is then 34 itself hashed to produce the result. 35 """ 36 finder = get_file_finder(base_path) 37 h = hashlib.sha256() 38 files = {} 39 if finder: 40 for pattern in patterns: 41 found = list(finder.find(pattern)) 42 if found: 43 files.update(found) 44 else: 45 raise Exception("%s did not match anything" % pattern) 46 for path in sorted(files.keys()): 47 if path.endswith((".pyc", ".pyd", ".pyo")): 48 continue 49 h.update( 50 f"{hash_path(mozpath.abspath(mozpath.join(base_path, path)))} {mozpath.normsep(path)}\n".encode() 51 ) 52 53 return h.hexdigest()