blob: 3abf87b4846865a4b23653e4863a946e4d1decd4 [file] [log] [blame]
Sean Dague4fb255c2013-10-14 14:07:00 -04001#!/usr/bin/env python
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15# bash8 - a pep8 equivalent for bash scripts
16#
17# this program attempts to be an automated style checker for bash scripts
18# to fill the same part of code review that pep8 does in most OpenStack
19# projects. It starts from humble beginnings, and will evolve over time.
20#
21# Currently Supported checks
22#
23# Errors
Sean Dague16dd8b32014-02-03 09:10:54 +090024# Basic white space errors, for consistent indenting
Sean Dague4fb255c2013-10-14 14:07:00 -040025# - E001: check that lines do not end with trailing whitespace
26# - E002: ensure that indents are only spaces, and not hard tabs
27# - E003: ensure all indents are a multiple of 4 spaces
Ian Wienandb8e25022014-02-21 16:14:29 +110028# - E004: file did not end with a newline
Sean Dague16dd8b32014-02-03 09:10:54 +090029#
30# Structure errors
31#
32# A set of rules that help keep things consistent in control blocks.
33# These are ignored on long lines that have a continuation, because
34# unrolling that is kind of "interesting"
35#
36# - E010: *do* not on the same line as *for*
37# - E011: *then* not on the same line as *if*
Ian Wienandb8e25022014-02-21 16:14:29 +110038# - E012: heredoc didn't end before EOF
Sean Dague4fb255c2013-10-14 14:07:00 -040039
40import argparse
41import fileinput
42import re
43import sys
44
Sean Dague4fb255c2013-10-14 14:07:00 -040045ERRORS = 0
Sean Dague0656e122014-02-03 08:49:30 +090046IGNORE = None
47
48
49def register_ignores(ignores):
50 global IGNORE
51 if ignores:
Chmouel Boudjnah86a8e972014-02-04 15:20:15 +010052 IGNORE = '^(' + '|'.join(ignores.split(',')) + ')'
Sean Dague0656e122014-02-03 08:49:30 +090053
54
55def should_ignore(error):
56 return IGNORE and re.search(IGNORE, error)
Sean Dague4fb255c2013-10-14 14:07:00 -040057
58
Ian Wienandb8e25022014-02-21 16:14:29 +110059def print_error(error, line,
60 filename=None, filelineno=None):
61 if not filename:
62 filename = fileinput.filename()
63 if not filelineno:
64 filelineno = fileinput.filelineno()
Sean Dague4fb255c2013-10-14 14:07:00 -040065 global ERRORS
66 ERRORS = ERRORS + 1
67 print("%s: '%s'" % (error, line.rstrip('\n')))
Ian Wienandb8e25022014-02-21 16:14:29 +110068 print(" - %s: L%s" % (filename, filelineno))
Sean Dague4fb255c2013-10-14 14:07:00 -040069
70
Sean Dague16dd8b32014-02-03 09:10:54 +090071def not_continuation(line):
72 return not re.search('\\\\$', line)
73
Chmouel Boudjnah86a8e972014-02-04 15:20:15 +010074
Sean Dague16dd8b32014-02-03 09:10:54 +090075def check_for_do(line):
76 if not_continuation(line):
Chmouel Boudjnah86a8e972014-02-04 15:20:15 +010077 match = re.match('^\s*(for|while|until)\s', line)
78 if match:
79 operator = match.group(1).strip()
Sean Dague16dd8b32014-02-03 09:10:54 +090080 if not re.search(';\s*do(\b|$)', line):
Chmouel Boudjnah86a8e972014-02-04 15:20:15 +010081 print_error('E010: Do not on same line as %s' % operator,
82 line)
Sean Dague16dd8b32014-02-03 09:10:54 +090083
84
85def check_if_then(line):
86 if not_continuation(line):
87 if re.search('^\s*if \[', line):
88 if not re.search(';\s*then(\b|$)', line):
89 print_error('E011: Then non on same line as if', line)
90
91
Sean Dague4fb255c2013-10-14 14:07:00 -040092def check_no_trailing_whitespace(line):
93 if re.search('[ \t]+$', line):
94 print_error('E001: Trailing Whitespace', line)
95
96
97def check_indents(line):
98 m = re.search('^(?P<indent>[ \t]+)', line)
99 if m:
100 if re.search('\t', m.group('indent')):
101 print_error('E002: Tab indents', line)
102 if (len(m.group('indent')) % 4) != 0:
103 print_error('E003: Indent not multiple of 4', line)
104
Ian Wienandaee18c72014-02-21 15:35:08 +1100105def check_function_decl(line):
106 failed = False
107 if line.startswith("function"):
108 if not re.search('^function [\w-]* \{$', line):
109 failed = True
110 else:
111 # catch the case without "function", e.g.
112 # things like '^foo() {'
113 if re.search('^\s*?\(\)\s*?\{', line):
114 failed = True
115
116 if failed:
117 print_error('E020: Function declaration not in format '
118 ' "^function name {$"', line)
119
Sean Dague4fb255c2013-10-14 14:07:00 -0400120
Sean Dague02d7fe12013-10-22 11:31:21 -0400121def starts_multiline(line):
122 m = re.search("[^<]<<\s*(?P<token>\w+)", line)
123 if m:
124 return m.group('token')
125 else:
126 return False
127
128
129def end_of_multiline(line, token):
130 if token:
131 return re.search("^%s\s*$" % token, line) is not None
132 return False
133
134
Sean Dagueb93ee252014-02-23 20:41:07 -0500135def check_files(files, verbose):
Sean Dague02d7fe12013-10-22 11:31:21 -0400136 in_multiline = False
Ian Wienandb8e25022014-02-21 16:14:29 +1100137 multiline_start = 0
138 multiline_line = ""
Sean Dague02d7fe12013-10-22 11:31:21 -0400139 logical_line = ""
140 token = False
Ian Wienandb8e25022014-02-21 16:14:29 +1100141 prev_file = None
142 prev_line = ""
143 prev_lineno = 0
144
Sean Dague4fb255c2013-10-14 14:07:00 -0400145 for line in fileinput.input(files):
Ian Wienandb8e25022014-02-21 16:14:29 +1100146 if fileinput.isfirstline():
147 # if in_multiline when the new file starts then we didn't
148 # find the end of a heredoc in the last file.
149 if in_multiline:
150 print_error('E012: heredoc did not end before EOF',
151 multiline_line,
152 filename=prev_file, filelineno=multiline_start)
153 in_multiline = False
154
155 # last line of a previous file should always end with a
156 # newline
157 if prev_file and not prev_line.endswith('\n'):
158 print_error('E004: file did not end with a newline',
159 prev_line,
160 filename=prev_file, filelineno=prev_lineno)
161
162 prev_file = fileinput.filename()
163
164 if verbose:
165 print "Running bash8 on %s" % fileinput.filename()
166
Sean Dague02d7fe12013-10-22 11:31:21 -0400167 # NOTE(sdague): multiline processing of heredocs is interesting
168 if not in_multiline:
169 logical_line = line
170 token = starts_multiline(line)
171 if token:
172 in_multiline = True
Ian Wienandb8e25022014-02-21 16:14:29 +1100173 multiline_start = fileinput.filelineno()
174 multiline_line = line
Sean Dague02d7fe12013-10-22 11:31:21 -0400175 continue
176 else:
177 logical_line = logical_line + line
178 if not end_of_multiline(line, token):
179 continue
180 else:
181 in_multiline = False
182
183 check_no_trailing_whitespace(logical_line)
184 check_indents(logical_line)
Sean Dague16dd8b32014-02-03 09:10:54 +0900185 check_for_do(logical_line)
186 check_if_then(logical_line)
Ian Wienandaee18c72014-02-21 15:35:08 +1100187 check_function_decl(logical_line)
Sean Dague4fb255c2013-10-14 14:07:00 -0400188
Ian Wienandb8e25022014-02-21 16:14:29 +1100189 prev_line = logical_line
190 prev_lineno = fileinput.filelineno()
Sean Dague4fb255c2013-10-14 14:07:00 -0400191
192def get_options():
193 parser = argparse.ArgumentParser(
194 description='A bash script style checker')
195 parser.add_argument('files', metavar='file', nargs='+',
196 help='files to scan for errors')
Sean Dague0656e122014-02-03 08:49:30 +0900197 parser.add_argument('-i', '--ignore', help='Rules to ignore')
Sean Dagueb93ee252014-02-23 20:41:07 -0500198 parser.add_argument('-v', '--verbose', action='store_true', default=False)
Sean Dague4fb255c2013-10-14 14:07:00 -0400199 return parser.parse_args()
200
201
202def main():
203 opts = get_options()
Sean Dague0656e122014-02-03 08:49:30 +0900204 register_ignores(opts.ignore)
Sean Dagueb93ee252014-02-23 20:41:07 -0500205 check_files(opts.files, opts.verbose)
Sean Dague4fb255c2013-10-14 14:07:00 -0400206
207 if ERRORS > 0:
208 print("%d bash8 error(s) found" % ERRORS)
209 return 1
210 else:
211 return 0
212
213
214if __name__ == "__main__":
215 sys.exit(main())