Skip to content

Commit 9bd08f4

Browse files
committed
cli: Simplify path handling.
Instead of converting a path to an open file, getting the file name, closing it again, and then opening it again, just use the given name. Sometimes simplicity is better. And it will let us use run repl in a future commit.
1 parent e1b0894 commit 9bd08f4

File tree

2 files changed

+19
-52
lines changed

2 files changed

+19
-52
lines changed

pybricksdev/cli/__init__.py

Lines changed: 18 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,11 @@
55

66
import argparse
77
import asyncio
8-
import contextlib
98
import logging
10-
import os
119
import sys
1210
from abc import ABC, abstractmethod
13-
from os import PathLike, path
11+
from os import path
1412
from tempfile import NamedTemporaryFile
15-
from typing import ContextManager, TextIO
1613

1714
import argcomplete
1815
from argcomplete.completers import FilesCompleter
@@ -50,44 +47,6 @@ async def run(self, args: argparse.Namespace):
5047
pass
5148

5249

53-
def _get_script_path(file: TextIO) -> ContextManager[PathLike]:
54-
"""
55-
Gets the path to a script on the file system.
56-
57-
If the file is ``sys.stdin``, the contents are copied to a temporary file
58-
and the path to the temporary file is returned. Otherwise, the file is closed
59-
and the path is returned.
60-
61-
The context manager will delete the temporary file, if applicable.
62-
"""
63-
if file is sys.stdin:
64-
# Have to close the temp file so that mpy-cross can read it, so we
65-
# create our own context manager to delete the file when we are done
66-
# using it.
67-
68-
@contextlib.contextmanager
69-
def temp_context():
70-
try:
71-
with NamedTemporaryFile(suffix=".py", delete=False) as temp:
72-
temp.write(file.buffer.read())
73-
74-
yield temp.name
75-
finally:
76-
try:
77-
os.remove(temp.name)
78-
except NameError:
79-
# if NamedTemporaryFile() throws, temp is not defined
80-
pass
81-
except OSError:
82-
# file was already deleted or other strangeness
83-
pass
84-
85-
return temp_context()
86-
87-
file.close()
88-
return contextlib.nullcontext(file.name)
89-
90-
9150
class Compile(Tool):
9251
def add_parser(self, subparsers: argparse._SubParsersAction):
9352
parser = subparsers.add_parser(
@@ -98,7 +57,7 @@ def add_parser(self, subparsers: argparse._SubParsersAction):
9857
"file",
9958
metavar="<file>",
10059
help="path to a MicroPython script or `-` for stdin",
101-
type=argparse.FileType(),
60+
type=str,
10261
)
10362
parser.add_argument(
10463
"--abi",
@@ -113,8 +72,12 @@ def add_parser(self, subparsers: argparse._SubParsersAction):
11372
async def run(self, args: argparse.Namespace):
11473
from pybricksdev.compile import compile_multi_file, print_mpy
11574

116-
with _get_script_path(args.file) as script_path:
117-
mpy = await compile_multi_file(script_path, args.abi)
75+
if args.file == "-":
76+
with NamedTemporaryFile(suffix=".py", delete=False) as temp:
77+
temp.write(sys.stdin.buffer.read())
78+
args.file = temp.name
79+
80+
mpy = await compile_multi_file(args.file, args.abi)
11881
print_mpy(mpy)
11982

12083

@@ -135,7 +98,7 @@ def add_parser(self, subparsers: argparse._SubParsersAction):
13598
"file",
13699
metavar="<file>",
137100
help="path to a MicroPython script or `-` for stdin",
138-
type=argparse.FileType(),
101+
type=str,
139102
)
140103
parser.add_argument(
141104
"-n",
@@ -213,11 +176,15 @@ def is_pybricks_usb(dev):
213176
# Connect to the address and run the script
214177
await hub.connect()
215178
try:
216-
with _get_script_path(args.file) as script_path:
217-
if args.start:
218-
await hub.run(script_path, args.wait)
219-
else:
220-
await hub.download(script_path)
179+
if args.file == "-":
180+
with NamedTemporaryFile(suffix=".py", delete=False) as temp:
181+
temp.write(sys.stdin.buffer.read())
182+
args.file = temp.name
183+
184+
if args.start:
185+
await hub.run(args.file, args.wait)
186+
else:
187+
await hub.download(args.file)
221188
finally:
222189
await hub.disconnect()
223190

tests/test_cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def test_add_parser(self):
4545
with patch("builtins.open", mock_file):
4646
args = parser.parse_args(["ble", "test.py"])
4747
assert args.conntype == "ble"
48-
assert args.file.name == "test.py"
48+
assert args.file == "test.py"
4949
assert args.name is None
5050

5151
# Test with optional name argument

0 commit comments

Comments
 (0)