Skip to content

Commit 6624496

Browse files
committed
chore: code improvements
1 parent 8ac02f0 commit 6624496

File tree

7 files changed

+39
-50
lines changed

7 files changed

+39
-50
lines changed

src/stubber/basicgit.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -38,26 +38,26 @@ def _run_git(
3838
elif capture_output and echo_output: # pragma: no cover
3939
log.error(stderr)
4040
if not expect_stderr:
41-
raise Exception(stderr)
41+
raise ChildProcessError(stderr)
4242

4343
if result.returncode < 0:
44-
raise Exception(result.stderr.decode("utf-8"))
44+
raise ChildProcessError(result.stderr.decode("utf-8"))
4545
return result
4646

4747

4848
def clone(remote_repo: str, path: Path, shallow=False, tag: Optional[str] = None) -> bool:
49-
"git clone [--depth 1] [--branch <tag_name>] <remote> <directory>"
49+
"""git clone [--depth 1] [--branch <tag_name>] <remote> <directory>"""
5050
cmd = ["git", "clone"]
5151
if shallow:
5252
cmd += ["--depth", "1"]
5353
if tag in ("latest", "master"):
5454
tag = None
55-
if not tag:
56-
cmd += [remote_repo, str(path)]
57-
else:
58-
cmd += [remote_repo, "--branch", tag, str(path)]
59-
result = _run_git(cmd, expect_stderr=True, capture_output=False)
60-
if result:
55+
cmd += (
56+
[remote_repo, "--branch", tag, str(path)]
57+
if tag
58+
else [remote_repo, str(path)]
59+
)
60+
if result := _run_git(cmd, expect_stderr=True, capture_output=False):
6161
return result.returncode == 0
6262
else:
6363
return False
@@ -81,10 +81,11 @@ def get_tag(repo: Optional[Union[str, Path]] = None, abbreviate: bool = True) ->
8181
tag: str = result.stdout.decode("utf-8")
8282
tag = tag.replace("\r", "").replace("\n", "")
8383
if abbreviate and "-" in tag:
84-
# this may or not be the latest on the main branch
85-
# result = _run_git(["git", "rev-parse", "--abbrev-ref", "HEAD"], repo=repo, expect_stderr=True)
86-
result = _run_git(["git", "status", "--branch"], repo=repo.as_posix(), expect_stderr=True)
87-
if result:
84+
if result := _run_git(
85+
["git", "status", "--branch"],
86+
repo=repo.as_posix(),
87+
expect_stderr=True,
88+
):
8889
lines = result.stdout.decode("utf-8").replace("\r", "").split("\n")
8990
if lines[0].startswith("On branch"):
9091
if lines[0].endswith("master"):
@@ -134,11 +135,11 @@ def synch_submodules(repo: Optional[Union[Path, str]] = None) -> bool:
134135
["git", "submodule", "update", "--quiet"],
135136
]
136137
for cmd in cmds:
137-
result = _run_git(cmd, repo=repo, expect_stderr=True)
138-
if not result:
138+
if result := _run_git(cmd, repo=repo, expect_stderr=True):
139+
# actually a good result
140+
log.debug(result.stderr.decode("utf-8"))
141+
else:
139142
return False
140-
# actually a good result
141-
log.debug(result.stderr.decode("utf-8"))
142143
return True
143144

144145

@@ -203,9 +204,7 @@ def fetch(repo: Union[Path, str]) -> bool:
203204

204205
cmd = ["git", "fetch", "--all", "--tags", "--quiet"]
205206
result = _run_git(cmd, repo=repo, echo_output=False)
206-
if not result:
207-
return False
208-
return result.returncode == 0
207+
return result.returncode == 0 if result else False
209208

210209

211210
def pull(repo: Union[Path, str], branch="main") -> bool:

src/stubber/utils/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class StubberConfig(Config):
4242
"list of recent versions"
4343

4444
def post_read_hook(self) -> dict:
45-
config_updates = dict()
45+
config_updates = {}
4646
# relative to stubs
4747
config_updates.update(fallback_path=self.stub_path / self.fallback_path)
4848

