From 2d53e4d45c5a3549a4578d66ddde948410872ae5 Mon Sep 17 00:00:00 2001 From: QianEric Date: Sun, 22 Nov 2026 19:46:11 +0800 Subject: [PATCH 1/2] Report file arguments that cannot be used Three options take a path, and each one mishandled a path that does not exist: * `--config`, `--toml`: `configparser.read()` silently ignores missing files, so a typo in the CI job silently ran codespell with no configuration at all: $ codespell --config .codespellrc src/ src/foo.py:1: teh ==> the $ echo $? 65 `--toml` crashed instead, because the file is opened directly: $ codespell --toml pyproject.toml src/ Traceback (most recent call last): File ".../codespell_lib/_codespell.py", line 760, in parse_options with open(toml_file, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: 'pyproject.toml' * `--exclude-file`: unlike `--ignore-words`, it has no existence check, so it ended in the same traceback: $ codespell --exclude-file .codespell-exclude src/ Traceback (most recent call last): File ".../codespell_lib/_codespell.py", line 1597, in main build_exclude_hashes(exclude_file, exclude_lines) FileNotFoundError: [Errno 2] No such file or directory: '.codespell-exclude' `--ignore-words` already answers this case properly: if not os.path.isfile(ignore_words_file): return _usage_error( parser, f"ERROR: cannot find ignore-words file: {ignore_words_file}", ) ## Fix `parse_options()` raises the new `_FileUsageError`, and `main()` turns it into the usual usage error, so all three behave like `--ignore-words`: ``` $ codespell --config /nope.toml src/ ; echo $? usage: codespell ... ERROR: cannot find config file: /nope.toml 64 ``` | case | before | after | |---|---|---| | `--config ` | exit 65, runs unconfigured | `ERROR: cannot find config file: ...`, exit 64 | | `--toml ` | traceback, exit 1 | `ERROR: cannot find toml file: ...`, exit 64 | | `--exclude-file ` | traceback, exit 1 | `ERROR: cannot find exclude-file: ...`, exit 64 | | `--config`/`--toml`/`--exclude-file` valid | works | unchanged | | auto-detected `setup.cfg`/`.codespellrc`/`pyproject.toml` missing | ignored | unchanged | The `_FileUsageError` type is needed because the three checks live in `parse_options()`, which returns `(options, parser, used_cfg_files)` and cannot return an exit code; `_usage_error()` stays as it is and is reused unchanged. ## Tests `test_basic` gains assertions for the three cases; they fail on the current tree (`assert 0 == 64` for the silent `--config` case, tracebacks for the other two). `pytest codespell_lib/tests/` gives 132 passed / 19 failed on this machine both before and after the change -- the 19 failures are pre-existing and unrelated (interactive-prompt and bitmask-option tests that need a TTY/`pytest-subtests` setup this sandbox does not provide). --- codespell_lib/_codespell.py | 31 +++++++++++++++++++++++++++++++ codespell_lib/tests/test_basic.py | 19 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index 0290b92717..f6ed607060 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -733,6 +733,11 @@ def convert_arg_line_to_args(self, arg_line: str) -> list[str]: # Load config files and look for ``codespell`` options. cfg_files = ["setup.cfg", ".codespellrc"] if options.config: + if not os.path.isfile(options.config): + raise _FileUsageError( + parser, + f"ERROR: cannot find config file: {options.config}", + ) cfg_files.append(options.config) config = configparser.ConfigParser(interpolation=None) @@ -743,6 +748,11 @@ def convert_arg_line_to_args(self, arg_line: str) -> list[str]: if os.path.isfile("pyproject.toml"): toml_files.append("pyproject.toml") if options.toml: + if not os.path.isfile(options.toml): + raise _FileUsageError( + parser, + f"ERROR: cannot find toml file: {options.toml}", + ) toml_files.append(options.toml) tomllib_raise_error = True if toml_files: @@ -1421,6 +1431,20 @@ def _script_main() -> int: return 130 +class _FileUsageError(Exception): + """A file argument given on the command line cannot be used. + + Raised from ``parse_options``, where the config files are read, so that + ``main`` can print the usage and return ``EX_USAGE`` like it does for the + other command-line validation errors. + """ + + def __init__(self, parser: argparse.ArgumentParser, message: str) -> None: + self.parser = parser + self.message = message + super().__init__(message) + + def _usage_error(parser: argparse.ArgumentParser, message: str) -> int: parser.print_usage() print(message, file=sys.stderr) @@ -1452,6 +1476,8 @@ def main(*args: str) -> int: """Contains flow control""" try: options, parser, used_cfg_files = parse_options(args) + except _FileUsageError as e: + return _usage_error(e.parser, e.message) except configparser.Error as e: print( f"ERROR: ill-formed config file: {e.message}", @@ -1594,6 +1620,11 @@ def main(*args: str) -> int: if options.exclude_file: exclude_files = flatten_clean_comma_separated_arguments(options.exclude_file) for exclude_file in exclude_files: + if not os.path.isfile(exclude_file): + return _usage_error( + parser, + f"ERROR: cannot find exclude-file: {exclude_file}", + ) build_exclude_hashes(exclude_file, exclude_lines) file_opener = FileOpener( diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py index 7ab1c8efc8..5039b397bd 100644 --- a/codespell_lib/tests/test_basic.py +++ b/codespell_lib/tests/test_basic.py @@ -136,6 +136,25 @@ def test_basic( code, _, stderr = result assert code == EX_USAGE # bad type assert "Unknown builtin dictionary" in stderr + result = cs.main( + fname, "--config", tmp_path / "does-not-exist", std=True + ) + assert isinstance(result, tuple) + code, _, stderr = result + assert code == EX_USAGE + assert "cannot find config file" in stderr + result = cs.main(fname, "--toml", tmp_path / "does-not-exist", std=True) + assert isinstance(result, tuple) + code, _, stderr = result + assert code == EX_USAGE + assert "cannot find toml file" in stderr + result = cs.main( + fname, "--exclude-file", tmp_path / "does-not-exist", std=True + ) + assert isinstance(result, tuple) + code, _, stderr = result + assert code == EX_USAGE + assert "cannot find exclude-file" in stderr result = cs.main(fname, "-D", tmp_path / "foo", std=True) assert isinstance(result, tuple) code, _, stderr = result From 579cd0f9f6c4119d3043e7c75f81b17f1e434623 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:46:36 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- codespell_lib/tests/test_basic.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py index 5039b397bd..b0abdf9d5c 100644 --- a/codespell_lib/tests/test_basic.py +++ b/codespell_lib/tests/test_basic.py @@ -136,9 +136,7 @@ def test_basic( code, _, stderr = result assert code == EX_USAGE # bad type assert "Unknown builtin dictionary" in stderr - result = cs.main( - fname, "--config", tmp_path / "does-not-exist", std=True - ) + result = cs.main(fname, "--config", tmp_path / "does-not-exist", std=True) assert isinstance(result, tuple) code, _, stderr = result assert code == EX_USAGE @@ -148,9 +146,7 @@ def test_basic( code, _, stderr = result assert code == EX_USAGE assert "cannot find toml file" in stderr - result = cs.main( - fname, "--exclude-file", tmp_path / "does-not-exist", std=True - ) + result = cs.main(fname, "--exclude-file", tmp_path / "does-not-exist", std=True) assert isinstance(result, tuple) code, _, stderr = result assert code == EX_USAGE