Skip to content

Commit bcd3f52

Browse files
committed
Improve typehints
1 parent 4efa9f7 commit bcd3f52

File tree

13 files changed

+143
-65
lines changed

13 files changed

+143
-65
lines changed

Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ format:
1414
lint:
1515
poetry run ruff openandroidinstaller/ --ignore E501
1616

17+
typing:
18+
poetry run mypy openandroidinstaller/. --ignore-missing-imports
19+
1720
test: format lint
1821
PYTHONPATH=openandroidinstaller:$(PYTHONPATH) poetry run pytest --cov=openandroidinstaller tests/
1922

openandroidinstaller/app_state.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import copy
1717
from pathlib import Path
18+
from typing import List, Optional
1819

1920
from installer_config import _load_config
2021

@@ -28,7 +29,7 @@ def __init__(
2829
config_path: Path,
2930
bin_path: Path,
3031
test: bool = False,
31-
test_config: str = None,
32+
test_config: Optional[str] = None,
3233
):
3334
self.platform = platform
3435
self.config_path = config_path
@@ -44,8 +45,22 @@ def __init__(
4445
self.recovery_path = None
4546
self.is_ab = None
4647

47-
# is this still needed?
48-
self.steps = None
48+
# store views
49+
self.default_views: List = []
50+
self.addon_views: List = []
51+
self.final_default_views: List = []
52+
53+
def add_default_views(self, views: List):
54+
"""Add default views to store"""
55+
self.default_views.extend(views)
56+
57+
def add_addon_views(self, views: List):
58+
"""Add addon views to store"""
59+
self.addon_views.extend(views)
60+
61+
def add_final_default_views(self, views: List):
62+
"""Add final default views to store"""
63+
self.final_default_views.extend(views)
4964

5065
def load_config(self, device_code: str):
5166
"""Load the config from file to state by device code."""

openandroidinstaller/installer_config.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# Author: Tobias Sterbak
1515

1616
from pathlib import Path
17-
from typing import List, Optional
17+
from typing import List, Optional, Dict
1818

1919
import schema
2020
import yaml
@@ -34,10 +34,10 @@ def __init__(
3434
title: str,
3535
type: str,
3636
content: str,
37-
command: str = None,
38-
img: str = None,
3937
allow_skip: bool = False,
40-
link: str = None,
38+
command: Optional[str] = None,
39+
img: Optional[str] = None,
40+
link: Optional[str] = None,
4141
):
4242
self.title = title
4343
self.type = type
@@ -51,7 +51,7 @@ def __init__(
5151
class InstallerConfig:
5252

5353
# map some detected device codes to their real code.
54-
device_code_mapping = {
54+
device_code_mapping: Dict[str, str] = {
5555
# Sony issues
5656
"C6603": "yuga",
5757
# OnePlus issues
@@ -80,9 +80,11 @@ def __init__(
8080
self.requirements = requirements
8181
self.device_code = metadata.get("devicecode")
8282
self.twrp_link = metadata.get("twrp-link")
83-
inverted_mapping = dict(map(reversed, self.device_code_mapping.items()))
83+
84+
# manage device codes and alternative device codes/names
85+
inverted_mapping: Dict[str, str] = dict(map(reversed, self.device_code_mapping.items())) # type: ignore
8486
self.alternative_device_code = inverted_mapping.get(
85-
self.device_code, self.device_code
87+
self.device_code, self.device_code # type: ignore
8688
)
8789

8890
@classmethod

openandroidinstaller/openandroidinstaller.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import click
2020
import functools
2121
from pathlib import Path
22+
from typing import List
2223

2324
import flet as ft
2425
from flet import (
@@ -114,24 +115,26 @@ def __init__(self, state: AppState):
114115
self.install_view,
115116
]
116117

117-
self.state.default_views = self.default_views
118-
self.state.final_default_views = self.final_default_views
119-
self.state.final_view = self.final_view
120-
121-
# stack of previous default views for the back-button
122-
self.previous_views = []
123-
124118
# initialize the addon view
125119
self.select_addon_view = AddonsView(
126120
on_confirm=self.to_next_view, state=self.state
127121
)
128122
self.install_addons_view = InstallAddonsView(
129123
on_confirm=self.to_next_view, state=self.state
130124
)
131-
self.state.addon_views = [
132-
self.install_addons_view,
133-
self.select_addon_view,
134-
]
125+
126+
# attach some views to the state to modify and reuse later
127+
self.state.add_default_views(views=self.default_views)
128+
self.state.add_addon_views(
129+
views=[
130+
self.install_addons_view,
131+
self.select_addon_view,
132+
]
133+
)
134+
self.state.add_final_default_views(views=self.final_default_views)
135+
136+
# stack of previous default views for the back-button
137+
self.previous_views: List = []
135138

136139
def build(self):
137140
self.view.controls.append(self.default_views.pop())

openandroidinstaller/py.typed

Whitespace-only changes.

openandroidinstaller/tooling.py

Lines changed: 43 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -24,42 +24,46 @@
2424
)
2525
import shlex
2626
from time import sleep
27-
from typing import List, Optional, Union
27+
from typing import List, Optional, Union, Generator, Callable
2828

2929
from loguru import logger
3030

31+
32+
TerminalResponse = Generator[Union[str, bool], None, None]
33+
34+
3135
PLATFORM = sys.platform
3236

3337

3438
def run_command(
35-
command: str, bin_path: Path, enable_logging: bool = True
36-
) -> Union[str, bool]:
39+
full_command: str, bin_path: Path, enable_logging: bool = True
40+
) -> TerminalResponse:
3741
"""Run a command with a tool (adb, fastboot, heimdall)."""
38-
yield f"${command}"
42+
yield f"${full_command}"
3943
# split the command and extract the tool part
40-
tool, *command = shlex.split(command)
44+
tool, *command = shlex.split(full_command)
4145
if tool not in ["adb", "fastboot", "heimdall"]:
4246
raise Exception(f"Unknown tool {tool}. Use adb, fastboot or heimdall.")
4347
if PLATFORM == "win32":
44-
full_command = [str(bin_path.joinpath(Path(f"{tool}"))) + ".exe"] + command
48+
command_list = [str(bin_path.joinpath(Path(f"{tool}"))) + ".exe"] + command
4549
# prevent Windows from opening terminal windows
46-
si = subprocess.STARTUPINFO()
47-
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
50+
si = subprocess.STARTUPINFO() # type: ignore
51+
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type: ignore
4852
else:
49-
full_command = [str(bin_path.joinpath(Path(f"{tool}")))] + command
53+
command_list = [str(bin_path.joinpath(Path(f"{tool}")))] + command
5054
si = None
5155
if enable_logging:
52-
logger.info(f"Run command: {full_command}")
56+
logger.info(f"Run command: {command_list}")
5357
# run the command
5458
with subprocess.Popen(
55-
full_command,
59+
command_list,
5660
stdout=PIPE,
5761
stderr=STDOUT,
5862
bufsize=1,
5963
universal_newlines=True,
6064
startupinfo=si,
6165
) as p:
62-
for line in p.stdout:
66+
for line in p.stdout: # type: ignore
6367
if enable_logging:
6468
logger.info(line.strip())
6569
yield line.strip()
@@ -68,14 +72,14 @@ def run_command(
6872
yield p.returncode == 0
6973

7074

71-
def add_logging(step_desc: str, return_if_fail: bool = False):
75+
def add_logging(step_desc: str, return_if_fail: bool = False) -> Callable:
7276
"""Logging decorator to wrap functions that yield lines.
7377
7478
Logs the `step_desc`.
7579
"""
7680

77-
def logging_decorator(func):
78-
def logging(*args, **kwargs):
81+
def logging_decorator(func) -> Callable:
82+
def logging(*args, **kwargs) -> TerminalResponse:
7983
logger.info(f"{step_desc} - Paramters: {kwargs}")
8084
for line in func(*args, **kwargs):
8185
if (type(line) == bool) and not line:
@@ -91,42 +95,42 @@ def logging(*args, **kwargs):
9195

9296

9397
@add_logging("Rebooting device with adb.")
94-
def adb_reboot(bin_path: Path) -> bool:
98+
def adb_reboot(bin_path: Path) -> TerminalResponse:
9599
"""Run adb reboot on the device and return success."""
96100
for line in run_command("adb reboot", bin_path):
97101
yield line
98102

99103

100104
@add_logging("Rebooting device into bootloader with adb.", return_if_fail=True)
101-
def adb_reboot_bootloader(bin_path: Path) -> Union[str, bool]:
105+
def adb_reboot_bootloader(bin_path: Path) -> TerminalResponse:
102106
"""Reboot the device into bootloader and return success."""
103107
for line in run_command("adb reboot bootloader", bin_path):
104108
yield line
105109
sleep(1)
106110

107111

108112
@add_logging("Rebooting device into download mode with adb.")
109-
def adb_reboot_download(bin_path: Path) -> Union[str, bool]:
113+
def adb_reboot_download(bin_path: Path) -> TerminalResponse:
110114
"""Reboot the device into download mode of samsung devices and return success."""
111115
for line in run_command("adb reboot download", bin_path):
112116
yield line
113117

114118

115119
@add_logging("Sideload the target to device with adb.")
116-
def adb_sideload(bin_path: Path, target: str) -> Union[str, bool]:
120+
def adb_sideload(bin_path: Path, target: str) -> TerminalResponse:
117121
"""Sideload the target to device and return success."""
118122
for line in run_command(f"adb sideload {target}", bin_path):
119123
yield line
120124

121125

122126
@add_logging("Activate sideloading in TWRP.", return_if_fail=True)
123-
def activate_sideload(bin_path: Path) -> Union[str, bool]:
127+
def activate_sideload(bin_path: Path) -> TerminalResponse:
124128
"""Activate sideload with adb shell in twrp."""
125129
for line in run_command("adb shell twrp sideload", bin_path):
126130
yield line
127131

128132

129-
def adb_twrp_copy_partitions(bin_path: Path, config_path: Path):
133+
def adb_twrp_copy_partitions(bin_path: Path, config_path: Path) -> TerminalResponse:
130134
# some devices like one plus 6t or motorola moto g7 power need the partitions copied to prevent a hard brick
131135
logger.info("Sideload copy_partitions script with adb.")
132136
# activate sideload
@@ -146,18 +150,18 @@ def adb_twrp_copy_partitions(bin_path: Path, config_path: Path):
146150
yield line
147151
sleep(7)
148152
# Copy partitions end #
149-
return True
153+
yield True
150154

151155

152156
@add_logging("Perform a factory reset with adb and twrp.", return_if_fail=True)
153-
def adb_twrp_format_data(bin_path: Path):
157+
def adb_twrp_format_data(bin_path: Path) -> TerminalResponse:
154158
"""Perform a factory reset with twrp and adb."""
155159
for line in run_command("adb shell twrp format data", bin_path):
156160
yield line
157161

158162

159163
@add_logging("Wipe the selected partition with adb and twrp.", return_if_fail=True)
160-
def adb_twrp_wipe_partition(bin_path: Path, partition: str):
164+
def adb_twrp_wipe_partition(bin_path: Path, partition: str) -> TerminalResponse:
161165
"""Perform a factory reset with twrp and adb."""
162166
for line in run_command(f"adb shell twrp wipe {partition}", bin_path):
163167
yield line
@@ -169,8 +173,8 @@ def adb_twrp_wipe_and_install(
169173
config_path: Path,
170174
is_ab: bool,
171175
install_addons=True,
172-
recovery: str = None,
173-
) -> bool:
176+
recovery: Optional[str] = None,
177+
) -> TerminalResponse:
174178
"""Wipe and format data with twrp, then flash os image with adb.
175179
176180
Only works for twrp recovery.
@@ -237,7 +241,9 @@ def adb_twrp_wipe_and_install(
237241
yield line
238242

239243

240-
def adb_twrp_install_addons(bin_path: Path, addons: List[str], is_ab: bool) -> bool:
244+
def adb_twrp_install_addons(
245+
bin_path: Path, addons: List[str], is_ab: bool
246+
) -> TerminalResponse:
241247
"""Flash addons through adb and twrp.
242248
243249
Only works for twrp recovery.
@@ -279,42 +285,42 @@ def adb_twrp_install_addons(bin_path: Path, addons: List[str], is_ab: bool) -> b
279285

280286

281287
@add_logging("Switch active boot partitions.", return_if_fail=True)
282-
def fastboot_switch_partition(bin_path: Path) -> Union[str, bool]:
288+
def fastboot_switch_partition(bin_path: Path) -> TerminalResponse:
283289
"""Switch the active boot partition with fastboot."""
284290
for line in run_command("fastboot set_active other", bin_path):
285291
yield line
286292

287293

288294
@add_logging("Unlock the device with fastboot and code.")
289-
def fastboot_unlock_with_code(bin_path: Path, unlock_code: str) -> Union[str, bool]:
295+
def fastboot_unlock_with_code(bin_path: Path, unlock_code: str) -> TerminalResponse:
290296
"""Unlock the device with fastboot and code given."""
291297
for line in run_command(f"fastboot oem unlock {unlock_code}", bin_path):
292298
yield line
293299

294300

295301
@add_logging("Unlock the device with fastboot without code.")
296-
def fastboot_unlock(bin_path: Path) -> Union[str, bool]:
302+
def fastboot_unlock(bin_path: Path) -> TerminalResponse:
297303
"""Unlock the device with fastboot and without code."""
298304
for line in run_command("fastboot flashing unlock", bin_path):
299305
yield line
300306

301307

302308
@add_logging("OEM unlocking the device with fastboot.")
303-
def fastboot_oem_unlock(bin_path: Path) -> Union[str, bool]:
309+
def fastboot_oem_unlock(bin_path: Path) -> TerminalResponse:
304310
"""OEM unlock the device with fastboot and without code."""
305311
for line in run_command("fastboot oem unlock", bin_path):
306312
yield line
307313

308314

309315
@add_logging("Get unlock data with fastboot")
310-
def fastboot_get_unlock_data(bin_path: Path) -> Union[str, bool]:
316+
def fastboot_get_unlock_data(bin_path: Path) -> TerminalResponse:
311317
"""Get the unlock data with fastboot"""
312318
for line in run_command("fastboot oem get_unlock_data", bin_path):
313319
yield line
314320

315321

316322
@add_logging("Rebooting device with fastboot.")
317-
def fastboot_reboot(bin_path: Path) -> Union[str, bool]:
323+
def fastboot_reboot(bin_path: Path) -> TerminalResponse:
318324
"""Reboot with fastboot"""
319325
for line in run_command("fastboot reboot", bin_path):
320326
yield line
@@ -323,7 +329,7 @@ def fastboot_reboot(bin_path: Path) -> Union[str, bool]:
323329
@add_logging("Flash or boot custom recovery with fastboot.")
324330
def fastboot_flash_recovery(
325331
bin_path: Path, recovery: str, is_ab: bool = True
326-
) -> Union[str, bool]:
332+
) -> TerminalResponse:
327333
"""Temporarily, flash custom recovery with fastboot."""
328334
if is_ab:
329335
logger.info("Boot custom recovery with fastboot.")
@@ -344,7 +350,7 @@ def fastboot_flash_recovery(
344350
yield line
345351

346352

347-
def fastboot_flash_boot(bin_path: Path, recovery: str) -> bool:
353+
def fastboot_flash_boot(bin_path: Path, recovery: str) -> TerminalResponse:
348354
"""Temporarily, flash custom recovery with fastboot to boot partition."""
349355
logger.info("Flash custom recovery with fastboot.")
350356
for line in run_command(f"fastboot flash boot {recovery}", bin_path):
@@ -366,7 +372,7 @@ def fastboot_flash_boot(bin_path: Path, recovery: str) -> bool:
366372

367373

368374
@add_logging("Flash custom recovery with heimdall.")
369-
def heimdall_flash_recovery(bin_path: Path, recovery: str) -> Union[str, bool]:
375+
def heimdall_flash_recovery(bin_path: Path, recovery: str) -> TerminalResponse:
370376
"""Temporarily, flash custom recovery with heimdall."""
371377
for line in run_command(
372378
f"heimdall flash --no-reboot --RECOVERY {recovery}", bin_path
@@ -414,7 +420,7 @@ def search_device(platform: str, bin_path: Path) -> Optional[str]:
414420
return None
415421

416422

417-
def check_ab_partition(platform: str, bin_path: Path) -> Optional[str]:
423+
def check_ab_partition(platform: str, bin_path: Path) -> Optional[bool]:
418424
"""Figure out, if its an a/b-partitioned device."""
419425
logger.info(f"Run on {platform} with {bin_path}...")
420426
try:

0 commit comments

Comments
 (0)