__main__.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import sys
  2. import os
  3. from . import ZipFile, ZIP_DEFLATED
  4. def main(args=None):
  5. import argparse
  6. description = 'A simple command-line interface for zipfile module.'
  7. parser = argparse.ArgumentParser(description=description)
  8. group = parser.add_mutually_exclusive_group(required=True)
  9. group.add_argument('-l', '--list', metavar='<zipfile>',
  10. help='Show listing of a zipfile')
  11. group.add_argument('-e', '--extract', nargs=2,
  12. metavar=('<zipfile>', '<output_dir>'),
  13. help='Extract zipfile into target dir')
  14. group.add_argument('-c', '--create', nargs='+',
  15. metavar=('<name>', '<file>'),
  16. help='Create zipfile from sources')
  17. group.add_argument('-t', '--test', metavar='<zipfile>',
  18. help='Test if a zipfile is valid')
  19. parser.add_argument('--metadata-encoding', metavar='<encoding>',
  20. help='Specify encoding of member names for -l, -e and -t')
  21. args = parser.parse_args(args)
  22. encoding = args.metadata_encoding
  23. if args.test is not None:
  24. src = args.test
  25. with ZipFile(src, 'r', metadata_encoding=encoding) as zf:
  26. badfile = zf.testzip()
  27. if badfile:
  28. print("The following enclosed file is corrupted: {!r}".format(badfile))
  29. print("Done testing")
  30. elif args.list is not None:
  31. src = args.list
  32. with ZipFile(src, 'r', metadata_encoding=encoding) as zf:
  33. zf.printdir()
  34. elif args.extract is not None:
  35. src, curdir = args.extract
  36. with ZipFile(src, 'r', metadata_encoding=encoding) as zf:
  37. zf.extractall(curdir)
  38. elif args.create is not None:
  39. if encoding:
  40. print("Non-conforming encodings not supported with -c.",
  41. file=sys.stderr)
  42. sys.exit(1)
  43. zip_name = args.create.pop(0)
  44. files = args.create
  45. def addToZip(zf, path, zippath):
  46. if os.path.isfile(path):
  47. zf.write(path, zippath, ZIP_DEFLATED)
  48. elif os.path.isdir(path):
  49. if zippath:
  50. zf.write(path, zippath)
  51. for nm in sorted(os.listdir(path)):
  52. addToZip(zf,
  53. os.path.join(path, nm), os.path.join(zippath, nm))
  54. # else: ignore
  55. with ZipFile(zip_name, 'w') as zf:
  56. for path in files:
  57. zippath = os.path.basename(path)
  58. if not zippath:
  59. zippath = os.path.basename(os.path.dirname(path))
  60. if zippath in ('', os.curdir, os.pardir):
  61. zippath = ''
  62. addToZip(zf, path, zippath)
  63. if __name__ == "__main__":
  64. main()