Repository navigation
Expand file tree
/
Copy pathformat.py
More file actions
executable file
·87 lines (70 loc) · 2.26 KB
/
Copy pathformat.py
File metadata and controls
executable file
·87 lines (70 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: The LineageOS Project
# SPDX-License-Identifier: Apache-2.0
#
import sys
from pathlib import Path
from xml.etree import ElementTree
from xml.sax.saxutils import quoteattr
apn_attribute_order = ['mcc', 'mnc', 'carrier', 'apn']
def sort_apn_attributes(item):
key, _ = item
try:
return (0, apn_attribute_order.index(key))
except ValueError:
return (1, key)
def pretty_apn(elem, indent):
attrs = sorted(elem.attrib.items(), key=sort_apn_attributes)
lines = [f'{indent}<{elem.tag}']
for k, v in attrs:
lines.append(f'{indent} {k}={quoteattr(v)}')
lines.append(f'{indent}/>')
return '\n'.join(lines)
def format_elem(elem, depth=0):
indent = ' ' * 4 * depth
out = []
if elem.tag == 'apn':
out.append(pretty_apn(elem, indent))
else:
attrs = ' '.join(f'{k}={quoteattr(v)}' for k, v in elem.attrib.items())
if attrs:
out.append(f'{indent}<{elem.tag} {attrs}>')
else:
out.append(f'{indent}<{elem.tag}>')
for child in sorted(
elem,
key=lambda e: tuple(
e.get(attr) or '' for attr in apn_attribute_order
),
):
out.append(format_elem(child, depth + 1))
out.append(f'{indent}</{elem.tag}>')
return '\n'.join(out)
def process_file(xml_path):
tree = ElementTree.parse(xml_path)
formatted = format_elem(tree.getroot())
upstream_dir = Path(__file__).resolve().parent / 'upstream'
copyright_holders = (
('Google Inc',)
if Path(xml_path).resolve().is_relative_to(upstream_dir)
else ('The LineageOS Project',)
)
with open(xml_path, 'w', encoding='utf-8') as f:
header = [
'<?xml version="1.0" encoding="utf-8"?>',
# REUSE-IgnoreStart
'<!--',
*(
f' SPDX-FileCopyrightText: {holder}'
for holder in copyright_holders
),
' SPDX-License-Identifier: Apache-2.0',
'-->\n',
# REUSE-IgnoreEnd
]
f.write('\n'.join(header))
f.write(formatted + '\n')
if __name__ == '__main__':
for xml_path in sys.argv[1:]:
process_file(xml_path)