|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Command-line script to calculate and print file checksums. |
| 4 | +
|
| 5 | +Usage: |
| 6 | + python scripts/local/checksum.py <file_path> [--algorithm <algorithm>] |
| 7 | +
|
| 8 | +Examples: |
| 9 | + python scripts/local/checksum.py README.md |
| 10 | + python scripts/local/checksum.py README.md --algorithm md5 |
| 11 | + python scripts/local/checksum.py README.md --algorithm sha1 |
| 12 | + python scripts/local/checksum.py README.md --algorithm sha512 |
| 13 | +""" |
| 14 | + |
| 15 | +import argparse |
| 16 | +import sys |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +# Add the project root to the Python path |
| 20 | +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) |
| 21 | + |
| 22 | +from src.utils.file import calculate_file_checksum, print_file_checksum |
| 23 | + |
| 24 | + |
| 25 | +def main(): |
| 26 | + parser = argparse.ArgumentParser( |
| 27 | + description="Calculate and print file checksums", |
| 28 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 29 | + epilog=""" |
| 30 | +Examples: |
| 31 | + %(prog)s README.md |
| 32 | + %(prog)s README.md --algorithm md5 |
| 33 | + %(prog)s README.md --algorithm sha1 |
| 34 | + %(prog)s README.md --algorithm sha512 |
| 35 | +
|
| 36 | +Supported algorithms: md5, sha1, sha256 (default), sha512 |
| 37 | + """ |
| 38 | + ) |
| 39 | + |
| 40 | + parser.add_argument( |
| 41 | + "file_path", |
| 42 | + help="Path to the file to checksum" |
| 43 | + ) |
| 44 | + |
| 45 | + parser.add_argument( |
| 46 | + "--algorithm", "-a", |
| 47 | + default="sha256", |
| 48 | + choices=["md5", "sha1", "sha256", "sha512"], |
| 49 | + help="Hash algorithm to use (default: sha256)" |
| 50 | + ) |
| 51 | + |
| 52 | + parser.add_argument( |
| 53 | + "--quiet", "-q", |
| 54 | + action="store_true", |
| 55 | + help="Only output the checksum value (no filename or algorithm label)" |
| 56 | + ) |
| 57 | + |
| 58 | + args = parser.parse_args() |
| 59 | + |
| 60 | + try: |
| 61 | + if args.quiet: |
| 62 | + checksum = calculate_file_checksum(args.file_path, args.algorithm) |
| 63 | + print(checksum) |
| 64 | + else: |
| 65 | + print_file_checksum(args.file_path, args.algorithm) |
| 66 | + except (FileNotFoundError, ValueError) as e: |
| 67 | + print(f"Error: {e}", file=sys.stderr) |
| 68 | + sys.exit(1) |
| 69 | + except KeyboardInterrupt: |
| 70 | + print("\nOperation cancelled by user.", file=sys.stderr) |
| 71 | + sys.exit(1) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + main() |
0 commit comments