blob: 64ab1cdd702b15efd78aa66f63f4f9e1c1fa763b [file]
# Copyright (C) 2026 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .parser import (BlankLine, Comment, Module, Primitive, Property, String,
Bool, Identifier, Integer, List, Map)
def composeModule(module_type, name, properties=None):
"""
Creates a Module object with the given type, name, and properties.
Properties with a value of None are not included in the final result.
Args:
module_type: The type of the module (e.g., 'android_app').
name: The name property of the module.
properties: A dictionary of additional properties.
Returns:
A parser.Module object.
"""
items = []
items.append(Property(Identifier("name"), String(name)))
if properties:
for k, v in properties.items():
if v is None:
continue
items.append(Property(Identifier(k), _to_bp_value(v)))
return Module(module_type, items)
def addProperties(module, properties, update=False):
items = []
for p in module:
items.append(p)
for k, v in properties.items():
if k in module:
if not update:
raise AttributeError(f"{k} already defined in module.")
# Delete the key. We'll add it back in a moment (or not if v is None)
items = [i for i in items if i.name.value != k]
if v is None:
continue
items.append(Property(Identifier(k), _to_bp_value(v)))
return Module(module.module_type, items)
def _to_bp_value(v):
"""Recursively converts Python types to bpparser types."""
if isinstance(v, (Primitive, List, Map, Comment)):
return v
if isinstance(v, str):
return String(v)
if isinstance(v, bool):
return Bool(v)
if isinstance(v, int):
return Integer(v)
if isinstance(v, list):
return List([_to_bp_value(item) for item in v])
if isinstance(v, dict):
props = []
for k, val in v.items():
props.append(Property(Identifier(k), _to_bp_value(val)))
return Map(props)
raise TypeError(f"Unsupported type: {type(v)}")
def upsert_module(module, android_bp):
for i, m in enumerate(android_bp):
if not isinstance(m, Module):
continue
if not "name" in m:
continue # Assume modules without names are not for us to mess with, like `package`
if m["name"] == module["name"]:
android_bp[i] = module
return False
android_bp.append(module)
android_bp.append(BlankLine())
return True