mpbuild 0.5__tar.gz → 0.6__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,8 +1,9 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: mpbuild
3
- Version: 0.5
3
+ Version: 0.6
4
4
  Summary: Build MicroPython firmware with ease!
5
5
  Author-email: Matt Trentini <matt.trentini@gmail.com>
6
+ License-File: LICENSE
6
7
  Requires-Python: >=3.9
7
8
  Requires-Dist: rich>=13.7.1
8
9
  Requires-Dist: typer>=0.12.3
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mpbuild"
3
- version = "0.5"
3
+ version = "0.6"
4
4
  description = "Build MicroPython firmware with ease!"
5
5
  authors = [
6
6
  { name = "Matt Trentini", email = "matt.trentini@gmail.com" }
@@ -40,6 +40,10 @@ from dataclasses import dataclass, field
40
40
  from glob import glob
41
41
 
42
42
 
43
+ class MpbuildMpyDirectoryException(Exception):
44
+ pass
45
+
46
+
43
47
  @dataclass(order=True)
44
48
  class Variant:
45
49
  name: str
@@ -91,10 +95,15 @@ class Board:
91
95
  Files that explain how to deploy for this board:
92
96
  Example: ["../PYBV10/deploy.md"]
93
97
  """
94
- port: Port | None= field(default=None, compare=False)
98
+ physical_board: bool
99
+ """
100
+ physical_board is False for 'special' builds, namely unix, webassembly, windows.
101
+ True for all regular boards.
102
+ """
103
+ port: Port = field(compare=False)
95
104
 
96
105
  @staticmethod
97
- def factory(filename_json: Path) -> Board:
106
+ def factory(port: Port, filename_json: Path) -> Board:
98
107
  with filename_json.open() as f:
99
108
  board_json = json.load(f)
100
109
 
@@ -107,12 +116,52 @@ class Board:
107
116
  vendor=board_json["vendor"],
108
117
  images=board_json["images"],
109
118
  deploy=board_json["deploy"],
119
+ physical_board=True,
120
+ port=port,
110
121
  )
111
122
  board.variants.extend(
112
- sorted([Variant(*v, board) for v in board_json.get("variants", {}).items()])
123
+ sorted(
124
+ [
125
+ Variant(*v, board=board)
126
+ for v in board_json.get("variants", {}).items()
127
+ ]
128
+ )
113
129
  )
114
130
  return board
115
131
 
132
+ @property
133
+ def directory(self) -> Path:
134
+ """
135
+ Example: ports/stm32/boards/PYBV11
136
+ """
137
+ if self.physical_board:
138
+ directory_ = self.port.directory / "boards" / self.name
139
+ else:
140
+ directory_ = self.port.directory
141
+ if not directory_.is_dir():
142
+ raise ValueError(f"Directory does not exist: {directory_}")
143
+ return directory_
144
+
145
+ @property
146
+ def deploy_filename(self) -> Path:
147
+ """
148
+ Returns the filename of the deploy-markdown.
149
+ """
150
+ return self.directory / self.deploy[0]
151
+
152
+ # TODO(mst): Update Variant to allow comparisons to strings. This method can
153
+ # then be removed.
154
+ # ie add Variant.__eq__(self, other) where other can be a string.
155
+ def find_variant(self, variant: str) -> Variant | None:
156
+ """
157
+ Returns the variant, None if not found.
158
+ """
159
+ for v in self.variants:
160
+ if v.name == variant:
161
+ return v
162
+
163
+ return None
164
+
116
165
 
117
166
  @dataclass(order=True)
118
167
  class Port:
@@ -120,11 +169,25 @@ class Port:
120
169
  """
121
170
  Example: "stm32"
122
171
  """
172
+ directory: Path
173
+ """
174
+ The directory of the port source code.
175
+ Example: "ports/stm32"
176
+ """
123
177
  boards: dict[str, Board] = field(default_factory=dict, repr=False)
124
178
  """
125
179
  Example key: "PYBV11"
126
180
  """
127
181
 
182
+ @property
183
+ def directory_repo(self) -> Path:
184
+ """
185
+ The top directory of the MicroPython repo
186
+ """
187
+ repo = self.directory.parent.parent
188
+ Database.assert_mpy_root_direcory(repo)
189
+ return repo
190
+
128
191
 
129
192
  @dataclass
130
193
  class Database:
@@ -139,23 +202,27 @@ class Database:
139
202
  boards: dict[str, Board] = field(default_factory=dict)
140
203
 
141
204
  def __post_init__(self) -> None:
142
- mpy_dir = self.mpy_root_directory
205
+ if not (self.mpy_root_directory / "ports").is_dir():
206
+ raise ValueError(
207
+ f"'mpy_root_directory' should point to the top of a MicroPython repo: {self.mpy_root_directory}"
208
+ )
209
+
143
210
  # Take care to avoid using Path.glob! Performance was 15x slower.
144
- for p in glob(f"{mpy_dir}/ports/**/boards/**/board.json"):
211
+ for p in glob(f"{self.mpy_root_directory}/ports/*/boards/*/board.json"):
145
212
  filename_json = Path(p)
146
- port_name = filename_json.parent.parent.parent.name
213
+ port_directory = filename_json.parent.parent.parent
214
+ port_name = port_directory.name
147
215
  if self.port_filter and self.port_filter != port_name:
148
216
  continue
149
217
 
150
218
  # Create a port
151
219
  port = self.ports.get(port_name, None)
152
220
  if port is None:
153
- port = Port(port_name)
221
+ port = Port(name=port_name, directory=port_directory)
154
222
  self.ports[port_name] = port
155
223
 
156
224
  # Load board.json and attach it to the board
157
- board = Board.factory(filename_json)
158
- board.port = port
225
+ board = Board.factory(port=port, filename_json=filename_json)
159
226
 
160
227
  port.boards[board.name] = board
161
228
  self.boards[board.name] = board
@@ -165,23 +232,40 @@ class Database:
165
232
  for special_port_name in ["unix", "webassembly", "windows"]:
166
233
  if self.port_filter and self.port_filter != special_port_name:
167
234
  continue
168
- path = Path(mpy_dir, "ports", special_port_name)
235
+ path = self.mpy_root_directory / "ports" / special_port_name
169
236
  variant_names = [
170
237
  var.name for var in path.glob("variants/*") if var.is_dir()
171
238
  ]
239
+ port = Port(
240
+ name=special_port_name,
241
+ directory=path,
242
+ boards={special_port_name: board},
243
+ )
172
244
  board = Board(
173
- special_port_name,
174
- [],
175
- f"https://github.com/micropython/micropython/blob/master/ports/{special_port_name}/README.md",
176
- "",
177
- "",
178
- "",
179
- [],
180
- [],
245
+ name=special_port_name,
246
+ variants=[],
247
+ url=f"https://github.com/micropython/micropython/blob/master/ports/{special_port_name}/README.md",
248
+ mcu="",
249
+ product="",
250
+ vendor="",
251
+ images=[],
252
+ deploy=[],
253
+ physical_board=False,
254
+ port=port,
181
255
  )
182
- board.variants = [Variant(v, "", board) for v in variant_names]
183
- port = Port(special_port_name, {special_port_name: board})
184
- board.port = port
256
+ board.variants = [
257
+ Variant(name=v, text="", board=board) for v in variant_names
258
+ ]
185
259
 
186
260
  self.ports[special_port_name] = port
187
261
  self.boards[board.name] = board
262
+
263
+ @staticmethod
264
+ def assert_mpy_root_direcory(directory: Path) -> None:
265
+ """
266
+ raises ValueError if 'directory' does not point to a micropyhon repo.
267
+ """
268
+ if not (directory / "ports").is_dir():
269
+ raise MpbuildMpyDirectoryException(
270
+ f"Directory does not point to the top of a micropython repo: {directory}"
271
+ )
@@ -10,6 +10,7 @@ from rich.panel import Panel
10
10
  from rich.markdown import Markdown
11
11
 
12
12
  from . import board_database, find_mpy_root
13
+ from .board_database import Board
13
14
 
14
15
  ARM_BUILD_CONTAINER = "micropython/build-micropython-arm"
15
16
  BUILD_CONTAINERS = {
@@ -20,68 +21,90 @@ BUILD_CONTAINERS = {
20
21
  "renesas-ra": ARM_BUILD_CONTAINER,
21
22
  "samd": ARM_BUILD_CONTAINER,
22
23
  "esp32": "espressif/idf",
24
+ "esp8266": "larsks/esp-open-sdk",
23
25
  "unix": "gcc:12-bookworm", # Special, doesn't have boards
24
26
  }
25
27
 
26
- IDF_DEFAULT = "v5.2.2"
27
28
 
28
- nprocs = multiprocessing.cpu_count()
29
+ class MpbuildNotSupportedException(Exception):
30
+ pass
29
31
 
30
32
 
31
- def build_board(
32
- board: str,
33
- variant: Optional[str] = None,
34
- extra_args: List[str] = [],
35
- build_container_override: Optional[str] = None,
36
- idf: Optional[str] = IDF_DEFAULT,
37
- mpy_dir: str|Path|None = None,
38
- ) -> None:
39
- # mpy_dir = mpy_dir or Path.cwd()
40
- # mpy_dir = Path(mpy_dir)
41
- mpy_dir, _ = find_mpy_root(mpy_dir)
42
- db = board_database(mpy_dir)
33
+ def get_build_container(board: Board, variant: Optional[str] = None) -> str:
34
+ """
35
+ Returns the container to be used for this board/variant.
43
36
 
44
- if board not in db.boards.keys():
45
- print("Invalid board")
46
- raise SystemExit()
37
+ Example: board="RPI_PICO" => "micropython/build-micropython-arm"
38
+ Example: board="RPI_PICO", variant="RISCV" => "micropython/build-micropython-rp2350riscv"
39
+ """
40
+ port = board.port
47
41
 
48
- _board = db.boards[board]
49
- port = _board.port.name
42
+ if board.name == "RPI_PICO2":
43
+ if variant == "RISCV":
44
+ # Special case: This board supports an ARM core as default
45
+ # and a RISC-V core as a variant
46
+ return "micropython/build-micropython-rp2350riscv"
50
47
 
51
- if variant and variant not in [v.name for v in _board.variants]:
52
- print("Invalid variant")
53
- raise SystemExit()
48
+ # RP2 requires a recent version of gcc
49
+ return "micropython/build-micropython-arm:bookworm"
54
50
 
55
- if port not in BUILD_CONTAINERS.keys():
56
- print(f"Sorry, builds are not supported for the {port} port at this time")
57
- raise SystemExit()
51
+ try:
52
+ return BUILD_CONTAINERS[port.name]
53
+ except KeyError as e:
54
+ raise MpbuildNotSupportedException(f"{board.name}-{variant}") from e
58
55
 
59
- if port != "esp32" and idf != IDF_DEFAULT:
60
- print("An IDF version can only be specified for ESP32 builds")
61
- raise SystemExit()
56
+
57
+ IDF_DEFAULT = "v5.2.2"
58
+
59
+ nprocs = multiprocessing.cpu_count()
60
+
61
+
62
+ def docker_build_cmd(
63
+ board: Board,
64
+ variant: Optional[str] = None,
65
+ extra_args: List[str] = [],
66
+ do_clean: bool = False,
67
+ build_container_override: str | None = None,
68
+ idf: str = IDF_DEFAULT,
69
+ docker_interactive: bool = True,
70
+ ) -> str:
71
+ """
72
+ Returns the docker-command which will build the firmware.
73
+ """
74
+
75
+ port = board.port
76
+
77
+ if variant:
78
+ v = board.find_variant(variant)
79
+ if not v:
80
+ raise ValueError(
81
+ f"Variant '{variant}' not found for board '{board.name}': Valid variants are: {[v.name for v in board.variants]}"
82
+ )
62
83
 
63
84
  build_container = (
64
- build_container_override if build_container_override else BUILD_CONTAINERS[port]
85
+ build_container_override
86
+ if build_container_override
87
+ else get_build_container(board=board, variant=variant)
65
88
  )
66
89
 
67
- if port == "esp32" and not build_container_override:
90
+ if port.name == "esp32" and not build_container_override:
68
91
  if not idf:
69
92
  idf = IDF_DEFAULT
70
93
  build_container += f":{idf}"
71
94
 
72
- variant_param = "VARIANT" if board == port else "BOARD_VARIANT"
73
- variant_cmd = f" {variant_param}={variant}" if variant else ""
95
+ variant_param = "BOARD_VARIANT" if board.physical_board else "VARIANT"
96
+ variant_cmd = "" if variant is None else f" {variant_param}={variant}"
74
97
 
75
98
  args = " " + " ".join(extra_args)
76
99
 
77
100
  make_mpy_cross_cmd = "make -C mpy-cross && "
78
101
  update_submodules_cmd = (
79
- f"make -C ports/{port} submodules BOARD={board}{variant_cmd} && "
102
+ f"make -C ports/{port.name} submodules BOARD={board.name}{variant_cmd} && "
80
103
  )
81
104
 
82
105
  uid, gid = os.getuid(), os.getgid()
83
106
 
84
- if extra_args and extra_args[0].strip() == "clean":
107
+ if do_clean:
85
108
  # When cleaning we run with full privs
86
109
  uid, gid = 0, 0
87
110
  # Don't need to build mpy_cross or update submodules
@@ -89,11 +112,12 @@ def build_board(
89
112
  update_submodules_cmd = ""
90
113
 
91
114
  home = os.environ["HOME"]
92
- mpy_dir = db.mpy_root_directory
115
+ mpy_dir = str(port.directory_repo)
93
116
 
94
117
  # fmt: off
95
118
  build_cmd = (
96
- f"docker run -it --rm "
119
+ f"docker run --rm "
120
+ f"{'-it ' if docker_interactive else ''}"
97
121
  f"-v /sys/bus:/sys/bus " # provides access to USB for deploy
98
122
  f"-v /dev:/dev " # provides access to USB for deploy
99
123
  f"--net=host --privileged " # provides access to USB for deploy
@@ -105,39 +129,81 @@ def build_board(
105
129
  f"git config --global --add safe.directory '*' 2> /dev/null;"
106
130
  f'{make_mpy_cross_cmd}'
107
131
  f'{update_submodules_cmd}'
108
- f'make -j {nprocs} -C ports/{port} BOARD={board}{variant_cmd}{args}"'
132
+ f'make -j {nprocs} -C ports/{port.name} BOARD={board.name}{variant_cmd}{args}"'
109
133
  )
110
134
  # fmt: on
111
135
 
112
- title = "Build" if "clean" not in extra_args else "Clean"
136
+ return build_cmd
137
+
138
+
139
+ def build_board(
140
+ board: str,
141
+ variant: Optional[str] = None,
142
+ extra_args: List[str] = [],
143
+ build_container_override: Optional[str] = None,
144
+ idf: Optional[str] = IDF_DEFAULT,
145
+ mpy_dir: str | Path | None = None,
146
+ ) -> None:
147
+ """
148
+ Build the firmware.
149
+
150
+ This command writes to stdout/stderr and may exit the program on failure.
151
+ """
152
+ mpy_dir, _ = find_mpy_root(mpy_dir)
153
+ db = board_database(mpy_dir)
154
+ mpy_dir = db.mpy_root_directory
155
+
156
+ if board not in db.boards.keys():
157
+ print("Invalid board")
158
+ raise SystemExit()
159
+
160
+ _board = db.boards[board]
161
+ port = _board.port.name
162
+
163
+ if variant is not None:
164
+ _variant = _board.find_variant(variant)
165
+ if _variant is None:
166
+ print(f"Invalid variant '{variant}'")
167
+ raise SystemExit()
168
+
169
+ if port not in BUILD_CONTAINERS.keys():
170
+ print(f"Sorry, builds are not supported for the {port} port at this time")
171
+ raise SystemExit()
172
+
173
+ if port != "esp32" and idf != IDF_DEFAULT:
174
+ print("An IDF version can only be specified for ESP32 builds")
175
+ raise SystemExit()
176
+
177
+ do_clean = bool(extra_args and extra_args[0].strip() == "clean")
178
+ build_cmd = docker_build_cmd(
179
+ board=_board,
180
+ variant=variant,
181
+ extra_args=extra_args,
182
+ do_clean=do_clean,
183
+ build_container_override=build_container_override,
184
+ idf=idf,
185
+ )
186
+
187
+ title = "Build" if do_clean else "Clean"
113
188
  title += f" {port}/{board}" + (f" ({variant})" if variant else "")
114
189
  print(Panel(build_cmd, title=title, title_align="left", padding=1))
115
190
 
116
- subprocess.run(build_cmd, shell=True)
191
+ proc = subprocess.run(build_cmd, shell=True, check=False)
117
192
 
118
- # Display deployment markdown
193
+ if proc.returncode != 0:
194
+ print(f"ERROR: The following command returned {proc.returncode}: {build_cmd}")
195
+ raise SystemExit(proc.returncode)
196
+
197
+ # Display deployment markdown for successful builds
119
198
  # Note: Only displaying the first deploy file.
120
199
  # Q: Are there cases where there's >1? A: Currently, no.
121
200
  # >>> sum([len(b.deploy) for b in db.boards.values()])
122
201
  # 166
123
202
  # >>> len(db.boards())
124
203
  # 169 # 3x boards are the 'special' boards without deployment instructions.
125
- if _board.deploy and "clean" not in extra_args:
126
- deploy_filename = Path(
127
- "/".join(
128
- [
129
- str(mpy_dir),
130
- "ports",
131
- _board.port.name,
132
- "boards",
133
- _board.name,
134
- _board.deploy[0],
135
- ]
136
- )
137
- )
138
- if deploy_filename.is_file():
139
- with open(deploy_filename) as deployfile:
140
- print(Panel(Markdown(deployfile.read())))
204
+ if _board.deploy and "clean" not in extra_args and proc.returncode == 0:
205
+ if _board.deploy_filename.is_file():
206
+ print(Panel(Markdown(_board.deploy_filename.read_text())))
141
207
 
142
208
 
143
209
  def clean_board(
@@ -4,13 +4,13 @@ from functools import cache
4
4
 
5
5
 
6
6
  @cache
7
- def find_mpy_root(root: str| Path | None = None):
7
+ def find_mpy_root(root: str| Path | None = None) -> tuple[Path, str]:
8
8
  if root is None:
9
9
  root = Path(os.environ.get("MICROPY_DIR", ".")).resolve()
10
10
  else:
11
11
  root = Path(root)
12
12
 
13
- port = None
13
+ port = ""
14
14
  while True:
15
15
  # If run from a port folder, store that for use in filters
16
16
  if root.parent.name == "ports":
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
File without changes