File: xmlpo

package info (click to toggle)
debmake-doc 1.24-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,840 kB
  • sloc: makefile: 914; sh: 692; python: 202; ansic: 114; sed: 16
file content (200 lines) | stat: -rw-r--r-- 8,174 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/python3
# vim:se tw=0 sts=4 ts=4 et ai:
"""
Copyright © 2024 Osamu Aoki

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
"""
import argparse
import locale
import collections
import sys
import xml.etree.ElementTree as ET

#######################################################################
# Global variables
#######################################################################
verbose = 0  # quiet
# verbose = 1: default
# verbose = 2: verbose
# verbose = 3: debug


#######################################################################
# main: parse command line parser
#######################################################################
def main():
    locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
    parser = argparse.ArgumentParser(
        description="""\
xml tag checker for po-file

When PO file is generated from DocBook XML or similar file, it will contain
some XML markers.  Many translation errors come from typos around such markers.

This checker will find unmatched set of XML markers between msgid a msgstr.

Return 0, if no error.  Return count of errors, if the error is found.

copyright 2024 Osamu Aoki <osamu@debian.org>
license: MIT

"""
    )
    parser.add_argument("-v", "--verbose", action="count", default=1, help="verbose")
    parser.add_argument(
        "-m",
        "--msg",
        action="store_true",
        default=False,
        help="print msgid and msgstr for each error",
    )
    parser.add_argument(
        "-f",
        "--test-fuzzy",
        action="store_true",
        default=False,
        help="test applies to fuzzy msg too",
    )
    parser.add_argument("pofile", help="po file to be analyzed")
    #######################################################################
    # generate argument parser instance
    #######################################################################
    args = parser.parse_args()
    # verbose = args.verbose
    #######################################################################
    state = ""  # "msgid"/"msgstr"/""
    state_last = ""
    msgid_str = ""
    msgstr_str = ""
    fuzzy = False
    msgstr_lnum = 0
    error_count = 0
    with open(args.pofile, "r") as fp:
        for lnum, line in enumerate(fp.readlines()):
            line = line.strip()  # remove NL
            if line.startswith("msgid"):
                state = "msgid"
                msgid_str = line[len("msgid ") :].strip()[1:-1]
            elif line.startswith("msgstr"):
                state = "msgstr"
                msgstr_lnum = lnum
                msgstr_str = line[len("msgstr ") :].strip()[1:-1]
            elif line.startswith('"'):
                if state == "msgid":
                    msgid_str += line[1:-1]
                elif state == "msgstr":
                    msgstr_str += line[1:-1]
                else:
                    # line number should start at 1 like editor
                    print("E: **INVALID** PO file line={}: '{}'".format(lnum + 1, line))
                    sys.exit(2)
            elif line.startswith("#") and "fuzzy" in line:
                state = "#"
                fuzzy = True
            elif line.startswith("#"):
                state = "#"
            else:
                state = ""
            if state == "" and state_last == "msgstr":
                fuzzy_in = fuzzy
                fuzzy = False
                # ready to report
                # print("I: ----------------------------------------------------------")
                if msgid_str == "" or msgstr_str == "" or "<" not in msgid_str:
                    # notworth analyzing
                    continue
                if not args.test_fuzzy and fuzzy_in:
                    # test_fuzzy=*,     fuzzy_in=False -> test
                    # test_fuzzy=True,  fuzzy_in=True  -> test
                    # test_fuzzy=False, fuzzy_in=True  -> don't test
                    continue
                # normalize
                msgid_str = msgid_str.replace("xl:href", "href").replace('\\"', '"')
                msgstr_str = msgstr_str.replace("xl:href", "href").replace('\\"', '"')
                # msgstr is not "" and msgid may have XML tag
                xml_msgid = ET.fromstring("<msg></msg>")
                xml_msgstr = ET.fromstring("<msg></msg>")
                err0_str = ""
                try:
                    xml_msgid = ET.fromstring("<msg>" + msgid_str + "</msg>")
                except ET.ParseError as err0:
                    valid_msgid = False
                    # look for error position
                    col0 = max(err0.position[1] - len("<msg>"), 0)
                    err0_str = msgid_str[col0 : col0 + 20]
                except Exception as err0:
                    valid_msgid = False
                    print(f"err0 unexpected {err0=}, {type(err0)=}")
                else:
                    valid_msgid = True
                err1_str = ""
                try:
                    xml_msgstr = ET.fromstring("<msg>" + msgstr_str + "</msg>")
                except ET.ParseError as err1:
                    valid_msgstr = False
                    # look for error position
                    col1 = max(err1.position[1] - len("<msg>"), 0)
                    err1_str = msgstr_str[col1 : col1 + 20]
                except Exception as _:
                    valid_msgstr = False
                else:
                    valid_msgstr = True
                if valid_msgid and valid_msgstr:
                    tags_msgid = collections.Counter(
                        [element.tag for element in xml_msgid.iter()]
                    )
                    del tags_msgid["msg"]
                    tags_msgstr = collections.Counter(
                        [element.tag for element in xml_msgstr.iter()]
                    )
                    del tags_msgstr["msg"]
                    if tags_msgid == tags_msgstr:
                        # print("I: line={} valid XML and       matched XML tags msgid={}".format(msgstr_lnum, tags_msgid))
                        pass
                    else:
                        # line number should start at 1 like editor
                        print(
                            "E: line={} **UNMATCHED XML TAG: fuzzy={} tags_msgid={} tags_msgstr={}".format(
                                msgstr_lnum + 1, fuzzy_in, tags_msgid, tags_msgstr
                            )
                        )
                        if args.msg:
                            print("   msgid  = '{}'".format(msgid_str))
                            print("   msgstr = '{}'".format(msgstr_str))
                        error_count += 1
                else:
                    # line number should start at 1 like editor
                    print(
                        "E: line={} **INVALID** XML: fuzzy={} error at msgid='{}' msgstr='{}' (truncated)".format(
                            msgstr_lnum + 1, fuzzy_in, err0_str, err1_str
                        )
                    )
                    if args.msg:
                        print("   msgid  = '{}'".format(msgid_str))
                        print("   msgstr = '{}'".format(msgstr_str))
                    error_count += 1
            state_last = state
        print("ERROR COUNT = {}".format(error_count))
        sys.exit(error_count)


#######################################################################
# Test code
#######################################################################
if __name__ == "__main__":
    main()
# vim:set sw=4 sts=4: