Debian Codegraph @

i18n/posplit

raw
1 #!/usr/bin/env python3
2 #
3 # posplit - split messages in paragraphs on .po/.pot files
4 #
5 # license: MIT/X11/Expat
6 #
7
8 from __future__ import annotations
9
10 import polib
11 import re
12 import sys
13
14
15 def addentry(po, entry, cache):
16 e = cache.get(entry.msgid)
17 if e:
18 e.occurrences.extend(entry.occurrences)
19
20 # merge comments from entry
21 for comment in entry.comment.split('\n'):
22 if comment and comment not in e.comment:
23 if not e.comment:
24 e.comment = comment
25 else:
26 e.comment += '\n' + comment
27 else:
28 po.append(entry)
29 cache[entry.msgid] = entry
30
31
32 def mkentry(orig, delta, msgid, msgstr):
33 entry = polib.POEntry()
34 entry.merge(orig)
35 entry.msgid = msgid or orig.msgid
36 entry.msgstr = msgstr or orig.msgstr
37 entry.occurrences = [(p, int(l) + delta) for (p, l) in orig.occurrences]
38 return entry
39
40
41 if __name__ == "__main__":
42 po = polib.pofile(sys.argv[1])
43
44 cache = {}
45 entries = po[:]
46 po[:] = []
47 findd = re.compile(r' *\.\. (\w+)::') # for finding directives
48 for entry in entries:
49 msgids = entry.msgid.split(u'\n\n')
50 if entry.msgstr:
51 msgstrs = entry.msgstr.split(u'\n\n')
52 else:
53 msgstrs = [u''] * len(msgids)
54
55 if len(msgids) != len(msgstrs):
56 # places the whole existing translation as a fuzzy
57 # translation for each paragraph, to give the
58 # translator a chance to recover part of the old
59 # translation - erasing extra paragraphs is
60 # probably better than retranslating all from start
61 if 'fuzzy' not in entry.flags:
62 entry.flags.append('fuzzy')
63 msgstrs = [entry.msgstr] * len(msgids)
64
65 delta = 0
66 for msgid, msgstr in zip(msgids, msgstrs):
67 if msgid and msgid != '::':
68 newentry = mkentry(entry, delta, msgid, msgstr)
69 mdirective = findd.match(msgid)
70 if mdirective:
71 if not msgid[mdirective.end() :].rstrip():
72 # only directive, nothing to translate here
73 delta += 2
74 continue
75 directive = mdirective.group(1)
76 if directive in ('container', 'include'):
77 if msgid.rstrip('\n').count('\n') == 0:
78 # only rst syntax, nothing to translate
79 delta += 2
80 continue
81 else:
82 # lines following directly, unexpected
83 print(
84 'Warning: text follows line with directive'
85 ' %s' % directive
86 )
87 comment = 'do not translate: .. %s::' % directive
88 if not newentry.comment:
89 newentry.comment = comment
90 elif comment not in newentry.comment:
91 newentry.comment += '\n' + comment
92 addentry(po, newentry, cache)
93 delta += 2 + msgid.count('\n')
94 po.save()