(args=None)
| 2314 | |
| 2315 | |
| 2316 | def main(args=None): |
| 2317 | import argparse |
| 2318 | |
| 2319 | description = 'A simple command-line interface for zipfile module.' |
| 2320 | parser = argparse.ArgumentParser(description=description, color=True) |
| 2321 | group = parser.add_mutually_exclusive_group(required=True) |
| 2322 | group.add_argument('-l', '--list', metavar='<zipfile>', |
| 2323 | help='Show listing of a zipfile') |
| 2324 | group.add_argument('-e', '--extract', nargs=2, |
| 2325 | metavar=('<zipfile>', '<output_dir>'), |
| 2326 | help='Extract zipfile into target dir') |
| 2327 | group.add_argument('-c', '--create', nargs='+', |
| 2328 | metavar=('<name>', '<file>'), |
| 2329 | help='Create zipfile from sources') |
| 2330 | group.add_argument('-t', '--test', metavar='<zipfile>', |
| 2331 | help='Test if a zipfile is valid') |
| 2332 | parser.add_argument('--metadata-encoding', metavar='<encoding>', |
| 2333 | help='Specify encoding of member names for -l, -e and -t') |
| 2334 | args = parser.parse_args(args) |
| 2335 | |
| 2336 | encoding = args.metadata_encoding |
| 2337 | |
| 2338 | if args.test is not None: |
| 2339 | src = args.test |
| 2340 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2341 | badfile = zf.testzip() |
| 2342 | if badfile: |
| 2343 | print("The following enclosed file is corrupted: {!r}".format(badfile)) |
| 2344 | print("Done testing") |
| 2345 | |
| 2346 | elif args.list is not None: |
| 2347 | src = args.list |
| 2348 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2349 | zf.printdir() |
| 2350 | |
| 2351 | elif args.extract is not None: |
| 2352 | src, curdir = args.extract |
| 2353 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2354 | zf.extractall(curdir) |
| 2355 | |
| 2356 | elif args.create is not None: |
| 2357 | if encoding: |
| 2358 | print("Non-conforming encodings not supported with -c.", |
| 2359 | file=sys.stderr) |
| 2360 | sys.exit(1) |
| 2361 | |
| 2362 | zip_name = args.create.pop(0) |
| 2363 | files = args.create |
| 2364 | |
| 2365 | def addToZip(zf, path, zippath): |
| 2366 | if os.path.isfile(path): |
| 2367 | zf.write(path, zippath, ZIP_DEFLATED) |
| 2368 | elif os.path.isdir(path): |
| 2369 | if zippath: |
| 2370 | zf.write(path, zippath) |
| 2371 | for nm in sorted(os.listdir(path)): |
| 2372 | addToZip(zf, |
| 2373 | os.path.join(path, nm), os.path.join(zippath, nm)) |
nothing calls this directly
no test coverage detected
searching dependent graphs…