From dab719947830dd8549f7b12acdc340feaaf862ab Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 11 Dec 2021 14:35:07 +0100 Subject: [PATCH] Avoid bailing out with uncaught `PermissionError` --- codespell_lib/_codespell.py | 16 ++++++++++++++-- codespell_lib/tests/test_basic.py | 7 +++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index 598aa72aa5a..b3037a5ff12 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -647,14 +647,26 @@ def parse_file(filename, colors, summary, misspellings, exclude_lines, if not os.path.isfile(filename): return bad_count - text = is_text_file(filename) + try: + text = is_text_file(filename) + except PermissionError as e: + print("WARNING: %s: %s" % (e.strerror, filename), + file=sys.stderr) + return bad_count + except OSError: + return bad_count + if not text: if not options.quiet_level & QuietLevels.BINARY_FILE: print("WARNING: Binary file: %s" % filename, file=sys.stderr) return bad_count try: lines, encoding = file_opener.open(filename) - except Exception: + except PermissionError as e: + print("WARNING: %s: %s" % (e.strerror, filename), + file=sys.stderr) + return bad_count + except OSError: return bad_count for i, line in enumerate(lines): diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py index 8b73584a46e..a1ed43b438f 100644 --- a/codespell_lib/tests/test_basic.py +++ b/codespell_lib/tests/test_basic.py @@ -117,6 +117,13 @@ def test_basic(tmpdir, capsys): assert stdout == stderr == '' assert cs.main(d) == 0 + # unreadable file + if sys.platform == 'linux': # cannot create unreadable file on Windows + with open(op.join(d, 'unreadable.txt'), 'w') as f: + os.chmod(f, 0o000) + code, _, stderr = cs.main(f.name, std=True) + assert 'WARNING:' in stderr # strerror(EACCES) would depend on the locale + # empty directory os.mkdir(op.join(d, 'test')) assert cs.main(d) == 0