1#!/usr/bin/env python3 2#-*- coding: utf-8 -*- 3 4# Copyright (C) 2021 The Android Open Source Project 5# 6# Licensed under the Apache License, Version 2.0 (the 'License'); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an 'AS IS' BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17 18""" 19Finalize resource values in <staging-public-group> tags 20and convert those to <staging-public-group-final> 21 22Usage: finalize_res.py core/res/res/values/public.xml public_finalized.xml 23""" 24 25import re, sys, codecs 26 27def finalize_item(raw): 28 global _type_ids, _type 29 id = _type_ids[_type] 30 _type_ids[_type] += 1 31 name = raw.group(1) 32 val = '<public type="%s" name="%s" id="%s" />' % (_type, name, '0x{0:0{1}x}'.format(id,8)) 33 if re.match(r'_*removed.+', name): 34 val = '<!-- ' + val.replace('<public', '< public') + ' -->' 35 return val 36 37def finalize_group(raw): 38 global _type_ids, _type 39 _type = raw.group(1) 40 id = int(raw.group(2), 16) 41 _type_ids[_type] = _type_ids.get(_type, id) 42 (res, count) = re.subn(r' {0,2}<public name="(.+?)" */>', finalize_item, raw.group(3)) 43 if count > 0: 44 res = raw.group(0).replace("staging-public-group", "staging-public-group-final") + '\n' + res 45 return res 46 47def collect_ids(raw): 48 global _type_ids 49 for m in re.finditer(r'<public type="(.+?)" name=".+?" id="(.+?)" />', raw): 50 type = m.group(1) 51 id = int(m.group(2), 16) 52 _type_ids[type] = max(id + 1, _type_ids.get(type, 0)) 53 54with open(sys.argv[1]) as f: 55 global _type_ids, _type 56 _type_ids = {} 57 raw = f.read() 58 collect_ids(raw) 59 raw = re.sub(r'<staging-public-group type="(.+?)" first-id="(.+?)">(.+?)</staging-public-group>', finalize_group, raw, flags=re.DOTALL) 60 raw = re.sub(r' *\n', '\n', raw) 61 raw = re.sub(r'\n{3,}', '\n\n', raw) 62 with open(sys.argv[2], "w") as f: 63 f.write(raw) 64 65