summaryrefslogtreecommitdiff
path: root/bin/sqlformat
blob: fcee452bc51b5602c9e22c9cd173716262c05f8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python

# Copyright (C) 2008 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.

import optparse
import os
import sys

import sqlparse
from sqlparse.exceptions import SQLParseError


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


parser = optparse.OptionParser(usage='%prog [OPTIONS] FILE, ...',
                               version='%%prog %s' % sqlparse.__version__)
parser.set_description(('Format FILE according to OPTIONS. Use "-" as FILE '
                        'to read from stdin.'))
parser.add_option('-v', '--verbose', dest='verbose', action='store_true')
parser.add_option('-o', '--outfile', dest='outfile', metavar='FILE',
                  help='write output to FILE (defaults to stdout)')
group = parser.add_option_group('Formatting Options')
group.add_option('-k', '--keywords', metavar='CHOICE',
                 dest='keyword_case', choices=_CASE_CHOICES,
                 help=('change case of keywords, CHOICE is one of %s'
                       % ', '.join('"%s"' % x for x in _CASE_CHOICES)))
group.add_option('-i', '--identifiers', metavar='CHOICE',
                 dest='identifier_case', choices=_CASE_CHOICES,
                 help=('change case of identifiers, CHOICE is one of %s'
                       % ', '.join('"%s"' % x for x in _CASE_CHOICES)))
group.add_option('-l', '--language', metavar='LANG',
                 dest='output_format', choices=['python', 'php'],
                 help=('output a snippet in programming language LANG, '
                       'choices are "python", "php"'))
group.add_option('--strip-comments', dest='strip_comments',
                 action='store_true', default=False,
                 help='remove comments')
group.add_option('-r', '--reindent', dest='reindent',
                 action='store_true', default=False,
                 help='reindent statements')
group.add_option('--indent_width', dest='indent_width', default=2,
                 help='indentation width (defaults to 2 spaces)')

_FORMATTING_GROUP = group


def _error(msg, exit_=None):
    """Print msg and optionally exit with return code exit_."""
    sys.stderr.write('[ERROR] %s\n' % msg)
    if exit_ is not None:
        sys.exit(exit_)


def _build_formatter_opts(options):
    """Convert command line options to dictionary."""
    d = {}
    for option in _FORMATTING_GROUP.option_list:
        d[option.dest] = getattr(options, option.dest)
    return d


def main():
    options, args = parser.parse_args()
    if options.verbose:
        sys.stderr.write('Verbose mode\n')

    if len(args) != 1:
        _error('No input data.')
        parser.print_usage()
        sys.exit(1)

    if '-' in args:  # read from stdin
        data = sys.stdin.read()
    else:
        try:
            data = '\n'.join(open(args[0]).readlines())
        except OSError:
            err = sys.exc_info()[1]  # Python 2.5 compatibility
            _error('Failed to read %s: %s' % (args[0], err), exit_=1)

    if options.outfile:
        try:
            stream = open(options.outfile, 'w')
        except OSError:
            err = sys.exc_info()[1]  # Python 2.5 compatibility
            _error('Failed to open %s: %s' % (options.outfile, err), exit_=1)
    else:
        stream = sys.stdout

    formatter_opts = _build_formatter_opts(options)
    try:
        formatter_opts = sqlparse.formatter.validate_options(formatter_opts)
    except SQLParseError:
        err = sys.exc_info()[1]  # Python 2.5 compatibility
        _error('Invalid options: %s' % err, exit_=1)

    s = sqlparse.format(data, **formatter_opts)
    if sys.version_info < (3,):
        s = s.encode('utf-8', 'replace')
    stream.write(s)
    stream.flush()


if __name__ == '__main__':
    main()