devtools/fix_po_encoding
author Aurelien Campeas <aurelien.campeas@logilab.fr>
Fri, 25 Jan 2013 13:28:23 +0100
changeset 8682 20bd1cdf86ae
parent 0 b97547f5f1fa
permissions -rwxr-xr-x
[cwctl] fix cubicweb-ctl shell command (closes #2583919) * add an uri parsing utility that documents a bit the uri cubicweb supports out of the box * cwctl: use this utility and refactor a bit for clarity (the novelty here being real support for old style 'myapp', or: * 'inmemory://myapp' * 'pyro://pyro-ns-host:pyro-ns-port/myapp' (pyro access through a pyro concentrator) * 'pyroloc://host:port/pyro-instance-id' (direct access to a pyro repository) * 'zmqpickle-tcp://host:port' * dbapi: refactor to sort out some of the complexity and restore functionality lost in 62213a34726e

#!/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)