Coverage for /Users/marco/Code/django-rosetta/rosetta/polib : 58.48%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -* coding: utf-8 -*- # # License: MIT (see LICENSE file provided) # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
**polib** allows you to manipulate, create, modify gettext files (pot, po and mo files). You can load existing files, iterate through it's entries, add, modify entries, comments or metadata, etc. or create new po files from scratch.
**polib** provides a simple and pythonic API via the :func:`~polib.pofile` and :func:`~polib.mofile` convenience functions. """
'default_encoding', 'escape', 'unescape', 'detect_encoding', ]
# the default encoding to use when encoding cannot be detected
# python 2/3 compatibility helpers {{{
else: PY3 = True text_type = str
def b(s): return s.encode("latin-1")
def u(s): return s # }}} # _pofile_or_mofile {{{
""" Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to honor the DRY concept. """ # get the file encoding
# parse the file f, encoding=enc, check_for_duplicates=kwargs.get('check_for_duplicates', False), klass=kwargs.get('klass') ) # }}} # function pofile() {{{
""" Convenience function that parses the po or pot file ``pofile`` and returns a :class:`~polib.POFile` instance.
Arguments:
``pofile`` string, full or relative path to the po/pot file or its content (data).
``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext (optional, default: ``78``).
``encoding`` string, the encoding to use (e.g. "utf-8") (default: ``None``, the encoding will be auto-detected).
``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``).
``klass`` class which is used to instantiate the return value (optional, default: ``None``, the return value with be a :class:`~polib.POFile` instance). """ # }}} # function mofile() {{{
""" Convenience function that parses the mo file ``mofile`` and returns a :class:`~polib.MOFile` instance.
Arguments:
``mofile`` string, full or relative path to the mo file or its content (data).
``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext to generate the po file that was used to format the mo file (optional, default: ``78``).
``encoding`` string, the encoding to use (e.g. "utf-8") (default: ``None``, the encoding will be auto-detected).
``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``).
``klass`` class which is used to instantiate the return value (optional, default: ``None``, the return value with be a :class:`~polib.POFile` instance). """ return _pofile_or_mofile(mofile, 'mofile', **kwargs) # }}} # function detect_encoding() {{{
""" Try to detect the encoding used by the ``file``. The ``file`` argument can be a PO or MO file path or a string containing the contents of the file. If the encoding cannot be detected, the function will return the value of ``default_encoding``.
Arguments:
``file`` string, full or relative path to the po/mo file or its content.
``binary_mode`` boolean, set this to True if ``file`` is a mo file. """
"""Check whether ``charset`` is valid or not.""" except LookupError: return False
except (ValueError, UnicodeEncodeError): is_file = False
match = rxt.search(file) if match: enc = match.group(1).strip() if charset_exists(enc): return enc else: # For PY3, always treat as binary mode = 'rb' rx = rxb else: f.close() return default_encoding # }}} # function escape() {{{
""" Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in the given string ``st`` and returns it. """ .replace('\t', r'\t')\ .replace('\r', r'\r')\ .replace('\n', r'\n')\ .replace('\"', r'\"') # }}} # function unescape() {{{
""" Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in the given string ``st`` and returns it. """ return '\t' return '\r' return '\\' # }}} # class _BaseFile {{{
""" Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile` classes. This class should **not** be instanciated directly. """
""" Constructor, accepts the following keyword arguments:
``pofile`` string, the path to the po or mo file, or its content as a string.
``wrapwidth`` integer, the wrap width, only useful when the ``-w`` option was passed to xgettext (optional, default: ``78``).
``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional).
``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file, (optional, default: ``False``). """ # the opened file handle else: self.fpath = kwargs.get('fpath') # the width at which lines should be wrapped # the file encoding # whether to check for duplicate entries or not # header # both po and mo files have metadata
""" Returns the unicode representation of the file. """ [e for e in self if not e.obsolete] ret.append(entry.__unicode__(self.wrapwidth))
#if type(ret) != text_type: # return unicode(ret, self.encoding)
def __str__(self): return self.__unicode__() else: """ Returns the string representation of the file. """ return unicode(self).encode(self.encoding)
""" Overriden ``list`` method to implement the membership test (in and not in). The method considers that an entry is in the file if it finds an entry that has the same msgid (the test is **case sensitive**) and the same msgctxt (or none for both entries).
Argument:
``entry`` an instance of :class:`~polib._BaseEntry`. """ return self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt) \ is not None
return str(self) == str(other)
""" Overriden method to check for duplicates entries, if a user tries to add an entry that is already in the file, the method will raise a ``ValueError`` exception.
Argument:
``entry`` an instance of :class:`~polib._BaseEntry`. """ raise ValueError('Entry "%s" already exists' % entry.msgid)
""" Overriden method to check for duplicates entries, if a user tries to add an entry that is already in the file, the method will raise a ``ValueError`` exception.
Arguments:
``index`` index at which the entry should be inserted.
``entry`` an instance of :class:`~polib._BaseEntry`. """ if self.check_for_duplicates and entry in self: raise ValueError('Entry "%s" already exists' % entry.msgid) super(_BaseFile, self).insert(index, entry)
""" Returns the file metadata as a :class:`~polib.POFile` instance. """ # Strip whitespace off each line in a multi-line entry e.flags.append('fuzzy')
""" Saves the po file to ``fpath``. If it is an existing file and no ``fpath`` is provided, then the existing file is rewritten with the modified data.
Keyword arguments:
``fpath`` string, full or relative path to the file.
``repr_method`` string, the method to use for output. """ raise IOError('You must provide a file path to save() method') else: contents = contents.decode(self.encoding) # set the file path if not set self.fpath = fpath
msgctxt=False): """ Find the entry which msgid (or property identified by the ``by`` argument) matches the string ``st``.
Keyword arguments:
``st`` string, the string to search for.
``by`` string, the property to use for comparison (default: ``msgid``).
``include_obsolete_entries`` boolean, whether to also search in entries that are obsolete.
``msgctxt`` string, allows to specify a specific message context for the search. """ entries = self[:] else: continue
""" Convenience method that returns an ordered version of the metadata dictionary. The return value is list of tuples (metadata name, metadata_value). """ # copy the dict first 'Project-Id-Version', 'Report-Msgid-Bugs-To', 'POT-Creation-Date', 'PO-Revision-Date', 'Last-Translator', 'Language-Team', 'MIME-Version', 'Content-Type', 'Content-Transfer-Encoding' ] except KeyError: pass # the rest of the metadata will be alphabetically ordered since there # are no specs for this AFAIK
""" Return the binary representation of the file. """
# the keys are sorted in the .mo file # msgfmt compares entries with msgctxt if it exists self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid other_msgid = other.msgctxt and other.msgctxt or other.msgid if self_msgid > other_msgid: return 1 elif self_msgid < other_msgid: return -1 else: return 0 # add metadata entry #mentry.msgstr = mentry.msgstr.replace('\\n', '').lstrip() # For each string, we need size and file offset. Each string is # NUL terminated; the NUL does not count into the size. # Contexts are stored by storing the concatenation of the # context, a <EOT> byte, and the original string msgid = self._encode(e.msgctxt + '\4') else:
# The header is 7 32-bit unsigned integers. # and the values start after the keys # The string table first has the list of keys, then the list of values. # Each entry has first the size of the string, then the file offset. # check endianness for magic number else: magic_number = MOFile.BIG_ENDIAN
"Iiiiiii", # Magic number magic_number, # Version 0, # number of entries entries_len, # start of key index 7 * 4, # start of value index 7 * 4 + entries_len * 8, # size and offset of hash table, we don't use hash tables 0, keystart
) output += array.array("i", offsets).tobytes() else:
""" Encodes the given ``mixed`` argument with the file encoding if and only if it's an unicode string and returns the encoded string. """ # }}} # class POFile {{{
""" Po (or Pot) file reader/writer. This class inherits the :class:`~polib._BaseFile` class and, by extension, the python ``list`` type. """
""" Returns the unicode representation of the po file. """ ret += '#%s\n' % header else:
ret = ret.decode(self.encoding)
""" Saves the binary representation of the file to given ``fpath``.
Keyword argument:
``fpath`` string, full or relative path to the mo file. """
""" Convenience method that returns the percentage of translated messages. """ return 100
""" Convenience method that returns the list of translated entries. """
""" Convenience method that returns the list of untranslated entries. """ and not 'fuzzy' in e.flags]
""" Convenience method that returns the list of fuzzy entries. """
""" Convenience method that returns the list of obsolete entries. """
""" Convenience method that merges the current pofile with the pot file provided. It behaves exactly as the gettext msgmerge utility:
* comments of this file will be preserved, but extracted comments and occurrences will be discarded; * any translations or comments in the file will be discarded, however, dot comments and file positions will be preserved; * the fuzzy flags are preserved.
Keyword argument:
``refpot`` object POFile, the reference catalog. """ # Store entries in dict/set for faster access self_entries = dict((entry.msgid, entry) for entry in self) refpot_msgids = set(entry.msgid for entry in refpot) # Merge entries that are in the refpot for entry in refpot: e = self_entries.get(entry.msgid) if e is None: e = POEntry() self.append(e) e.merge(entry) # ok, now we must "obsolete" entries that are not in the refpot anymore for entry in self: if entry.msgid not in refpot_msgids: entry.obsolete = True # }}} # class MOFile {{{
""" Mo file reader/writer. This class inherits the :class:`~polib._BaseFile` class and, by extension, the python ``list`` type. """
""" Constructor, accepts all keywords arguments accepted by :class:`~polib._BaseFile` class. """ _BaseFile.__init__(self, *args, **kwargs) self.magic_number = None self.version = 0
""" Saves the mofile as a pofile to ``fpath``.
Keyword argument:
``fpath`` string, full or relative path to the file. """ _BaseFile.save(self, fpath)
""" Saves the mofile to ``fpath``.
Keyword argument:
``fpath`` string, full or relative path to the file. """ _BaseFile.save(self, fpath, 'to_binary')
""" Convenience method to keep the same interface with POFile instances. """ return 100
""" Convenience method to keep the same interface with POFile instances. """ return self
""" Convenience method to keep the same interface with POFile instances. """ return []
""" Convenience method to keep the same interface with POFile instances. """ return []
""" Convenience method to keep the same interface with POFile instances. """ return [] # }}} # class _BaseEntry {{{
""" Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes. This class should **not** be instanciated directly. """
""" Constructor, accepts the following keyword arguments:
``msgid`` string, the entry msgid.
``msgstr`` string, the entry msgstr.
``msgid_plural`` string, the entry msgid_plural.
``msgstr_plural`` list, the entry msgstr_plural lines.
``msgctxt`` string, the entry context (msgctxt).
``obsolete`` bool, whether the entry is "obsolete" or not.
``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional). """
""" Returns the unicode representation of the entry. """ delflag = '#~ ' else: # write the msgctxt if any wrapwidth) # write the msgid # write the msgid_plural if any self.msgid_plural, wrapwidth) # write the msgstr_plural if any wrapwidth) else: # otherwise write the msgstr wrapwidth)
def __str__(self): return self.__unicode__() else: """ Returns the string representation of the entry. """ return unicode(self).encode(self.encoding)
return str(self) == str(other)
wrapwidth=78): else: # comparison must take into account fieldname length + one space # + 2 quotes (eg. msgid "<string>") flength += len(plural_index) # Wrap the line but take field name into account escaped_field, wrapwidth - 2, # 2 for quotes "" drop_whitespace=False, break_long_words=False )] else: # quick and dirty trick to get the real field name fieldname = fieldname[9:]
escape(lines.pop(0)))] #import pdb; pdb.set_trace() # }}} # class POEntry {{{
""" Represents a po file entry. """
""" Constructor, accepts the following keyword arguments:
``comment`` string, the entry comment.
``tcomment`` string, the entry translator comment.
``occurrences`` list, the entry occurrences.
``flags`` list, the entry flags.
``previous_msgctxt`` string, the entry previous context.
``previous_msgid`` string, the entry previous msgid.
``previous_msgid_plural`` string, the entry previous msgid_plural. """
""" Returns the unicode representation of the entry. """ return _BaseEntry.__unicode__(self, wrapwidth)
# comments first, if any (with text wrapping as xgettext does) ret += wrap( comment, wrapwidth, initial_indent=c[1], subsequent_indent=c[1], break_long_words=False ) else:
# occurrences (with text wrapping as xgettext does) else: filelist.append(fpath) # textwrap split words that contain hyphen, this is not # what we want for filenames, so the dirty hack is to # temporally replace hyphens with a char that a file cannot # contain, like "*" ret += [l.replace('*', '-') for l in wrap( filestr.replace('-', '*'), wrapwidth, initial_indent='#: ', subsequent_indent='#: ', break_long_words=False )] else:
# flags (TODO: wrapping ?) ret.append('#, %s' % ', '.join(self.flags))
# previous context and previous msgid/msgid_plural 'previous_msgid_plural'] ret += self._str_field(f, "#| ", "", val, wrapwidth)
#if type(ret) != types.UnicodeType: # return unicode(ret, self.encoding)
""" Called by comparison operations if rich comparison is not defined. """
# First: Obsolete test if self.obsolete != other.obsolete: if self.obsolete: return -1 else: return 1 # Work on a copy to protect original occ1 = sorted(self.occurrences[:]) occ2 = sorted(other.occurrences[:]) pos = 0 for entry1 in occ1: try: entry2 = occ2[pos] except IndexError: return 1 pos = pos + 1 if entry1[0] != entry2[0]: if entry1[0] > entry2[0]: return 1 else: return -1 if entry1[1] != entry2[1]: if entry1[1] > entry2[1]: return 1 else: return -1 # Finally: Compare message ID if self.msgid > other.msgid: return 1 elif self.msgid < other.msgid: return -1 return 0
return self.__cmp__(other) > 0
return self.__cmp__(other) < 0
return self.__cmp__(other) >= 0
return self.__cmp__(other) <= 0
return self.__cmp__(other) == 0
return self.__cmp__(other) != 0
""" Returns ``True`` if the entry has been translated or ``False`` otherwise. """ return False
""" Merge the current entry with the given pot entry. """ self.msgid = other.msgid self.msgctxt = other.msgctxt self.occurrences = other.occurrences self.comment = other.comment fuzzy = 'fuzzy' in self.flags self.flags = other.flags[:] # clone flags if fuzzy: self.flags.append('fuzzy') self.msgid_plural = other.msgid_plural self.obsolete = other.obsolete self.previous_msgctxt = other.previous_msgctxt self.previous_msgid = other.previous_msgid self.previous_msgid_plural = other.previous_msgid_plural if other.msgstr_plural: for pos in other.msgstr_plural: try: # keep existing translation at pos if any self.msgstr_plural[pos] except KeyError: self.msgstr_plural[pos] = '' # }}} # class MOEntry {{{
""" Represents a mo file entry. """ # }}} # class _POFileParser {{{
""" A finite state machine to parse efficiently and correctly po file format. """
""" Constructor.
Keyword arguments:
``pofile`` string, path to the po file or its content
``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional).
``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). """ except LookupError: enc = default_encoding self.fhandle = codecs.open(pofile, 'rU', enc) else: self.fhandle = pofile.splitlines()
pofile=pofile, encoding=enc, check_for_duplicates=kwargs.get('check_for_duplicates', False) ) # two memo flags used in handlers # Configure the state machine, by adding transitions. # Signification of symbols: # * ST: Beginning of the file (start) # * HE: Header # * TC: a translation comment # * GC: a generated comment # * OC: a file/line occurence # * FL: a flags line # * CT: a message context # * PC: a previous msgctxt # * PM: a previous msgid # * PP: a previous msgid_plural # * MI: a msgid # * MP: a msgid plural # * MS: a msgstr # * MX: a msgstr plural # * MC: a msgid or msgstr continuation line 'MS', 'MP', 'MX', 'MI']
'MP', 'MX', 'MI'], 'TC') 'PP', 'MS', 'MX'], 'CT') 'PM', 'PP', 'MS', 'MX'], 'MI')
""" Run the state machine, parse the file line by line and call process() with the current matched symbol. """
'msgctxt': 'CT', 'msgid': 'MI', 'msgstr': 'MS', 'msgid_plural': 'MP', } 'msgid_plural': 'PP', 'msgid': 'PM', 'msgctxt': 'PC', }
continue
else:
# Take care of keywords like # msgid, msgid_plural, msgctxt & msgstr. raise IOError('Syntax error in po file %s (line %s): ' 'unescaped double quote found' % (self.instance.fpath, i))
continue # we are on a occurrences line
# we are on a continuation line raise IOError('Syntax error in po file %s (line %s): ' 'unescaped double quote found' % (self.instance.fpath, i))
# we are on a msgstr plural
continue # we are on a flags line
# we are on a translator comment line
continue # we are on a generated comment line
elif tokens[0] == '#|': if nb_tokens <= 1: raise IOError('Syntax error in po file %s (line %s)' % (self.instance.fpath, i))
# Remove the marker and any whitespace right after that. line = line[2:].lstrip() self.current_token = line
if tokens[1].startswith('"'): # Continuation of previous metadata. self.process('MC', i) continue
if nb_tokens == 2: # Invalid continuation line. raise IOError('Syntax error in po file %s (line %s): ' 'invalid continuation line' % (self.instance.fpath, i))
# we are on a "previous translation" comment line, if tokens[1] not in prev_keywords: # Unknown keyword in previous translation comment. raise IOError('Syntax error in po file %s (line %s): ' 'unknown keyword %s' % (self.instance.fpath, i, tokens[1]))
# Remove the keyword and any whitespace # between it and the starting quote. line = line[len(tokens[1]):].lstrip() self.current_token = line self.process(prev_keywords[tokens[1]], i)
else: raise IOError('Syntax error in po file %s (line %s)' % (self.instance.fpath, i))
# since entries are added when another entry is found, we must add # the last entry here (only if there are lines) # before returning the instance, check if there's metadata and if # so extract it in a dict # remove the entry except (ValueError, KeyError): if key is not None: self.instance.metadata[key] += '\n' + msg.strip() # close opened file
""" Add a transition to the state machine.
Keywords arguments:
``symbol`` string, the matched token (two chars symbol).
``states`` list, a list of states (two chars symbols).
``next_state`` the next state the fsm will have after the action. """
""" Process the transition corresponding to the current state and the symbol provided.
Keywords arguments:
``symbol`` string, the matched token (two chars symbol).
``linenum`` integer, the current line number of the parsed file. """ except Exception: raise IOError('Syntax error in po file (line %s)' % linenum)
# state handlers
"""Handle a header comment."""
"""Handle a translator comment.""" self.current_entry.tcomment += '\n'
"""Handle a generated comment.""" self.current_entry.comment += '\n'
"""Handle a file:num occurence.""" fil = fil + line line = '' except (ValueError, AttributeError): self.current_entry.occurrences.append((occurrence, ''))
"""Handle a flags line.""" self.instance.append(self.current_entry) self.current_entry = POEntry()
"""Handle a previous msgid_plural line.""" if self.current_state in ['MC', 'MS', 'MX']: self.instance.append(self.current_entry) self.current_entry = POEntry() self.current_entry.previous_msgid_plural = \ unescape(self.current_token[1:-1]) return True
"""Handle a previous msgid line.""" if self.current_state in ['MC', 'MS', 'MX']: self.instance.append(self.current_entry) self.current_entry = POEntry() self.current_entry.previous_msgid = \ unescape(self.current_token[1:-1]) return True
"""Handle a previous msgctxt line.""" if self.current_state in ['MC', 'MS', 'MX']: self.instance.append(self.current_entry) self.current_entry = POEntry() self.current_entry.previous_msgctxt = \ unescape(self.current_token[1:-1]) return True
"""Handle a msgctxt."""
"""Handle a msgid."""
"""Handle a msgid plural."""
"""Handle a msgstr."""
"""Handle a msgstr plural."""
"""Handle a msgid or msgstr continuation line.""" self.current_entry.msgctxt += token elif self.current_state == 'PP': token = token[3:] self.current_entry.previous_msgid_plural += token elif self.current_state == 'PM': token = token[3:] self.current_entry.previous_msgid += token elif self.current_state == 'PC': token = token[3:] self.current_entry.previous_msgctxt += token # don't change the current state # }}} # class _MOFileParser {{{
""" A class to parse binary mo files. """
""" Constructor.
Keyword arguments:
``mofile`` string, path to the mo file or its content
``encoding`` string, the encoding to use, defaults to ``default_encoding`` global variable (optional).
``check_for_duplicates`` whether to check for duplicate entries when adding entries to the file (optional, default: ``False``). """ self.fhandle = open(mofile, 'rb')
klass = kwargs.get('klass') if klass is None: klass = MOFile self.instance = klass( fpath=mofile, encoding=kwargs.get('encoding', default_encoding), check_for_duplicates=kwargs.get('check_for_duplicates', False) )
""" Build the instance with the file handle provided in the constructor. """ # parse magic number magic_number = self._readbinary('<I', 4) if magic_number == MOFile.LITTLE_ENDIAN: ii = '<II' elif magic_number == MOFile.BIG_ENDIAN: ii = '>II' else: raise IOError('Invalid mo file, magic number is incorrect !') self.instance.magic_number = magic_number # parse the version number and the number of strings self.instance.version, numofstrings = self._readbinary(ii, 8) # original strings and translation strings hash table offset msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8) # move to msgid hash table and read length and offset of msgids self.fhandle.seek(msgids_hash_offset) msgids_index = [] for i in range(numofstrings): msgids_index.append(self._readbinary(ii, 8)) # move to msgstr hash table and read length and offset of msgstrs self.fhandle.seek(msgstrs_hash_offset) msgstrs_index = [] for i in range(numofstrings): msgstrs_index.append(self._readbinary(ii, 8)) # build entries encoding = self.instance.encoding for i in range(numofstrings): self.fhandle.seek(msgids_index[i][1]) msgid = self.fhandle.read(msgids_index[i][0])
self.fhandle.seek(msgstrs_index[i][1]) msgstr = self.fhandle.read(msgstrs_index[i][0]) if i == 0: # metadata raw_metadata, metadata = msgstr.split(b('\n')), {} for line in raw_metadata: tokens = line.split(b(':'), 1) if tokens[0] != b(''): try: k = tokens[0].decode(encoding) v = tokens[1].decode(encoding) metadata[k] = v.strip() except IndexError: metadata[k] = u('') self.instance.metadata = metadata continue # test if we have a plural entry msgid_tokens = msgid.split(b('\0')) if len(msgid_tokens) > 1: entry = self._build_entry( msgid=msgid_tokens[0], msgid_plural=msgid_tokens[1], msgstr_plural=dict((k, v) for k, v in enumerate(msgstr.split(b('\0')))) ) else: entry = self._build_entry(msgid=msgid, msgstr=msgstr) self.instance.append(entry) # close opened file self.fhandle.close() return self.instance
msgstr_plural=None): msgctxt_msgid = msgid.split(b('\x04')) encoding = self.instance.encoding if len(msgctxt_msgid) > 1: kwargs = { 'msgctxt': msgctxt_msgid[0].decode(encoding), 'msgid': msgctxt_msgid[1].decode(encoding), } else: kwargs = {'msgid': msgid.decode(encoding)} if msgstr: kwargs['msgstr'] = msgstr.decode(encoding) if msgid_plural: kwargs['msgid_plural'] = msgid_plural.decode(encoding) if msgstr_plural: for k in msgstr_plural: msgstr_plural[k] = msgstr_plural[k].decode(encoding) kwargs['msgstr_plural'] = msgstr_plural return MOEntry(**kwargs)
""" Private method that unpack n bytes of data using format <fmt>. It returns a tuple or a mixed value if the tuple length is 1. """ bytes = self.fhandle.read(numbytes) tup = struct.unpack(fmt, bytes) if len(tup) == 1: return tup[0] return tup # }}} # class TextWrapper {{{
""" Subclass of textwrap.TextWrapper that backport the drop_whitespace option. """ drop_whitespace = kwargs.pop('drop_whitespace', True) textwrap.TextWrapper.__init__(self, *args, **kwargs) self.drop_whitespace = drop_whitespace
"""_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width)
# Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse()
while chunks:
# Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0
# Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent
# Maximum width for this line. width = self.width - len(indent)
# First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1]
while chunks: l = len(chunks[-1])
# Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l
# Nope, this line is full. else: break
# The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width)
# If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and not cur_line[-1].strip(): del cur_line[-1]
# Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line))
return lines # }}} # function wrap() {{{
""" Wrap a single paragraph of text, returning a list of wrapped lines. """ return TextWrapper(width=width, **kwargs).wrap(text)
# }}} |