You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hash.py 1.7KB

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