图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB

  1. import hashlib
  2. import logging
  3. import sys
  4. from optparse import Values
  5. from typing import List
  6. from pip._internal.cli.base_command import Command
  7. from pip._internal.cli.status_codes import ERROR, SUCCESS
  8. from pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES
  9. from pip._internal.utils.misc import read_chunks, write_output
  10. logger = logging.getLogger(__name__)
  11. class HashCommand(Command):
  12. """
  13. Compute a hash of a local package archive.
  14. These can be used with --hash in a requirements file to do repeatable
  15. installs.
  16. """
  17. usage = "%prog [options] <file> ..."
  18. ignore_require_venv = True
  19. def add_options(self) -> None:
  20. self.cmd_opts.add_option(
  21. "-a",
  22. "--algorithm",
  23. dest="algorithm",
  24. choices=STRONG_HASHES,
  25. action="store",
  26. default=FAVORITE_HASH,
  27. help="The hash algorithm to use: one of {}".format(
  28. ", ".join(STRONG_HASHES)
  29. ),
  30. )
  31. self.parser.insert_option_group(0, self.cmd_opts)
  32. def run(self, options: Values, args: List[str]) -> int:
  33. if not args:
  34. self.parser.print_usage(sys.stderr)
  35. return ERROR
  36. algorithm = options.algorithm
  37. for path in args:
  38. write_output(
  39. "%s:\n--hash=%s:%s", path, algorithm, _hash_of_file(path, algorithm)
  40. )
  41. return SUCCESS
  42. def _hash_of_file(path: str, algorithm: str) -> str:
  43. """Return the hash digest of a file."""
  44. with open(path, "rb") as archive:
  45. hash = hashlib.new(algorithm)
  46. for chunk in read_chunks(archive):
  47. hash.update(chunk)
  48. return hash.hexdigest()