Debian Codegraph @

snappy/__main__.py

raw
1 from __future__ import absolute_import
2
3 import argparse
4 import io
5 import sys
6
7 from . import snappy_formats as formats
8 from .snappy import UncompressError
9
10
11 def cmdline_main():
12 """This method is what is run when invoking snappy via the commandline.
13 Try python -m snappy --help
14 """
15 stdin = sys.stdin
16 if hasattr(sys.stdin, "buffer"):
17 stdin = sys.stdin.buffer
18 stdout = sys.stdout
19 if hasattr(sys.stdout, "buffer"):
20 stdout = sys.stdout.buffer
21
22 parser = argparse.ArgumentParser(
23 description="Compress or decompress snappy archive"
24 )
25
26 group = parser.add_mutually_exclusive_group(required=True)
27
28 group.add_argument(
29 '-c',
30 dest='compress',
31 action='store_true',
32 help='Compress'
33 )
34 group.add_argument(
35 '-d',
36 dest='decompress',
37 action='store_true',
38 help='Decompress'
39 )
40
41 parser.add_argument(
42 '-t',
43 dest='target_format',
44 default=formats.DEFAULT_FORMAT,
45 choices=formats.ALL_SUPPORTED_FORMATS,
46 help=(
47 'Target format, default is "{}"'.format(formats.DEFAULT_FORMAT)
48 )
49 )
50
51 parser.add_argument(
52 'infile',
53 nargs='?',
54 type=argparse.FileType(mode='rb'),
55 default=stdin,
56 help="Input file (or stdin)"
57 )
58 parser.add_argument(
59 'outfile',
60 nargs='?',
61 type=argparse.FileType(mode='wb'),
62 default=stdout,
63 help="Output file (or stdout)"
64 )
65
66 args = parser.parse_args()
67
68 # workaround for https://bugs.python.org/issue14156
69 if isinstance(args.infile, io.TextIOWrapper):
70 args.infile = stdin
71 if isinstance(args.outfile, io.TextIOWrapper):
72 args.outfile = stdout
73
74 additional_args = {}
75 if args.compress:
76 method = formats.get_compress_function(args.target_format)
77 else:
78 try:
79 method, read_chunk = formats.get_decompress_function(
80 args.target_format,
81 args.infile
82 )
83 except UncompressError as err:
84 sys.exit("Failed to get decompress function: {}".format(err))
85 additional_args['start_chunk'] = read_chunk
86
87 method(args.infile, args.outfile, **additional_args)
88
89
90 if __name__ == "__main__":
91 try:
92 cmdline_main()
93 except Exception as err:
94 sys.exit("%s: %s" % (err.__class__.__name__, err))