Skip to content

Commit 5dde67e

Browse files
authored
Merge pull request #922 from ianmcorvidae/nanopb-options-inject
Inject options in nanopb .options files into the protobuf files used for code generation
2 parents fddaad3 + a7d13eb commit 5dde67e

23 files changed

Lines changed: 1944 additions & 458 deletions

bin/inject_nanopb_options.py

Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
#!/usr/bin/env python3
2+
"""Inject nanopb .options constraints as inline field options into a .proto file.
3+
4+
The nanopb .options file format is specific to the nanopb C generator and is
5+
ignored by standard protoc (including --python_out). By injecting the options
6+
directly into the proto file's field declarations, protoc will embed them in
7+
the serialized descriptor, making them accessible in Python via:
8+
9+
from meshtastic.protobuf import mesh_pb2, nanopb_pb2
10+
field = mesh_pb2.DESCRIPTOR.message_types_by_name['User'].fields_by_name['long_name']
11+
opts = field.GetOptions().Extensions[nanopb_pb2.nanopb]
12+
print(opts.max_size) # 40
13+
14+
Usage:
15+
inject_nanopb_options.py <options_file> <proto_file>
16+
17+
The proto_file is modified in-place. Intended to operate on temporary copies
18+
generated by regen-protobufs.sh, not the source .proto files.
19+
"""
20+
21+
import re
22+
import sys
23+
from pathlib import Path
24+
from typing import Any, Dict, List, Tuple
25+
26+
# IntSize enum values from nanopb.proto
27+
INT_SIZE_ENUM = {8: "IS_8", 16: "IS_16", 32: "IS_32", 64: "IS_64"}
28+
29+
# Options that are valid proto FieldOptions and useful outside of C code generation.
30+
# We skip C-only options (anonymous_oneof, no_unions, skip_message, packed_struct,
31+
# packed_enum, mangle_names, callback_datatype, callback_function, descriptorsize,
32+
# type_override) since they either don't apply to proto fields or are C-specific.
33+
FIELD_OPTIONS = frozenset(
34+
{
35+
"max_size",
36+
"max_length",
37+
"max_count",
38+
"int_size",
39+
"fixed_length",
40+
"fixed_count",
41+
"long_names",
42+
"proto3",
43+
"default_has",
44+
"sort_by_tag",
45+
"msgid",
46+
}
47+
)
48+
49+
50+
def parse_value(s: str) -> Any:
51+
"""Convert an option value string to an appropriate Python type."""
52+
if re.fullmatch(r"-?[0-9]+", s):
53+
return int(s)
54+
if s.lower() == "true":
55+
return True
56+
if s.lower() == "false":
57+
return False
58+
return s
59+
60+
61+
def parse_options_file(
62+
path: Path,
63+
) -> Tuple[Dict[Tuple[str, ...], Dict[str, Any]], Dict[str, Dict[str, Any]]]:
64+
"""Parse a nanopb .options file.
65+
66+
Returns:
67+
specific: maps (message_path..., field_name) -> {option: value}
68+
e.g. ('User', 'long_name') or ('Route', 'Link', 'uid')
69+
wildcard: maps field_name -> {option: value}
70+
applies to any field with this name in the same proto file
71+
"""
72+
specific: Dict[Tuple[str, ...], Dict[str, Any]] = {}
73+
wildcard: Dict[str, Dict[str, Any]] = {}
74+
75+
with open(path, encoding="utf-8") as f:
76+
for line in f:
77+
# Strip inline comments
78+
comment_pos = line.find("#")
79+
if comment_pos >= 0:
80+
line = line[:comment_pos]
81+
line = line.strip().lstrip("*").strip()
82+
if not line:
83+
continue
84+
85+
tokens = line.split()
86+
if len(tokens) < 2:
87+
continue
88+
89+
pattern = tokens[0]
90+
opts: Dict[str, Any] = {}
91+
for tok in tokens[1:]:
92+
if ":" in tok:
93+
k, v = tok.split(":", 1)
94+
if k in FIELD_OPTIONS:
95+
opts[k] = parse_value(v)
96+
97+
if not opts:
98+
continue
99+
100+
if "." in pattern:
101+
# e.g. "User.long_name" -> key=('User', 'long_name')
102+
# or "Route.Link.uid" -> key=('Route', 'Link', 'uid')
103+
parts = tuple(pattern.split("."))
104+
if parts in specific:
105+
specific[parts].update(opts)
106+
else:
107+
specific[parts] = opts
108+
else:
109+
# wildcard: applies to any field with this name
110+
if pattern in wildcard:
111+
wildcard[pattern].update(opts)
112+
else:
113+
wildcard[pattern] = opts
114+
115+
return specific, wildcard
116+
117+
118+
def format_nanopb_opts(opts: Dict[str, Any]) -> str:
119+
"""Format a dict of nanopb options as a proto field options annotation string."""
120+
parts = []
121+
for k, v in opts.items():
122+
if k == "int_size":
123+
enum_val = INT_SIZE_ENUM.get(v, f"IS_{v}")
124+
parts.append(f"(nanopb).int_size = {enum_val}")
125+
elif isinstance(v, bool):
126+
parts.append(f"(nanopb).{k} = {'true' if v else 'false'}")
127+
else:
128+
parts.append(f"(nanopb).{k} = {v}")
129+
return ", ".join(parts)
130+
131+
132+
def message_path_matches(
133+
context_stack: List[Tuple[str, str]], msg_path: Tuple[str, ...]
134+
) -> bool:
135+
"""Check if the current message context ends with msg_path.
136+
137+
context_stack entries are ('message'|'oneof'|'enum', name).
138+
msg_path is the tuple of message names from the options pattern,
139+
e.g. ('User',) or ('Route', 'Link').
140+
"""
141+
msg_names = [name for kind, name in context_stack if kind == "message"]
142+
n = len(msg_path)
143+
return len(msg_names) >= n and tuple(msg_names[-n:]) == msg_path
144+
145+
146+
def inject_into_proto(
147+
content: str,
148+
specific: Dict[Tuple[str, ...], Dict[str, Any]],
149+
wildcard: Dict[str, Dict[str, Any]],
150+
nanopb_import_path: str,
151+
) -> str:
152+
"""Inject nanopb field options into a proto file's text content.
153+
154+
Adds an import for nanopb.proto if not already present.
155+
Returns the modified content.
156+
"""
157+
if not specific and not wildcard:
158+
return content
159+
160+
lines = content.split("\n")
161+
162+
# Check if nanopb is already imported (after sed fixup, it will be
163+
# 'meshtastic/protobuf/nanopb.proto')
164+
nanopb_already_imported = any(
165+
"nanopb.proto" in line
166+
for line in lines
167+
if line.strip().startswith("import")
168+
)
169+
170+
# Track the index of the last import line so we can insert after it
171+
last_import_idx = max(
172+
(
173+
i
174+
for i, line in enumerate(lines)
175+
if line.strip().startswith("import ") and line.strip().endswith(";")
176+
),
177+
default=-1,
178+
)
179+
180+
# State
181+
context_stack: List[Tuple[str, str]] = [] # ('message'|'oneof'|'enum', name)
182+
result: List[str] = []
183+
import_added = nanopb_already_imported
184+
185+
# Patterns for proto structural elements
186+
message_re = re.compile(r"^(\s*)message\s+(\w+)\s*\{")
187+
oneof_re = re.compile(r"^(\s*)oneof\s+(\w+)\s*\{")
188+
enum_re = re.compile(r"^(\s*)enum\s+(\w+)\s*\{")
189+
close_re = re.compile(r"^\s*\}")
190+
191+
# Pattern for field declarations:
192+
# indent [optional|repeated] type name = number [options] ;
193+
# We exclude map<> fields (different syntax, nanopb handles them differently)
194+
# and enum value lines (no type keyword before the name).
195+
field_re = re.compile(
196+
r"^(\s*)" # (1) indent
197+
r"(optional\s+|repeated\s+)?" # (2) optional qualifier
198+
r"([\w.]+)\s+" # (3) field type (possibly qualified like google.protobuf.Any)
199+
r"(\w+)\s*" # (4) field name
200+
r"=\s*(\d+)" # (5) field number
201+
r"(?:\s*\[([^\]]*)\])?" # (6) existing options, without brackets
202+
r"\s*;" # trailing semicolon
203+
)
204+
205+
for i, line in enumerate(lines):
206+
# Insert nanopb import right after the last existing import line.
207+
# Only do this when there IS an existing import (last_import_idx >= 0);
208+
# if there are no imports we fall through to the syntax-line fallback below.
209+
if not import_added and last_import_idx >= 0 and i == last_import_idx + 1:
210+
result.append(f'import "{nanopb_import_path}";')
211+
import_added = True
212+
213+
# --- Track message/oneof/enum nesting ---
214+
m = message_re.match(line)
215+
if m:
216+
context_stack.append(("message", m.group(2)))
217+
result.append(line)
218+
continue
219+
220+
m = oneof_re.match(line)
221+
if m:
222+
context_stack.append(("oneof", m.group(2)))
223+
result.append(line)
224+
continue
225+
226+
m = enum_re.match(line)
227+
if m:
228+
context_stack.append(("enum", m.group(2)))
229+
result.append(line)
230+
continue
231+
232+
if close_re.match(line) and context_stack:
233+
context_stack.pop()
234+
result.append(line)
235+
continue
236+
237+
# Skip field injection inside enum bodies (enum values look like fields
238+
# but should not have nanopb options added)
239+
in_enum = bool(context_stack) and context_stack[-1][0] == "enum"
240+
241+
# --- Try to match and modify a field declaration ---
242+
m = field_re.match(line)
243+
if m and not in_enum:
244+
indent = m.group(1)
245+
qualifier = m.group(2) or ""
246+
ftype = m.group(3)
247+
fname = m.group(4)
248+
fnum = m.group(5)
249+
existing_opts = m.group(6) or ""
250+
251+
# Collect applicable nanopb options (wildcard < specific)
252+
extra: Dict[str, Any] = {}
253+
254+
# 1. Wildcard: any field with this name in this proto file
255+
if fname in wildcard:
256+
extra.update(wildcard[fname])
257+
258+
# 2. Specific: check all keys whose last element is fname and whose
259+
# preceding path matches the current message context
260+
for key, opts in specific.items():
261+
if key[-1] == fname:
262+
msg_path = key[:-1]
263+
if message_path_matches(context_stack, msg_path):
264+
extra.update(opts)
265+
break
266+
267+
if extra:
268+
nanopb_str = format_nanopb_opts(extra)
269+
if existing_opts.strip():
270+
opts_block = f"[{existing_opts}, {nanopb_str}]"
271+
else:
272+
opts_block = f"[{nanopb_str}]"
273+
qual = qualifier.rstrip()
274+
sep = " " if qual else ""
275+
line = f"{indent}{qual}{sep}{ftype} {fname} = {fnum} {opts_block};"
276+
277+
result.append(line)
278+
279+
# Edge case: if there were no import lines, add nanopb import after syntax line
280+
if not import_added:
281+
for i, line in enumerate(result):
282+
if line.strip().startswith("syntax") and line.strip().endswith(";"):
283+
result.insert(i + 1, f'import "{nanopb_import_path}";')
284+
break
285+
286+
return "\n".join(result)
287+
288+
289+
def main() -> int:
290+
"""Parse an .options file and inject its constraints into a .proto file in-place."""
291+
if len(sys.argv) != 3:
292+
print(
293+
f"Usage: {sys.argv[0]} <options_file> <proto_file>",
294+
file=sys.stderr,
295+
)
296+
return 1
297+
298+
opts_path = Path(sys.argv[1])
299+
proto_path = Path(sys.argv[2])
300+
301+
if not opts_path.exists():
302+
print(f"Options file not found: {opts_path}", file=sys.stderr)
303+
return 1
304+
305+
if not proto_path.exists():
306+
print(f"Proto file not found: {proto_path}", file=sys.stderr)
307+
return 1
308+
309+
specific, wildcard = parse_options_file(opts_path)
310+
total = len(specific) + len(wildcard)
311+
312+
if total == 0:
313+
print(f" [{opts_path.name}] No injectable options found, skipping.")
314+
return 0
315+
316+
content = proto_path.read_text(encoding="utf-8")
317+
318+
# After regen-protobufs.sh's sed fixup, the nanopb import path is:
319+
nanopb_import_path = "meshtastic/protobuf/nanopb.proto"
320+
321+
modified = inject_into_proto(content, specific, wildcard, nanopb_import_path)
322+
proto_path.write_text(modified, encoding="utf-8")
323+
324+
print(
325+
f" [{opts_path.name}] Injected {len(specific)} specific + "
326+
f"{len(wildcard)} wildcard option(s) into {proto_path.name}"
327+
)
328+
return 0
329+
330+
331+
if __name__ == "__main__":
332+
sys.exit(main())

