hash.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from __future__ import absolute_import
  2. import hashlib
  3. import logging
  4. import sys
  5. from pip.basecommand import Command
  6. from pip.status_codes import ERROR
  7. from pip.utils import read_chunks
  8. from pip.utils.hashes import FAVORITE_HASH, STRONG_HASHES
  9. logger = logging.getLogger(__name__)
  10. class HashCommand(Command):
  11. """
  12. Compute a hash of a local package archive.
  13. These can be used with --hash in a requirements file to do repeatable
  14. installs.
  15. """
  16. name = 'hash'
  17. usage = '%prog [options] <file> ...'
  18. summary = 'Compute hashes of package archives.'
  19. def __init__(self, *args, **kw):
  20. super(HashCommand, self).__init__(*args, **kw)
  21. self.cmd_opts.add_option(
  22. '-a', '--algorithm',
  23. dest='algorithm',
  24. choices=STRONG_HASHES,
  25. action='store',
  26. default=FAVORITE_HASH,
  27. help='The hash algorithm to use: one of %s' %
  28. ', '.join(STRONG_HASHES))
  29. self.parser.insert_option_group(0, self.cmd_opts)
  30. def run(self, options, args):
  31. if not args:
  32. self.parser.print_usage(sys.stderr)
  33. return ERROR
  34. algorithm = options.algorithm
  35. for path in args:
  36. logger.info('%s:\n--hash=%s:%s',
  37. path, algorithm, _hash_of_file(path, algorithm))
  38. def _hash_of_file(path, algorithm):
  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()