hash.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import hashlib
  2. import logging
  3. import sys
  4. from optparse import Values
  5. from typing import List
  6. from pip._internal.cli.base_command import Command
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
  9. from pip._internal.utils.misc import read_chunks, write_output
  10. logger = logging.getLogger(__name__)
  11. class HashCommand(Command):
  12. """
  13. Compute a hash of a local package archive.
  14. These can be used with --hash in a requirements file to do repeatable
  15. installs.
  16. """
  17. usage = '%prog [options] <file> ...'
  18. ignore_require_venv = True
  19. def add_options(self) -> None:
  20. self.cmd_opts.add_option(
  21. '-a', '--algorithm',
  22. dest='algorithm',
  23. choices=STRONG_HASHES,
  24. action='store',
  25. default=FAVORITE_HASH,
  26. help='The hash algorithm to use: one of {}'.format(
  27. ', '.join(STRONG_HASHES)))
  28. self.parser.insert_option_group(0, self.cmd_opts)
  29. def run(self, options: Values, args: List[str]) -> int:
  30. if not args:
  31. self.parser.print_usage(sys.stderr)
  32. return ERROR
  33. algorithm = options.algorithm
  34. for path in args:
  35. write_output('%s:\n--hash=%s:%s',
  36. path, algorithm, _hash_of_file(path, algorithm))
  37. return SUCCESS
  38. def _hash_of_file(path: str, algorithm: str) -> str:
  39. """Return the hash digest of a file."""
  40. with open(path, 'rb') as archive:
  41. hash = hashlib.new(algorithm)
  42. for chunk in read_chunks(archive):
  43. hash.update(chunk)
  44. return hash.hexdigest()