Skip to content

gh-133403: Type Tools/build/update_file.py and check it with mypy #133404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Tools/build/mypy.ini
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
[mypy]
files =
Tools/build/compute-changes.py,
Tools/build/generate_sbom.py
Tools/build/generate_sbom.py,
Tools/build/update_file.py

pretty = True

# Make sure Python can still be built
Expand All @@ -10,6 +12,8 @@ python_version = 3.10

# ...And be strict:
strict = True
strict_bytes = True
local_partial_types = True
extra_checks = True
enable_error_code = ignore-without-code,redundant-expr,truthy-bool,possibly-undefined
warn_unreachable = True
24 changes: 21 additions & 3 deletions Tools/build/update_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,27 @@
actually change the in-tree generated code.
"""

from __future__ import annotations

import contextlib
import os
import os.path
import sys

TYPE_CHECKING = False
if TYPE_CHECKING:
import typing
from collections.abc import Iterator
from io import TextIOWrapper

_Outcome: typing.TypeAlias = typing.Literal['created', 'updated', 'same']


@contextlib.contextmanager
def updating_file_with_tmpfile(filename, tmpfile=None):
def updating_file_with_tmpfile(
filename: str,
tmpfile: str | None = None,
) -> Iterator[tuple[TextIOWrapper, TextIOWrapper]]:
"""A context manager for updating a file via a temp file.

The context manager provides two open files: the source file open
Expand Down Expand Up @@ -46,13 +59,18 @@ def updating_file_with_tmpfile(filename, tmpfile=None):
update_file_with_tmpfile(filename, tmpfile)


def update_file_with_tmpfile(filename, tmpfile, *, create=False):
def update_file_with_tmpfile(
filename: str,
tmpfile: str,
*,
create: bool = False,
) -> _Outcome:
try:
targetfile = open(filename, 'rb')
except FileNotFoundError:
if not create:
raise # re-raise
outcome = 'created'
outcome: _Outcome = 'created'
os.replace(tmpfile, filename)
else:
with targetfile:
Expand Down
Loading