summaryrefslogtreecommitdiffstats
path: root/util/locale_database/localetools.py
blob: cc3ec1b4c5bb7e1e4f4456c458cb024651c4e686 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#############################################################################
##
## Copyright (C) 2021 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the test suite of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:COMM$
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and The Qt Company. For licensing terms
## and conditions see https://www.qt.io/terms-conditions. For further
## information use the contact form at https://www.qt.io/contact-us.
##
## $QT_END_LICENSE$
##
##
##
##
##
##
##
##
############################################################################
"""Utilities shared among the CLDR extraction tools.

Functions:
  unicode2hex() -- converts unicode text to UCS-2 in hex form.
  wrap_list() -- map list to comma-separated string, 20 entries per line.

Classes:
  Error -- A shared error class.
  Transcriber -- edit a file by writing a temporary file, then renaming.
  SourceFileEditor -- adds standard prelude and tail handling to Transcriber.
"""

import os
import tempfile

class Error (StandardError):
    __upinit = StandardError.__init__
    def __init__(self, msg, *args):
        self.__upinit(msg, *args)
        self.message = msg
    def __str__(self):
        return self.message

def unicode2hex(s):
    lst = []
    for x in s:
        v = ord(x)
        if v > 0xFFFF:
            # make a surrogate pair
            # copied from qchar.h
            high = (v >> 10) + 0xd7c0
            low = (v % 0x400 + 0xdc00)
            lst.append(hex(high))
            lst.append(hex(low))
        else:
            lst.append(hex(v))
    return lst

def wrap_list(lst):
    def split(lst, size):
        while lst:
            head, lst = lst[:size], lst[size:]
            yield head
    return ",\n".join(", ".join(x) for x in split(lst, 20))

class Transcriber (object):
    """Helper class to facilitate rewriting source files.

    This class takes care of the temporary file manipulation. Derived
    classes need to implement transcribing of the content, with
    whatever modifications they may want.  Members reader and writer
    are exposed; use writer.write() to output to the new file; use
    reader.readline() or iterate reader to read the original.

    Callers should call close() on success or cleanup() on failure (to
    clear away the temporary file).
    """
    def __init__(self, path, temp):
        # Open the old file
        self.reader = open(path)
        # Create a temp file to write the new data into
        temp, tempPath = tempfile.mkstemp(os.path.split(path)[1], dir = temp)
        self.__names = path, tempPath
        self.writer = os.fdopen(temp, "w")

    def close(self):
        self.reader.close()
        self.writer.close()
        self.reader = self.writer = None
        source, temp = self.__names
        os.remove(source)
        os.rename(temp, source)

    def cleanup(self):
        if self.__names:
            self.reader.close()
            self.writer.close()
            # Remove temp-file:
            os.remove(self.__names[1])
            self.__names = ()

class SourceFileEditor (Transcriber):
    """Transcriber with transcription of code around a gnerated block.

    We have a common pattern of source files with a generated part
    embedded in a context that's not touched by the regeneration
    scripts. The generated part is, in each case, marked with a common
    pair of start and end markers. We transcribe the old file to a new
    temporary file; on success, we then remove the original and move
    the new version to replace it.

    This class takes care of transcribing the parts before and after
    the generated content; on creation, an instance will copy the
    preamble up to the start marker; its close() will skip over the
    original's generated content and resume transcribing with the end
    marker. Derived classes need only implement the generation of the
    content in between.

    Callers should call close() on success or cleanup() on failure (to
    clear away the temporary file); see Transcriber.
    """
    __upinit = Transcriber.__init__
    def __init__(self, path, temp):
        """Set up the source file editor.

        Requires two arguments: the path to the source file to be read
        and, on success, replaced with a new version; and the
        directory in which to store the temporary file during the
        rewrite."""
        self.__upinit(path, temp)
        self.__copyPrelude()

    __upclose = Transcriber.close
    def close(self):
        self.__copyTail()
        self.__upclose()

    # Implementation details:
    GENERATED_BLOCK_START = '// GENERATED PART STARTS HERE'
    GENERATED_BLOCK_END = '// GENERATED PART ENDS HERE'

    def __copyPrelude(self):
        # Copy over the first non-generated section to the new file
        for line in self.reader:
            self.writer.write(line)
            if line.strip() == self.GENERATED_BLOCK_START:
                break

    def __copyTail(self):
        # Skip through the old generated data in the old file
        for line in self.reader:
            if line.strip() == self.GENERATED_BLOCK_END:
                self.writer.write(line)
                break
        # Transcribe the remainder:
        for line in self.reader:
            self.writer.write(line)