bin/regen-protobufs.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,19 @@ $SEDCMD 's/^import "meshtastic\//import "meshtastic\/protobuf\//' "${INDIR}/"*.p
4646

4747
$SEDCMD 's/^import "nanopb.proto"/import "meshtastic\/protobuf\/nanopb.proto"/' "${INDIR}/"*.proto
4848

49+
# Inject nanopb .options constraints as inline proto field options so that
50+
# protoc --python_out embeds them in the generated descriptors. Python code
51+
# can then read them via:
52+
# field.GetOptions().Extensions[nanopb_pb2.nanopb].max_size
53+
echo "Injecting nanopb options into proto files..."
54+
for OPTS_FILE in "${INDIR}"/*.options; do
55+
BASENAME=$(basename "${OPTS_FILE}" .options)
56+
PROTO_FILE="${INDIR}/${BASENAME}.proto"
57+
if [ -f "${PROTO_FILE}" ]; then
58+
python3 ./bin/inject_nanopb_options.py "${OPTS_FILE}" "${PROTO_FILE}"
59+
fi
60+
done
61+
4962
# Generate the python files
5063
./nanopb-0.4.8/generator-bin/protoc -I=$TMPDIR/in --python_out "${OUTDIR}" "--mypy_out=${PYIDIR}" $INDIR/*.proto
5164

0 commit comments

Comments
 (0)