1 from __future__ import absolute_import
7 from pip.basecommand import Command
8 from pip.status_codes import ERROR
9 from pip.utils import read_chunks
10 from pip.utils.hashes import FAVORITE_HASH, STRONG_HASHES
13 logger = logging.getLogger(__name__)
16 class HashCommand(Command):
18 Compute a hash of a local package archive.
20 These can be used with --hash in a requirements file to do repeatable
25 usage = '%prog [options] <file> ...'
26 summary = 'Compute hashes of package archives.'
28 def __init__(self, *args, **kw):
29 super(HashCommand, self).__init__(*args, **kw)
30 self.cmd_opts.add_option(
33 choices=STRONG_HASHES,
35 default=FAVORITE_HASH,
36 help='The hash algorithm to use: one of %s' %
37 ', '.join(STRONG_HASHES))
38 self.parser.insert_option_group(0, self.cmd_opts)
40 def run(self, options, args):
42 self.parser.print_usage(sys.stderr)
45 algorithm = options.algorithm
47 logger.info('%s:\n--hash=%s:%s',
48 path, algorithm, _hash_of_file(path, algorithm))
51 def _hash_of_file(path, algorithm):
52 """Return the hash digest of a file."""
53 with open(path, 'rb') as archive:
54 hash = hashlib.new(algorithm)
55 for chunk in read_chunks(archive):
57 return hash.hexdigest()