From 2478510b919e0f8e4284739a5e3cc5eebec1aec3 Mon Sep 17 00:00:00 2001 From: Edwin Kofler Date: Tue, 27 Dec 2022 05:32:12 -0800 Subject: [PATCH] ci(checkstyle): Add no-pwd-capture test --- scripts/checkstyle.py | 43 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/scripts/checkstyle.py b/scripts/checkstyle.py index c303bc64..35ad8a36 100755 --- a/scripts/checkstyle.py +++ b/scripts/checkstyle.py @@ -30,20 +30,34 @@ class c: BOLD = '\033[1m' UNDERLINE = '\033[4m' +def utilGetStrs(line, m): + return ( + line[0:m.start('match')], + line[m.start('match'):m.end('match')], + line[m.end('match'):] + ) + # Before: printf '%s\\n' '^w^' # After: printf '%s\n' '^w^' -def noDoubleBackslashFixer(line: str, rule: Dict[str, str], m: re.Match[str]) -> str: - prestr = line[0:m.start('match')] - midstr = line[m.start('match'):m.end('match')] - poststr = line[m.end('match'):] +def noDoubleBackslashFixer(line: str, rule: Dict[str, str], m) -> str: + prestr, midstr, poststr = utilGetStrs(line, m) - fixed_line = f'{prestr}{midstr[1:]}{poststr}' - return fixed_line + return f'{prestr}{midstr[1:]}{poststr}' + +# Before: $(pwd) +# After: $PWD +def noPwdCapture(line: str, rule: Dict[str, str], m) -> str: + prestr, midstr, poststr = utilGetStrs(line, m) + + return f'{prestr}$PWD{poststr}' def lintfile(filepath: Path, rules: List[Dict[str, str]], options: Dict[str, Any]): content_arr = filepath.read_text().split('\n') for line_i, line in enumerate(content_arr): + if 'checkstyle-ignore' in line: + continue + for rule in rules: m = re.search(rule['regex'], line) if m is not None and m.group('match') is not None: @@ -58,7 +72,7 @@ def lintfile(filepath: Path, rules: List[Dict[str, str]], options: Dict[str, Any print() if options['fix']: - content_arr[line_i] = rule['fixer_fn'](line, rule, m) + content_arr[line_i] = rule['fixerFn'](line, rule, m) rule['found'] += 1 @@ -71,7 +85,7 @@ def main(): 'name': 'no-double-backslash', 'regex': '".*?(?P\\\\\\\\[abeEfnrtv\'"?xuUc]).*?(?', - 'fixer_fn': noDoubleBackslashFixer, + 'fixerFn': noDoubleBackslashFixer, 'testPositiveMatches': [ 'printf "%s\\\\n" "Hai"', 'echo -n "Hello\\\\n"' @@ -82,6 +96,19 @@ def main(): ], 'found': 0 }, + { + 'name': 'no-pwd-capture', + 'regex': '(?P\\$\\(pwd\\))', + 'reason': '$PWD is essentially equivalent to $(pwd) without the overhead of a subshell', + 'fixerFn': noPwdCapture, + 'testPositiveMatches': [ + '$(pwd)' + ], + 'testNegativeMatches': [ + '$PWD' + ], + 'found': 0 + }, ] parser = argparse.ArgumentParser()