diff options
| author | Victor Uriarte <victor.m.uriarte@intel.com> | 2016-06-15 15:29:29 -0700 |
|---|---|---|
| committer | Victor Uriarte <victor.m.uriarte@intel.com> | 2016-06-15 19:17:16 -0700 |
| commit | 5eab09b6d3e60c9c530d372f0d51849f438a8a7b (patch) | |
| tree | cae6cf86aaa577b995587ac0cbeb5c6ad612d003 /sqlparse | |
| parent | f266ffb600b7a20f593a67dae67fa21700717adc (diff) | |
| download | sqlparse-5eab09b6d3e60c9c530d372f0d51849f438a8a7b.tar.gz | |
Separate __main__ and main() to allow for testing
Also reference example in:
https://github.com/ionelmc/cookiecutter-pylibrary
Diffstat (limited to 'sqlparse')
| -rw-r--r-- | sqlparse/__init__.py | 3 | ||||
| -rw-r--r-- | sqlparse/__main__.py | 143 | ||||
| -rw-r--r-- | sqlparse/cli.py | 163 |
3 files changed, 173 insertions, 136 deletions
diff --git a/sqlparse/__init__.py b/sqlparse/__init__.py index 03f74d1..5c10f14 100644 --- a/sqlparse/__init__.py +++ b/sqlparse/__init__.py @@ -9,6 +9,7 @@ # Setup namespace from sqlparse import sql +from sqlparse import cli from sqlparse import engine from sqlparse import tokens from sqlparse import filters @@ -17,7 +18,7 @@ from sqlparse import formatter from sqlparse.compat import text_type __version__ = '0.2.0.dev0' -__all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens'] +__all__ = ['engine', 'filters', 'formatter', 'sql', 'tokens', 'cli'] def parse(sql, encoding=None): diff --git a/sqlparse/__main__.py b/sqlparse/__main__.py index e6c6ed7..0020038 100644 --- a/sqlparse/__main__.py +++ b/sqlparse/__main__.py @@ -6,144 +6,17 @@ # This module is part of python-sqlparse and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php -import argparse -import sys - -import sqlparse -from sqlparse.compat import PY2 -from sqlparse.exceptions import SQLParseError - -_CASE_CHOICES = ['upper', 'lower', 'capitalize'] - -# TODO: Add CLI Tests -# TODO: Simplify formatter by using argparse `type` arguments -parser = argparse.ArgumentParser( - prog='sqlformat', - description='Format FILE according to OPTIONS. Use "-" as FILE ' - 'to read from stdin.', - usage='%(prog)s [OPTIONS] FILE, ...', -) - -parser.add_argument('filename') - -parser.add_argument( - '-o', '--outfile', - dest='outfile', - metavar='FILE', - help='write output to FILE (defaults to stdout)') - -parser.add_argument( - '--version', - action='version', - version=sqlparse.__version__) - -group = parser.add_argument_group('Formatting Options') - -group.add_argument( - '-k', '--keywords', - metavar='CHOICE', - dest='keyword_case', - choices=_CASE_CHOICES, - help='change case of keywords, CHOICE is one of {0}'.format( - ', '.join('"{0}"'.format(x) for x in _CASE_CHOICES))) - -group.add_argument( - '-i', '--identifiers', - metavar='CHOICE', - dest='identifier_case', - choices=_CASE_CHOICES, - help='change case of identifiers, CHOICE is one of {0}'.format( - ', '.join('"{0}"'.format(x) for x in _CASE_CHOICES))) - -group.add_argument( - '-l', '--language', - metavar='LANG', - dest='output_format', - choices=['python', 'php'], - help='output a snippet in programming language LANG, ' - 'choices are "python", "php"') - -group.add_argument( - '--strip-comments', - dest='strip_comments', - action='store_true', - default=False, - help='remove comments') +"""Entrypoint module for `python -m sqlparse`. -group.add_argument( - '-r', '--reindent', - dest='reindent', - action='store_true', - default=False, - help='reindent statements') +Why does this file exist, and why __main__? For more info, read: +- https://www.python.org/dev/peps/pep-0338/ +- https://docs.python.org/2/using/cmdline.html#cmdoption-m +- https://docs.python.org/3/using/cmdline.html#cmdoption-m +""" -group.add_argument( - '--indent_width', - dest='indent_width', - default=2, - type=int, - help='indentation width (defaults to 2 spaces)') - -group.add_argument( - '-a', '--reindent_aligned', - action='store_true', - default=False, - help='reindent statements to aligned format') - -group.add_argument( - '-s', '--use_space_around_operators', - action='store_true', - default=False, - help='place spaces around mathematical operators') - -group.add_argument( - '--wrap_after', - dest='wrap_after', - default=0, - type=int, - help='Column after which lists should be wrapped') - - -def _error(msg): - """Print msg and optionally exit with return code exit_.""" - sys.stderr.write('[ERROR] %s\n' % msg) - - -def main(args=None): - args = parser.parse_args(args) - - if args.filename == '-': # read from stdin - data = sys.stdin.read() - else: - try: - data = ''.join(open(args.filename).readlines()) - except IOError as e: - _error('Failed to read %s: %s' % (args.filename, e)) - return 1 - - if args.outfile: - try: - stream = open(args.outfile, 'w') - except IOError as e: - _error('Failed to open %s: %s' % (args.outfile, e)) - return 1 - else: - stream = sys.stdout - - formatter_opts = vars(args) - try: - formatter_opts = sqlparse.formatter.validate_options(formatter_opts) - except SQLParseError as e: - _error('Invalid options: %s' % e) - return 1 - - s = sqlparse.format(data, **formatter_opts) - if PY2: - s = s.encode('utf-8', 'replace') - stream.write(s) - stream.flush() - return 0 +import sys +from sqlparse.cli import main if __name__ == '__main__': sys.exit(main()) diff --git a/sqlparse/cli.py b/sqlparse/cli.py new file mode 100644 index 0000000..1009413 --- /dev/null +++ b/sqlparse/cli.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com +# +# This module is part of python-sqlparse and is released under +# the BSD License: http://www.opensource.org/licenses/bsd-license.php + +"""Module that contains the command line app. + +Why does this file exist, and why not put this in __main__? + You might be tempted to import things from __main__ later, but that will + cause problems: the code will get executed twice: + - When you run `python -m sqlparse` python will execute + ``__main__.py`` as a script. That means there won't be any + ``sqlparse.__main__`` in ``sys.modules``. + - When you import __main__ it will get executed again (as a module) because + there's no ``sqlparse.__main__`` in ``sys.modules``. + Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration +""" + +import argparse +import sys + +import sqlparse +from sqlparse.compat import PY2 +from sqlparse.exceptions import SQLParseError + + +# TODO: Add CLI Tests +# TODO: Simplify formatter by using argparse `type` arguments +def create_parser(): + _CASE_CHOICES = ['upper', 'lower', 'capitalize'] + + parser = argparse.ArgumentParser( + prog='sqlformat', + description='Format FILE according to OPTIONS. Use "-" as FILE ' + 'to read from stdin.', + usage='%(prog)s [OPTIONS] FILE, ...', + ) + + parser.add_argument('filename') + + parser.add_argument( + '-o', '--outfile', + dest='outfile', + metavar='FILE', + help='write output to FILE (defaults to stdout)') + + parser.add_argument( + '--version', + action='version', + version=sqlparse.__version__) + + group = parser.add_argument_group('Formatting Options') + + group.add_argument( + '-k', '--keywords', + metavar='CHOICE', + dest='keyword_case', + choices=_CASE_CHOICES, + help='change case of keywords, CHOICE is one of {0}'.format( + ', '.join('"{0}"'.format(x) for x in _CASE_CHOICES))) + + group.add_argument( + '-i', '--identifiers', + metavar='CHOICE', + dest='identifier_case', + choices=_CASE_CHOICES, + help='change case of identifiers, CHOICE is one of {0}'.format( + ', '.join('"{0}"'.format(x) for x in _CASE_CHOICES))) + + group.add_argument( + '-l', '--language', + metavar='LANG', + dest='output_format', + choices=['python', 'php'], + help='output a snippet in programming language LANG, ' + 'choices are "python", "php"') + + group.add_argument( + '--strip-comments', + dest='strip_comments', + action='store_true', + default=False, + help='remove comments') + + group.add_argument( + '-r', '--reindent', + dest='reindent', + action='store_true', + default=False, + help='reindent statements') + + group.add_argument( + '--indent_width', + dest='indent_width', + default=2, + type=int, + help='indentation width (defaults to 2 spaces)') + + group.add_argument( + '-a', '--reindent_aligned', + action='store_true', + default=False, + help='reindent statements to aligned format') + + group.add_argument( + '-s', '--use_space_around_operators', + action='store_true', + default=False, + help='place spaces around mathematical operators') + + group.add_argument( + '--wrap_after', + dest='wrap_after', + default=0, + type=int, + help='Column after which lists should be wrapped') + + return parser + + +def _error(msg): + """Print msg and optionally exit with return code exit_.""" + sys.stderr.write('[ERROR] %s\n' % msg) + + +def main(args=None): + parser = create_parser() + args = parser.parse_args(args) + + if args.filename == '-': # read from stdin + data = sys.stdin.read() + else: + try: + data = ''.join(open(args.filename).readlines()) + except IOError as e: + _error('Failed to read %s: %s' % (args.filename, e)) + return 1 + + if args.outfile: + try: + stream = open(args.outfile, 'w') + except IOError as e: + _error('Failed to open %s: %s' % (args.outfile, e)) + return 1 + else: + stream = sys.stdout + + formatter_opts = vars(args) + try: + formatter_opts = sqlparse.formatter.validate_options(formatter_opts) + except SQLParseError as e: + _error('Invalid options: %s' % e) + return 1 + + s = sqlparse.format(data, **formatter_opts) + if PY2: + s = s.encode('utf-8', 'replace') + stream.write(s) + stream.flush() + return 0 |
