Skip to content

Commit e331dcf

Browse files
committed
Migrate optparse to argparse; optparse deprecated in py2.7
cleanup example
1 parent db0f924 commit e331dcf

1 file changed

Lines changed: 106 additions & 77 deletions

File tree

sqlparse/__main__.py

Lines changed: 106 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -6,110 +6,139 @@
66
# This module is part of python-sqlparse and is released under
77
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
88

9-
import optparse
9+
import argparse
1010
import sys
1111

1212
import sqlparse
13+
from sqlparse.compat import PY2
1314
from sqlparse.exceptions import SQLParseError
1415

1516
_CASE_CHOICES = ['upper', 'lower', 'capitalize']
1617

17-
parser = optparse.OptionParser(usage='%prog [OPTIONS] FILE, ...',
18-
version='%%prog %s' % sqlparse.__version__)
19-
parser.set_description(('Format FILE according to OPTIONS. Use "-" as FILE '
20-
'to read from stdin.'))
21-
parser.add_option('-v', '--verbose', dest='verbose', action='store_true')
22-
parser.add_option('-o', '--outfile', dest='outfile', metavar='FILE',
23-
help='write output to FILE (defaults to stdout)')
24-
group = parser.add_option_group('Formatting Options')
25-
group.add_option('-k', '--keywords', metavar='CHOICE',
26-
dest='keyword_case', choices=_CASE_CHOICES,
27-
help=('change case of keywords, CHOICE is one of %s'
28-
% ', '.join('"%s"' % x for x in _CASE_CHOICES)))
29-
group.add_option('-i', '--identifiers', metavar='CHOICE',
30-
dest='identifier_case', choices=_CASE_CHOICES,
31-
help=('change case of identifiers, CHOICE is one of %s'
32-
% ', '.join('"%s"' % x for x in _CASE_CHOICES)))
33-
group.add_option('-l', '--language', metavar='LANG',
34-
dest='output_format', choices=['python', 'php'],
35-
help=('output a snippet in programming language LANG, '
36-
'choices are "python", "php"'))
37-
group.add_option('--strip-comments', dest='strip_comments',
38-
action='store_true', default=False,
39-
help='remove comments')
40-
group.add_option('-r', '--reindent', dest='reindent',
41-
action='store_true', default=False,
42-
help='reindent statements')
43-
group.add_option('--indent_width', dest='indent_width', default=2,
44-
help='indentation width (defaults to 2 spaces)')
45-
group.add_option('-a', '--reindent_aligned',
46-
action='store_true', default=False,
47-
help='reindent statements to aligned format')
48-
group.add_option('-s', '--use_space_around_operators',
49-
action='store_true', default=False,
50-
help='place spaces around mathematical operators')
51-
group.add_option('--wrap_after', dest='wrap_after', default=0,
52-
help='Column after which lists should be wrapped')
53-
54-
_FORMATTING_GROUP = group
55-
56-
57-
def _error(msg, exit_=None):
18+
# TODO: Add CLI Tests
19+
# TODO: Simplify formatter by using argparse `type` arguments
20+
parser = argparse.ArgumentParser(
21+
prog='sqlparse',
22+
description='Format FILE according to OPTIONS. Use "-" as FILE '
23+
'to read from stdin.',
24+
usage='%(prog)s [OPTIONS] FILE, ...',
25+
version=sqlparse.__version__,)
26+
27+
parser.add_argument('filename')
28+
29+
parser.add_argument(
30+
'-o', '--outfile',
31+
dest='outfile',
32+
metavar='FILE',
33+
help='write output to FILE (defaults to stdout)')
34+
35+
group = parser.add_argument_group('Formatting Options')
36+
37+
group.add_argument(
38+
'-k', '--keywords',
39+
metavar='CHOICE',
40+
dest='keyword_case',
41+
choices=_CASE_CHOICES,
42+
help='change case of keywords, CHOICE is one of {0}'.format(
43+
', '.join('"{0}"'.format(x) for x in _CASE_CHOICES)))
44+
45+
group.add_argument(
46+
'-i', '--identifiers',
47+
metavar='CHOICE',
48+
dest='identifier_case',
49+
choices=_CASE_CHOICES,
50+
help='change case of identifiers, CHOICE is one of {0}'.format(
51+
', '.join('"{0}"'.format(x) for x in _CASE_CHOICES)))
52+
53+
group.add_argument(
54+
'-l', '--language',
55+
metavar='LANG',
56+
dest='output_format',
57+
choices=['python', 'php'],
58+
help='output a snippet in programming language LANG, '
59+
'choices are "python", "php"')
60+
61+
group.add_argument(
62+
'--strip-comments',
63+
dest='strip_comments',
64+
action='store_true',
65+
default=False,
66+
help='remove comments')
67+
68+
group.add_argument(
69+
'-r', '--reindent',
70+
dest='reindent',
71+
action='store_true',
72+
default=False,
73+
help='reindent statements')
74+
75+
group.add_argument(
76+
'--indent_width',
77+
dest='indent_width',
78+
default=2,
79+
type=int,
80+
help='indentation width (defaults to 2 spaces)')
81+
82+
group.add_argument(
83+
'-a', '--reindent_aligned',
84+
action='store_true',
85+
default=False,
86+
help='reindent statements to aligned format')
87+
88+
group.add_argument(
89+
'-s', '--use_space_around_operators',
90+
action='store_true',
91+
default=False,
92+
help='place spaces around mathematical operators')
93+
94+
group.add_argument(
95+
'--wrap_after',
96+
dest='wrap_after',
97+
default=0,
98+
type=int,
99+
help='Column after which lists should be wrapped')
100+
101+
102+
def _error(msg):
58103
"""Print msg and optionally exit with return code exit_."""
59104
sys.stderr.write('[ERROR] %s\n' % msg)
60-
if exit_ is not None:
61-
sys.exit(exit_)
62105

