blob: 74a6885b6f66db62cbcdf23321ebf8e6f14978a6 [file]
#!/usr/bin/env python3
# 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.
# To run this script execute
# m combine_textprotos.py && out/host/linux-x86/bin/combine_textprotos.py
import argparse
from google.protobuf import text_format
from proto import policy_metadata_pb2
def main():
parser = argparse.ArgumentParser(
description='Merge multiple PolicyMetadata textprotos into one.'
)
parser.add_argument(
'--input', nargs='+', required=True, help='Input textproto files'
)
parser.add_argument('--output', required=True, help='Output textproto file')
args = parser.parse_args()
policy_metadata_lists = readTextProtos(args.input)
combined = combineTextProtos(policy_metadata_lists)
writeTextProto(combined, args.output)
def readTextProtos(paths):
return [readTextProto(path) for path in paths]
def readTextProto(path):
result = policy_metadata_pb2.PolicyMetadataList()
with open(path, 'r', encoding='utf-8') as f:
return text_format.Parse(f.read(), result)
def writeTextProto(proto, path):
with open(path, 'w', encoding='utf-8') as f:
f.write(text_format.MessageToString(proto))
def iterAllPolicies(metadata_lists):
for metadata_list in metadata_lists:
for policy in metadata_list.policy_metadata:
yield policy
def iterAllGroups(metadata_lists):
for metadata_list in metadata_lists:
for group in metadata_list.policy_groups:
yield group
def checkNoDuplicateGroups(groups):
# Check for duplicate groups based on package and class name.
seen_groups = set()
for group in groups:
key = (group.class_name.package_name, group.class_name.class_name)
if key in seen_groups:
raise ValueError(
'Duplicate group detected: '
f'{group.class_name.package_name}.{group.class_name.class_name}'
)
seen_groups.add(key)
def combineTextProtos(policy_metadata_lists):
all_policies = list(iterAllPolicies(policy_metadata_lists))
# Sort policies alphabetically so the output is stable.
all_policies.sort(key=lambda p: p.identifier.field_name)
all_groups = list(iterAllGroups(policy_metadata_lists))
checkNoDuplicateGroups(all_groups)
sorted_groups = list(all_groups)
sorted_groups.sort(
key=lambda g: (g.class_name.package_name, g.class_name.class_name)
)
# Create the combined PolicyMetadataList
combined = policy_metadata_pb2.PolicyMetadataList()
combined.policy_metadata.extend(all_policies)
combined.policy_groups.extend(sorted_groups)
return combined
if __name__ == '__main__':
main()