| 1 |
#!/usr/bin/python |
| 2 |
# generate_gsettings_schemas.py |
| 3 |
# |
| 4 |
# Generate GSettings schema XML files by parsing @gsetting decorators. |
| 5 |
# Invoked by data/meson.build as a build-time custom target. |
| 6 |
# |
| 7 |
# Copyright 2026 Igalia, S.L. |
| 8 |
# Author: Joanmarie Diggs <[email protected]> |
| 9 |
# |
| 10 |
# This library is free software; you can redistribute it and/or |
| 11 |
# modify it under the terms of the GNU Lesser General Public |
| 12 |
# License as published by the Free Software Foundation; either |
| 13 |
# version 2.1 of the License, or (at your option) any later version. |
| 14 |
# |
| 15 |
# This library is distributed in the hope that it will be useful, |
| 16 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 17 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 18 |
# Lesser General Public License for more details. |
| 19 |
# |
| 20 |
# You should have received a copy of the GNU Lesser General Public |
| 21 |
# License along with this library; if not, write to the |
| 22 |
# Free Software Foundation, Inc., Franklin Street, Fifth Floor, |
| 23 |
# Boston MA 02110-1301 USA. |
| 24 |
|
| 25 |
# pylint: disable=too-many-branches |
| 26 |
# pylint: disable=too-many-nested-blocks |
| 27 |
|
| 28 |
"""Generate GSettings schema XML files by parsing @gsetting decorators.""" |
| 29 |
|
| 30 |
import argparse |
| 31 |
import ast |
| 32 |
import xml.etree.ElementTree as ET |
| 33 |
from pathlib import Path |
| 34 |
from typing import Any |
| 35 |
from xml.dom import minidom |
| 36 |
|
| 37 |
REQUIRED_SETTING_FIELDS = {"key", "schema", "default"} |
| 38 |
|
| 39 |
|
| 40 |
def _extract_gsettings_schemas(tree: ast.Module) -> list[tuple[str, str]]: |
| 41 |
"""Extract @gsettings_schema class decorator arguments from a parsed AST.""" |
| 42 |
|
| 43 |
schemas: list[tuple[str, str]] = [] |
| 44 |
for node in ast.walk(tree): |
| 45 |
if not isinstance(node, ast.ClassDef): |
| 46 |
continue |
| 47 |
|
| 48 |
for decorator in node.decorator_list: |
| 49 |
if not isinstance(decorator, ast.Call): |
| 50 |
continue |
| 51 |
func = decorator.func |
| 52 |
if isinstance(func, ast.Attribute): |
| 53 |
if func.attr != "gsettings_schema": |
| 54 |
continue |
| 55 |
elif isinstance(func, ast.Name): |
| 56 |
if func.id != "gsettings_schema": |
| 57 |
continue |
| 58 |
else: |
| 59 |
continue |
| 60 |
|
| 61 |
schema_id = None |
| 62 |
schema_name = None |
| 63 |
|
| 64 |
if decorator.args and isinstance(decorator.args[0], ast.Constant): |
| 65 |
schema_id = str(decorator.args[0].value) |
| 66 |
|
| 67 |
for keyword in decorator.keywords: |
| 68 |
if keyword.arg == "name" and isinstance(keyword.value, ast.Constant): |
| 69 |
schema_name = str(keyword.value.value) |
| 70 |
|
| 71 |
if schema_id and schema_name: |
| 72 |
schemas.append((schema_id, schema_name)) |
| 73 |
|
| 74 |
return schemas |
| 75 |
|
| 76 |
|
| 77 |
def _collect_class_constants(tree: ast.Module) -> dict[str, Any]: |
| 78 |
"""Collect class-level NAME = CONSTANT assignments for resolving references.""" |
| 79 |
|
| 80 |
constants: dict[str, Any] = {} |
| 81 |
for node in ast.walk(tree): |
| 82 |
if not isinstance(node, ast.ClassDef): |
| 83 |
continue |
| 84 |
for stmt in node.body: |
| 85 |
if not isinstance(stmt, ast.Assign) or len(stmt.targets) != 1: |
| 86 |
continue |
| 87 |
target = stmt.targets[0] |
| 88 |
if isinstance(target, ast.Name) and isinstance(stmt.value, ast.Constant): |
| 89 |
constants[target.id] = stmt.value.value |
| 90 |
return constants |
| 91 |
|
| 92 |
|
| 93 |
def _extract_gsetting_decorators(tree: ast.Module, source_path: str) -> list[dict]: |
| 94 |
"""Extract @gsetting decorator arguments from a parsed AST.""" |
| 95 |
|
| 96 |
class_constants = _collect_class_constants(tree) |
| 97 |
settings: list[dict] = [] |
| 98 |
for node in ast.walk(tree): |
| 99 |
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): |
| 100 |
continue |
| 101 |
|
| 102 |
for decorator in node.decorator_list: |
| 103 |
if not isinstance(decorator, ast.Call): |
| 104 |
continue |
| 105 |
func = decorator.func |
| 106 |
if isinstance(func, ast.Name): |
| 107 |
if func.id != "gsetting": |
| 108 |
continue |
| 109 |
elif isinstance(func, ast.Attribute): |
| 110 |
if func.attr != "gsetting": |
| 111 |
continue |
| 112 |
else: |
| 113 |
continue |
| 114 |
|
| 115 |
setting: dict = {} |
| 116 |
for keyword in decorator.keywords: |
| 117 |
if isinstance(keyword.value, ast.Constant): |
| 118 |
setting[keyword.arg] = keyword.value.value |
| 119 |
elif isinstance(keyword.value, ast.Name) and keyword.value.id in class_constants: |
| 120 |
setting[keyword.arg] = class_constants[keyword.value.id] |
| 121 |
elif isinstance(keyword.value, ast.Dict): |
| 122 |
d = {} |
| 123 |
for k, v in zip(keyword.value.keys, keyword.value.values, strict=True): |
| 124 |
if isinstance(k, ast.Constant) and isinstance(v, ast.Constant): |
| 125 |
d[k.value] = v.value |
| 126 |
setting[keyword.arg] = d |
| 127 |
elif isinstance(keyword.value, ast.List): |
| 128 |
items = [ |
| 129 |
elt.value for elt in keyword.value.elts if isinstance(elt, ast.Constant) |
| 130 |
] |
| 131 |
setting[keyword.arg] = items |
| 132 |
|
| 133 |
missing = REQUIRED_SETTING_FIELDS - set(setting) |
| 134 |
if missing: |
| 135 |
raise ValueError( |
| 136 |
f"@gsetting on {node.name} in {source_path} missing required fields: {missing}" |
| 137 |
) |
| 138 |
settings.append(setting) |
| 139 |
|
| 140 |
return settings |
| 141 |
|
| 142 |
|
| 143 |
def _extract_gsettings_enums(tree: ast.Module) -> dict[str, dict[str, int]]: |
| 144 |
"""Extract @gsettings_enum decorator arguments from a parsed AST.""" |
| 145 |
|
| 146 |
enums: dict[str, dict[str, int]] = {} |
| 147 |
for node in ast.walk(tree): |
| 148 |
if not isinstance(node, ast.ClassDef): |
| 149 |
continue |
| 150 |
|
| 151 |
for decorator in node.decorator_list: |
| 152 |
if not isinstance(decorator, ast.Call): |
| 153 |
continue |
| 154 |
func = decorator.func |
| 155 |
if isinstance(func, ast.Name): |
| 156 |
if func.id != "gsettings_enum": |
| 157 |
continue |
| 158 |
elif isinstance(func, ast.Attribute): |
| 159 |
if func.attr != "gsettings_enum": |
| 160 |
continue |
| 161 |
else: |
| 162 |
continue |
| 163 |
|
| 164 |
enum_id = None |
| 165 |
values: dict[str, int] = {} |
| 166 |
|
| 167 |
if decorator.args and isinstance(decorator.args[0], ast.Constant): |
| 168 |
enum_id = str(decorator.args[0].value) |
| 169 |
|
| 170 |
for keyword in decorator.keywords: |
| 171 |
if keyword.arg == "enum_id" and isinstance(keyword.value, ast.Constant): |
| 172 |
enum_id = str(keyword.value.value) |
| 173 |
elif keyword.arg == "values" and isinstance(keyword.value, ast.Dict): |
| 174 |
for k, v in zip(keyword.value.keys, keyword.value.values, strict=True): |
| 175 |
if ( |
| 176 |
isinstance(k, ast.Constant) |
| 177 |
and isinstance(v, ast.Constant) |
| 178 |
and isinstance(v.value, int) |
| 179 |
): |
| 180 |
values[str(k.value)] = v.value |
| 181 |
|
| 182 |
if enum_id and values: |
| 183 |
enums[enum_id] = values |
| 184 |
|
| 185 |
return enums |
| 186 |
|
| 187 |
|
| 188 |
def _discover_schemas( |
| 189 |
src_dir: Path, |
| 190 |
) -> tuple[dict[str, str], list[dict], dict[str, dict[str, int]]]: |
| 191 |
"""Scan source files for @gsettings_schema, @gsetting, and @gsettings_enum decorators.""" |
| 192 |
|
| 193 |
schemas: dict[str, str] = {} |
| 194 |
all_settings: list[dict] = [] |
| 195 |
all_enums: dict[str, dict[str, int]] = {} |
| 196 |
|
| 197 |
orca_dir = src_dir / "orca" |
| 198 |
for source_file in sorted(orca_dir.glob("*.py")): |
| 199 |
text = source_file.read_text(encoding="utf-8") |
| 200 |
if "gsetting" not in text: |
| 201 |
continue |
| 202 |
|
| 203 |
tree = ast.parse(text) |
| 204 |
|
| 205 |
for schema_id, schema_name in _extract_gsettings_schemas(tree): |
| 206 |
if schema_name in schemas and schemas[schema_name] != schema_id: |
| 207 |
raise ValueError( |
| 208 |
f"Schema name '{schema_name}' declared with conflicting IDs: " |
| 209 |
f"'{schemas[schema_name]}' vs '{schema_id}' in {source_file}" |
| 210 |
) |
| 211 |
schemas[schema_name] = schema_id |
| 212 |
|
| 213 |
all_settings.extend(_extract_gsetting_decorators(tree, str(source_file))) |
| 214 |
|
| 215 |
for enum_id, values in _extract_gsettings_enums(tree).items(): |
| 216 |
if enum_id in all_enums and all_enums[enum_id] != values: |
| 217 |
raise ValueError( |
| 218 |
f"Enum '{enum_id}' declared with conflicting values: " |
| 219 |
f"{all_enums[enum_id]} vs {values} in {source_file}" |
| 220 |
) |
| 221 |
all_enums[enum_id] = values |
| 222 |
|
| 223 |
setting_schemas = {s.get("schema") for s in all_settings} |
| 224 |
unknown = setting_schemas - set(schemas) |
| 225 |
if unknown: |
| 226 |
raise ValueError(f"@gsetting decorators reference undeclared schemas: {unknown}") |
| 227 |
|
| 228 |
return schemas, all_settings, all_enums |
| 229 |
|
| 230 |
|
| 231 |
def _format_default(gtype: str, default: Any, key_name: str) -> str: # pylint: disable=too-many-return-statements |
| 232 |
"""Format a default value for GSettings schema XML.""" |
| 233 |
|
| 234 |
if gtype == "b": |
| 235 |
return "true" if default else "false" |
| 236 |
if gtype == "d": |
| 237 |
if default is None: |
| 238 |
raise ValueError(f"Missing default for double setting '{key_name}'") |
| 239 |
return str(float(default)) |
| 240 |
if gtype == "s": |
| 241 |
if default is None: |
| 242 |
raise ValueError(f"Missing default for string setting '{key_name}'") |
| 243 |
return f"'{default}'" |
| 244 |
if gtype == "i": |
| 245 |
if default is None: |
| 246 |
raise ValueError(f"Missing default for integer setting '{key_name}'") |
| 247 |
return str(int(default)) |
| 248 |
if gtype == "a{ss}": |
| 249 |
return "@a{ss} {}" |
| 250 |
if gtype == "a{saas}": |
| 251 |
return "@a{saas} {}" |
| 252 |
if gtype == "as": |
| 253 |
if not default: |
| 254 |
return "@as []" |
| 255 |
items = ", ".join(f"'{v}'" for v in default) |
| 256 |
return f"[{items}]" |
| 257 |
raise ValueError(f"Unsupported gtype '{gtype}' for setting '{key_name}'") |
| 258 |
|
| 259 |
|
| 260 |
# pylint: disable-next=too-many-locals |
| 261 |
def generate_schema_xml(src_dir: Path, output_path: str) -> None: |
| 262 |
"""Generate schema XML from @gsetting decorators in source files.""" |
| 263 |
|
| 264 |
schemas, all_settings, all_enums = _discover_schemas(src_dir) |
| 265 |
|
| 266 |
schemalist = ET.Element("schemalist") |
| 267 |
|
| 268 |
for enum_id in sorted(all_enums): |
| 269 |
enum_el = ET.SubElement(schemalist, "enum", id=enum_id) |
| 270 |
for nick, int_value in all_enums[enum_id].items(): |
| 271 |
ET.SubElement(enum_el, "value", nick=nick, value=str(int_value)) |
| 272 |
|
| 273 |
for schema_name in sorted(schemas): |
| 274 |
schema_id = schemas[schema_name] |
| 275 |
settings = [s for s in all_settings if s.get("schema") == schema_name] |
| 276 |
|
| 277 |
schema = ET.SubElement(schemalist, "schema", id=schema_id) |
| 278 |
|
| 279 |
for setting in settings: |
| 280 |
genum = setting.get("genum") |
| 281 |
key_name = setting["key"] |
| 282 |
default = setting.get("default") |
| 283 |
|
| 284 |
if genum: |
| 285 |
default_str = f"'{default}'" |
| 286 |
key = ET.SubElement(schema, "key", name=key_name, enum=genum) |
| 287 |
else: |
| 288 |
gtype = setting.get("gtype", "s") |
| 289 |
default_str = _format_default(gtype, default, key_name) |
| 290 |
key = ET.SubElement(schema, "key", name=key_name, type=gtype) |
| 291 |
|
| 292 |
ET.SubElement(key, "default").text = default_str |
| 293 |
ET.SubElement(key, "summary").text = setting.get("summary", "") |
| 294 |
|
| 295 |
rough_string = ET.tostring(schemalist, encoding="unicode") |
| 296 |
reparsed = minidom.parseString(rough_string) |
| 297 |
pretty_xml = reparsed.toprettyxml(indent=" ") |
| 298 |
|
| 299 |
lines = pretty_xml.split("\n") |
| 300 |
lines[0] = '<?xml version="1.0" encoding="UTF-8"?>' |
| 301 |
clean_lines = [line for line in lines if line.strip()] |
| 302 |
|
| 303 |
with open(output_path, "w", encoding="utf-8") as f: |
| 304 |
f.write("\n".join(clean_lines)) |
| 305 |
f.write("\n") |
| 306 |
|
| 307 |
|
| 308 |
if __name__ == "__main__": |
| 309 |
parser = argparse.ArgumentParser(description="Generate Orca GSettings schemas") |
| 310 |
parser.add_argument("src_dir", help="Path to src directory") |
| 311 |
parser.add_argument("output", help="Output XML file path") |
| 312 |
args = parser.parse_args() |
| 313 |
|
| 314 |
generate_schema_xml(Path(args.src_dir), args.output) |