mpflash 1.0.0__py3-none-any.whl → 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. mpflash/add_firmware.py +98 -98
  2. mpflash/ask_input.py +236 -236
  3. mpflash/basicgit.py +284 -284
  4. mpflash/bootloader/__init__.py +2 -2
  5. mpflash/bootloader/activate.py +60 -60
  6. mpflash/bootloader/detect.py +82 -82
  7. mpflash/bootloader/manual.py +101 -101
  8. mpflash/bootloader/micropython.py +12 -12
  9. mpflash/bootloader/touch1200.py +36 -36
  10. mpflash/cli_download.py +129 -129
  11. mpflash/cli_flash.py +224 -216
  12. mpflash/cli_group.py +111 -111
  13. mpflash/cli_list.py +87 -87
  14. mpflash/cli_main.py +39 -39
  15. mpflash/common.py +210 -166
  16. mpflash/config.py +44 -44
  17. mpflash/connected.py +104 -77
  18. mpflash/download.py +364 -364
  19. mpflash/downloaded.py +130 -130
  20. mpflash/errors.py +9 -9
  21. mpflash/flash/__init__.py +55 -55
  22. mpflash/flash/esp.py +59 -59
  23. mpflash/flash/stm32.py +19 -19
  24. mpflash/flash/stm32_dfu.py +104 -104
  25. mpflash/flash/uf2/__init__.py +88 -88
  26. mpflash/flash/uf2/boardid.py +15 -15
  27. mpflash/flash/uf2/linux.py +136 -130
  28. mpflash/flash/uf2/macos.py +42 -42
  29. mpflash/flash/uf2/uf2disk.py +12 -12
  30. mpflash/flash/uf2/windows.py +43 -43
  31. mpflash/flash/worklist.py +170 -170
  32. mpflash/list.py +106 -106
  33. mpflash/logger.py +41 -41
  34. mpflash/mpboard_id/__init__.py +93 -93
  35. mpflash/mpboard_id/add_boards.py +251 -251
  36. mpflash/mpboard_id/board.py +37 -37
  37. mpflash/mpboard_id/board_id.py +86 -86
  38. mpflash/mpboard_id/store.py +43 -43
  39. mpflash/mpremoteboard/__init__.py +266 -266
  40. mpflash/mpremoteboard/mpy_fw_info.py +141 -141
  41. mpflash/mpremoteboard/runner.py +140 -140
  42. mpflash/vendor/click_aliases.py +91 -91
  43. mpflash/vendor/dfu.py +165 -165
  44. mpflash/vendor/pydfu.py +605 -605
  45. mpflash/vendor/readme.md +2 -2
  46. mpflash/versions.py +135 -135
  47. {mpflash-1.0.0.dist-info → mpflash-1.0.2.dist-info}/LICENSE +20 -20
  48. {mpflash-1.0.0.dist-info → mpflash-1.0.2.dist-info}/METADATA +1 -1
  49. mpflash-1.0.2.dist-info/RECORD +53 -0
  50. mpflash-1.0.0.dist-info/RECORD +0 -53
  51. {mpflash-1.0.0.dist-info → mpflash-1.0.2.dist-info}/WHEEL +0 -0
  52. {mpflash-1.0.0.dist-info → mpflash-1.0.2.dist-info}/entry_points.txt +0 -0
