The user wants a Python CLI tool to compare directory structures.
1. Understand the Goal:
Input: Two directory paths (let's call them Source and Target).
Output: Differences between the two structures. This usually includes:
Files/dirs present in Source but not in Target (Missing in Target).
Files/dirs present in Target but not in Source (Extra in Target / Obsolete).
Files common to both but potentially different (Content/Size/Time comparison).
Interface: Command Line Interface (CLI).
2. Core Logic:
I need to walk through both directories.
I need to relativize paths (compare dir1/file.txt vs dir2/file.txt).
I need sets of relative paths to perform set operations (difference, intersection).
3. Features to include:
Recursive comparison: Check subdirectories.
File content/attributes: Just check existence? Or check if files are identical?
Existence only: Fast, good for structure.
Content: Hashing (MD5/SHA) or size/modification time.
Output format:
Human-readable (indented lists).
JSON (for scripting).
Exclusion: Ignore .git, __pycache__, etc.
4. Library Selection:
os / os.path: Standard, but pathlib is more modern and easier to handle cross-platform paths.
argparse: For CLI arguments.
difflib: Maybe for specific file diffs, but usually overkill for directory structures.
filecmp: Built-in module specifically for this. filecmp.dircmp is a strong candidate.
5. Approach using filecmp.dircmp (The Built-in Way):
filecmp.dircmp recursively compares directories.
Pros: Built-in, handles recursion.
Cons: The default output is a bit verbose/clunky to parse programmatically for custom formatting. It requires subclassing or recursive function wrapping to get a clean list of all differences.
6. Approach using pathlib and Sets (The Custom Way):
Walk both dirs, generate set of relative paths.
Compare sets.
Pros: granular control over output, easy to implement filtering.
Cons: Might be slower on massive directories compared to optimized C-modules (though Python's os.scandir is fast now).
7. Decision:
I will use pathlib for the traversal because it offers the most flexibility for a CLI tool (e.g., easier filtering, JSON output, cleaner logic for relative paths).
8. Step-by-Step Implementation Plan:
Setup: Imports (pathlib, argparse, sys, hashlib).
Argument Parsing:
dir1, dir2 (positional).
--content or -c (flag to check content hash).
--output or -o (format: text vs json).
--exclude (patterns to ignore).
Core Functionality (DirectoryDiff class or functions):
Get all files recursively from Dir A and Dir B.
Store as dictionary: { relative_path: stats }.
Compare Keys:
only_in_a
only_in_b
common
If --content flag is set: Compare hashes of common files to find modified files.
Output:
Print differences clearly.
Refinement: Add a hashing function (MD5 or SHA256) for content comparison.
9. Drafting the Code (Mental or scratchpad):
python
def get_files(path):
return set of relative paths
# ... argument parsing ...
set_a = get_files(dir_a)
set_b = get_files(dir_b)
missing = set_a - set_b
extra = set_b - set_a
Self-Correction: Simply checking existence isn't enough. Usually, users want to know if a file has changed.
Improved Plan:
Collect all relative paths for Dir A and Dir B.
Identify "Left Only" (Missing in Right) and "Right Only" (Missing in Left).
For intersection (Common files):
If not checking content: Assume same (or maybe check size/date).
If checking content: Hash them.
10. Writing the Code Structure:
Imports:argparse, pathlib, sys, hashlib, json.
Hashing: Small helper function to hash a file in chunks (memory efficient).
Scanning: A generator function to yield relative paths and file objects.
Comparison:
Build dict A and dict B.
Calculate differences.
CLI:
Help text.
Validation (paths exist).
11. Refining the Output:
A simple visual diff looks like:
> file_in_a.txt< file_in_b.txt! modified_file.txt
Or categorized:
Files only in /path/A: ...Files only in /path/B: ...Changed files: ...
12. Final Code Polish:
Add an exclusion list (e.g., .git).
Add error handling (PermissionError).
Make it executable (if __name__ == "__main__":).
Let's write the actual code. I will provide a robust solution using pathlib and argparse.
Feature Check:
Compare 2 dirs.
Detect added/removed files.
Detect modified files (via hash).
Output modes (Text vs JSON).
Exclusion patterns.
Hashing Logic:
Use hashlib.md5. Read in 4KB chunks.
Walking Logic:path.rglob('*'). Check is_file(). Relative path via path.relative_to(root).
Constructing the Response:
Introduction: Explain the approach (using pathlib for flexibility).
The Code: Single file script.
Usage Examples: How to run it.
Extensions: Ideas for improvement.
Let's refine the CLI args.
dir1, dir2.
--mode: strict (hash check) or quick (file size check) or structure (existence only). Let's stick to existence + optional hash to keep it simple but powerful. Flag: --check-content.
(Self-Correction during coding): filecmp.dircmp is actually really good for a "quick" comparison, but building a custom walker allows for better JSON export and exclusion handling which users usually want. I'll stick to the custom pathlib walker.
Let's add color output for better readability if the terminal supports it (optional but nice). I'll keep it standard text to avoid dependencies like colorama, using ANSI codes directly if possible, or just clean text formatting. Let's stick to clean text to ensure maximum compatibility.
Final check of requirements: "Python CLI tool".
So, argparse is mandatory.
Let's go.
Here is a complete, robust Python CLI tool to compare directory structures. It uses the built-in pathlib and argparse libraries, so it requires no external dependencies.
Features
Structure Comparison: Identifies files/directories unique to the left or right side.
Content Comparison (Optional): Uses file size and MD5 hashing to identify files that exist in both places but have different content.
Exclusions: Allows ignoring specific directories (like .git or __pycache__).
Output Formats: Supports standard text output or JSON for scripting.
The Code (dircompare.py)
Save the following code into a file named dircompare.py.
python
How to use it
Open your terminal and run the script.
1. Basic Structure Comparison
Checks which files/folders are missing from either directory.
If you want to pipe the output to another tool (like jq or a Python script):
bash
python dircompare.py folderA folderB -o json
5. Quiet Mode
Only show differences, hiding the list of identical files to reduce noise:
bash
python dircompare.py folderA folderB -q
import argparse
import hashlib
import json
import sys
from pathlib import Path
def calculate_md5(filepath, block_size=8192):
"""Calculates the MD5 hash of a file."""
hasher = hashlib.md5()
try:
with open(filepath, 'rb') as f:
while chunk := f.read(block_size):
hasher.update(chunk)
return hasher.hexdigest()
except OSError as e:
print(f"Error reading {filepath}: {e}", file=sys.stderr)
return None
def scan_directory(path, exclude_dirs=None):
"""
Scans a directory recursively.
Returns a dictionary: { 'relative/path': (type, size, hash) }
"""
files = {}
base_path = Path(path).resolve()
exclude_dirs = set(exclude_dirs or [])
for item in base_path.rglob('*'):
# Check if any part of the path is in the exclusion list
if any(part in exclude_dirs for part in item.parts):
continue
try:
relative_path = str(item.relative_to(base_path))
if item.is_dir():
files[relative_path] = ('dir', 0, None)
elif item.is_file():
# We store size immediately, hash is calculated lazily or if needed
files[relative_path] = ('file', item.stat().st_size, None)
except OSError as e:
print(f"Access error skipping {item}: {e}", file=sys.stderr)
return files
def compare_directories(dir1, dir2, check_content=False, exclude_dirs=None):
"""
Compares two directories.
"""
print(f"Scanning '{dir1}'...")
map1 = scan_directory(dir1, exclude_dirs)
print(f"Scanning '{dir2}'...")
map2 = scan_directory(dir2, exclude_dirs)
results = {
"left_only": [], # Items only in dir1
"right_only": [], # Items only in dir2
"diff_content": [], # Items in both but different content/size
"identical": [] # Items in both with same content
}
all_keys = set(map1.keys()) | set(map2.keys())
for key in sorted(all_keys):
in_left = key in map1
in_right = key in map2
if in_left and not in_right:
results["left_only"].append(key)
elif not in_left and in_right:
results["right_only"].append(key)
else:
# Item exists in both. Check type/size/content
type1, size1, _ = map1[key]
type2, size2, _ = map2[key]
if type1 != type2:
# One is file, one is dir
results["diff_content"].append(f"{key} (Type mismatch)")
elif type1 == 'dir':
# Directories are considered identical if names match
results["identical"].append(key)
else:
# It's a file. Check size first (fast)
if size1 != size2:
results["diff_content"].append(key)
elif check_content:
# Sizes match, verify hash if requested
h1 = calculate_md5(Path(dir1) / key)
h2 = calculate_md5(Path(dir2) / key)
if h1 != h2:
results["diff_content"].append(f"{key} (Hash mismatch)")
else:
results["identical"].append(key)
else:
# Sizes match and no content check requested
results["identical"].append(key)
return results
def main():
parser = argparse.ArgumentParser(
description="Compare the structure and content of two directories.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("dir1", help="Path to the first (left) directory")
parser.add_argument("dir2", help="Path to the second (right) directory")
parser.add_argument(
"-c", "--content",
action="store_true",
help="Compare file contents via MD5 hash (slower)"
)
parser.add_argument(
"-e", "--exclude",
nargs="+",
default=[],
help="List of directory names to exclude (e.g., .git __pycache__)"
)
parser.add_argument(
"-o", "--output",
choices=["text", "json"],
default="text",
help="Output format (default: text)"
)
parser.add_argument(
"-q", "--quiet",
action="store_true",
help="Only show differences (hide identical files)"
)
args = parser.parse_args()
p1 = Path(args.dir1)
p2 = Path(args.dir2)
if not p1.exists() or not p2.exists():
print("Error: One or both directories do not exist.", file=sys.stderr)
sys.exit(1)
results = compare_directories(p1, p2, args.content, args.exclude)
if args.output == "json":
print(json.dumps(results, indent=4))
else:
# Text Output
if results["left_only"]:
print(f"\n📁 Only in '{args.dir1}':")
for item in results["left_only"]:
print(f" + {item}")
if results["right_only"]:
print(f"\n📁 Only in '{args.dir2}':")
for item in results["right_only"]:
print(f" - {item}")
if results["diff_content"]:
print(f"\n⚠️ Content Diffs:")
for item in results["diff_content"]:
print(f" ! {item}")
if not args.quiet and results["identical"]:
print(f"\n✅ Identical Files/Folders: {len(results['identical'])}")
# Summary
total_diffs = len(results["left_only"]) + len(results["right_only"]) + len(results["diff_content"])
if total_diffs == 0:
print("\n✨ Directory structures are identical.")
else:
print(f"\n🚨 Found {total_diffs} differences.")
if __name__ == "__main__":
main()