Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import argparse
- from re import match
- parser = argparse.ArgumentParser(description='Synchronizes translated values from a .PO file with another one. By MikiSoft')
- parser.add_argument('source_file', type=argparse.FileType('r'))
- parser.add_argument('target_file', type=argparse.FileType('r'))
- args = parser.parse_args()
- def extract_strings(lines):
- c = []
- o = []
- last = None
- def checkappend(c, o, last, m=False):
- if len(o) == 0 or not m and (last in o[-1] or last == 'msgctxt') or m and last[0] in o[-1]:
- if len(c) > 0:
- o.append({'#': c.copy()})
- c[:] = []
- else:
- o.append({})
- for l in lines:
- if l.strip() == '':
- continue
- r = match('^(?:(?P<key>msgid(?:_plural)?|msgstr|msgctxt)(?:\[(?P<i>\d)\])? )?"(?P<value>.*?)"$', l)
- if not r:
- if l[0] == '#':
- c.append(l[1:])
- continue
- if r.group('i') or not r.group('key') and isinstance(last, list):
- if not r.group('i'):
- o[-1][last[0]][last[1]].append(r.group('value'))
- elif r.group('key') in o[-1] and r.group('i') not in o[-1][last[0]]:
- last[1] = r.group('i')
- o[-1][last[0]][last[1]] = [r.group('value')]
- else:
- last = [r.group('key'), r.group('i')]
- checkappend(c, o, last, True)
- o[-1][last[0]] = {last[1]: [r.group('value')]}
- else:
- if not r.group('key'):
- o[-1][last].append(r.group('value'))
- else:
- last = r.group('key')
- checkappend(c, o, last)
- o[-1][last] = [r.group('value')]
- if len(c) > 0:
- o[-1]['#'] = c
- return o
- files = [args.source_file.readlines(), args.target_file.readlines()]
- args.source_file.close()
- for i, f in enumerate(files):
- files[i] = extract_strings(f)
- for s in files[0]:
- for s1 in files[1]:
- if s['msgid'] == s1['msgid'] and ('msgid_plural' not in s and 'msgid_plural' not in s1 or s['msgid_plural'] == s1['msgid_plural']):
- s1['msgstr'] = s['msgstr']
- def output_strings(lst, file):
- def gen(s, f, i=None):
- out = f+('['+i+'] ' if i else ' ')
- for l in (s[f][i] if i else s[f]):
- out += '"'+l+'"\n'
- return out
- for s in lst:
- out = ''
- if '#' in s:
- for l in s['#']:
- out += '#'+l
- for t in ['msgctxt', 'msgid', 'msgid_plural']:
- if t in s:
- out += gen(s, t)
- if isinstance(s['msgstr'], list):
- out += gen(s, 'msgstr')
- else:
- for i in range(0, len(s['msgstr'].keys())):
- out += gen(s, 'msgstr', str(i))
- file.write(out+'\n')
- args.target_file = open(args.target_file.name, 'w')
- output_strings(files[1], args.target_file)
- args.target_file.close()
Add Comment
Please, Sign In to add comment