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