Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
271 lines (241 loc) · 11 KB
/
Copy pathbuild.py
File metadata and controls
271 lines (241 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/usr/bin/env python3
#
# Copyright (c) 2026 Chengdong Wang <wangcd91@gmail.com>
#
# Build and run the given board (replacement for the former
# run_qemu.sh and run_qemu.py; works on Linux, Windows and macOS
# hosts).
#
# The build lives in build/<board with / -> _>, or build/<app> when
# --app selects an application sample as the build entry. Three
# actions can be selected individually or combined:
#
# --full full rebuild: wipe the build directory first, then
# configure and build from scratch
# --build incremental build: (re)configure and build without
# wiping, so only changed inputs rebuild
# --run run the image: boot it under QEMU (qemu/ boards and
# the raspi4b smoke target) or flash it on the hardware
# board via OpenOCD (everything else)
#
# With no options the image is just built (--build); pass --run to
# boot/flash it.
#
# Usage:
# python3 build.py [--full] [--build] [--run]
# [--module <dir> [<dir> ...]]
# [--app <name>] [--ext <dir>] <board>
#
# --module selects what to build on top of the board: a module
# directory (e.g. a sample, whose prj.conf is merged over the board
# defconfig) or a .config fragment file -- see the MODULES
# documentation in cmake/modules.cmake. One --module takes several
# values (space or comma separated), and --module may repeat; later
# entries win. A bare board name ends the list (and becomes the
# board). "--module ''" clears modules cached from an earlier
# configure.
#
# --app <name> makes the application sample samples/application/
# <name> the build entry (cmake -S ...): the sample owns the image
# through its main() override, and the build lands in build/<name>.
# At most one application sample may be linked -- never combine
# --app with an application sample in --module. Third-party-
# dependent apps (bleprph) need --ext too.
#
# --ext <dir> passes -DEAS_EXTERNAL_ROOT=<dir>: the external content
# root holding manifest.yaml plus the third-party checkouts and app
# directories eastra integrates (see cmake/external.cmake).
#
# Exit code: 0 on success, 1 on failure (unknown board, build error,
# QEMU/flash exited non-zero).
import argparse
import re
import shutil
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent
# Action options; they may be combined and default to build.
OPTIONS = ("--full", "--build", "--run")
# Shorthand aliases (without the qemu/ prefix).
BOARD_ALIASES = {
"--qemu_arm64": "qemu/arm64",
"--qemu_stm32": "qemu/b-l475",
"--qemu_rv32": "qemu/riscv32",
"--qemu_rv64": "qemu/riscv64",
"--qemu_pi4b": "qemu/raspi4b",
"--raspi4b": "raspi4b",
"--stm32": "stm32f407zg-explorer",
}
# Boards listed in the help text (order matters).
USAGE_BOARDS = [
("qemu/arm64", "QEMU virt ARM64 (aarch64)"),
("qemu/b-l475", "QEMU b-l475e-iot01a (STM32L4x5, Cortex-M4)"),
("qemu/riscv32", "QEMU virt RISC-V 32-bit"),
("qemu/riscv64", "QEMU virt RISC-V 64-bit"),
("qemu/raspi4b", "QEMU raspi4b (BCM2711, Cortex-A72)"),
("raspi4b", "Raspberry Pi 4B (real hardware, QEMU smoke test)"),
("stm32f407zg-explorer", "STM32F407ZG-Explorer (Cortex-M4)"),
("nrf5340dk", "Nordic nRF5340 DK, app core (Cortex-M33)"),
]
# Known board names: they end a --module value list and count as
# the board token.
KNOWN_BOARDS = {name for name, _ in USAGE_BOARDS}
# Boards outside qemu/: any qemu/* name passes this script's check
# (cmake validates it further), everything else must be listed.
NON_QEMU_BOARDS = {name for name, _ in USAGE_BOARDS
if not name.startswith("qemu/")}
def boards_epilog():
lines = ["boards:"]
lines += [f" {name:<19} {desc}" for name, desc in USAGE_BOARDS]
lines.append("")
lines.append("shorthand aliases (without the qemu/ prefix):")
lines += [f" {alias:<19} {board}" for alias, board in BOARD_ALIASES.items()]
return "\n".join(lines)
def build_parser():
p = argparse.ArgumentParser(
prog="build.py",
description="Build the given board "
"(QEMU boot or hardware flash needs --run).",
epilog=boards_epilog(),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
act = p.add_argument_group("actions (combine freely; default: --build)")
act.add_argument("--full", action="store_true",
help="full rebuild: wipe the build directory first")
act.add_argument("--build", action="store_true",
help="incremental build (configure is idempotent)")
act.add_argument("--run", action="store_true",
help="flash & run on hardware / boot under QEMU")
p.add_argument("--app", metavar="<name>",
help="make samples/application/<name> the build entry "
"(cmake -S): the app owns the image through its "
"main() override, the build lands in build/<name>. "
"A path works too. bleprph needs --ext")
p.add_argument("--ext", metavar="<dir>",
help="external content root for -DEAS_EXTERNAL_ROOT: "
"manifest.yaml + third-party checkouts + apps "
"(see cmake/external.cmake)")
p.add_argument("--module", metavar="<dir>", nargs="+", action="append",
help="module(s) to build on top: sample directories "
"(their prj.conf merges over the board defconfig) "
"or .config fragment files; separate with spaces "
"or commas, repeat --module freely (later ones "
"win, '' clears cached ones)")
# Board shorthands as flag options; the bare name works too.
for alias, board in BOARD_ALIASES.items():
p.add_argument(alias, dest="board_alias", action="store_const",
const=board, help=f"shorthand for {board}")
p.add_argument("board", nargs="?", metavar="board",
help="board to build (see the list below)")
return p
def split_board_from_modules(values):
"""The historical CLI lets a bare board name end a --module
list and become the board. Return (modules, board, leftovers):
the values before the first board name, the board itself (None
if absent), and everything after it (which the old parser
rejected as extra arguments)."""
for idx, v in enumerate(values):
if v in KNOWN_BOARDS:
return values[:idx], v, values[idx + 1:]
return values, None, []
def run(cmd):
print(f"$ {' '.join(str(c) for c in cmd)}")
subprocess.run([str(c) for c in cmd], cwd=REPO_ROOT, check=True)
def main():
parser = build_parser()
ns = parser.parse_args()
def fail(msg):
# Keep the historical exit code (1) for post-parse errors.
parser.exit(1, f"build.py: {msg}\n"
"Run 'build.py --help' for usage.\n")
# --module: flatten the repeated groups, keep the comma form,
# apply the '' clears, and lift a trailing bare board name out.
flat = [v for group in (ns.module or []) for v in group]
raw, board_from_modules, leftovers = split_board_from_modules(flat)
if leftovers:
fail(f"unexpected arguments after '{board_from_modules}': "
f"{' '.join(leftovers)}")
modules = []
for v in raw:
if v == "":
modules.clear()
else:
modules.extend(p for p in re.split("[,;]", v) if p)
# The board may arrive as the positional, as a --shorthand flag,
# or as the bare name ending a --module list -- exactly one.
candidates = [c for c in (ns.board, ns.board_alias, board_from_modules)
if c is not None]
if len(candidates) > 1:
fail(f"multiple boards given: {' '.join(candidates)}")
if not candidates:
fail("no board given")
board = candidates[0]
if not (board.startswith("qemu/") or board in NON_QEMU_BOARDS):
fail(f"unknown board '{board}'")
opts = [o for o in OPTIONS if getattr(ns, o[2:])]
if not opts:
opts = ["--build"]
# The build entry: --app names an application sample, and the
# build tree moves to build/<app>. A value that exists as a
# path (absolute or relative to the caller's cwd) is used
# as-is; anything else is a bare name resolved against
# samples/application/. Without --app the platform checkout
# itself is the entry (no -S), build tree build/<board>.
app_dir = None
if ns.app is not None:
app_dir = Path(ns.app)
if (not app_dir.is_absolute()
and not (app_dir / "CMakeLists.txt").exists()):
app_dir = REPO_ROOT / "samples" / "application" / ns.app
app_dir = app_dir.resolve()
if not (app_dir / "CMakeLists.txt").exists():
fail(f"no application entry at {app_dir} "
f"(expected samples/application/<name> or a path)")
build_dir = REPO_ROOT / "build" / app_dir.name
else:
build_dir = REPO_ROOT / "build" / board.replace("/", "_")
if "--full" in opts or "--build" in opts:
if "--full" in opts:
shutil.rmtree(build_dir, ignore_errors=True)
if app_dir is not None:
cmd = ["cmake", "-S", app_dir, "-B", build_dir,
f"-DBOARD={board}", "-GNinja"]
# An entry outside this checkout has no relative path to
# the platform: hand find_package(Eas) the hint directly.
if not app_dir.is_relative_to(REPO_ROOT):
cmd.append(f"-DEAS_BASE={REPO_ROOT}")
else:
cmd = ["cmake", "-B", build_dir, f"-DBOARD={board}", "-GNinja"]
if ns.ext:
# Absolute so the value does not depend on the caller's cwd.
# A manifest file selects -DMANIFEST (its directory is
# the external content root); a directory -DEAS_EXTERNAL_ROOT.
ext = str(Path(ns.ext).resolve())
if ext.endswith((".yaml", ".yml")):
cmd.append(f"-DMANIFEST={ext}")
else:
cmd.append(f"-DEAS_EXTERNAL_ROOT={ext}")
if modules:
# Absolute paths (against this repo) so the value does not
# depend on the caller's cwd; "" entries clear fragments
# cached in the build tree.
modules = [str((REPO_ROOT / c).resolve()) if c else ""
for c in modules]
cmd.append(f"-DMODULES={';'.join(modules)}")
run(cmd)
run(["cmake", "--build", build_dir])
if "--run" in opts:
if not (build_dir / "build.ninja").exists():
fail(f"{build_dir} is not configured; "
"run with --build (or --full) first")
if board.startswith("qemu/") or board == "raspi4b":
run(["cmake", "--build", build_dir, "--target", "qemu"])
else:
run(["cmake", "--build", build_dir, "--target", "flash"])
if __name__ == "__main__":
try:
main()
except subprocess.CalledProcessError as e:
cmd = " ".join(str(c) for c in e.cmd)
sys.exit(f"build.py: command failed ({e.returncode}): {cmd}")