| 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 functools |
| 6 |
import hashlib |
| 7 |
import os |
| 8 |
|
| 9 |
from taskgraph.util import path as mozpath |
| 10 |
from taskgraph.util.vcs import get_repository |
| 11 |
|
| 12 |
|
| 13 |
@functools.lru_cache(maxsize=None) |
| 14 |
def hash_path(path): |
| 15 |
"""Hash a single file. |
| 16 |
|
| 17 |
Returns the SHA-256 hash in hex form. |
| 18 |
""" |
| 19 |
with open(path, "rb") as fh: |
| 20 |
return hashlib.sha256(fh.read()).hexdigest() |
| 21 |
|
| 22 |
|
| 23 |
def hash_paths(base_path, patterns): |
| 24 |
""" |
| 25 |
Give a list of path patterns, return a digest of the contents of all |
| 26 |
the corresponding files, similarly to git tree objects or mercurial |
| 27 |
manifests. |
| 28 |
|
| 29 |
Each file is hashed. The list of all hashes and file paths is then |
| 30 |
itself hashed to produce the result. |
| 31 |
""" |
| 32 |
h = hashlib.sha256() |
| 33 |
|
| 34 |
found = set() |
| 35 |
for pattern in patterns: |
| 36 |
matches = _find_matching_files(base_path, pattern) |
| 37 |
if matches: |
| 38 |
found.update(matches) |
| 39 |
else: |
| 40 |
raise Exception(f"{pattern} did not match anything") |
| 41 |
for path in sorted(found): |
| 42 |
h.update( |
| 43 |
f"{hash_path(mozpath.abspath(mozpath.join(base_path, path)))} {mozpath.normsep(path)}\n".encode() |
| 44 |
) |
| 45 |
return h.hexdigest() |
| 46 |
|
| 47 |
|
| 48 |
@functools.lru_cache(maxsize=None) |
| 49 |
def _find_matching_files(base_path, pattern): |
| 50 |
files = _get_all_files(base_path) |
| 51 |
return [path for path in files if mozpath.match(path, pattern)] |
| 52 |
|
| 53 |
|
| 54 |
@functools.lru_cache(maxsize=None) |
| 55 |
def _get_all_files(base_path): |
| 56 |
repo = get_repository(os.getcwd()) |
| 57 |
return repo.get_tracked_files(base_path) |