Debian Codegraph @

private/collect-metadata

raw
1 #!/usr/bin/env python3
2 # encoding=UTF-8
3
4 # Copyright © 2012-2025 Jakub Wilk <[email protected]>
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the “Software”), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 # SOFTWARE.
23
24 import argparse
25 import collections
26 import functools
27 import itertools
28 import os
29 import re
30 import sys
31
32 import polib
33
34 int(0_0) # Python >= 3.6 is required
35
36 def init_polib():
37 # Happily decode any file, even when encoding declaration is broken or
38 # missing.
39 polib.default_encoding = 'ISO-8859-1'
40
41 is_sane_field_name = re.compile('^[a-zA-Z-]+$').match
42
43 _extract_address = re.compile(r'''^(?:
44 .*< ( [^<>]+@[^<>]+ ) >\s* |
45 ( \S+@\S+ ) |
46 .*< ( https?://[^<>]+ ) >\s* |
47 .*[(] ( https?://[^()]+ ) [)]\s* |
48 \s* (https?://\S+) \s*
49 )$''', re.VERBOSE).match
50
51 def extract_address(s):
52 match = _extract_address(s)
53 if match is None:
54 return
55 [result] = filter(None, match.groups())
56 return result
57
58 def main():
59 init_polib()
60 ap = argparse.ArgumentParser()
61 ap.add_argument('files', metavar='FILE', nargs='+')
62 ap.add_argument('-F', '--field', help='only this field')
63 ap.add_argument('--insane', action='store_true', help='allow insane field names')
64 ap.add_argument('--extract-addresses', action='store_true')
65 ap.add_argument('--all-test-cases', action='store_true')
66 ap.add_argument('--plural-only', action='store_true', help='consider only translations with plural forms')
67 ap.add_argument('--stdin', action='store_true', help='read filenames from stdin')
68 options = ap.parse_args()
69 metadata = collections.defaultdict(collections.Counter)
70 if options.all_test_cases:
71 test_cases = collections.defaultdict(set)
72 else:
73 test_cases = {}
74 files = options.files
75 if options.stdin:
76 files = itertools.chain(
77 files,
78 (l.rstrip() for l in sys.stdin)
79 )
80 eprint = functools.partial(print, file=sys.stderr, flush=True)
81 for path in files:
82 eprint(path, end=' ... ')
83 try:
84 extension = os.path.splitext(path)[-1]
85 if extension == '.po':
86 constructor = polib.pofile
87 elif extension in {'.mo', '.gmo'}:
88 constructor = polib.mofile
89 else:
90 raise NotImplementedError(repr(extension))
91 file = constructor(path)
92 if options.plural_only:
93 for msg in file.translated_entries():
94 if msg.msgstr_plural:
95 break
96 else:
97 eprint('skip')
98 continue
99 for k, v in file.metadata.items():
100 if (not is_sane_field_name(k)) and (not options.insane):
101 continue
102 if not (options.field is None or k == options.field):
103 continue
104 if options.extract_addresses:
105 v = extract_address(v)
106 metadata[k][v] += 1
107 if options.all_test_cases:
108 test_cases[k, v].add(path)
109 else:
110 test_cases[k, v] = path
111 file = None
112 except Exception as exc: # pylint: disable=broad-except
113 eprint('error:', exc)
114 else:
115 eprint('ok')
116 for key, values in sorted(metadata.items()):
117 print(f'{key!r}:')
118 for value, n in values.most_common():
119 if options.all_test_cases:
120 print(f' {n:6} {value!r}')
121 for path in sorted(test_cases[key, value]):
122 print(f' + {path!r}')
123 else:
124 path = test_cases[key, value]
125 print(f' {n:6} {value!r}; test-case: {path!r}')
126
127 if __name__ == '__main__':
128 main()
129
130 # vim:ts=4 sts=4 sw=4 et