63106

64-
def _build_formatter_opts(options):
65-
"""Convert command line options to dictionary."""
66-
d = {}
67-
for option in _FORMATTING_GROUP.option_list:
68-
d[option.dest] = getattr(options, option.dest)
69-
return d
107+
def main(args=None):
108+
args = parser.parse_args(args)
70109

71-
72-
def main():
73-
options, args = parser.parse_args()
74-
if options.verbose:
75-
sys.stderr.write('Verbose mode\n')
76-
77-
if len(args) != 1:
78-
_error('No input data.')
79-
parser.print_usage()
80-
sys.exit(1)
81-
82-
if '-' in args: # read from stdin
110+
if args.filename == '-': # read from stdin
83111
data = sys.stdin.read()
84112
else:
85113
try:
86-
data = ''.join(open(args[0]).readlines())
87-
except OSError:
88-
err = sys.exc_info()[1] # Python 2.5 compatibility
89-
_error('Failed to read %s: %s' % (args[0], err), exit_=1)
114+
data = ''.join(open(args.filename).readlines())
115+
except IOError as e:
116+
_error('Failed to read %s: %s' % (args.filename, e))
117+
return 1
90118

91-
if options.outfile:
119+
if args.outfile:
92120
try:
93-
stream = open(options.outfile, 'w')
94-
except OSError:
95-
err = sys.exc_info()[1] # Python 2.5 compatibility
96-
_error('Failed to open %s: %s' % (options.outfile, err), exit_=1)
121+
stream = open(args.outfile, 'w')
122+
except IOError as e:
123+
_error('Failed to open %s: %s' % (args.outfile, e))
124+
return 1
97125
else:
98126
stream = sys.stdout
99127

100-
formatter_opts = _build_formatter_opts(options)
128+
formatter_opts = vars(args)
101129
try:
102130
formatter_opts = sqlparse.formatter.validate_options(formatter_opts)
103-
except SQLParseError:
104-
err = sys.exc_info()[1] # Python 2.5 compatibility
105-
_error('Invalid options: %s' % err, exit_=1)
131+
except SQLParseError as e:
132+
_error('Invalid options: %s' % e)
133+
return 1
106134

107135
s = sqlparse.format(data, **formatter_opts)
108-
if sys.version_info < (3,):
136+
if PY2:
109137
s = s.encode('utf-8', 'replace')
110138
stream.write(s)
111139
stream.flush()
140+
return 0
112141

113142

114143
if __name__ == '__main__':
115-
main()
144+
sys.exit(main())

0 commit comments

Comments
 (0)