File: collect-metadata

package info (click to toggle)
i18nspector 0.25.8-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,260 kB
  • sloc: python: 8,525; sh: 91; makefile: 61
file content (128 lines) | stat: -rwxr-xr-x 4,848 bytes parent folder | download | duplicates (2)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3

# Copyright © 2012-2016 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import argparse
import collections
import itertools
import os
import re
import sys

import polib

def init_polib():
    # Happily decode any file, even when encoding declaration is broken or
    # missing.
    polib.default_encoding = 'ISO-8859-1'

is_sane_field_name = re.compile('^[a-zA-Z-]+$').match

_extract_address = re.compile(r'''^(?:
.*< ( [^<>]+@[^<>]+ ) >\s*  |
( \S+@\S+ ) |
.*< ( https?://[^<>]+ ) >\s* |
.*[(] ( https?://[^()]+ ) [)]\s* |
\s* (https?://\S+) \s*
)$''', re.VERBOSE).match

def extract_address(s):
    match = _extract_address(s)
    if match is None:
        return
    [result] = filter(None, match.groups())
    return result

def main():
    init_polib()
    ap = argparse.ArgumentParser()
    ap.add_argument('files', metavar='<file>', nargs='*')
    ap.add_argument('-F', '--field', help='only this field')
    ap.add_argument('--insane', action='store_true', help='allow insane field names')
    ap.add_argument('--extract-addresses', action='store_true')
    ap.add_argument('--all-test-cases', action='store_true')
    ap.add_argument('--plural-only', action='store_true', help='consider only translations with plural forms')
    ap.add_argument('--stdin', action='store_true', help='read filenames from stdin')
    options = ap.parse_args()
    metadata = collections.defaultdict(collections.Counter)
    if options.all_test_cases:
        test_cases = collections.defaultdict(set)
    else:
        test_cases = {}
    files = options.files
    if options.stdin:
        files = itertools.chain(
            files,
            (l.rstrip() for l in sys.stdin)
        )
    for path in files:
        print(path, end=' ... ', file=sys.stderr)
        sys.stderr.flush()
        try:
            extension = os.path.splitext(path)[-1]
            if extension == '.po':
                constructor = polib.pofile
            elif extension in ('.mo', '.gmo'):
                constructor = polib.mofile
            else:
                raise NotImplementedError(repr(extension))
            file = constructor(path)
            if options.plural_only:
                for msg in file.translated_entries():
                    if msg.msgstr_plural:
                        break
                else:
                    print('skip', file=sys.stderr)
                    sys.stderr.flush()
                    continue
            for k, v in file.metadata.items():
                if (not is_sane_field_name(k)) and (not options.insane):
                    continue
                if not (options.field is None or k == options.field):
                    continue
                if options.extract_addresses:
                    v = extract_address(v)
                metadata[k][v] += 1
                if options.all_test_cases:
                    test_cases[k, v].add(path)
                else:
                    test_cases[k, v] = path
            file = None
        except Exception as exc:  # pylint: disable=broad-except
            print('error:', exc, file=sys.stderr)
        else:
            print('ok', file=sys.stderr)
        sys.stderr.flush()
    for key, values in sorted(metadata.items()):
        print('{key!r}:'.format(key=key))
        for value, n in values.most_common():
            if options.all_test_cases:
                print(' {n:6} {value!r}'.format(n=n, value=value))
                for path in sorted(test_cases[key, value]):
                    print('        + {path!r}'.format(path=path))
            else:
                path = test_cases[key, value]
                print(' {n:6} {value!r}; test-case: {path!r}'.format(n=n, value=value, path=path))

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et