OSDN Git Service

27cca0bfa409121799aa9260d659727b094a76db
[stux/ultron.git] / venv / Lib / site-packages / pip / commands / hash.py
1 from __future__ import absolute_import
2
3 import hashlib
4 import logging
5 import sys
6
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
11
12
13 logger = logging.getLogger(__name__)
14
15
16 class HashCommand(Command):
17     """
18     Compute a hash of a local package archive.
19
20     These can be used with --hash in a requirements file to do repeatable
21     installs.
22
23     """
24     name = 'hash'
25     usage = '%prog [options] <file> ...'
26     summary = 'Compute hashes of package archives.'
27
28     def __init__(self, *args, **kw):
29         super(HashCommand, self).__init__(*args, **kw)
30         self.cmd_opts.add_option(
31             '-a', '--algorithm',
32             dest='algorithm',
33             choices=STRONG_HASHES,
34             action='store',
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)
39
40     def run(self, options, args):
41         if not args:
42             self.parser.print_usage(sys.stderr)
43             return ERROR
44
45         algorithm = options.algorithm
46         for path in args:
47             logger.info('%s:\n--hash=%s:%s',
48                         path, algorithm, _hash_of_file(path, algorithm))
49
50
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):
56             hash.update(chunk)
57     return hash.hexdigest()