Path: blob/master/venv/Lib/site-packages/pip/_internal/commands/hash.py
811 views
# The following comment should be removed at some point in the future.1# mypy: disallow-untyped-defs=False23from __future__ import absolute_import45import hashlib6import logging7import sys89from pip._internal.cli.base_command import Command10from pip._internal.cli.status_codes import ERROR11from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES12from pip._internal.utils.misc import read_chunks, write_output1314logger = logging.getLogger(__name__)151617class HashCommand(Command):18"""19Compute a hash of a local package archive.2021These can be used with --hash in a requirements file to do repeatable22installs.23"""2425usage = '%prog [options] <file> ...'26ignore_require_venv = True2728def __init__(self, *args, **kw):29super(HashCommand, self).__init__(*args, **kw)30self.cmd_opts.add_option(31'-a', '--algorithm',32dest='algorithm',33choices=STRONG_HASHES,34action='store',35default=FAVORITE_HASH,36help='The hash algorithm to use: one of {}'.format(37', '.join(STRONG_HASHES)))38self.parser.insert_option_group(0, self.cmd_opts)3940def run(self, options, args):41if not args:42self.parser.print_usage(sys.stderr)43return ERROR4445algorithm = options.algorithm46for path in args:47write_output('%s:\n--hash=%s:%s',48path, algorithm, _hash_of_file(path, algorithm))495051def _hash_of_file(path, algorithm):52"""Return the hash digest of a file."""53with open(path, 'rb') as archive:54hash = hashlib.new(algorithm)55for chunk in read_chunks(archive):56hash.update(chunk)57return hash.hexdigest()585960