src/stubber/utils/manifest.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def manifest(
3737
firmware = firmware.replace("--", "-")
3838
firmware = firmware.replace("--", "-")
3939

40-
mod_manifest = {
40+
return {
4141
"$schema": "https://raw.githubusercontent.com/Josverl/micropython-stubber/main/data/schema/stubber-v1_4_0.json",
4242
"firmware": {
4343
"family": family,
@@ -56,7 +56,6 @@ def manifest(
5656
},
5757
"modules": [],
5858
}
59-
return mod_manifest
6059

6160

6261
def make_manifest(folder: Path, family: str, port: str, version: str, release: str = "", stubtype: str = "", board: str = "") -> bool:
@@ -65,7 +64,7 @@ def make_manifest(folder: Path, family: str, port: str, version: str, release: s
6564
try:
6665
# list all *.py files, not strictly modules but decent enough for documentation
6766
files = list(folder.glob("**/*.py"))
68-
if len(files) == 0:
67+
if not files:
6968
files = list(folder.glob("**/*.pyi"))
7069

7170
# sort the list

src/stubber/utils/repos.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def switch(tag: str, *, mpy_path: Path, mpy_lib_path: Path):
2626
git.fetch(mpy_path)
2727
git.fetch(mpy_lib_path)
2828

29-
if not tag or tag in ["master", ""]:
29+
if not tag or tag in {"master", ""}:
3030
tag = "latest"
3131
if tag == "latest":
3232
git.switch_branch(repo=mpy_path, branch="master")
@@ -48,7 +48,7 @@ def read_micropython_lib_commits(filename="data/micropython_tags.csv"):
4848
"""
4949
data = pkgutil.get_data("stubber", filename)
5050
if not data:
51-
raise Exception(f"Resource {filename} not found")
51+
raise FileNotFoundError(f"Resource {filename} not found")
5252
version_commit = defaultdict() # lgtm [py/multiple-definition]
5353
with tempfile.NamedTemporaryFile(prefix="tags", suffix=".csv", mode="w+t") as ntf:
5454
ntf.file.write(data.decode(encoding="utf8"))

src/stubber/utils/stubmaker.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def generate_pyi_files(modules_folder: Path) -> bool:
5757
# stubgen cannot process folders with duplicate modules ( ie v1.14 and v1.15 )
5858
# NOTE: FIX 1 add __init__.py to umqtt
5959
if (modules_folder / "umqtt/robust.py").exists(): # and not (freeze_path / "umqtt" / "__init__.py").exists():
60-
log.debug(f"add missing : umqtt/__init__.py")
60+
log.debug("add missing : umqtt/__init__.py")
6161
with open(modules_folder / "umqtt" / "__init__.py", "a") as f:
6262
f.write("")
6363

@@ -68,7 +68,6 @@ def generate_pyi_files(modules_folder: Path) -> bool:
6868
for mod_manifest in modlist:
6969
## generate fyi files for folder
7070
r = r and generate_pyi_files(mod_manifest.parent)
71-
return r
7271
else: # one or less module manifests
7372
## generate fyi files for folder
7473
log.debug("::group::[stubgen] running stubgen on {0}".format(modules_folder))
@@ -113,4 +112,5 @@ def generate_pyi_files(modules_folder: Path) -> bool:
113112
for py in py_files:
114113
r = r and generate_pyi_from_file(py)
115114
# todo: report failures by adding to module manifest
116-
return r
115+
116+
return r

src/stubber/utils/typed_config_toml.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ def __init__(self, filename: str, prefix: Optional[str] = None, must_exist: bool
6060
self.data = {}
6161

6262
# Quick checks on data format
63-
6463
assert isinstance(self.data, Dict)
6564
for k, v in self.data.items():
6665
assert isinstance(k, str)

src/stubber/utils/versions.py

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,16 @@ def clean_version(
1414
"Clean up and transform the many flavours of versions"
1515
# 'v1.13.0-103-gb137d064e' --> 'v1.13-103'
1616

17-
if version in ["", "-"]:
17+
if version in {"", "-"}:
1818
return version
1919
nibbles = version.split("-")
20-
if not patch:
21-
if nibbles[0] >= "1.10.0" and nibbles[0].endswith(".0"):
20+
if not patch and nibbles[0] >= "1.10.0" and nibbles[0].endswith(".0"):
2221
# remove the last ".0"
23-
nibbles[0] = nibbles[0][0:-2]
22+
nibbles[0] = nibbles[0][:-2]
2423
if len(nibbles) == 1:
2524
version = nibbles[0]
2625
elif build:
27-
if not commit:
28-
version = "-".join(nibbles[0:-1])
29-
else:
30-
version = "-".join(nibbles)
26+
version = "-".join(nibbles) if commit else "-".join(nibbles[:-1])
3127
else:
3228
# version = "-".join((nibbles[0], LATEST))
3329
# HACK: this is not always right, but good enough most of the time
@@ -39,19 +35,15 @@ def clean_version(
3935

4036
if drop_v:
4137
version = version.lstrip("v")
42-
else:
43-
# prefix with `v` but not before latest
44-
if not version.startswith("v") and version.lower() != "latest":
45-
version = "v" + version
38+
elif not version.startswith("v") and version.lower() != "latest":
39+
version = "v" + version
4640
return version
4741

4842

4943
def micropython_versions(start="v1.9.2"):
50-
g = Github()
51-
repo = g.get_repo("micropython/micropython")
52-
return [tag.name for tag in repo.get_tags() if parse(tag.name) >= parse(start)]
53-
54-
55-
# def micropython_versions():
56-
# "static version"
57-
# return ['v1.19.1', 'v1.19', 'v1.18', 'v1.17', 'v1.16', 'v1.15', 'v1.14', 'v1.13', 'v1.12', 'v1.11', 'v1.10', 'v1.9.4', 'v1.9.3']
44+
try:
45+
g = Github()
46+
repo = g.get_repo("micropython/micropython")
47+
return [tag.name for tag in repo.get_tags() if parse(tag.name) >= parse(start)]
48+
except Exception:
49+
return ['v1.19.1', 'v1.19', 'v1.18', 'v1.17', 'v1.16', 'v1.15', 'v1.14', 'v1.13', 'v1.12', 'v1.11', 'v1.10', 'v1.9.4', 'v1.9.3']

0 commit comments

Comments
 (0)