gh-58032: Do not use argparse.FileType in module CLIs and scripts (GH-113649)

Open and close files manually. It prevents from leaking files,
preliminary creation of output files, and accidental closing of stdin
and stdout.
This commit is contained in:
Serhiy Storchaka 2024-01-10 15:07:19 +02:00 committed by GitHub
parent a8629816c6
commit b3d2427f22
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 56 additions and 41 deletions

View file

@ -1154,12 +1154,13 @@ def output_markdown(
print("Stats gathered on:", date.today(), file=out)
def output_stats(inputs: list[Path], json_output=TextIO | None):
def output_stats(inputs: list[Path], json_output=str | None):
match len(inputs):
case 1:
data = load_raw_data(Path(inputs[0]))
if json_output is not None:
save_raw_data(data, json_output) # type: ignore
with open(json_output, 'w', encoding='utf-8') as f:
save_raw_data(data, f) # type: ignore
stats = Stats(data)
output_markdown(sys.stdout, LAYOUT, stats)
case 2:
@ -1195,7 +1196,6 @@ def main():
parser.add_argument(
"--json-output",
nargs="?",
type=argparse.FileType("w"),
help="Output complete raw results to the given JSON file.",
)