Skip to content

Commit

Permalink
Merge pull request #164 from BrianPugh/fix-new-cmd
Browse files Browse the repository at this point in the history
fix "belay new" CLI command
  • Loading branch information
BrianPugh authored Jul 8, 2024
2 parents b477778 + c7bec71 commit 893dee5
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 105 deletions.
22 changes: 7 additions & 15 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: "v0.0.284"
rev: "v0.5.1"
hooks:
- id: ruff
args: []
exclude: ^(belay/snippets/)

- repo: https://github.com/psf/black
rev: 23.7.0
rev: 24.4.2
hooks:
- id: black
args:
Expand All @@ -20,13 +20,13 @@ repos:
exclude: ^(belay/snippets/)

- repo: https://github.com/asottile/blacken-docs
rev: 1.15.0
rev: 1.18.0
hooks:
- id: blacken-docs
exclude: ^(docs/source/How Belay Works.rst)

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-ast
Expand All @@ -53,20 +53,12 @@ repos:
exclude: \.(html|svg)$

- repo: https://github.com/fredrikaverpil/creosote.git
rev: v2.6.3
rev: v3.0.2
hooks:
- id: creosote
args:
- "--venv=.venv"
- "--paths=belay"
- "--deps-file=pyproject.toml"
- "--sections=tool.poetry.dependencies"
- "--exclude-deps"
- "importlib_resources"
- "pydantic"

- repo: https://github.com/codespell-project/codespell
rev: v2.2.5
rev: v2.3.0
hooks:
- id: codespell
exclude: ^(poetry.lock)
Expand Down
7 changes: 4 additions & 3 deletions belay/cli/new.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pathlib import Path

from packaging.utils import canonicalize_name
from typer import Argument, Option
from typer import Argument

if sys.version_info < (3, 9, 0):
import importlib_resources
Expand All @@ -18,7 +18,7 @@ def new(project_name: str = Argument(..., help="Project Name.")):
dst_dir = Path() / project_name
template_dir = importlib_resources.files("belay") / "cli" / "new_template"

shutil.copytree(str(template_dir), str(dst_dir))
shutil.copytree(str(template_dir), str(dst_dir), ignore=shutil.ignore_patterns("*.pyc", "__pycache__"))

