Skip to content

Report a report directory that can't be created instead of an internal error - #22552

Open
qianeric-backup wants to merge 2 commits into
python:masterfrom
qianeric-backup:fix/report-dir-cant-be-created
Open

qianeric-backup wants to merge 2 commits into
python:masterfrom
qianeric-backup:fix/report-dir-cant-be-created

Conversation

@qianeric-backup

Copy link
Copy Markdown

Passing a report output directory that cannot be created makes mypy blame itself:

$ mypy --html-report /nope/html ok.py
error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
If this issue continues with mypy master, please report a bug at https://github.com/python/mypy/issues
version: 2.5.0+dev
note: please use --show-traceback to print a traceback when reporting a bug

AbstractReporter.__init__() creates the output directory with a bare
os.makedirs(output_dir, exist_ok=True), and the same OSError escapes from
Reports.finish() when a reporter writes its files, so the top-level handler reports a bad
user-supplied path as a mypy bug. This affects --html-report, --linecoverage-report,
--any-exprs-report, --cobertura-xml-report, --xml-report and the other report options.

Other user-supplied paths are reported normally, from the build phase:

$ mypy --config-file /nope.ini ok.py
mypy: error: Cannot find config file '/nope.ini'

Change

mypy/report.py:

+from mypy.errors import CompileError
...
     def __init__(self, reports: Reports, output_dir: str) -> None:
         self.output_dir = output_dir
         if output_dir != "<memory>":
-            os.makedirs(output_dir, exist_ok=True)
+            try:
+                os.makedirs(output_dir, exist_ok=True)
+            except OSError as err:
+                raise CompileError(
+                    [f"mypy: error: Cannot create report directory {output_dir}: {err}"]
+                ) from err
...
     def finish(self) -> None:
         for reporter in self.reporters:
-            reporter.on_finish()
+            try:
+                reporter.on_finish()
+            except OSError as err:
+                raise CompileError(
+                    [
+                        "mypy: error: Cannot write "
+                        f"{reporter.__class__.__name__} output to {reporter.output_dir}: {err}"
+                    ]
+                ) from err

CompileError is how the build phase already reports problems (build_error() raises
CompileError([f"mypy: error: {msg}"])), so the message text and the exit code match the rest of
the build: one mypy: error: ... line, exit 2.

invocation before after
--html-report /nope/html error: INTERNAL ERROR -- Please try using mypy master ..., exit 2 mypy: error: Cannot create report directory /nope/html: [Errno 13] Permission denied: '/nope', exit 2
--linecoverage-report /nope/lc, --any-exprs-report /nope/ae same internal error same one-line message with the path
--html-report htmlcov report written unchanged
--html-report "" (in-memory) unchanged unchanged

Test

mypy/test/testutil.py (module-level functions are not collected here — pyproject.toml sets
python_functions = [], so this is a TestCase):

class TestReports(TestCase):
    def test_report_output_dir_cant_be_created(self) -> None:
        # A report directory we cannot create is a usage problem, not an internal error
        with tempfile.TemporaryDirectory() as tmpdir:
            blocker = os.path.join(tmpdir, "blocker")
            with open(blocker, "w") as f:
                f.write("this is a file, not a directory\n")

            reports = Reports("", {})
            with pytest.raises(CompileError, match="Cannot create report directory"):
                reports.add_report("linecount", os.path.join(blocker, "linecount.txt"))

pytest mypy/test/testutil.py: 8 passed. The new test fails on an unmodified checkout with
FileExistsError from os.makedirs() (the "file used as a directory" trick keeps it
root-proof).

qianeric-backup and others added 2 commits November 25, 2026 18:05
…l error

Passing a report output directory that cannot be created makes mypy blame itself:

```
$ mypy --html-report /nope/html ok.py
error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
If this issue continues with mypy master, please report a bug at https://github.com/python/mypy/issues
version: 2.5.0+dev
note: please use --show-traceback to print a traceback when reporting a bug
```

`AbstractReporter.__init__()` creates the output directory with a bare
`os.makedirs(output_dir, exist_ok=True)`, and the same `OSError` escapes from
`Reports.finish()` when a reporter writes its files, so the top-level handler reports a bad
user-supplied path as a mypy bug. This affects `--html-report`, `--linecoverage-report`,
`--any-exprs-report`, `--cobertura-xml-report`, `--xml-report` and the other report options.

Other user-supplied paths are reported normally, from the build phase:

```
$ mypy --config-file /nope.ini ok.py
mypy: error: Cannot find config file '/nope.ini'
```

## Change

`mypy/report.py`:

```python
+from mypy.errors import CompileError
...
     def __init__(self, reports: Reports, output_dir: str) -> None:
         self.output_dir = output_dir
         if output_dir != "<memory>":
-            os.makedirs(output_dir, exist_ok=True)
+            try:
+                os.makedirs(output_dir, exist_ok=True)
+            except OSError as err:
+                raise CompileError(
+                    [f"mypy: error: Cannot create report directory {output_dir}: {err}"]
+                ) from err
...
     def finish(self) -> None:
         for reporter in self.reporters:
-            reporter.on_finish()
+            try:
+                reporter.on_finish()
+            except OSError as err:
+                raise CompileError(
+                    [
+                        "mypy: error: Cannot write "
+                        f"{reporter.__class__.__name__} output to {reporter.output_dir}: {err}"
+                    ]
+                ) from err
```

`CompileError` is how the build phase already reports problems (`build_error()` raises
`CompileError([f"mypy: error: {msg}"])`), so the message text and the exit code match the rest of
the build: one `mypy: error: ...` line, exit 2.

| invocation | before | after |
|---|---|---|
| `--html-report /nope/html` | `error: INTERNAL ERROR -- Please try using mypy master ...`, exit 2 | `mypy: error: Cannot create report directory /nope/html: [Errno 13] Permission denied: '/nope'`, exit 2 |
| `--linecoverage-report /nope/lc`, `--any-exprs-report /nope/ae` | same internal error | same one-line message with the path |
| `--html-report htmlcov` | report written | unchanged |
| `--html-report ""` (in-memory) | unchanged | unchanged |

## Test

`mypy/test/testutil.py` (module-level functions are not collected here — `pyproject.toml` sets
`python_functions = []`, so this is a `TestCase`):

```python
class TestReports(TestCase):
    def test_report_output_dir_cant_be_created(self) -> None:
        # A report directory we cannot create is a usage problem, not an internal error
        with tempfile.TemporaryDirectory() as tmpdir:
            blocker = os.path.join(tmpdir, "blocker")
            with open(blocker, "w") as f:
                f.write("this is a file, not a directory\n")

            reports = Reports("", {})
            with pytest.raises(CompileError, match="Cannot create report directory"):
                reports.add_report("linecount", os.path.join(blocker, "linecount.txt"))
```

`pytest mypy/test/testutil.py`: 8 passed. The new test fails on an unmodified checkout with
`FileExistsError` from `os.makedirs()` (the "file used as a directory" trick keeps it
root-proof).
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant