mpbuild 0.8__tar.gz → 0.9__tar.gz

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.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mpbuild
3
- Version: 0.8
3
+ Version: 0.9
4
4
  Summary: Build MicroPython firmware with ease!
5
5
  Author-email: Matt Trentini <matt.trentini@gmail.com>
6
6
  License-File: LICENSE
7
- Requires-Python: >=3.9
7
+ Requires-Python: >=3.12
8
8
  Requires-Dist: rich>=13.7.1
9
9
  Requires-Dist: typer>=0.12.3
10
10
  Description-Content-Type: text/markdown
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mpbuild"
3
- version = "0.8"
3
+ version = "0.9"
4
4
  description = "Build MicroPython firmware with ease!"
5
5
  authors = [
6
6
  { name = "Matt Trentini", email = "matt.trentini@gmail.com" }
@@ -10,7 +10,7 @@ dependencies = [
10
10
  "rich>=13.7.1",
11
11
  ]
12
12
  readme = "README.md"
13
- requires-python = ">= 3.9"
13
+ requires-python = ">= 3.12"
14
14
 
15
15
  [project.scripts]
16
16
  mpbuild = "mpbuild.__main__:main"
@@ -111,11 +111,11 @@ class Board:
111
111
  name=filename_json.parent.name,
112
112
  variants=[],
113
113
  url=board_json.get("url", "http://micropython.org"),
114
- mcu=board_json["mcu"],
115
- product=board_json["product"],
116
- vendor=board_json["vendor"],
117
- images=board_json["images"],
118
- deploy=board_json["deploy"],
114
+ mcu=board_json.get("mcu", ""),
115
+ product=board_json.get("product", ""),
116
+ vendor=board_json.get("vendor", ""),
117
+ images=board_json.get("images", []),
118
+ deploy=board_json.get("deploy", []),
119
119
  physical_board=True,
120
120
  port=port,
121
121
  )
@@ -256,7 +256,9 @@ class Database:
256
256
  port=port,
257
257
  )
258
258
  port.boards = {special_port_name: board}
259
- board.variants = [Variant(name=v, text="", board=board) for v in variant_names]
259
+ board.variants = [
260
+ Variant(name=v, text="", board=board) for v in variant_names
261
+ ]
260
262
  self.ports[special_port_name] = port
261
263
  self.boards[board.name] = board
262
264
 
@@ -269,3 +271,32 @@ class Database:
269
271
  raise MpbuildMpyDirectoryException(
270
272
  f"Directory does not point to the top of a micropython repo: {directory}"
271
273
  )
274
+
275
+ @staticmethod
276
+ def check_board_json(
277
+ board_json: dict, board_name: str, port_name: str
278
+ ) -> list[str]:
279
+ """
280
+ Checks a board.json file for missing or invalid keys.
281
+ Returns a list of issues found.
282
+ """
283
+ issues = []
284
+ required_keys = ["mcu", "product", "vendor", "images", "deploy"]
285
+
286
+ for key in required_keys:
287
+ if key not in board_json:
288
+ issues.append(f"{port_name}/{board_name}: Missing required key '{key}'")
289
+
290
+ if "url" not in board_json:
291
+ issues.append(f"{port_name}/{board_name}: Missing URL key")
292
+
293
+ if "variants" in board_json and not isinstance(board_json["variants"], dict):
294
+ issues.append(f"{port_name}/{board_name}: 'variants' is not a dictionary")
295
+
296
+ if "images" in board_json and not isinstance(board_json["images"], list):
297
+ issues.append(f"{port_name}/{board_name}: 'images' is not a list")
298
+
299
+ if "deploy" in board_json and not isinstance(board_json["deploy"], list):
300
+ issues.append(f"{port_name}/{board_name}: 'deploy' is not a list")
301
+
302
+ return issues
@@ -4,6 +4,8 @@ from typing import Optional, List
4
4
  from pathlib import Path
5
5
  import multiprocessing
6
6
  import subprocess
7
+ import sys
8
+ import glob
7
9
 
8
10
  from rich import print
9
11
  from rich.panel import Panel
@@ -20,7 +22,8 @@ BUILD_CONTAINERS = {
20
22
  "mimxrt": ARM_BUILD_CONTAINER,
21
23
  "renesas-ra": ARM_BUILD_CONTAINER,
22
24
  "samd": ARM_BUILD_CONTAINER,
23
- "esp32": "espressif/idf:v5.2.2",
25
+ "psoc6": "ifxmakers/mpy-mtb-ci",
26
+ "esp32": "espressif/idf:v5.4.1",
24
27
  "esp8266": "larsks/esp-open-sdk",
25
28
  "unix": "gcc:12-bookworm", # Special, doesn't have boards
26
29
  }
@@ -90,8 +93,9 @@ def docker_build_cmd(
90
93
  args = " " + " ".join(extra_args)
91
94
 
92
95
  make_mpy_cross_cmd = "make -C mpy-cross && "
93
- update_submodules_cmd = f"make -C ports/{port.name} submodules && "
94
-
96
+ update_submodules_cmd = (
97
+ f"make -C ports/{port.name} BOARD={board.name}{variant_cmd} submodules && "
98
+ )
95
99
  uid, gid = os.getuid(), os.getgid()
96
100
 
97
101
  if do_clean:
@@ -101,19 +105,28 @@ def docker_build_cmd(
101
105
  make_mpy_cross_cmd = ""
102
106
  update_submodules_cmd = ""
103
107
 
104
- home = os.environ["HOME"]
105
108
  mpy_dir = str(port.directory_repo)
106
109
 
110
+ # Dynamically find all ttyACM and ttyUSB devices
111
+ tty_devices = []
112
+ for pattern in ["/dev/ttyACM*", "/dev/ttyUSB*"]:
113
+ tty_devices.extend(glob.glob(pattern))
114
+
115
+ # Build device flags
116
+ device_flags = ""
117
+ if os.path.exists("/dev/bus/usb/") and os.listdir("/dev/bus/usb/"):
118
+ device_flags += "--device /dev/bus/usb/ " # USB access
119
+ for device in tty_devices:
120
+ device_flags += f"--device {device} "
121
+
107
122
  # fmt: off
108
123
  build_cmd = (
109
124
  f"docker run --rm "
110
125
  f"{'-it ' if docker_interactive else ''}"
111
- f"-v /sys/bus:/sys/bus " # provides access to USB for deploy
112
- f"-v /dev:/dev " # provides access to USB for deploy
113
- f"--net=host --privileged " # provides access to USB for deploy
126
+ f"{device_flags}" # provides access to USB and serial devices for deploy
114
127
  f"-v {mpy_dir}:{mpy_dir} -w {mpy_dir} " # mount micropython dir with same path so elf/map paths match host
115
128
  f"--user {uid}:{gid} " # match running user id so generated files aren't owned by root
116
- f"-v {home}:{home} -e HOME={home} " # when changing user id to one not present in container this ensures home is writable
129
+ f"-e HOME=/tmp " # set HOME to /tmp for container
117
130
  f"{build_container} "
118
131
  f'bash -c "'
119
132
  f"git config --global --add safe.directory '*' 2> /dev/null;"
@@ -166,6 +179,7 @@ def build_board(
166
179
  extra_args=extra_args,
167
180
  do_clean=do_clean,
168
181
  build_container_override=build_container_override,
182
+ docker_interactive=sys.stdin.isatty(),
169
183
  )
170
184
 
171
185
  title = "Build" if do_clean else "Clean"
@@ -1,4 +1,5 @@
1
1
  from . import board_database
2
+ import json
2
3
 
3
4
  from urllib.request import Request, urlopen
4
5
  from urllib.error import HTTPError
@@ -9,47 +10,64 @@ from rich.panel import Panel
9
10
  from rich.table import Table
10
11
 
11
12
 
12
- def check_images(verbose: bool = False, mpy_dir: str = None) -> None:
13
+ def check_boards(verbose: bool = False, mpy_dir: str = None) -> None:
13
14
  db = board_database(mpy_dir)
14
- # TODO(mst) A minor improvement: Should count the number of images in all
15
- # the boards for each port (this assumes one per board).
16
15
  num_boards = len(db.boards)
17
16
 
18
- # no_images = [("stm32", "fooobar"), ("rp2", "PICO")] # []
19
- # image_not_found = [("stm32", "fooobar", "https://raw.githubusercontent.com/micropython/micropython-media/main/boards/VK_RA6M5/VK-RA6M5.jpg"),
20
- # ("stm32", "fooobar", "https://raw.githubusercontent.com/micropython/micropython-media/main/boards/VK_RA6M5/VK-RA6M5.jpg"),
21
- # ("rp2", "PICO", "https://raw.githubusercontent.com/micropython/micropython-media/main/boards/VK_RA6M5/VK-RA6M5.jpg")] # []
22
- # image_too_large = [("esp32", "GENERIC", "https://raw.githubusercontent.com/micropython/micropython-media/main/boards/VK_RA6M5/VK-RA6M5.jpg", 500_000),
23
- # ("rp2", "PICO", "https://raw.githubusercontent.com/micropython/micropython-media/main/boards/VK_RA6M5/VK-RA6M5.jpg", 400_000)] # []
17
+ # Lists to store issues
24
18
  no_images = []
25
19
  image_not_found = []
26
20
  image_too_large = []
21
+ board_json_issues = []
27
22
 
28
23
  base_url = (
29
24
  r"https://raw.githubusercontent.com/micropython/micropython-media/main/boards"
30
25
  )
26
+
31
27
  with Progress(transient=True) as progress:
32
- task1 = progress.add_task("[cyan]Checking images...", total=num_boards)
28
+ task1 = progress.add_task("[cyan]Checking boards...", total=num_boards)
29
+
30
+ # Check each board
33
31
  for _board in db.boards.values():
32
+ if _board.physical_board:
33
+ # Check board.json file format
34
+ json_path = _board.directory / "board.json"
35
+ try:
36
+ if json_path.exists():
37
+ with open(json_path) as f:
38
+ board_json = json.load(f)
39
+ # Check for issues in board.json
40
+ issues = db.check_board_json(
41
+ board_json, _board.name, _board.port.name
42
+ )
43
+ board_json_issues.extend(issues)
44
+ except (json.JSONDecodeError, IOError) as e:
45
+ board_json_issues.append(
46
+ f"{_board.port.name}/{_board.name}: Error reading board.json: {str(e)}"
47
+ )
48
+
49
+ # Check images
34
50
  image_list = _board.images
35
51
  if len(image_list) == 0:
36
- # No images specified in build.json (should be at least one)
52
+ # No images specified in board.json (should be at least one)
37
53
  no_images.append((_board.port.name, _board.name))
54
+
38
55
  for image in image_list:
39
56
  # Check each image listed in board.json
40
57
  image_url = f"{base_url}/{_board.name}/{image}"
41
58
  req = Request(image_url, method="HEAD")
42
59
  try:
43
60
  f = urlopen(req)
61
+ if f.status == 200:
62
+ # Check size < ~500KB
63
+ image_size = int(f.headers["Content-Length"])
64
+ if image_size > 500_000:
65
+ image_too_large.append(
66
+ (_board.port.name, _board.name, image_url, image_size)
67
+ )
44
68
  except HTTPError:
45
69
  image_not_found.append((_board.port.name, _board.name, image_url))
46
- if f.status == 200:
47
- # Check size < ~500KB
48
- image_size = int(f.headers["Content-Length"])
49
- if image_size > 500_000:
50
- image_too_large.append(
51
- (_board.port.name, _board.name, image_url, image_size)
52
- )
70
+
53
71
  progress.update(task1, advance=1)
54
72
 
55
73
  # Display output
@@ -57,7 +75,8 @@ def check_images(verbose: bool = False, mpy_dir: str = None) -> None:
57
75
  grid.add_column()
58
76
  grid.add_column()
59
77
  grid.add_column()
60
- grid.add_row(
78
+
79
+ first_row = [
61
80
  Panel(
62
81
  "\n".join([f"{p}/[bright_white]{b}[/]" for p, b in no_images]),
63
82
  title="No images",
@@ -83,5 +102,23 @@ def check_images(verbose: bool = False, mpy_dir: str = None) -> None:
83
102
  title="Too large",
84
103
  subtitle="Image > 500KB",
85
104
  ),
86
- )
105
+ ]
106
+
107
+ grid.add_row(*first_row)
108
+
109
+ # Add board.json issues panel if there are any
110
+ if board_json_issues:
111
+ json_panel = Panel(
112
+ "\n".join(board_json_issues),
113
+ title="board.json issues",
114
+ subtitle="Missing or invalid keys",
115
+ )
116
+ grid.add_row(json_panel)
117
+
87
118
  print(grid)
119
+
120
+
121
+ # Backwards compatibility
122
+ def check_images(verbose: bool = False, mpy_dir: str = None) -> None:
123
+ """Legacy function, redirects to check_boards"""
124
+ check_boards(verbose, mpy_dir)
@@ -6,7 +6,7 @@ import typer
6
6
  from . import __app_name__, __version__, OutputFormat
7
7
  from .build import build_board, clean_board
8
8
  from .list_boards import print_boards
9
- from .check_images import check_images
9
+ from .check_images import check_boards
10
10
  from .completions import list_ports, list_boards, list_variants_for_board
11
11
 
12
12
  app = typer.Typer(chain=True, context_settings={"help_option_names": ["-h", "--help"]})
@@ -86,14 +86,25 @@ def list_boards_and_variants(
86
86
  print_boards(port, fmt)
87
87
 
88
88
 
89
- @app.command("check_images")
89
+ @app.command("check_boards")
90
+ def board_check(
91
+ verbose: Annotated[bool, typer.Option(help="More verbose output")] = False,
92
+ ) -> None:
93
+ """
94
+ Check boards for issues with board.json files and images
95
+ """
96
+ check_boards(verbose)
97
+
98
+
99
+ # Keep old command for backwards compatibility
100
+ @app.command("check_images", hidden=True)
90
101
  def image_check(
91
102
  verbose: Annotated[bool, typer.Option(help="More verbose output")] = False,
92
103
  ) -> None:
93
104
  """
94
- Check images
105
+ Check images (deprecated, use check_boards instead)
95
106
  """
96
- check_images(verbose)
107
+ check_boards(verbose)
97
108
 
98
109
 
99
110
  def _version_callback(value: bool) -> None:
@@ -0,0 +1,273 @@
1
+ """
2
+ Interactive TUI for mpbuild using Textual.
3
+ """
4
+ from pathlib import Path
5
+ from typing import Any, Optional
6
+
7
+ from textual import on
8
+ from textual.app import App, ComposeResult
9
+ from textual.binding import Binding
10
+ from textual.containers import Container, Horizontal, Vertical
11
+ from textual.widgets import Button, Footer, Header, Label, Static, Tree
12
+ from textual.widgets.tree import TreeNode
13
+ import subprocess
14
+
15
+ from . import board_database
16
+ from .board_database import Board, Port, Variant
17
+ from .build import docker_build_cmd
18
+
19
+
20
+ class BoardDetails(Static):
21
+ """Widget to display details about a selected board."""
22
+
23
+ def __init__(self, board: Optional[Board] = None) -> None:
24
+ super().__init__()
25
+ self.board = board
26
+
27
+ def update_board(self, board: Optional[Board]) -> None:
28
+ """Update the displayed board details."""
29
+ self.board = board
30
+ self.update_content()
31
+
32
+ def update_content(self) -> None:
33
+ """Update the content based on the current board."""
34
+ if self.board is None:
35
+ self.update(f"No board selected")
36
+ return
37
+
38
+ # Build details about the board
39
+ content = f"# {self.board.product}\n\n"
40
+ content += f"**Board:** {self.board.name}\n"
41
+ content += f"**Port:** {self.board.port.name}\n"
42
+ content += f"**MCU:** {self.board.mcu}\n"
43
+ content += f"**Vendor:** {self.board.vendor}\n"
44
+
45
+ if self.board.variants:
46
+ content += f"\n**Variants:**\n"
47
+ for variant in self.board.variants:
48
+ content += f"- {variant.name}: {variant.text}\n"
49
+
50
+ if self.board.url:
51
+ content += f"\n**URL:** {self.board.url}\n"
52
+
53
+ self.update(content)
54
+
55
+ def compose(self) -> ComposeResult:
56
+ """Create child widgets."""
57
+ self.update_content()
58
+ yield from []
59
+
60
+
61
+ class BuildLog(Static):
62
+ """Widget to display build logs."""
63
+
64
+ def clear_log(self) -> None:
65
+ """Clear the build log."""
66
+ self.update("")
67
+
68
+ def add_log(self, text: str) -> None:
69
+ """Add text to the build log."""
70
+ current = self.render()
71
+ self.update(f"{current}\n{text}")
72
+
73
+
74
+ class MpbuildApp(App):
75
+ """A Textual app for interactive mpbuild."""
76
+
77
+ CSS = """
78
+ #tree-view {
79
+ width: 25%;
80
+ min-width: 20;
81
+ border: solid cornflowerblue;
82
+ }
83
+
84
+ #details-panel {
85
+ border: solid cornflowerblue;
86
+ height: 60%;
87
+ padding: 1;
88
+ }
89
+
90
+ #log-panel {
91
+ height: 40%;
92
+ border: solid cornflowerblue;
93
+ padding: 1;
94
+ overflow: auto;
95
+ }
96
+
97
+ #build-button {
98
+ margin: 1;
99
+ }
100
+
101
+ .build-controls {
102
+ height: auto;
103
+ align: center middle;
104
+ }
105
+
106
+ Tree {
107
+ padding: 1;
108
+ }
109
+
110
+ Header {
111
+ background: cornflowerblue;
112
+ }
113
+ """
114
+
115
+ BINDINGS = [
116
+ Binding("q", "quit", "Quit"),
117
+ Binding("b", "build", "Build"),
118
+ ]
119
+
120
+ def __init__(self, mpy_dir: Optional[Path] = None) -> None:
121
+ """Initialize the app."""
122
+ super().__init__()
123
+ self.db = board_database(mpy_dir)
124
+ self.selected_board: Optional[Board] = None
125
+ self.selected_variant: Optional[Variant] = None
126
+ self.building = False
127
+
128
+ def compose(self) -> ComposeResult:
129
+ """Create child widgets."""
130
+ yield Header(show_clock=True)
131
+ with Horizontal():
132
+ yield Tree("MicroPython Boards", id="tree-view")
133
+ with Vertical():
134
+ yield BoardDetails(id="details-panel")
135
+ with Container(classes="build-controls"):
136
+ yield Button("Build", id="build-button", disabled=True)
137
+ yield BuildLog("", id="log-panel")
138
+ yield Footer()
139
+
140
+ def on_mount(self) -> None:
141
+ """Event fired when the app is mounted."""
142
+ # Populate the tree with ports and boards
143
+ tree = self.query_one(Tree)
144
+
145
+ # Create nodes for each port
146
+ for port_name, port in sorted(self.db.ports.items()):
147
+ port_node = tree.root.add(f"{port_name} ({len(port.boards)})", {"type": "port", "port": port})
148
+
149
+ # Add boards for this port
150
+ for board_name, board in sorted(port.boards.items()):
151
+ variant_text = ""
152
+ if board.variants:
153
+ variant_names = [v.name for v in board.variants]
154
+ variant_text = f" [{', '.join(variant_names)}]"
155
+ board_node = port_node.add(f"{board_name}{variant_text}", {"type": "board", "board": board})
156
+
157
+ tree.root.expand()
158
+
159
+ def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
160
+ """Event fired when a tree node is selected."""
161
+ node_data = event.node.data
162
+ if node_data and node_data.get("type") == "board":
163
+ self.selected_board = node_data["board"]
164
+ self.selected_variant = None
165
+ self.query_one(BoardDetails).update_board(self.selected_board)
166
+ self.query_one("#build-button").disabled = False
167
+ else:
168
+ self.selected_board = None
169
+ self.selected_variant = None
170
+ self.query_one(BoardDetails).update_board(None)
171
+ self.query_one("#build-button").disabled = True
172
+
173
+ @on(Button.Pressed, "#build-button")
174
+ def on_build_button(self) -> None:
175
+ """Event fired when the build button is pressed."""
176
+ if self.selected_board and not self.building:
177
+ self.action_build()
178
+
179
+ def action_build(self) -> None:
180
+ """Build the selected board."""
181
+ if not self.selected_board or self.building:
182
+ return
183
+
184
+ self.building = True
185
+ self.query_one("#build-button").disabled = True
186
+
187
+ # Clear the log and show build starting
188
+ log_widget = self.query_one(BuildLog)
189
+ log_widget.clear_log()
190
+ log_widget.add_log(f"Building {self.selected_board.name}...")
191
+
192
+ # Start the build process
193
+ self.start_build()
194
+
195
+ def start_build(self) -> None:
196
+ """Start the build process in the background."""
197
+ if not self.selected_board:
198
+ return
199
+
200
+ log_widget = self.query_one(BuildLog)
201
+
202
+ try:
203
+ build_cmd = docker_build_cmd(
204
+ board=self.selected_board,
205
+ variant=self.selected_variant.name if self.selected_variant else None,
206
+ extra_args=[],
207
+ do_clean=False,
208
+ docker_interactive=False,
209
+ )
210
+
211
+ log_widget.add_log(f"Running: {build_cmd}")
212
+
213
+ # Start the process and set up to capture output
214
+ self.set_interval(0.1, self.check_build_output)
215
+
216
+ # Start the build process and capture output
217
+ self.build_process = subprocess.Popen(
218
+ build_cmd,
219
+ shell=True,
220
+ stdout=subprocess.PIPE,
221
+ stderr=subprocess.STDOUT,
222
+ text=True,
223
+ bufsize=1,
224
+ )
225
+
226
+ except Exception as e:
227
+ log_widget.add_log(f"Error starting build: {e}")
228
+ self.building = False
229
+ self.query_one("#build-button").disabled = False
230
+
231
+ def check_build_output(self) -> None:
232
+ """Check for output from the build process."""
233
+ if not hasattr(self, "build_process"):
234
+ return
235
+
236
+ log_widget = self.query_one(BuildLog)
237
+
238
+ # Read any available output
239
+ if self.build_process.stdout:
240
+ for line in iter(self.build_process.stdout.readline, ""):
241
+ if not line:
242
+ break
243
+ log_widget.add_log(line.rstrip())
244
+
245
+ # Check if process has ended
246
+ if self.build_process.poll() is not None:
247
+ # Process has completed
248
+ returncode = self.build_process.returncode
249
+ log_widget.add_log(f"\nBuild finished with return code: {returncode}")
250
+
251
+ if returncode == 0:
252
+ log_widget.add_log("Build completed successfully!")
253
+ else:
254
+ log_widget.add_log("Build failed!")
255
+
256
+ # Clean up
257
+ self.building = False
258
+ self.query_one("#build-button").disabled = False
259
+
260
+ # Stop checking for output
261
+ self.clear_interval()
262
+
263
+ # Handle deployment instructions if build succeeded
264
+ if returncode == 0 and self.selected_board.deploy:
265
+ if self.selected_board.deploy_filename.is_file():
266
+ log_widget.add_log("\nDeployment instructions:")
267
+ log_widget.add_log(self.selected_board.deploy_filename.read_text())
268
+
269
+
270
+ def run_interactive(mpy_dir: Optional[Path] = None) -> None:
271
+ """Run the interactive TUI application."""
272
+ app = MpbuildApp(mpy_dir)
273
+ app.run()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes