Sean Dague | 4fb255c | 2013-10-14 14:07:00 -0400 | [diff] [blame^] | 1 | #!/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 |
| 24 | # - E001: check that lines do not end with trailing whitespace |
| 25 | # - E002: ensure that indents are only spaces, and not hard tabs |
| 26 | # - E003: ensure all indents are a multiple of 4 spaces |
| 27 | |
| 28 | import argparse |
| 29 | import fileinput |
| 30 | import re |
| 31 | import sys |
| 32 | |
| 33 | |
| 34 | ERRORS = 0 |
| 35 | |
| 36 | |
| 37 | def print_error(error, line): |
| 38 | global ERRORS |
| 39 | ERRORS = ERRORS + 1 |
| 40 | print("%s: '%s'" % (error, line.rstrip('\n'))) |
| 41 | print(" - %s: L%s" % (fileinput.filename(), fileinput.filelineno())) |
| 42 | |
| 43 | |
| 44 | def check_no_trailing_whitespace(line): |
| 45 | if re.search('[ \t]+$', line): |
| 46 | print_error('E001: Trailing Whitespace', line) |
| 47 | |
| 48 | |
| 49 | def check_indents(line): |
| 50 | m = re.search('^(?P<indent>[ \t]+)', line) |
| 51 | if m: |
| 52 | if re.search('\t', m.group('indent')): |
| 53 | print_error('E002: Tab indents', line) |
| 54 | if (len(m.group('indent')) % 4) != 0: |
| 55 | print_error('E003: Indent not multiple of 4', line) |
| 56 | |
| 57 | |
| 58 | def check_files(files): |
| 59 | for line in fileinput.input(files): |
| 60 | check_no_trailing_whitespace(line) |
| 61 | check_indents(line) |
| 62 | |
| 63 | |
| 64 | def get_options(): |
| 65 | parser = argparse.ArgumentParser( |
| 66 | description='A bash script style checker') |
| 67 | parser.add_argument('files', metavar='file', nargs='+', |
| 68 | help='files to scan for errors') |
| 69 | return parser.parse_args() |
| 70 | |
| 71 | |
| 72 | def main(): |
| 73 | opts = get_options() |
| 74 | check_files(opts.files) |
| 75 | |
| 76 | if ERRORS > 0: |
| 77 | print("%d bash8 error(s) found" % ERRORS) |
| 78 | return 1 |
| 79 | else: |
| 80 | return 0 |
| 81 | |
| 82 | |
| 83 | if __name__ == "__main__": |
| 84 | sys.exit(main()) |