Analyze disk usage by implementing a Merkle tree. Recursively scan directories computing file hashes where directory hashes are hashes of children's hashes, allowing rapid detection of which sub-branch changed between scans.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Providing Python code that recursively scans directories, computes file hashes, builds a Merkle tree with directory hashes as combined children hashes, and includes a function to compare two snapshots to detect changed subtrees quickly.
Below is a self-contained Python example that:
Recursively walks a directory.
Computes a cryptographic hash of each file’s content.
Computes a directory hash by hashing the concatenation of each child’s hash.
Builds a Merkle tree you can serialize and store between scans.
Provides a simple comparison function to quickly detect which subtree(s) changed between two scans.
You can save this as something like merkle_disk_usage.py and adapt it as needed.
python
import os
import hashlib
import json
from dataclasses import dataclass, field
from typing import List, Optional
# =============== DATA STRUCTURES ===============
@dataclass
class MerkleNode:
"""Represents a file or directory entry in the Merkle tree."""
path: str
node_type: str # "file" or "dir"
size: int
hash: str
children: List["MerkleNode"] = field(default_factory=list)
# =============== CORE HASHING HELPERS ===============
def hash_file(filepath: str, chunk_size: int = 65536) -> str:
"""Compute SHA-256 hash of a file's contents."""
h = hashlib.sha256()
with open(filepath, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def hash_directory(children_hashes: List[str]) -> str:
"""
Compute directory hash by hashing the concatenation of child hashes.
This ensures any change in any child's hash will update the directory hash.
"""
h = hashlib.sha256()
for chash in sorted(children_hashes):
h.update(chash.encode("utf-8"))
return h.hexdigest()
# =============== TREE BUILDING ===============
def build_merkle_tree(root_path: str) -> MerkleNode:
"""
Recursively build a Merkle tree from the directory specified by root_path.
Returns a MerkleNode representing the root.
"""
root_path = os.path.abspath(root_path)
if os.path.isfile(root_path):
# File node
fhash = hash_file(root_path)
fsize = os.path.getsize(root_path)
return MerkleNode(
path=root_path,
node_type="file",
size=fsize,
hash=fhash,
)
# Directory node
children = []
total_size = 0
child_hashes = []
# Use os.scandir for efficiency
with os.scandir(root_path) as it:
for entry in it:
# Skip special files or links if you prefer
if entry.is_symlink():
continue
child_path = entry.path
# Recurse
child_node = build_merkle_tree(child_path)
children.append(child_node)
child_hashes.append(child_node.hash)
total_size += child_node.size
dir_hash = hash_directory(child_hashes)
return MerkleNode(
path=root_path,
node_type="dir",
size=total_size,
hash=dir_hash,
children=children
)
# =============== SERIALIZATION HELPERS ===============
def merkle_to_dict(node: MerkleNode) -> dict:
"""Convert MerkleNode to a JSON-serializable dictionary."""
return {
"path": node.path,
"type": node.node_type,
"size": node.size,
"hash": node.hash,
"children": [merkle_to_dict(c) for c in node.children],
}
def dict_to_merkle(d: dict) -> MerkleNode:
"""Convert a dictionary back to a MerkleNode."""
children = [dict_to_merkle(c) for c in d.get("children", [])]
return MerkleNode(
path=d["path"],
node_type=d["type"],
size=d["size"],
hash=d["hash"],
children=children
)
# =============== COMPARISON LOGIC ===============
def compare_trees(old_tree: MerkleNode, new_tree: MerkleNode) -> List[str]:
"""
Compare two Merkle trees (old vs new) and return a list
of paths to subtrees that changed. This is a simple approach:
- If hashes differ, either path changed or underlying children changed.
- Recursively descend into directories if hashes differ.
"""
changed_paths = []
# If hash is the same, no need to explore further
if old_tree.hash == new_tree.hash:
return changed_paths
# If node types differ or paths differ, mark as changed at this level
if old_tree.node_type != new_tree.node_type or old_tree.path != new_tree.path:
return [new_tree.path]
# If file nodes differ, mark as changed
if old_tree.node_type == "file":
return [new_tree.path]
# Otherwise, descend into children
# Build a map from name -> child node for old tree
old_children_map = {os.path.basename(c.path): c for c in old_tree.children}
new_children_map = {os.path.basename(c.path): c for c in new_tree.children}
# Check for children present in both trees
for name, new_child in new_children_map.items():
if name in old_children_map:
changed_paths.extend(compare_trees(old_children_map[name], new_child))
else:
# New child present that wasn't in old tree
changed_paths.append(new_child.path)
# Check for children that existed before but not now
for name, old_child in old_children_map.items():
if name not in new_children_map:
changed_paths.append(old_child.path)
return changed_paths
# =============== EXAMPLE USAGE ===============
if __name__ == "__main__":
# 1) Build a Merkle tree of a directory
root_dir = "./your_directory_here"
tree = build_merkle_tree(root_dir)
# 2) Convert to JSON string for storage (e.g., on disk)
tree_json = json.dumps(merkle_to_dict(tree), indent=2)
print("Current tree hash:", tree.hash)
# Optionally write to file
# with open("snapshot.json", "w") as f:
# f.write(tree_json)
# 3) Later, load an old snapshot and compare
# with open("snapshot.json", "r") as f:
# old_data = json.load(f)
# old_tree = dict_to_merkle(old_data)
# changed = compare_trees(old_tree, tree)
# print("Changed sub-paths:", changed)
How It Works
File Hashing
Each file’s content is hashed with SHA-256. The file’s Merkle node stores the file size and hash.
Directory Hashing
For each directory, the hashes of all children (files or subdirectories) are sorted and concatenated before hashing. Any change in a child’s hash will alter the directory’s hash.
Merkle Tree
The root node’s hash effectively represents the entire directory content. You can store the root node as a snapshot. On a new scan, build another Merkle tree and compare root hashes. If they differ, drill down to the changed children to find which sub-branches changed.
Comparison
The compare_trees function returns paths to nodes whose contents or structure changed. Because each directory hash encapsulates all its descendants’ hashes, unchanged subtrees are skipped.
You can refine this further by adding parallel scanning, handling symlinks more gracefully, or storing additional metadata. This approach allows rapid detection of changes between scans and can be combined with disk usage analysis (e.g., by inspecting each node’s size).