devtools/fix_po_encoding
author Aurelien Campeas <aurelien.campeas@logilab.fr>
Mon, 26 Aug 2013 16:12:30 +0200
changeset 9255 46f41c3e1443
parent 0 b97547f5f1fa
permissions -rwxr-xr-x
remove 3.8 bw compat - cwconfig: old keys such as depends_cubes and non-dict dependencies - cwctl: fall back to docstring if no short descr, forget 'short_descr' - dbapi: session_data, get_session_data, set_session_data, del_session_data - dbapi & testlib, session: eid_key is gone - migractions: cachekey is gone - doc/datamodel/definition, schemaserial: BoundConstraint -> BoundaryConstraint - formwidgets: separator - primary view: render_entity_metadata Related to #2782004.

#!/usr/bin/python

"""usage: fix-po-encodings [filename...]
change the encoding of the po files passed as arguments to utf-8
"""
import sys
import re
import codecs

def change_encoding(filename, target='UTF-8'):
    fdesc = open(filename)
    data = fdesc.read()
    fdesc.close()
    encoding = find_encoding(data)
    if encoding == target:
        return
    data = fix_encoding(data, target)
    data = unicode(data, encoding)
    fdesc = codecs.open(filename, 'wb', encoding=target)
    fdesc.write(data)
    fdesc.close()

def find_encoding(data):
    regexp = re.compile(r'"Content-Type:.* charset=([a-zA-Z0-9-]+)\\n"', re.M)
    mo = regexp.search(data)
    if mo is None:
        raise ValueError('No encoding declaration')
    return mo.group(1)

def fix_encoding(data, target_encoding):
    regexp = re.compile(r'("Content-Type:.* charset=)(.*)(\\n")', re.M)
    return regexp.sub(r'\1%s\3' % target_encoding, data)
    


for filename in sys.argv[1:]:
    print filename
    change_encoding(filename)