(args=None)
| 2358 | |
| 2359 | |
| 2360 | def main(args=None): |
| 2361 | import argparse |
| 2362 | |
| 2363 | description = 'A simple command-line interface for zipfile module.' |
| 2364 | parser = argparse.ArgumentParser(description=description, color=True) |
| 2365 | group = parser.add_mutually_exclusive_group(required=True) |
| 2366 | group.add_argument('-l', '--list', metavar='<zipfile>', |
| 2367 | help='Show listing of a zipfile') |
| 2368 | group.add_argument('-e', '--extract', nargs=2, |
| 2369 | metavar=('<zipfile>', '<output_dir>'), |
| 2370 | help='Extract zipfile into target dir') |
| 2371 | group.add_argument('-c', '--create', nargs='+', |
| 2372 | metavar=('<name>', '<file>'), |
| 2373 | help='Create zipfile from sources') |
| 2374 | group.add_argument('-t', '--test', metavar='<zipfile>', |
| 2375 | help='Test if a zipfile is valid') |
| 2376 | parser.add_argument('--metadata-encoding', metavar='<encoding>', |
| 2377 | help='Specify encoding of member names for -l, -e and -t') |
| 2378 | args = parser.parse_args(args) |
| 2379 | |
| 2380 | encoding = args.metadata_encoding |
| 2381 | |
| 2382 | if args.test is not None: |
| 2383 | src = args.test |
| 2384 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2385 | badfile = zf.testzip() |
| 2386 | if badfile: |
| 2387 | print("The following enclosed file is corrupted: {!r}".format(badfile)) |
| 2388 | print("Done testing") |
| 2389 | |
| 2390 | elif args.list is not None: |
| 2391 | src = args.list |
| 2392 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2393 | zf.printdir() |
| 2394 | |
| 2395 | elif args.extract is not None: |
| 2396 | src, curdir = args.extract |
| 2397 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2398 | zf.extractall(curdir) |
| 2399 | |
| 2400 | elif args.create is not None: |
| 2401 | if encoding: |
| 2402 | print("Non-conforming encodings not supported with -c.", |
| 2403 | file=sys.stderr) |
| 2404 | sys.exit(1) |
| 2405 | |
| 2406 | zip_name = args.create.pop(0) |
| 2407 | files = args.create |
| 2408 | |
| 2409 | def addToZip(zf, path, zippath): |
| 2410 | if os.path.isfile(path): |
| 2411 | zf.write(path, zippath, ZIP_DEFLATED) |
| 2412 | elif os.path.isdir(path): |
| 2413 | if zippath: |
| 2414 | zf.write(path, zippath) |
| 2415 | for nm in sorted(os.listdir(path)): |
| 2416 | addToZip(zf, |
| 2417 | os.path.join(path, nm), os.path.join(zippath, nm)) |
nothing calls this directly
no test coverage detected