Analyzing the Project's Scope
I'm focused on grasping the core aim: crafting a Python CLI tool for directory structure comparison. I've broken down the main task and now, I'm identifying the desired functionalities, specifically pinpointing discrepancies like missing files and folders, as well as file content differences.
Outlining Implementation Strategy
I'm leaning towards the filecmp.dircmp approach. I'm strategizing how to adapt it for a recursive depth-first comparison. My focus now is on extending its default functionality to achieve a thorough comparison of the directory structures and reporting all differences comprehensively, including file content variations. I'm considering writing a wrapper function to ensure it behaves precisely as needed.
Developing Comparison Logic
I'm now focusing on how the directory comparison will actually happen. Using filecmp.dircmp as the core, I'm thinking about extending its default, level-specific behavior with a recursive function to navigate nested directories. This will give me a proper traversal of the two directories being compared.
Considering User Interface & Output
I'm now revising the output strategy for better user experience. Instead of immediate printing, I'm opting to gather all discrepancies into organized lists during the directory traversal. These lists will include files unique to each directory, differing content, and potentially identical files, if requested. A final, concise summary will then present the findings, enhancing readability.
Implementing Recursive Traversal
I'm now integrating the recursive function to traverse subdirectories using filecmp.dircmp. I'm going beyond the base class to recursively compare subdirectories and aggregate the discrepancies. I plan to use the subdirs attribute to go through nested directories. Furthermore, I'm thinking of creating distinct lists for different types of differences, which makes the subsequent reporting phase more structured.
Implementing Core Functionality
I'm now fully focused on creating the DirectoryComparator class and its recursive comparison method. I have integrated the filecmp.dircmp to handle the heavy lifting. I'm focusing on crafting output that clearly identifies the differences between directories, and it's organized and easy to understand.
Implementing Final Code & Testing
I'm now putting the finishing touches on the DirectoryComparator class. I'm incorporating the ANSI color codes for enhanced readability of the CLI output, marking differences clearly. My focus includes error handling for cases like non-existent directories, ensuring the tool is robust. Then, I plan to test it comprehensively with varied directory structures to ensure the tool operates correctly.
Refining Output Structure
I'm now prioritizing the readability and user experience of the tool's output. I'm moving away from printing directly during the comparison, and towards gathering all discrepancies into organized lists or dictionaries. These will include files unique to each directory, files with differing content, and potentially identical files, if the user opts in. I'm aiming for a final, concise, and easy-to-understand summary of the comparison results.
Here is a robust, ready-to-use Python CLI tool to compare directory structures.
It uses the standard library filecmp module for efficient comparison and includes color-coded output, recursion, and summary statistics.
The Python Script (dircomp.py)
Save the following code into a file named dircomp.py.
import argparse
import filecmp
import os
import sys
from pathlib import Path
# ANSI Color Codes for terminal output
class Colors:
GREEN = '\033[92m' # Only in Dir 1
BLUE = '\033[94m' # Only in Dir 2
RED = '\033[91m' # Diff content
RESET = '\033[0m'
BOLD = '\033[1m'
class DirComparator:
def __init__(self, dir1, dir2, shallow=True, show_common=False):
self.dir1 = Path(dir1)
self.dir2 = Path(dir2)
self.shallow = shallow
self.show_common = show_common
# Statistics
self.stats = {
"left_only": 0,
"right_only": 0,
"diff": 0,
"errors": 0
}
def compare(self):
print(f"{Colors.BOLD}Comparing:{Colors.RESET}")
print(f" A: {self.dir1}")
print(f" B: {self.dir2}\n")
if not self.dir1.exists() or not self.dir2.exists():
print(f"{Colors.RED}Error: One or both directories do not exist.{Colors.RESET}")
sys.exit(1)
self._recursive_compare(self.dir1, self.dir2)
self._print_summary()
def _recursive_compare(self, d1, d2):
# filecmp.dircmp performs the comparison
# shallow=True compares stat signatures (time/size), False compares contents
dcmp = filecmp.dircmp(d1, d2)
# 1. Files/Dirs only in Left (Dir 1)
if dcmp.left_only:
for name in dcmp.left_only:
path = os.path.join(d1, name)
print(f"{Colors.GREEN}[<] Only in A: {path}{Colors.RESET}")
self.stats["left_only"] += 1
# 2. Files/Dirs only in Right (Dir 2)
if dcmp.right_only:
for name in dcmp.right_only:
path = os.path.join(d2, name)
print(f"{Colors.BLUE}[>] Only in B: {path}{Colors.RESET}")
self.stats["right_only"] += 1
# 3. Files that differ
if dcmp.diff_files:
for name in dcmp.diff_files:
path = os.path.join(d1, name)
print(f"{Colors.RED}[!] Content Differs: {path}{Colors.RESET}")
self.stats["diff"] += 1
# 4. Funny/Error files (could not be compared)
if dcmp.funny_files:
for name in dcmp.funny_files:
print(f"{Colors.RED}[?] Error comparing: {os.path.join(d1, name)}{Colors.RESET}")
self.stats["errors"] += 1
# 5. Optional: Show identical files
if self.show_common and dcmp.common_files:
for name in dcmp.common_files:
print(f" Match: {os.path.join(d1, name)}")
# 6. Recursion for common subdirectories
for sub_dir in dcmp.subdirs.values():
self._recursive_compare(sub_dir.left, sub_dir.right)
def _print_summary(self):
print(f"\n{Colors.BOLD}--- Summary ---{Colors.RESET}")
print(f"Only in {self.dir1.name}: {self.stats['left_only']}")
print(f"Only in {self.dir2.name}: {self.stats['right_only']}")
print(f"Differing content: {self.stats['diff']}")
if self.stats['errors'] > 0:
print(f"Errors: {self.stats['errors']}")
print("----------------")
def main():
parser = argparse.ArgumentParser(description="Compare two directory structures recursively.")
parser.add_argument("dir1", help="Path to the first directory (Reference)")
parser.add_argument("dir2", help="Path to the second directory (Target)")
parser.add_argument("--deep", action="store_false", dest="shallow",
help="Perform deep comparison (read file contents). Default is shallow (metadata only).")
parser.add_argument("--verbose", "-v", action="store_true",
help="Show identical files as well.")
args = parser.parse_args()
comparator = DirComparator(args.dir1, args.dir2, shallow=args.shallow, show_common=args.verbose)
comparator.compare()
if __name__ == "__main__":
main()
Features
- Recursive Comparison: It automatically traverses into sub-directories that exist in both locations.
- Color Coded Output:
- Green
<: Item exists only in Directory 1.
- Blue
>: Item exists only in Directory 2.
- Red
!: Item exists in both but content is different.
- Shallow vs Deep:
- By default, it uses "Shallow" comparison (checks file size and modification time). This is very fast.
- Use the
--deep flag to force the tool to read the actual file bytes (useful if timestamps are identical but content might differ).
- Summary Statistics: Prints a count of differences at the end of the execution.
How to use it
-
Basic Comparison:
python dircomp.py ./folder_v1 ./folder_v2
-
Deep Comparison:
Use this if you suspect files verify matches content modification without date changes.
python dircomp.py ./folder_v1 ./folder_v2 --deep
-
Verbose (Show matches):
To see files that are identical in addition to the differences.
python dircomp.py ./folder_v1 ./folder_v2 --verbose
How it works (Technical Details)
argparse: Handles the command line input.
filecmp.dircmp: This is the core logic. It is a Python built-in class that compares directories. It lazily evaluates attributes like left_only (files in dir1 only), right_only, diff_files, and common_dirs.
- Recursion: The
dircmp class provides a subdirs dictionary. The script loops through this dictionary to recursively call the comparison method on subfolders effectively traversing the entire tree.