mpflash/add_firmware.py CHANGED
@@ -1,98 +1,98 @@
1
- import shutil
2
- from pathlib import Path
3
- from typing import Union
4
-
5
- import jsonlines
6
- import requests
7
- from loguru import logger as log
8
-
9
- # re-use logic from mpremote
10
- from mpremote.mip import _rewrite_url as rewrite_url # type: ignore
11
-
12
- from mpflash.common import FWInfo
13
- from mpflash.config import config
14
- from mpflash.versions import get_preview_mp_version, get_stable_mp_version
15
-
16
-
17
- def add_firmware(
18
- source: Union[Path, str],
19
- new_fw: FWInfo,
20
- *,
21
- force: bool = False,
22
- custom: bool = False,
23
- description: str = "",
24
- ) -> bool:
25
- """Add a firmware to the firmware folder.
26
-
27
- stored in the port folder, with the same filename as the source.
28
-
29
- """
30
- # Check minimal info needed
31
- if not new_fw.port or not new_fw.board:
32
- log.error("Port and board are required")
33
- return False
34
- if not isinstance(source, Path) and not source.startswith("http"):
35
- log.error(f"Invalid source {source}")
36
- return False
37
-
38
- # use sensible defaults
39
- source_2 = Path(source)
40
- new_fw.ext = new_fw.ext or source_2.suffix
41
- new_fw.variant = new_fw.variant or new_fw.board
42
- new_fw.custom = new_fw.custom or custom
43
- new_fw.description = new_fw.description or description
44
- if not new_fw.version:
45
- # TODO: Get version from filename
46
- # or use the last preview version
47
- new_fw.version = get_preview_mp_version() if new_fw.preview else get_stable_mp_version()
48
-
49
- config.firmware_folder.mkdir(exist_ok=True)
50
-
51
- fw_filename = config.firmware_folder / new_fw.port / source_2.name
52
-
53
- new_fw.filename = str(fw_filename.relative_to(config.firmware_folder))
54
- new_fw.firmware = source.as_uri() if isinstance(source, Path) else source
55
-
56
- if not copy_firmware(source, fw_filename, force):
57
- log.error(f"Failed to copy {source} to {fw_filename}")
58
- return False
59
- # add to inventory
60
- with jsonlines.open(config.firmware_folder / "firmware.jsonl", "a") as writer:
61
- log.info(f"Adding {new_fw.port} {new_fw.board}")
62
- log.info(f" to {fw_filename}")
63
-
64
- writer.write(new_fw.to_dict())
65
- return True
66
-
67
-
68
- def copy_firmware(source: Union[Path, str], fw_filename: Path, force: bool = False):
69
- """Add a firmware to the firmware folder.
70
- stored in the port folder, with the same filename as the source.
71
- """
72
- if fw_filename.exists() and not force:
73
- log.error(f" {fw_filename} already exists. Use --force to overwrite")
74
- return False
75
- fw_filename.parent.mkdir(exist_ok=True)
76
- if isinstance(source, Path):
77
- if not source.exists():
78
- log.error(f"File {source} does not exist")
79
- return False
80
- # file copy
81
- log.debug(f"Copy {source} to {fw_filename}")
82
- shutil.copy(source, fw_filename)
83
- return True
84
- # handle github urls
85
- url = rewrite_url(source)
86
- if str(source).startswith("http://") or str(source).startswith("https://"):
87
- log.debug(f"Download {url} to {fw_filename}")
88
- response = requests.get(url)
89
-
90
- if response.status_code == 200:
91
- with open(fw_filename, "wb") as file:
92
- file.write(response.content)
93
- log.info("File downloaded and saved successfully.")
94
- return True
95
- else:
96
- print("Failed to download the file.")
97
- return False
98
- return False
1
+ import shutil
2
+ from pathlib import Path
3
+ from typing import Union
4
+
5
+ import jsonlines
6
+ import requests
7
+ from loguru import logger as log
8
+
9
+ # re-use logic from mpremote
10
+ from mpremote.mip import _rewrite_url as rewrite_url # type: ignore
11
+
12
+ from mpflash.common import FWInfo
13
+ from mpflash.config import config
14
+ from mpflash.versions import get_preview_mp_version, get_stable_mp_version
15
+
16
+
17
+ def add_firmware(
18
+ source: Union[Path, str],
19
+ new_fw: FWInfo,
20
+ *,
21
+ force: bool = False,
22
+ custom: bool = False,
23
+ description: str = "",
24
+ ) -> bool:
25
+ """Add a firmware to the firmware folder.
26
+
27
+ stored in the port folder, with the same filename as the source.
28
+
29
+ """
30
+ # Check minimal info needed
31
+ if not new_fw.port or not new_fw.board:
32
+ log.error("Port and board are required")
33
+ return False
34
+ if not isinstance(source, Path) and not source.startswith("http"):
35
+ log.error(f"Invalid source {source}")
36
+ return False
37
+
38
+ # use sensible defaults
39
+ source_2 = Path(source)
40
+ new_fw.ext = new_fw.ext or source_2.suffix
41
+ new_fw.variant = new_fw.variant or new_fw.board
42
+ new_fw.custom = new_fw.custom or custom
43
+ new_fw.description = new_fw.description or description
44
+ if not new_fw.version:
45
+ # TODO: Get version from filename
46
+ # or use the last preview version
47
+ new_fw.version = get_preview_mp_version() if new_fw.preview else get_stable_mp_version()
48
+
49
+ config.firmware_folder.mkdir(exist_ok=True)
50
+
51
+ fw_filename = config.firmware_folder / new_fw.port / source_2.name
52
+
53
+ new_fw.filename = str(fw_filename.relative_to(config.firmware_folder))
54
+ new_fw.firmware = source.as_uri() if isinstance(source, Path) else source
55
+
56
+ if not copy_firmware(source, fw_filename, force):
57
+ log.error(f"Failed to copy {source} to {fw_filename}")
58
+ return False
59
+ # add to inventory
60
+ with jsonlines.open(config.firmware_folder / "firmware.jsonl", "a") as writer:
61
+ log.info(f"Adding {new_fw.port} {new_fw.board}")
62
+ log.info(f" to {fw_filename}")
63
+
64
+ writer.write(new_fw.to_dict())
65
+ return True
66
+
67
+
68
+ def copy_firmware(source: Union[Path, str], fw_filename: Path, force: bool = False):
69
+ """Add a firmware to the firmware folder.
70
+ stored in the port folder, with the same filename as the source.
71
+ """
72
+ if fw_filename.exists() and not force:
73
+ log.error(f" {fw_filename} already exists. Use --force to overwrite")
74
+ return False
75
+ fw_filename.parent.mkdir(exist_ok=True)
76
+ if isinstance(source, Path):
77
+ if not source.exists():
78
+ log.error(f"File {source} does not exist")
79
+ return False
80
+ # file copy
81
+ log.debug(f"Copy {source} to {fw_filename}")
82
+ shutil.copy(source, fw_filename)
83
+ return True
84
+ # handle github urls
85
+ url = rewrite_url(source)
86
+ if str(source).startswith("http://") or str(source).startswith("https://"):
87
+ log.debug(f"Download {url} to {fw_filename}")
88
+ response = requests.get(url)
89
+
90
+ if response.status_code == 200:
91
+ with open(fw_filename, "wb") as file:
92
+ file.write(response.content)
93
+ log.info("File downloaded and saved successfully.")
94
+ return True
95
+ else:
96
+ print("Failed to download the file.")
97
+ return False
98
+ return False
mpflash/ask_input.py CHANGED
@@ -1,236 +1,236 @@
1
- """
2
- Interactive input for mpflash.
3
-
4
- Note: The prompts can use "{version}" and "{action}" to insert the version and action in the prompt without needing an f-string.
5
- The values are provided from the answers dictionary.
6
- """
7
-
8
- from typing import List, Sequence, Tuple, Union
9
-
10
- from loguru import logger as log
11
-
12
- from .common import DownloadParams, FlashParams, ParamType
13
- from .config import config
14
- from .mpboard_id import (get_known_boards_for_port, get_known_ports,
15
- known_stored_boards)
16
- from .mpremoteboard import MPRemoteBoard
17
- from .versions import micropython_versions
18
-
19
-
20
- def ask_missing_params(
21
- params: ParamType,
22
- ) -> ParamType:
23
- """
24
- Asks the user for parameters that have not been supplied on the commandline and returns the updated params.
25
-
26
- Args:
27
- params (ParamType): The parameters to be updated.
28
-
29
- Returns:
30
- ParamType: The updated parameters.
31
- """
32
- if not config.interactive:
33
- # no interactivity allowed
34
- log.info("Interactive mode disabled. Skipping ask for user input.")
35
- return params
36
-
37
- import inquirer
38
-
39
- log.trace(f"ask_missing_params: {params}")
40
-
41
- # if action flash, single input
42
- # if action download, multiple input
43
- multi_select = isinstance(params, DownloadParams)
44
- action = "download" if isinstance(params, DownloadParams) else "flash"
45
-
46
- questions = []
47
- answers: dict[str, Union[str, List]] = {"action": action}
48
- if not multi_select:
49
- if not params.serial or "?" in params.serial:
50
- questions.append(ask_serialport(multi_select=False, bluetooth=False))
51
- else:
52
- answers["serial"] = params.serial
53
-
54
- if params.versions == [] or "?" in params.versions:
55
- questions.append(ask_mp_version(multi_select=multi_select, action=action))
56
- else:
57
- # versions is used to show only the boards for the selected versions
58
- answers["versions"] = params.versions # type: ignore
59
-
60
- if not params.boards or "?" in params.boards:
61
- questions.extend(ask_port_board(multi_select=multi_select, action=action))
62
- if questions:
63
- answers = inquirer.prompt(questions, answers=answers) # type: ignore
64
- if not answers:
65
- # input cancelled by user
66
- return [] # type: ignore
67
- log.trace(f"answers: {answers}")
68
- if isinstance(params, FlashParams) and "serial" in answers:
69
- if isinstance(answers["serial"], str):
70
- answers["serial"] = [answers["serial"]]
71
- params.serial = [s.split()[0] for s in answers["serial"]] # split to remove the description
72
- if "port" in answers:
73
- # params.ports = [p for p in params.ports if p != "?"] # remove the "?" if present
74
- if isinstance(answers["port"], str):
75
- params.ports.append(answers["port"])
76
- elif isinstance(answers["port"], list): # type: ignore
77
- params.ports.extend(answers["port"])
78
- else:
79
- raise ValueError(f"Unexpected type for answers['port']: {type(answers['port'])}")
80
-
81
- if "boards" in answers:
82
- params.boards = [b for b in params.boards if b != "?"] # remove the "?" if present
83
- params.boards.extend(answers["boards"] if isinstance(answers["boards"], list) else [answers["boards"]])
84
- if "versions" in answers:
85
- params.versions = [v for v in params.versions if v != "?"] # remove the "?" if present
86
- # make sure it is a list
87
- if isinstance(answers["versions"], (list, tuple)):
88
- params.versions.extend(answers["versions"])
89
- else:
90
- params.versions.append(answers["versions"])
91
- # remove duplicates
92
- params.ports = list(set(params.ports))
93
- params.boards = list(set(params.boards))
94
- params.versions = list(set(params.versions))
95
- log.trace(f"ask_missing_params returns: {params}")
96
-
97
- return params
98
-
99
-
100
- def filter_matching_boards(answers: dict) -> Sequence[Tuple[str, str]]:
101
- """
102
- Filters the known boards based on the selected versions and returns the filtered boards.
103
-
104
- Args:
105
- answers (dict): The user's answers.
106
-
107
- Returns:
108
- Sequence[Tuple[str, str]]: The filtered boards.
109
- """
110
- versions = None
111
- # if version is not asked ; then need to get the version from the inputs
112
- if "versions" in answers:
113
- versions = list(answers["versions"])
114
- if "stable" in versions:
115
- versions.remove("stable")
116
- versions.append(micropython_versions()[-2]) # latest stable
117
- elif "preview" in versions:
118
- versions.remove("preview")
119
- versions.extend((micropython_versions()[-1], micropython_versions()[-2])) # latest preview and stable
120
-
121
- some_boards = known_stored_boards(answers["port"], versions) # or known_mp_boards(answers["port"])
122
-
123
- if some_boards:
124
- # Create a dictionary where the keys are the second elements of the tuples
125
- # This will automatically remove duplicates because dictionaries cannot have duplicate keys
126
- unique_dict = {item[1]: item for item in some_boards}
127
- # Get the values of the dictionary, which are the unique items from the original list
128
- some_boards = list(unique_dict.values())
129
- else:
130
- some_boards = [(f"No {answers['port']} boards found for version(s) {versions}", "")]
131
- return some_boards
132
-
133
-
134
- def ask_port_board(*, multi_select: bool, action: str):
135
- """
136
- Asks the user for the port and board selection.
137
-
138
- Args:
139
- questions (list): The list of questions to be asked.
140
- action (str): The action to be performed.
141
-
142
- Returns:
143
- None
144
- """
145
- # import only when needed to reduce load time
146
- import inquirer
147
-
148
- # if action flash, single input
149
- # if action download, multiple input
150
- inquirer_ux = inquirer.Checkbox if multi_select else inquirer.List
151
- return [
152
- inquirer.List(
153
- "port",
154
- message="Which port do you want to {action} " + "to {serial} ?" if action == "flash" else "?",
155
- choices=get_known_ports(),
156
- # autocomplete=True,
157
- ),
158
- inquirer_ux(
159
- "boards",
160
- message=(
161
- "Which {port} board firmware do you want to {action} " + "to {serial} ?" if action == "flash" else "?"
162
- ),
163
- choices=filter_matching_boards,
164
- validate=at_least_one_validation, # type: ignore
165
- # validate=lambda _, x: True if x else "Please select at least one board", # type: ignore
166
- ),
167
- ]
168
-
169
- def at_least_one_validation(answers, current) -> bool:
170
- import inquirer.errors
171
- if not current:
172
- raise inquirer.errors.ValidationError("", reason="Please select at least one item.")
173
- if isinstance(current, list) and not any(current):
174
- raise inquirer.errors.ValidationError("", reason="Please select at least one item.")
175
- return True
176
-
177
- def ask_mp_version(multi_select: bool, action: str):
178
- """
179
- Asks the user for the version selection.
180
-
181
- Args:
182
- questions (list): The list of questions to be asked.
183
- action (str): The action to be performed.
184
-
185
- Returns:
186
-
187
- """
188
- # import only when needed to reduce load time
189
- import inquirer
190
- import inquirer.errors
191
-
192
- input_ux = inquirer.Checkbox if multi_select else inquirer.List
193
-
194
- mp_versions: List[str] = micropython_versions()
195
- mp_versions.reverse() # newest first
196
-
197
- # remove the versions for which there are no known boards in the board_info.json
198
- # todo: this may be a little slow
199
- mp_versions = [v for v in mp_versions if "preview" in v or get_known_boards_for_port("stm32", [v])]
200
-
201
- message = "Which version(s) do you want to {action} " + ("to {serial} ?" if action == "flash" else "?")
202
- q = input_ux(
203
- # inquirer.List(
204
- "versions",
205
- message=message,
206
- # Hints would be nice , but needs a hint for each and every option
207
- # hints=["Use space to select multiple options"],
208
- choices=mp_versions,
209
- autocomplete=True,
210
- validate=at_least_one_validation, # type: ignore
211
- )
212
- return q
213
-
214
-
215
- def ask_serialport(*, multi_select: bool = False, bluetooth: bool = False):
216
- """
217
- Asks the user for the serial port selection.
218
-
219
- Args:
220
- questions (list): The list of questions to be asked.
221
- action (str): The action to be performed.
222
-
223
- Returns:
224
- None
225
- """
226
- # import only when needed to reduce load time
227
- import inquirer
228
-
229
- comports = MPRemoteBoard.connected_boards(bluetooth=bluetooth, description=True)
230
- return inquirer.List(
231
- "serial",
232
- message="Which serial port do you want to {action} ?",
233
- choices=comports,
234
- other=True,
235
- validate=lambda _, x: True if x else "Please select or enter a serial port", # type: ignore
236
- )
1
+ """
2
+ Interactive input for mpflash.
3
+
4
+ Note: The prompts can use "{version}" and "{action}" to insert the version and action in the prompt without needing an f-string.
5
+ The values are provided from the answers dictionary.
6
+ """
7
+
8
+ from typing import List, Sequence, Tuple, Union
9
+
10
+ from loguru import logger as log
11
+
12
+ from .common import DownloadParams, FlashParams, ParamType
13
+ from .config import config
14
+ from .mpboard_id import (get_known_boards_for_port, get_known_ports,
15
+ known_stored_boards)
16
+ from .mpremoteboard import MPRemoteBoard
17
+ from .versions import micropython_versions
18
+
19
+
20
+ def ask_missing_params(
21
+ params: ParamType,
22
+ ) -> ParamType:
23
+ """
24
+ Asks the user for parameters that have not been supplied on the commandline and returns the updated params.
25
+
26
+ Args:
27
+ params (ParamType): The parameters to be updated.
28
+
29
+ Returns:
30
+ ParamType: The updated parameters.
31
+ """
32
+ if not config.interactive:
33
+ # no interactivity allowed
34
+ log.info("Interactive mode disabled. Skipping ask for user input.")
35
+ return params
36
+
37
+ import inquirer
38
+
39
+ log.trace(f"ask_missing_params: {params}")
40
+
41
+ # if action flash, single input
42
+ # if action download, multiple input
43
+ multi_select = isinstance(params, DownloadParams)
44
+ action = "download" if isinstance(params, DownloadParams) else "flash"
45
+
46
+ questions = []
47
+ answers: dict[str, Union[str, List]] = {"action": action}
48
+ if not multi_select:
49
+ if not params.serial or "?" in params.serial:
50
+ questions.append(ask_serialport(multi_select=False, bluetooth=False))
51
+ else:
52
+ answers["serial"] = params.serial
53
+
54
+ if params.versions == [] or "?" in params.versions:
55
+ questions.append(ask_mp_version(multi_select=multi_select, action=action))
56
+ else:
57
+ # versions is used to show only the boards for the selected versions
58
+ answers["versions"] = params.versions # type: ignore
59
+
60
+ if not params.boards or "?" in params.boards:
61
+ questions.extend(ask_port_board(multi_select=multi_select, action=action))
62
+ if questions:
63
+ answers = inquirer.prompt(questions, answers=answers) # type: ignore
64
+ if not answers:
65
+ # input cancelled by user
66
+ return [] # type: ignore
67
+ log.trace(f"answers: {answers}")
68
+ if isinstance(params, FlashParams) and "serial" in answers:
69
+ if isinstance(answers["serial"], str):
70
+ answers["serial"] = [answers["serial"]]
71
+ params.serial = [s.split()[0] for s in answers["serial"]] # split to remove the description
72
+ if "port" in answers:
73
+ # params.ports = [p for p in params.ports if p != "?"] # remove the "?" if present
74
+ if isinstance(answers["port"], str):
75
+ params.ports.append(answers["port"])
76
+ elif isinstance(answers["port"], list): # type: ignore
77
+ params.ports.extend(answers["port"])
78
+ else:
79
+ raise ValueError(f"Unexpected type for answers['port']: {type(answers['port'])}")
80
+
81
+ if "boards" in answers:
82
+ params.boards = [b for b in params.boards if b != "?"] # remove the "?" if present
83
+ params.boards.extend(answers["boards"] if isinstance(answers["boards"], list) else [answers["boards"]])
84
+ if "versions" in answers:
85
+ params.versions = [v for v in params.versions if v != "?"] # remove the "?" if present
86
+ # make sure it is a list
87
+ if isinstance(answers["versions"], (list, tuple)):
88
+ params.versions.extend(answers["versions"])
89
+ else:
90
+ params.versions.append(answers["versions"])
91
+ # remove duplicates
92
+ params.ports = list(set(params.ports))
93
+ params.boards = list(set(params.boards))
94
+ params.versions = list(set(params.versions))
95
+ log.trace(f"ask_missing_params returns: {params}")
96
+
97
+ return params
98
+
99
+
100
+ def filter_matching_boards(answers: dict) -> Sequence[Tuple[str, str]]:
101
+ """
102
+ Filters the known boards based on the selected versions and returns the filtered boards.
103
+
104
+ Args:
105
+ answers (dict): The user's answers.
106
+
107
+ Returns:
108
+ Sequence[Tuple[str, str]]: The filtered boards.
109
+ """
110
+ versions = None
111
+ # if version is not asked ; then need to get the version from the inputs
112
+ if "versions" in answers:
113
+ versions = list(answers["versions"])
114
+ if "stable" in versions:
115
+ versions.remove("stable")
116
+ versions.append(micropython_versions()[-2]) # latest stable
117
+ elif "preview" in versions:
118
+ versions.remove("preview")
119
+ versions.extend((micropython_versions()[-1], micropython_versions()[-2])) # latest preview and stable
120
+
121
+ some_boards = known_stored_boards(answers["port"], versions) # or known_mp_boards(answers["port"])
122
+
123
+ if some_boards:
124
+ # Create a dictionary where the keys are the second elements of the tuples
125
+ # This will automatically remove duplicates because dictionaries cannot have duplicate keys
126
+ unique_dict = {item[1]: item for item in some_boards}
127
+ # Get the values of the dictionary, which are the unique items from the original list
128
+ some_boards = list(unique_dict.values())
129
+ else:
130
+ some_boards = [(f"No {answers['port']} boards found for version(s) {versions}", "")]
131
+ return some_boards
132
+
133
+
134
+ def ask_port_board(*, multi_select: bool, action: str):
135
+ """
136
+ Asks the user for the port and board selection.
137
+
138
+ Args:
139
+ questions (list): The list of questions to be asked.
140
+ action (str): The action to be performed.
141
+
142
+ Returns:
143
+ None
144
+ """
145
+ # import only when needed to reduce load time
146
+ import inquirer
147
+
148
+ # if action flash, single input
149
+ # if action download, multiple input
150
+ inquirer_ux = inquirer.Checkbox if multi_select else inquirer.List
151
+ return [
152
+ inquirer.List(
153
+ "port",
154
+ message="Which port do you want to {action} " + "to {serial} ?" if action == "flash" else "?",
155
+ choices=get_known_ports(),
156
+ # autocomplete=True,
157
+ ),
158
+ inquirer_ux(
159
+ "boards",
160
+ message=(
161
+ "Which {port} board firmware do you want to {action} " + "to {serial} ?" if action == "flash" else "?"
162
+ ),
163
+ choices=filter_matching_boards,
164
+ validate=at_least_one_validation, # type: ignore
165
+ # validate=lambda _, x: True if x else "Please select at least one board", # type: ignore
166
+ ),
167
+ ]
168
+
169
+ def at_least_one_validation(answers, current) -> bool:
170
+ import inquirer.errors
171
+ if not current:
172
+ raise inquirer.errors.ValidationError("", reason="Please select at least one item.")
173
+ if isinstance(current, list) and not any(current):
174
+ raise inquirer.errors.ValidationError("", reason="Please select at least one item.")
175
+ return True
176
+
177
+ def ask_mp_version(multi_select: bool, action: str):
178
+ """
179
+ Asks the user for the version selection.
180
+
181
+ Args:
182
+ questions (list): The list of questions to be asked.
183
+ action (str): The action to be performed.
184
+
185
+ Returns:
186
+
187
+ """
188
+ # import only when needed to reduce load time
189
+ import inquirer
190
+ import inquirer.errors
191
+
192
+ input_ux = inquirer.Checkbox if multi_select else inquirer.List
193
+
194
+ mp_versions: List[str] = micropython_versions()
195
+ mp_versions.reverse() # newest first
196
+
197
+ # remove the versions for which there are no known boards in the board_info.json
198
+ # todo: this may be a little slow
199
+ mp_versions = [v for v in mp_versions if "preview" in v or get_known_boards_for_port("stm32", [v])]
200
+
201
+ message = "Which version(s) do you want to {action} " + ("to {serial} ?" if action == "flash" else "?")
202
+ q = input_ux(
203
+ # inquirer.List(
204
+ "versions",
205
+ message=message,
206
+ # Hints would be nice , but needs a hint for each and every option
207
+ # hints=["Use space to select multiple options"],
208
+ choices=mp_versions,
209
+ autocomplete=True,
210
+ validate=at_least_one_validation, # type: ignore
211
+ )
212
+ return q
213
+
214
+
215
+ def ask_serialport(*, multi_select: bool = False, bluetooth: bool = False):
216
+ """
217
+ Asks the user for the serial port selection.
218
+
219
+ Args:
220
+ questions (list): The list of questions to be asked.
221
+ action (str): The action to be performed.
222
+
223
+ Returns:
224
+ None
225
+ """
226
+ # import only when needed to reduce load time
227
+ import inquirer
228
+
229
+ comports = MPRemoteBoard.connected_boards(bluetooth=bluetooth, description=True)
230
+ return inquirer.List(
231
+ "serial",
232
+ message="Which serial port do you want to {action} ?",
233
+ choices=comports,
234
+ other=True,
235
+ validate=lambda _, x: True if x else "Please select or enter a serial port", # type: ignore
236
+ )