Debian Codegraph @

src/conf2/tools/gschema_xml2yaml

raw
1 #!/usr/bin/python3
2 #
3 # libkysdk-system's Library
4 #
5 # Copyright (C) 2023, KylinSoft Co., Ltd.
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 3 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this library. If not, see <https://www.gnu.org/licenses/>.
19 #
20 # Authors: tianshaoshuai <[email protected]>
21 #
22 #
23
24 import os
25 import re
26 import sys
27 import xml.etree.ElementTree as ET
28 import yaml
29 import argparse
30 from concurrent.futures import ThreadPoolExecutor
31 from functools import partial
32 import multiprocessing
33 from collections import defaultdict
34
35 def process_enum(enum, organization, version):
36 """处理单个enum元素"""
37 enum_list = []
38 enum_id = enum.attrib.get('id')
39 group_list = enum_id[len(organization) + 1:].split('.')
40
41 for value in enum:
42 enum_list.append({
43 '_nick': value.get('nick'),
44 '_value': value.get('value')
45 })
46
47 return group_list[0], f'enum_{enum_id}', enum_list
48
49 def process_key(key):
50 """处理单个key元素"""
51 item = {}
52 key_name = key.attrib.get('name')
53 key_type = key.attrib.get('type')
54
55 if key_type is None:
56 enumid = key.attrib.get('enum')
57 item['_range'] = f'@enum_{enumid}'
58 item['_type'] = 'enum'
59 else:
60 item['_type'] = key_type
61
62 for child in key:
63 tag = child.tag
64 text = '' if child.text is None else child.text.strip().strip('\'\"').replace('\n\t','')
65 if tag == 'range':
66 text = f'{child.attrib.get("min")},{child.attrib.get("max")}'
67 item[f'_{tag}'] = text
68
69 return key_name, item
70
71 def convert_one_file(args):
72 """处理单个文件的转换"""
73 path, file, organization, version = args
74 file_data = defaultdict(lambda: {version: {}})
75
76 try:
77 file_path = os.path.join(path, file)
78 if not os.path.exists(file_path):
79 print(f"File not found: {file_path}")
80 return file_data
81
82 tree = ET.parse(file_path)
83 root = tree.getroot()
84
85 # 处理枚举
86 for enum in root.findall('.//enum'):
87 group_name, enum_id, enum_list = process_enum(enum, organization, version)
88 if group_name not in file_data:
89 file_data[group_name] = {version: {}}
90 file_data[group_name][version][enum_id] = enum_list
91
92 # 处理schema
93 for schema in root.findall('.//schema'):
94 schema_id = schema.attrib.get('id')
95 group_list = schema_id[len(organization) + 1:].split('.')
96
97 current = file_data[group_list[0]][version]
98 for group in group_list[1:]:
99 if group not in current:
100 current[group] = {}
101 current = current[group]
102
103 # 处理所有key
104 for key in schema.findall('.//key'):
105 key_name, key_data = process_key(key)
106 current[key_name] = key_data
107
108 return file_data
109 except Exception as e:
110 print(f"Error processing {file}: {str(e)}")
111 return file_data
112
113 def main():
114 parser = argparse.ArgumentParser(description='这是一个将gschema.xml文件转化为yaml格式的程序')
115 parser.add_argument('--id', '-i', type=str, required=True,
116 help="指定一个gschema.xml的一个id,例如org.ukui.control-center")
117 parser.add_argument('--version', '-v', type=str,
118 help="指定生成yaml文件的配置版本,默认为2.0.0.0-0k0.0")
119 parser.add_argument('--path', '-p', type=str,
120 help="指定yaml文件的生成目录,默认为${HOME}/yaml")
121 args = parser.parse_args()
122
123 app = args.id
124 version = args.version or '2.0.0-0k0.0'
125 schema_path = '/usr/share/glib-2.0/schemas'
126 out_path = args.path or os.path.join(os.getenv('HOME'), 'yaml')
127 organization = app.rsplit('.', 1)[0]
128
129 # 获取文件列表
130 pattern = re.compile(f'^{re.escape(app)}.*\\.gschema\\.xml$')
131 file_list = [
132 f for f in os.listdir(schema_path)
133 if pattern.match(f)
134 ]
135 file_list.sort(key=lambda x: len(x.split('.')))
136
137 # 处理文件列表为空的情况
138 if not file_list:
139 print(f"No matching files found for {app}")
140 result = defaultdict(lambda: {version: {}})
141 else:
142 # 准备并行处理参数
143 process_args = [(schema_path, file, organization, version) for file in file_list]
144
145 # 使用线程池并行处理文件
146 num_workers = max(1, min(multiprocessing.cpu_count() * 2, len(file_list)))
147 result = defaultdict(lambda: {version: {}})
148
149 with ThreadPoolExecutor(max_workers=num_workers) as executor:
150 for file_data in executor.map(convert_one_file, process_args):
151 for group, group_data in file_data.items():
152 result[group][version].update(group_data[version])
153
154 # 确保输出目录存在
155 os.makedirs(out_path, exist_ok=True)
156
157 # 生成yaml文件
158 output_file = os.path.join(out_path, f"{app}.yaml")
159 with open(output_file, 'w') as yaml_file:
160 yaml.safe_dump(dict(result), yaml_file, allow_unicode=True)
161
162 print(f"Conversion completed. Output file: {output_file}")
163
164 if __name__ == '__main__':
165 main()