-
Notifications
You must be signed in to change notification settings - Fork 981
/
cmake_easy_setup.py
executable file
·221 lines (188 loc) · 6.24 KB
/
cmake_easy_setup.py
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
#!/usr/bin/env python3
import argparse
import subprocess
import shutil
import tempfile
import os
from pathlib import Path
import json
from jinja2 import Environment, FileSystemLoader
import difflib
from parse_boards import parse_file
parser = argparse.ArgumentParser()
parser.add_argument(
"--cli",
"-x",
type=Path,
required=False,
default=shutil.which("arduino-cli"),
help="path to arduino-cli",
)
parser.add_argument("--board", "-b", type=str, default="", help="board name")
parser.add_argument(
"--fire",
action="store_true",
default=False,
help="launch the build immediately (use with caution!)",
)
output_args = parser.add_mutually_exclusive_group(required=True)
output_args.add_argument(
"--output", "-o", type=Path, help="output file (CMake) with placeholders"
)
output_args.add_argument(
"--sketch",
"-s",
type=Path,
help="output file (CMake) filled given a sketch folder",
)
shargs = parser.parse_args()
shargs.board = shargs.board.upper()
if shargs.sketch and not shargs.board:
print(
"""
Warning: you did not specify which board you were targeting;
please review the generated CMakeLists.txt to remove the placeholder
value before calling `cmake`.
"""
)
if shargs.cli is None:
print(
"""
Error: `arduino-cli` not found in $PATH.
Please install arduino-cli and make it available from your system $PATH,
or give its location through the `--cli` argument.
"""
)
exit(-1)
# Path management
scriptname = Path(__file__).resolve()
corepath = scriptname.parent.parent.parent.resolve()
boards_txt = corepath / "boards.txt"
userhome = Path.home()
def arduino(*args):
# return (out.stdout, logfile)
# raises an exception if the command fails
handle, logfile = tempfile.mkstemp()
os.close(handle)
out = subprocess.run(
(shargs.cli, "--log-file", logfile, "--log-format", "json", *args),
capture_output=True,
encoding="utf-8",
check=True,
).stdout
return (out, logfile)
def userhome_process(path):
lpath = str(path)
if path.is_relative_to(userhome):
lpath = f"~/{str(path.relative_to(userhome))}"
return lpath
def get_log(fname):
with open(fname) as file:
for line in file:
yield json.loads(line)
def get_boards():
# "reject" everything because we don't care about the values, only the keys
families = parse_file(boards_txt, lambda x: True)
del families["menu"]
boards = set()
for fam, famcfg in families.items():
boards.update(famcfg.menu.pnum.keys())
return boards
_, logf = arduino("lib", "list")
allboards = get_boards()
if shargs.board and shargs.board not in allboards:
print(f"Unrecognized board name: '{shargs.board}'")
print("Possible matches:")
options = difflib.get_close_matches(shargs.board, allboards, n=9, cutoff=0.0)
print("0. (keep as-is)")
for i, x in enumerate(options, start=1):
print(f"{i}. {x}")
choice = input("Choice number: ")
while not choice.isdecimal():
choice = input("Invalid choice *number*. Select a board: ")
choice = int(choice)
if choice != 0:
choice -= 1
shargs.board = options[choice]
libpaths = dict()
for line in get_log(logf):
if line["msg"] == "Adding libraries dir":
libpaths[line["location"]] = Path(line["dir"])
# platform lib path is already known, obviously, since that's where this script resides
if "user" in libpaths.keys():
userlibs = Path(libpaths["user"])
if userlibs.exists():
userlibs = userlibs.resolve()
libs = [u.name for u in userlibs.iterdir() if u.is_dir()]
else:
print(
f"""Warning: Cannot find {userlibs}.
This has likely to do with your arduino-cli configuration.
Please refer to the following link for setup details:
https://arduino.github.io/arduino-cli/latest/getting-started/#create-a-configuration-file
"""
)
libs = list()
else:
userlibs = Path.home() / "Arduino/libraries"
print(
f"""No user library path found through arduino-cli (falling back to {userlibs}).
This has likely to do with your arduino-cli configuration.
Please refer to the following link for setup details:
https://arduino.github.io/arduino-cli/latest/getting-started/#create-a-configuration-file
"""
)
libs = list()
j2_env = Environment(
loader=FileSystemLoader(str(corepath / "cmake" / "templates")),
trim_blocks=True,
lstrip_blocks=True,
)
cmake_template = j2_env.get_template("easy_cmake.cmake")
if shargs.sketch:
SOURCEFILE_EXTS = (".c", ".cpp", ".S", ".ino")
sources = {
file.relative_to(shargs.sketch)
for file in shargs.sketch.glob("*")
if file.is_file() and file.suffix in SOURCEFILE_EXTS
}
sources |= {
file.relative_to(shargs.sketch)
for file in shargs.sketch.rglob("src/*")
if file.is_file() and file.suffix in SOURCEFILE_EXTS
}
tgtname = shargs.sketch.resolve().name
else:
tgtname = ""
sources = set()
with open(shargs.output or shargs.sketch / "CMakeLists.txt", "w") as out:
out.write(
cmake_template.render(
corepath=userhome_process(corepath).replace(
"\\", "\\\\"
), # escape backslashes for CMake
userlibs=userhome_process(userlibs).replace("\\", "\\\\"),
libs=libs,
scriptfile=userhome_process(scriptname),
tgtname=tgtname,
scrcfiles=sources,
boardname=shargs.board,
)
)
print("Generated", shargs.output or shargs.sketch / "CMakeLists.txt")
print(
"""
Unless you are building a very simple sketch with no library (e.g., Blink),
you are advised to edit this file to fill in any missing dependency relationship.
For details, please refer to
https://github.com/stm32duino/Arduino_Core_STM32/wiki/Arduino-%28in%29compatibility#library-management
"""
)
if shargs.fire:
if not (shargs.sketch and shargs.board):
print(
"There remains some placeholder in the output file; I won't build _that_."
)
exit(1)
subprocess.run(("cmake", "-S", shargs.sketch, "-B", shargs.sketch / "build"))
subprocess.run(("cmake", "--build", shargs.sketch / "build"))