From 08875840ff436d7ad9f3ee4c4d42cfe95934de1c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Tue, 16 Nov 2021 11:01:07 +0100 Subject: [PATCH] Handle bad globs passed to if --skip/-S Co-authored-by: Peter Newman --- codespell_lib/_codespell.py | 8 ++++++++ codespell_lib/tests/test_basic.py | 22 +++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index df55894980f..5a17ed4489f 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -890,7 +890,15 @@ def main(*args): file_opener = FileOpener(options.hard_encoding_detection, options.quiet_level) + glob_match = GlobMatch(options.skip) + try: + glob_match.match("/random/path") # does not need a real path + except re.error: + print("ERROR: --skip/-S has been fed an invalid glob, " + "try escaping special characters", + file=sys.stderr) + return EX_USAGE bad_count = 0 for filename in options.files: diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py index 681ba204239..1e052c825ba 100644 --- a/codespell_lib/tests/test_basic.py +++ b/codespell_lib/tests/test_basic.py @@ -118,10 +118,30 @@ def test_basic(tmpdir, capsys): assert cs.main(d) == 0 # empty directory - os.mkdir(op.join(d, 'test')) + os.mkdir(op.join(d, 'empty')) assert cs.main(d) == 0 +def test_bad_glob(tmpdir, capsys): + # disregard invalid globs, properly handle escaped globs + g = op.join(tmpdir, 'glob') + os.mkdir(g) + fname = op.join(g, '[b-a].txt') + with open(fname, 'a') as f: + f.write('abandonned\n') + assert cs.main(g) == 1 + # bad glob is invalid + code, _, stderr = cs.main('--skip', '[b-a].txt', + g, std=True) + if sys.hexversion < 0x030A05F0: # Python < 3.10.5 raises re.error + assert code == EX_USAGE, 'invalid glob' + assert 'invalid glob' in stderr + else: # Python >= 3.10.5 does not match + assert code == 1 + # properly escaped glob is valid, and matches glob-like file name + assert cs.main('--skip', '[[]b-a[]].txt', g) == 0 + + @pytest.mark.skipif( not sys.platform == 'linux', reason='Only supported on Linux') def test_permission_error(tmp_path, capsys):