Last active
August 11, 2023 09:43
-
-
Save Ogaday/3f6f1fb1c15a9d54ba7ee650b9ba7278 to your computer and use it in GitHub Desktop.
Hash paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """Utility to produce the hash of a collection of file and directory paths. | |
| Usage:: | |
| ./hash_paths.py --help | |
| """ | |
| import argparse | |
| import hashlib | |
| import io | |
| from tarfile import GNU_FORMAT, TarFile | |
| def hash_paths(*paths: str, algorithm: str = "sha1") -> str: | |
| """Hash a collection of file and directory paths. | |
| Calculates the digest by adding the paths to an in-memory archive and hashing the | |
| contents. | |
| """ | |
| with io.BytesIO() as f: | |
| with TarFile(fileobj=f, mode="w", format=GNU_FORMAT) as tar: | |
| for path in paths: | |
| tar.add(path) | |
| f.seek(0) | |
| return hashlib.new(algorithm, f.read(), usedforsecurity=False).hexdigest() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser( | |
| description="Calculate the collective hash of a series of paths" | |
| ) | |
| parser.add_argument( | |
| "path", type=str, nargs="+", help="a file or directory path to add to the hash" | |
| ) | |
| parser.add_argument( | |
| "--algorithm", | |
| type=str, | |
| metavar="ALGO", | |
| default="sha1", | |
| help="openssl algorithm to use for hashing. (default: sha1)", | |
| ) | |
| args = parser.parse_args() | |
| print(hash_paths(*args.path, algorithm=args.algorithm)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| function hashpaths() { | |
| HASH_ALGO=${HASH_ALGO:-sha1sum} | |
| tar cf - "$@"| $HASH_ALGO | cut -f 1 -d ' ' | |
| return 0 | |
| } | |
| function usage() { | |
| cat <<USAGE | |
| $0 [-h] path [path ...] | |
| Calculate the collective hash of a series of paths. | |
| positional arguments: | |
| path a file or directory path to add to the hash | |
| options: | |
| -h, --help show this help message and exit | |
| env: | |
| HASH_ALGO select the hash algorithm. (default sha1sum) | |
| example: | |
| HASH_ALGO=md5sum $0 foo bar.txt | |
| USAGE | |
| return 0 | |
| } | |
| [[ -z $1 || $1 == "-h" || $1 == "--help" ]] && { usage; } || hashpaths "$@" | |
| exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment