aboutsummaryrefslogtreecommitdiff
path: root/i18nfix.py
blob: b00eef3f850450432935a6ce56f02cb16f590c54 (plain) (blame)
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
#!/usr/bin/env python3
#
# Copyright (C) 2017, 2018 GNUnet e.V.
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.
"""
Extract translations from a Jinja2 template, stripping leading newlines.

@author Florian Dold
"""

import re
import jinja2.ext


def normalize_str(message):
    if not isinstance(message, str):
        return message
    message = message.strip()
    # collapse whitespaces (including newlines) into one space.
    message = re.sub("\s+", " ", message)
    return message


def normalize(message):
    if isinstance(message, str):
        return normalize_str(message)
    elif isinstance(message, tuple):
        return tuple([normalize_str(x) for x in message])
    return message


def babel_extract(fileobj, keywords, comment_tags, options):
    res = jinja2.ext.babel_extract(fileobj, keywords, comment_tags, options)
    for lineno, funcname, message, comments in res:
        yield lineno, funcname, normalize(message), comments


def wrap_gettext(f):
    """
    Call gettext with whitespace normalized.
    """

    def wrapper(message):
        message = normalize(message)
        return f(message)

    return wrapper