├── test-requirements.txt ├── .gitignore ├── renovate.json ├── .travis.yml ├── tox.ini ├── README.rst ├── LICENSE ├── setup.py ├── tests └── test_checkers.py └── bashlint.py /test-requirements.txt: -------------------------------------------------------------------------------- 1 | nose==1.3.7 2 | testtools==2.4.0 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .tox 3 | .venv 4 | 5 | *.pyc 6 | 7 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | matrix: 3 | include: 4 | - python: 3.6 5 | env: TOXENV=py36 6 | - python: 3.7 7 | env: TOXENV=py37 8 | - python: 3.8 9 | env: TOXENV=py38 10 | - python: 3.8 11 | env: TOXENV=pep8 12 | install: 13 | - pip install tox 14 | script: 15 | - tox 16 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | minversion = 1.6 3 | skipsdist = True 4 | envlist = pep8,py36,py37,py38 5 | 6 | [testenv] 7 | usedevelop = True 8 | deps = -r{toxinidir}/test-requirements.txt 9 | commands = nosetests {posargs} --verbosity=2 tests 10 | 11 | [testenv:venv] 12 | commands = {posargs} 13 | 14 | [testenv:pep8] 15 | deps = hacking 16 | commands = flake8 {posargs} 17 | 18 | [flake8] 19 | builtins = _ 20 | ignore = W605 21 | exclude = .venv,.tox,doc,*egg,.git 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================ 2 | bashlint - Bash linting tool 3 | ============================ 4 | 5 | Simple Bash linting tool written in Python. 6 | 7 | .. image:: https://travis-ci.org/skudriashev/bashlint.svg?branch=master 8 | :target: https://travis-ci.org/skudriashev/bashlint 9 | 10 | Installation 11 | ------------ 12 | ``bashlint`` can be installed via the Python Package Index or from source. 13 | 14 | Using ``pip`` to install ``bashlint``:: 15 | 16 | $ pip install bashlint 17 | 18 | You can download the source tarball and install ``bashlint`` as follows:: 19 | 20 | $ python setup.py install 21 | 22 | or in development mode:: 23 | 24 | $ python setup.py develop 25 | 26 | 27 | Rules list 28 | ---------- 29 | **W201 Trailing whitespace**: Trailing whitespaces are superfluous:: 30 | 31 | Okay: echo Test# 32 | W201: echo Test # 33 | 34 | **W202 Blank line contains whitespace**: Trailing whitespaces on blank lines 35 | are superfluous:: 36 | 37 | Okay: # 38 | W202: # 39 | 40 | **W203 Trailing semicolon**: Trailing semicolons are superfluous:: 41 | 42 | Okay: echo Test# 43 | W203: echo Test;# 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Kudriashev Stanislav 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import codecs 2 | 3 | import setuptools 4 | 5 | 6 | setuptools.setup( 7 | name='bashlint', 8 | version='0.1.1', 9 | description='Bash linting tool', 10 | long_description=codecs.open('README.rst', 'r', 'utf-8').read(), 11 | keywords='bash', 12 | author='Stanislav Kudriashev', 13 | author_email='stas.kudriashev@gmail.com', 14 | url='https://github.com/skudriashev/bashlint', 15 | download_url='https://github.com/skudriashev/bashlint/tarball/0.1.1', 16 | license='MIT', 17 | py_modules=['bashlint'], 18 | zip_safe=False, 19 | entry_points={ 20 | 'console_scripts': [ 21 | 'bashlint = bashlint:main', 22 | ], 23 | }, 24 | classifiers=[ 25 | 'Development Status :: 2 - Pre-Alpha', 26 | 'Environment :: Console', 27 | 'Intended Audience :: Developers', 28 | 'License :: OSI Approved :: MIT License', 29 | 'Operating System :: OS Independent', 30 | 'Programming Language :: Python', 31 | 'Programming Language :: Python :: 3', 32 | 'Programming Language :: Python :: 3.6', 33 | 'Programming Language :: Python :: 3.7', 34 | 'Programming Language :: Python :: 3.8', 35 | 'Topic :: Software Development :: Libraries :: Python Modules', 36 | ], 37 | ) 38 | -------------------------------------------------------------------------------- /tests/test_checkers.py: -------------------------------------------------------------------------------- 1 | import testtools 2 | 3 | import bashlint 4 | 5 | 6 | class TestCheckers(testtools.TestCase): 7 | 8 | def _check_ok(self, checker, cases): 9 | for case in cases: 10 | self.assertIsNone(checker(case)) 11 | 12 | def _check_error(self, checker, cases): 13 | for case, offset in cases: 14 | result = checker(case) 15 | self.assertIsNotNone(result) 16 | self.assertEqual(result[0], offset, "\nTestcase: '%s'\n" % case) 17 | 18 | def test_w201_ok(self): 19 | self._check_ok(bashlint.checker_trailing_whitespace, [ 20 | "\n", 21 | "\r", 22 | "echo Test", 23 | "echo Test\n", 24 | "echo Test\r", 25 | ]) 26 | 27 | def test_w201_error(self): 28 | self._check_error(bashlint.checker_trailing_whitespace, [ 29 | ("\n ", 1), 30 | (" \n", 0), 31 | ("echo Test ", 9), 32 | ("echo Test\n ", 10), 33 | ("echo Test \n", 9), 34 | ("echo Test \n ", 11), 35 | ]) 36 | 37 | def test_w202_ok(self): 38 | self._check_ok(bashlint.checker_trailing_whitespace, [ 39 | "", 40 | ]) 41 | 42 | def test_w202_error(self): 43 | self._check_error(bashlint.checker_trailing_whitespace, [ 44 | (" ", 0), 45 | (" ", 0), 46 | ]) 47 | 48 | def test_w203_ok(self): 49 | self._check_ok(bashlint.checker_trailing_semicolon, [ 50 | "", 51 | "echo Test", 52 | "echo Test; echo Test2", 53 | " ;; ", 54 | "find -type f -exec cat {} \;", 55 | ]) 56 | 57 | def test_w203_error(self): 58 | self._check_error(bashlint.checker_trailing_semicolon, [ 59 | (";", 0), 60 | (" ;", 4), 61 | ("echo Test;", 9), 62 | ("echo Test; ", 9), 63 | ("echo Test; echo Test2;", 21), 64 | ]) 65 | -------------------------------------------------------------------------------- /bashlint.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import fnmatch 4 | import inspect 5 | import optparse 6 | import os 7 | import re 8 | import sys 9 | 10 | REGEXP_SEMICOLON_OK = re.compile(r'(?:\s*;;\s*|\s+\\;\s*)$') 11 | REGEXP_SEMICOLON_WARN = re.compile(r'.*\s*;\s*$') 12 | 13 | 14 | def filename_match(filename, patterns, default=True): 15 | """Check if patterns contains a pattern that matches filename. 16 | 17 | If patterns is not specified, this always returns True. 18 | """ 19 | if not patterns: 20 | return default 21 | 22 | return any(fnmatch.fnmatch(filename, pattern) for pattern in patterns) 23 | 24 | 25 | def read_lines(filename): 26 | """Read all lines from a given file.""" 27 | with open(filename) as fp: 28 | return fp.readlines() 29 | 30 | 31 | def checker_trailing_whitespace(physical_line): 32 | """Trailing whitespace is superfluous. 33 | 34 | Okay: echo Test# 35 | W201: echo Test # 36 | Okay: # 37 | W202: # 38 | """ 39 | physical_line = physical_line.rstrip('\n') # chr(10), newline 40 | physical_line = physical_line.rstrip('\r') # chr(13), carriage return 41 | physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L 42 | stripped = physical_line.rstrip(' \t\v') 43 | if physical_line != stripped: 44 | if stripped: 45 | return len(stripped), "W201 Trailing whitespace" 46 | else: 47 | return 0, "W202 Blank line contains whitespace" 48 | 49 | 50 | def checker_trailing_semicolon(physical_line): 51 | """Trailing semicolon is superfluous. 52 | 53 | Okay: echo Test# 54 | W203: echo Test;# 55 | """ 56 | if not REGEXP_SEMICOLON_OK.search(physical_line): 57 | if REGEXP_SEMICOLON_WARN.search(physical_line): 58 | return physical_line.rfind(';'), "W203 Trailing semicolon" 59 | 60 | 61 | class Violation(object): 62 | """Represents a single violation.""" 63 | 64 | __slots__ = ['_filename', '_line', '_line_number', '_offset', '_text'] 65 | 66 | def __init__(self, filename, line, line_number, offset, text): 67 | self._filename = filename 68 | self._line = line 69 | self._line_number = line_number 70 | self._offset = offset 71 | self._text = text 72 | 73 | def __str__(self): 74 | return "%s:%s:%s: %s" % (self._filename, self._line_number, 75 | self._offset, self._text) 76 | 77 | @property 78 | def line(self): 79 | return self._line[:-1] 80 | 81 | @property 82 | def pointer(self): 83 | return ' ' * self._offset + '^' 84 | 85 | 86 | class StyleGuide(object): 87 | """Bash style guide.""" 88 | 89 | FILE_PATTERNS = ('*.sh',) 90 | 91 | def __init__(self, options): 92 | self._options = options 93 | self._reporter = Reporter(options.show_source) 94 | self._checkers = self._load_checkers() 95 | self._errors_count = 0 96 | 97 | @property 98 | def errors_count(self): 99 | return self._errors_count 100 | 101 | def _load_checkers(self): 102 | """Load checkers from the current module.""" 103 | checkers = [] 104 | current_module = sys.modules.get(__name__) 105 | if current_module is not None: 106 | for name, func in inspect.getmembers(current_module, 107 | inspect.isfunction): 108 | if name.startswith('checker'): 109 | checkers.append(func) 110 | 111 | if self._options.verbose > 1: 112 | print("Loaded %s checker(s)." % len(checkers)) 113 | 114 | return checkers 115 | 116 | def check_paths(self, paths=None): 117 | """Run all checks on the paths.""" 118 | try: 119 | for path in paths or ["."]: 120 | if os.path.isdir(path): 121 | self._check_dir(path) 122 | except KeyboardInterrupt: 123 | print("... stopped") 124 | 125 | def _check_dir(self, path): 126 | """Check all files in the given directory and all subdirectories.""" 127 | for root, dirs, files in os.walk(path): 128 | for filename in sorted(files): 129 | if filename_match(filename, self.FILE_PATTERNS): 130 | if self._options.verbose: 131 | print("Checking %s" % filename) 132 | self._check_file(os.path.join(root, filename)) 133 | 134 | def _check_file(self, filename): 135 | """"Run checks for a given file.""" 136 | for line_number, line in enumerate(read_lines(filename), 1): 137 | for checker in self._checkers: 138 | result = checker(line) 139 | if result is not None: 140 | self._errors_count += 1 141 | offset, text = result 142 | violation = Violation(filename=filename, 143 | line=line, 144 | line_number=line_number, 145 | offset=offset, 146 | text=text) 147 | self._report(violation) 148 | 149 | def _report(self, violation): 150 | """Report a violation using reporter.""" 151 | self._reporter.report(violation) 152 | 153 | 154 | class Reporter(object): 155 | """Standard output violations reporter.""" 156 | 157 | def __init__(self, show_source=False): 158 | self._show_source = show_source 159 | 160 | def report(self, violation): 161 | """Report given violations.""" 162 | print(violation) 163 | if self._show_source: 164 | print(violation.line) 165 | print(violation.pointer) 166 | 167 | 168 | def parse_args(): 169 | parser = optparse.OptionParser(prog='bashlint', 170 | usage="%prog [options] []...") 171 | parser.add_option('-v', '--verbose', default=0, action='count', 172 | help="print debug messages") 173 | parser.add_option('--show-source', action='store_true', 174 | help="show source code for each error") 175 | return parser.parse_args() 176 | 177 | 178 | def main(): 179 | options, args = parse_args() 180 | guide = StyleGuide(options) 181 | guide.check_paths(args) 182 | if guide.errors_count: 183 | sys.exit(1) 184 | 185 | 186 | if __name__ == "__main__": 187 | main() 188 | --------------------------------------------------------------------------------