# Find/Replace Engine
replacements: dict[str, str] = {
Expand All @@ -33,7 +33,8 @@ def replace(string):
def _replace(match):
return replacements[match.group(0)]

return re.sub("|".join(r"\b%s\b" % re.escape(s) for s in replacements), _replace, string)
pattern = "|".join(rf"\b{re.escape(s)}\b" if " " not in s else re.escape(s) for s in replacements)
return re.sub(pattern, _replace, string)

for path in paths:
if path.is_dir():
Expand Down
24 changes: 8 additions & 16 deletions belay/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,15 +562,13 @@ def reconnect(self, attempts: Optional[int] = None) -> None:

@overload
@staticmethod
def setup(f: Callable[P, R]) -> Callable[P, R]:
...
def setup(f: Callable[P, R]) -> Callable[P, R]: ...

@overload
@staticmethod
def setup(
*, autoinit: bool = False, implementation: str = "", **kwargs
) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

@staticmethod
def setup(
Expand Down Expand Up @@ -626,13 +624,11 @@ def setup(

@overload
@staticmethod
def teardown(f: Callable[P, R]) -> Callable[P, R]:
...
def teardown(f: Callable[P, R]) -> Callable[P, R]: ...

@overload
@staticmethod
def teardown(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
def teardown(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

@staticmethod
def teardown(
Expand Down Expand Up @@ -677,13 +673,11 @@ def teardown(

@overload
@staticmethod
def task(f: Callable[P, R]) -> Callable[P, R]:
...
def task(f: Callable[P, R]) -> Callable[P, R]: ...

@overload
@staticmethod
def task(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
def task(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

@staticmethod
def task(
Expand Down Expand Up @@ -731,13 +725,11 @@ def task(

@overload
@staticmethod
def thread(f: Callable[P, R]) -> Callable[P, R]:
...
def thread(f: Callable[P, R]) -> Callable[P, R]: ...

@overload
@staticmethod
def thread(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
def thread(*, implementation: str = "", **kwargs) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

@staticmethod
def thread(
Expand Down
1 change: 1 addition & 0 deletions belay/device_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
https://github.com/mCodingLLC/VideosSampleCode/blob/master/videos/077_metaclasses_in_python/overloading.py
"""

from autoregistry import RegistryMeta

from .exceptions import NoMatchingExecuterError
Expand Down
18 changes: 6 additions & 12 deletions belay/executers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ def __call__(self):

class _GlobalExecuter(Executer, skip=True):
@overload
def __call__(self, f: Callable[P, R]) -> Callable[P, R]:
...
def __call__(self, f: Callable[P, R]) -> Callable[P, R]: ...

@overload
def __call__(
Expand All @@ -49,8 +48,7 @@ def __call__(
register: bool = True,
record: bool = True,
ignore_errors: bool = False,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

def __call__(
self,
Expand Down Expand Up @@ -103,8 +101,7 @@ class TeardownExecuter(_GlobalExecuter):

class TaskExecuter(Executer):
@overload
def __call__(self, f: Callable[P, R]) -> Callable[P, R]:
...
def __call__(self, f: Callable[P, R]) -> Callable[P, R]: ...

@overload
def __call__(
Expand All @@ -114,8 +111,7 @@ def __call__(
register: bool = True,
record: bool = False,
trusted: bool = False,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

def __call__(
self,
Expand Down Expand Up @@ -185,8 +181,7 @@ def gen_inner():

class ThreadExecuter(Executer):
@overload
def __call__(self, f: Callable[P, R]) -> Callable[P, R]:
...
def __call__(self, f: Callable[P, R]) -> Callable[P, R]: ...

@overload
def __call__(
Expand All @@ -195,8 +190,7 @@ def __call__(
minify: bool = True,
register: bool = True,
record: bool = True,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

def __call__(
self,
Expand Down
27 changes: 14 additions & 13 deletions belay/pyboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,16 @@
from threading import Lock, Thread
from typing import Union

from .exceptions import BelayException, ConnectionFailedError, DeviceNotFoundError
from .usb_specifier import UsbSpecifier
from .utils import env_parse_bool
from .webrepl import WebreplToSerial

try:
from pydantic.v1.error_wrappers import ValidationError
except ImportError:
from pydantic import ValidationError

from .exceptions import BelayException, ConnectionFailedError, DeviceNotFoundError
from .usb_specifier import UsbSpecifier
from .utils import env_parse_bool
from .webrepl import WebreplToSerial

try:
stdout = sys.stdout.buffer
Expand Down Expand Up @@ -309,7 +310,7 @@ def __init__(
Parameters
----------
device: str
Some device specificier like ``'/dev/ttyACM0'`` or ``'192.168.1.1'``.
Some device specifier like ``'/dev/ttyACM0'`` or ``'192.168.1.1'``.
baudrate: int
If a serial-like connection, this baudrate will be used.
user: str
Expand Down Expand Up @@ -573,7 +574,7 @@ def exec_raw_no_follow(self, command):
# check if we could exec command
data = self.serial.read(2)
if data != b"OK":
raise PyboardError("could not exec command (response: %r)" % data)
raise PyboardError(f"could not exec command (response: {data!r})")

def exec_raw(self, command, timeout=None, data_consumer=None):
self.exec_raw_no_follow(command)
Expand Down Expand Up @@ -602,7 +603,7 @@ def fs_ls(self, src):
cmd = (
"import uos\nfor f in uos.ilistdir(%s):\n"
" print('{:12} {}{}'.format(f[3]if len(f)>3 else 0,f[0],'/'if f[1]&0x4000 else ''))"
% (("'%s'" % src) if src else "")
% ((f"'{src}'") if src else "")
)
self.exec(cmd, data_consumer=stdout_write_bytes)

Expand All @@ -617,8 +618,8 @@ def fs_get(self, src, dest, chunk_size=256, progress_callback=None):
dest = Path(dest)
written = 0
if progress_callback:
src_size = int(self.exec("import os\nprint(os.stat('%s')[6])" % src))
self.exec("f=open('%s','rb')\nr=f.read" % src)
src_size = int(self.exec(f"import os\nprint(os.stat('{src}')[6])"))
self.exec(f"f=open('{src}','rb')\nr=f.read")
with dest.open("wb") as f:
while True:
data = bytearray()
Expand Down Expand Up @@ -649,7 +650,7 @@ def fs_put(self, src, dest, chunk_size=256, progress_callback=None):
src = Path(src)
written = 0
src_size = src.stat().st_size
self.exec("f=open('%s','wb')\nw=f.write" % dest)
self.exec(f"f=open('{dest}','wb')\nw=f.write")
with src.open("rb") as f:
while True:
data = f.read(chunk_size)
Expand All @@ -662,10 +663,10 @@ def fs_put(self, src, dest, chunk_size=256, progress_callback=None):
self.exec("f.close()")

def fs_mkdir(self, dir):
self.exec("import uos\nuos.mkdir('%s')" % dir)
self.exec(f"import uos\nuos.mkdir('{dir}')")

def fs_rmdir(self, dir):
self.exec("import uos\nuos.rmdir('%s')" % dir)
self.exec(f"import uos\nuos.rmdir('{dir}')")

def fs_rm(self, src):
self.exec("import uos\nuos.remove('%s')" % src)
self.exec(f"import uos\nuos.remove('{src}')")
17 changes: 9 additions & 8 deletions belay/webrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import errno
import socket
import struct
Expand Down Expand Up @@ -95,10 +96,10 @@ def read(self, size, text_ok=False, size_match=True):
break
if text_ok and fl == 0x81:
break
debugmsg("Got unexpected websocket record of type %x, skipping it" % fl)
debugmsg(f"Got unexpected websocket record of type {fl:x}, skipping it")
while sz:
skip = self.s.recv(sz)
debugmsg("Skip data: %s" % skip)
debugmsg(f"Skip data: {skip}")
sz -= len(skip)
data = self.recvexactly(sz)
if len(data) != sz:
Expand Down Expand Up @@ -203,14 +204,14 @@ def get_file(ws, local_file, remote_file):

def help(rc=0):
exename = sys.argv[0].rsplit("/", 1)[-1]
print("%s - Perform remote file operations using MicroPython WebREPL protocol" % exename)
print(f"{exename} - Perform remote file operations using MicroPython WebREPL protocol")
print("Arguments:")
print(" [-p password] <host>:<remote_file> <local_file> - Copy remote file to local file")
print(" [-p password] <local_file> <host>:<remote_file> - Copy local file to remote file")
print("Examples:")
print(" %s script.py 192.168.4.1:/another_name.py" % exename)
print(" %s script.py 192.168.4.1:/app/" % exename)
print(" %s -p password 192.168.4.1:/app/script.py ." % exename)
print(f" {exename} script.py 192.168.4.1:/another_name.py")
print(f" {exename} script.py 192.168.4.1:/app/")
print(f" {exename} -p password 192.168.4.1:/app/script.py .")
sys.exit(rc)


Expand Down Expand Up @@ -297,8 +298,8 @@ def read(self, size=1) -> bytes:
if self.ws is None:
raise WebsocketClosedError

readin = self.ws.read(size, text_ok=True, size_match=False)
self.fifo.extend(readin)
read_in = self.ws.read(size, text_ok=True, size_match=False)
self.fifo.extend(read_in)

data = b""
while len(data) < size and len(self.fifo) > 0:
Expand Down
2 changes: 1 addition & 1 deletion docs/source/Package Manager.rst
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ This is not a true virtual environment; currently the ``micropython`` binary mus

clean
-----
Removes any previously downloaded dependencies no longer specified in ``tool.belay.dependecies``.
Removes any previously downloaded dependencies no longer specified in ``tool.belay.dependencies``.

.. code-block:: bash
Expand Down
Loading

0 comments on commit 893dee5

Please sign in to comment.