pip/pip/commands/hash.py

60 lines
1.7 KiB
Python
Raw Normal View History

2015-10-08 05:41:24 +02:00
from __future__ import absolute_import
import hashlib
import logging
import sys
from pip.basecommand import Command
2015-10-12 20:01:32 +02:00
from pip.cmdoptions import strong_hashes
2015-10-08 05:41:24 +02:00
from pip.exceptions import FAVORITE_HASH
from pip.status_codes import ERROR
from pip.utils import read_chunks
2015-10-08 05:41:24 +02:00
logger = logging.getLogger(__name__)
class HashCommand(Command):
"""
Compute a hash of a local package archive.
These can be used with --hash in a requirements file to do repeatable
installs.
"""
name = 'hash'
usage = """%prog [options] <file> ..."""
summary = 'Compute hashes of package archives.'
2015-10-12 20:01:32 +02:00
def __init__(self, *args, **kw):
super(HashCommand, self).__init__(*args, **kw)
self.cmd_opts.add_option(
'-a', '--algorithm',
dest='algorithm',
choices=strong_hashes(),
action='store',
default=FAVORITE_HASH,
help='The hash algorithm to use: one of %s' %
', '.join(strong_hashes()))
self.parser.insert_option_group(0, self.cmd_opts)
2015-10-08 05:41:24 +02:00
def run(self, options, args):
if not args:
self.parser.print_usage(sys.stderr)
return ERROR
2015-10-12 20:01:32 +02:00
algorithm = options.algorithm
2015-10-08 05:41:24 +02:00
for path in args:
logger.info('%s:\n--hash=%s:%s' % (path,
2015-10-12 20:01:32 +02:00
algorithm,
_hash_of_file(path, algorithm)))
2015-10-08 05:41:24 +02:00
2015-10-12 20:01:32 +02:00
def _hash_of_file(path, algorithm):
2015-10-08 05:41:24 +02:00
"""Return the hash digest of a file."""
with open(path, 'rb') as archive:
2015-10-12 20:01:32 +02:00
hash = hashlib.new(algorithm)
for chunk in read_chunks(archive):
hash.update(chunk)
2015-10-08 05:41:24 +02:00
return hash.hexdigest()