Debian Codegraph @

pkg/lib/manifest2po

raw
1 #!/usr/bin/python3
2 #
3 # Copyright (C) 2025 Red Hat, Inc.
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6
7 import argparse
8 import json
9 import pathlib
10 from collections import defaultdict
11 from collections.abc import Iterable
12 from typing import Any
13
14 PO_HEADER = r"""msgid ""
15 msgstr ""
16 "Project-Id-Version: PACKAGE_VERSION\n"
17 "MIME-Version: 1.0\n"
18 "Content-Type: text/plain; charset=UTF-8\n"
19 "Content-Transfer-Encoding: 8bit\n"
20 "X-Generator: Cockpit manifest2po\n"
21 """
22
23
24 def get_docs_strings(docs: list[dict[str, str]]) -> Iterable[str]:
25 for doc in docs:
26 assert 'label' in doc, 'doc entry without label'
27 yield doc['label']
28
29
30 def get_keyword_strings(keywords: list[dict[str, list[str]]]) -> Iterable[str]:
31 for keyword in keywords:
32 assert 'matches' in keyword, 'keywords entry without matches'
33 for match in keyword['matches']:
34 yield match
35
36
37 def get_menu_strings(menu: dict[str, Any]) -> Iterable[str]:
38 for entry in menu.values():
39 if label := entry.get('label'):
40 yield label
41 if keywords := entry.get('keywords'):
42 yield from get_keyword_strings(keywords)
43 if docs := entry.get('docs'):
44 yield from get_docs_strings(docs)
45
46
47 def get_bridges_strings(bridges: list[dict[str, str]]) -> Iterable[str]:
48 for bridge in bridges:
49 if label := bridge.get('label'):
50 yield label
51
52
53 def get_manifest_strings(manifest: dict[str, Any]) -> Iterable[str]:
54 if menu := manifest.get('menu'):
55 yield from get_menu_strings(menu)
56 if tools := manifest.get('tools'):
57 yield from get_menu_strings(tools)
58 if bridges := manifest.get('bridges'):
59 yield from get_bridges_strings(bridges)
60
61
62 def main() -> None:
63 parser = argparse.ArgumentParser(prog='manifest2po',
64 description='Extracts translatable strings from manifest.json files')
65 parser.add_argument('-d', '--directory', help='Base directory for input files')
66 parser.add_argument('-o', '--output', help='Output files', required=True)
67 parser.add_argument('files', nargs='+', help='One or more input files', type=pathlib.Path, metavar='FILE')
68
69 args = parser.parse_args()
70 strings = defaultdict[str, set[str]](set)
71
72 files: Iterable[pathlib.Path] = args.files
73 for file in files:
74 if file.name != 'manifest.json':
75 continue
76
77 # Qualify the filename if necessary
78 full_path = args.directory / file if args.directory else file
79 with open(full_path, 'r') as fp:
80 manifest = json.load(fp)
81 for msgid in get_manifest_strings(manifest):
82 strings[msgid].add(str(file))
83
84 # Write PO file
85 with open(args.output, 'w') as fp:
86 fp.write(PO_HEADER)
87 for msgid in strings:
88 manifest_filenames = ' '.join([f'{fname}:0' for fname in sorted(strings[msgid])])
89 fp.write(f"\n#: {manifest_filenames}\n")
90 fp.write(f'msgid "{msgid}"\n')
91 fp.write('msgstr ""\n')
92
93
94 if __name__ == "__main__":
95 main()