"""Hashing, environment facts and small helpers shared by the harness.""" import hashlib import json import os import platform import subprocess REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) def sha256_bytes(data): return "sha256:" + hashlib.sha256(data).hexdigest() def sha256_text(text): return sha256_bytes(text.encode("utf-8")) def sha256_path(path): """Hash of a file, or of a directory tree (sorted relative paths and contents).""" h = hashlib.sha256() if os.path.isfile(path): with open(path, "rb") as f: h.update(f.read()) return "sha256:" + h.hexdigest() for root, dirs, files in os.walk(path): dirs[:] = sorted(d for d in dirs if d not in (".git", "__pycache__")) for name in sorted(files): full = os.path.join(root, name) rel = os.path.relpath(full, path) h.update(rel.encode() + b"\0") with open(full, "rb") as f: h.update(f.read()) h.update(b"\0") return "sha256:" + h.hexdigest() def sha256_path_cached(path): """`sha256_path` for large documentation trees, cached on disk by the tree's path, file count, total size and newest modification time.""" count, size, newest = 0, 0, 0.0 for root, dirs, files in os.walk(path) if os.path.isdir(path) else [(os.path.dirname(path), [], [os.path.basename(path)])]: dirs[:] = [d for d in dirs if d not in (".git", "__pycache__")] for name in files: st = os.stat(os.path.join(root, name)) count, size, newest = count + 1, size + st.st_size, max(newest, st.st_mtime) key = f"{os.path.realpath(path)}|{count}|{size}|{newest}" cache_file = os.path.join(os.path.expanduser("~"), ".cache", "ajieval", "hashes.json") try: cache = read_json(cache_file) except (OSError, ValueError): cache = {} if key not in cache: cache[key] = sha256_path(path) os.makedirs(os.path.dirname(cache_file), exist_ok=True) write_json(cache_file, cache) return cache[key] def git_commit(path=REPO): """`` or `+dirty` for the repository containing `path`.""" try: rev = subprocess.run(["git", "-C", path, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run(["git", "-C", path, "status", "--porcelain"], capture_output=True, text=True, check=True).stdout.strip() return rev + ("+dirty" if dirty else "") except (OSError, subprocess.CalledProcessError): return None def hardware(): info = {"machine": platform.machine(), "system": platform.system(), "release": platform.release(), "cpus": os.cpu_count()} try: with open("/proc/cpuinfo") as f: for line in f: if line.startswith("model name"): info["cpu"] = line.split(":", 1)[1].strip() break with open("/proc/meminfo") as f: info["mem_kb"] = int(f.readline().split()[1]) except OSError: pass return info def write_json(path, obj): with open(path, "w") as f: json.dump(obj, f, indent=2, sort_keys=True) f.write("\n") def read_json(path): with open(path) as f: return json.load(f) def estimate_tokens(nbytes): """Rough token estimate for byte counts the provider does not report (documentation inspected); flagged as an estimate in records.""" return (nbytes + 3) // 4