Play images and video from Synology PhotoStation server

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  1. # -* coding: utf-8 -*-
  2. #
  3. # License: MIT (see LICENSE file provided)
  4. # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
  5. """
  6. **polib** allows you to manipulate, create, modify gettext files (pot, po and
  7. mo files). You can load existing files, iterate through it's entries, add,
  8. modify entries, comments or metadata, etc. or create new po files from scratch.
  9. **polib** provides a simple and pythonic API via the :func:`~polib.pofile` and
  10. :func:`~polib.mofile` convenience functions.
  11. """
  12. __author__ = 'David Jean Louis <izimobil@gmail.com>'
  13. __version__ = '1.0.7'
  14. __all__ = ['pofile', 'POFile', 'POEntry', 'mofile', 'MOFile', 'MOEntry',
  15. 'default_encoding', 'escape', 'unescape', 'detect_encoding', ]
  16. import array
  17. import codecs
  18. import os
  19. import re
  20. import struct
  21. import sys
  22. import textwrap
  23. try:
  24. import io
  25. except ImportError:
  26. # replacement of io.open() for python < 2.6
  27. # we use codecs instead
  28. class io(object):
  29. @staticmethod
  30. def open(fpath, mode='r', encoding=None):
  31. return codecs.open(fpath, mode, encoding)
  32. # the default encoding to use when encoding cannot be detected
  33. default_encoding = 'utf-8'
  34. # python 2/3 compatibility helpers {{{
  35. if sys.version_info[:2] < (3, 0):
  36. PY3 = False
  37. text_type = unicode
  38. def b(s):
  39. return s
  40. def u(s):
  41. return unicode(s, "unicode_escape")
  42. else:
  43. PY3 = True
  44. text_type = str
  45. def b(s):
  46. return s.encode("latin-1")
  47. def u(s):
  48. return s
  49. # }}}
  50. # _pofile_or_mofile {{{
  51. def _pofile_or_mofile(f, type, **kwargs):
  52. """
  53. Internal function used by :func:`polib.pofile` and :func:`polib.mofile` to
  54. honor the DRY concept.
  55. """
  56. # get the file encoding
  57. enc = kwargs.get('encoding')
  58. if enc is None:
  59. enc = detect_encoding(f, type == 'mofile')
  60. # parse the file
  61. kls = type == 'pofile' and _POFileParser or _MOFileParser
  62. parser = kls(
  63. f,
  64. encoding=enc,
  65. check_for_duplicates=kwargs.get('check_for_duplicates', False),
  66. klass=kwargs.get('klass')
  67. )
  68. instance = parser.parse()
  69. instance.wrapwidth = kwargs.get('wrapwidth', 78)
  70. return instance
  71. # }}}
  72. # _is_file {{{
  73. def _is_file(filename_or_contents):
  74. """
  75. Safely returns the value of os.path.exists(filename_or_contents).
  76. Arguments:
  77. ``filename_or_contents``
  78. either a filename, or a string holding the contents of some file.
  79. In the latter case, this function will always return False.
  80. """
  81. try:
  82. return os.path.exists(filename_or_contents)
  83. except (ValueError, UnicodeEncodeError):
  84. return False
  85. # }}}
  86. # function pofile() {{{
  87. def pofile(pofile, **kwargs):
  88. """
  89. Convenience function that parses the po or pot file ``pofile`` and returns
  90. a :class:`~polib.POFile` instance.
  91. Arguments:
  92. ``pofile``
  93. string, full or relative path to the po/pot file or its content (data).
  94. ``wrapwidth``
  95. integer, the wrap width, only useful when the ``-w`` option was passed
  96. to xgettext (optional, default: ``78``).
  97. ``encoding``
  98. string, the encoding to use (e.g. "utf-8") (default: ``None``, the
  99. encoding will be auto-detected).
  100. ``check_for_duplicates``
  101. whether to check for duplicate entries when adding entries to the
  102. file (optional, default: ``False``).
  103. ``klass``
  104. class which is used to instantiate the return value (optional,
  105. default: ``None``, the return value with be a :class:`~polib.POFile`
  106. instance).
  107. """
  108. return _pofile_or_mofile(pofile, 'pofile', **kwargs)
  109. # }}}
  110. # function mofile() {{{
  111. def mofile(mofile, **kwargs):
  112. """
  113. Convenience function that parses the mo file ``mofile`` and returns a
  114. :class:`~polib.MOFile` instance.
  115. Arguments:
  116. ``mofile``
  117. string, full or relative path to the mo file or its content (data).
  118. ``wrapwidth``
  119. integer, the wrap width, only useful when the ``-w`` option was passed
  120. to xgettext to generate the po file that was used to format the mo file
  121. (optional, default: ``78``).
  122. ``encoding``
  123. string, the encoding to use (e.g. "utf-8") (default: ``None``, the
  124. encoding will be auto-detected).
  125. ``check_for_duplicates``
  126. whether to check for duplicate entries when adding entries to the
  127. file (optional, default: ``False``).
  128. ``klass``
  129. class which is used to instantiate the return value (optional,
  130. default: ``None``, the return value with be a :class:`~polib.POFile`
  131. instance).
  132. """
  133. return _pofile_or_mofile(mofile, 'mofile', **kwargs)
  134. # }}}
  135. # function detect_encoding() {{{
  136. def detect_encoding(file, binary_mode=False):
  137. """
  138. Try to detect the encoding used by the ``file``. The ``file`` argument can
  139. be a PO or MO file path or a string containing the contents of the file.
  140. If the encoding cannot be detected, the function will return the value of
  141. ``default_encoding``.
  142. Arguments:
  143. ``file``
  144. string, full or relative path to the po/mo file or its content.
  145. ``binary_mode``
  146. boolean, set this to True if ``file`` is a mo file.
  147. """
  148. PATTERN = r'"?Content-Type:.+? charset=([\w_\-:\.]+)'
  149. rxt = re.compile(u(PATTERN))
  150. rxb = re.compile(b(PATTERN))
  151. def charset_exists(charset):
  152. """Check whether ``charset`` is valid or not."""
  153. try:
  154. codecs.lookup(charset)
  155. except LookupError:
  156. return False
  157. return True
  158. if not _is_file(file):
  159. match = rxt.search(file)
  160. if match:
  161. enc = match.group(1).strip()
  162. if charset_exists(enc):
  163. return enc
  164. else:
  165. # For PY3, always treat as binary
  166. if binary_mode or PY3:
  167. mode = 'rb'
  168. rx = rxb
  169. else:
  170. mode = 'r'
  171. rx = rxt
  172. f = open(file, mode)
  173. for l in f.readlines():
  174. match = rx.search(l)
  175. if match:
  176. f.close()
  177. enc = match.group(1).strip()
  178. if not isinstance(enc, text_type):
  179. enc = enc.decode('utf-8')
  180. if charset_exists(enc):
  181. return enc
  182. f.close()
  183. return default_encoding
  184. # }}}
  185. # function escape() {{{
  186. def escape(st):
  187. """
  188. Escapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
  189. the given string ``st`` and returns it.
  190. """
  191. return st.replace('\\', r'\\')\
  192. .replace('\t', r'\t')\
  193. .replace('\r', r'\r')\
  194. .replace('\n', r'\n')\
  195. .replace('\"', r'\"')
  196. # }}}
  197. # function unescape() {{{
  198. def unescape(st):
  199. """
  200. Unescapes the characters ``\\\\``, ``\\t``, ``\\n``, ``\\r`` and ``"`` in
  201. the given string ``st`` and returns it.
  202. """
  203. def unescape_repl(m):
  204. m = m.group(1)
  205. if m == 'n':
  206. return '\n'
  207. if m == 't':
  208. return '\t'
  209. if m == 'r':
  210. return '\r'
  211. if m == '\\':
  212. return '\\'
  213. return m # handles escaped double quote
  214. return re.sub(r'\\(\\|n|t|r|")', unescape_repl, st)
  215. # }}}
  216. # class _BaseFile {{{
  217. class _BaseFile(list):
  218. """
  219. Common base class for the :class:`~polib.POFile` and :class:`~polib.MOFile`
  220. classes. This class should **not** be instantiated directly.
  221. """
  222. def __init__(self, *args, **kwargs):
  223. """
  224. Constructor, accepts the following keyword arguments:
  225. ``pofile``
  226. string, the path to the po or mo file, or its content as a string.
  227. ``wrapwidth``
  228. integer, the wrap width, only useful when the ``-w`` option was
  229. passed to xgettext (optional, default: ``78``).
  230. ``encoding``
  231. string, the encoding to use, defaults to ``default_encoding``
  232. global variable (optional).
  233. ``check_for_duplicates``
  234. whether to check for duplicate entries when adding entries to the
  235. file, (optional, default: ``False``).
  236. """
  237. list.__init__(self)
  238. # the opened file handle
  239. pofile = kwargs.get('pofile', None)
  240. if pofile and _is_file(pofile):
  241. self.fpath = pofile
  242. else:
  243. self.fpath = kwargs.get('fpath')
  244. # the width at which lines should be wrapped
  245. self.wrapwidth = kwargs.get('wrapwidth', 78)
  246. # the file encoding
  247. self.encoding = kwargs.get('encoding', default_encoding)
  248. # whether to check for duplicate entries or not
  249. self.check_for_duplicates = kwargs.get('check_for_duplicates', False)
  250. # header
  251. self.header = ''
  252. # both po and mo files have metadata
  253. self.metadata = {}
  254. self.metadata_is_fuzzy = 0
  255. def __unicode__(self):
  256. """
  257. Returns the unicode representation of the file.
  258. """
  259. ret = []
  260. entries = [self.metadata_as_entry()] + \
  261. [e for e in self if not e.obsolete]
  262. for entry in entries:
  263. ret.append(entry.__unicode__(self.wrapwidth))
  264. for entry in self.obsolete_entries():
  265. ret.append(entry.__unicode__(self.wrapwidth))
  266. ret = u('\n').join(ret)
  267. assert isinstance(ret, text_type)
  268. #if type(ret) != text_type:
  269. # return unicode(ret, self.encoding)
  270. return ret
  271. if PY3:
  272. def __str__(self):
  273. return self.__unicode__()
  274. else:
  275. def __str__(self):
  276. """
  277. Returns the string representation of the file.
  278. """
  279. return unicode(self).encode(self.encoding)
  280. def __contains__(self, entry):
  281. """
  282. Overridden ``list`` method to implement the membership test (in and
  283. not in).
  284. The method considers that an entry is in the file if it finds an entry
  285. that has the same msgid (the test is **case sensitive**) and the same
  286. msgctxt (or none for both entries).
  287. Argument:
  288. ``entry``
  289. an instance of :class:`~polib._BaseEntry`.
  290. """
  291. return self.find(entry.msgid, by='msgid', msgctxt=entry.msgctxt) \
  292. is not None
  293. def __eq__(self, other):
  294. return str(self) == str(other)
  295. def append(self, entry):
  296. """
  297. Overridden method to check for duplicates entries, if a user tries to
  298. add an entry that is already in the file, the method will raise a
  299. ``ValueError`` exception.
  300. Argument:
  301. ``entry``
  302. an instance of :class:`~polib._BaseEntry`.
  303. """
  304. if self.check_for_duplicates and entry in self:
  305. raise ValueError('Entry "%s" already exists' % entry.msgid)
  306. super(_BaseFile, self).append(entry)
  307. def insert(self, index, entry):
  308. """
  309. Overridden method to check for duplicates entries, if a user tries to
  310. add an entry that is already in the file, the method will raise a
  311. ``ValueError`` exception.
  312. Arguments:
  313. ``index``
  314. index at which the entry should be inserted.
  315. ``entry``
  316. an instance of :class:`~polib._BaseEntry`.
  317. """
  318. if self.check_for_duplicates and entry in self:
  319. raise ValueError('Entry "%s" already exists' % entry.msgid)
  320. super(_BaseFile, self).insert(index, entry)
  321. def metadata_as_entry(self):
  322. """
  323. Returns the file metadata as a :class:`~polib.POFile` instance.
  324. """
  325. e = POEntry(msgid='')
  326. mdata = self.ordered_metadata()
  327. if mdata:
  328. strs = []
  329. for name, value in mdata:
  330. # Strip whitespace off each line in a multi-line entry
  331. strs.append('%s: %s' % (name, value))
  332. e.msgstr = '\n'.join(strs) + '\n'
  333. if self.metadata_is_fuzzy:
  334. e.flags.append('fuzzy')
  335. return e
  336. def save(self, fpath=None, repr_method='__unicode__'):
  337. """
  338. Saves the po file to ``fpath``.
  339. If it is an existing file and no ``fpath`` is provided, then the
  340. existing file is rewritten with the modified data.
  341. Keyword arguments:
  342. ``fpath``
  343. string, full or relative path to the file.
  344. ``repr_method``
  345. string, the method to use for output.
  346. """
  347. if self.fpath is None and fpath is None:
  348. raise IOError('You must provide a file path to save() method')
  349. contents = getattr(self, repr_method)()
  350. if fpath is None:
  351. fpath = self.fpath
  352. if repr_method == 'to_binary':
  353. fhandle = open(fpath, 'wb')
  354. else:
  355. fhandle = io.open(fpath, 'w', encoding=self.encoding)
  356. if not isinstance(contents, text_type):
  357. contents = contents.decode(self.encoding)
  358. fhandle.write(contents)
  359. fhandle.close()
  360. # set the file path if not set
  361. if self.fpath is None and fpath:
  362. self.fpath = fpath
  363. def find(self, st, by='msgid', include_obsolete_entries=False,
  364. msgctxt=False):
  365. """
  366. Find the entry which msgid (or property identified by the ``by``
  367. argument) matches the string ``st``.
  368. Keyword arguments:
  369. ``st``
  370. string, the string to search for.
  371. ``by``
  372. string, the property to use for comparison (default: ``msgid``).
  373. ``include_obsolete_entries``
  374. boolean, whether to also search in entries that are obsolete.
  375. ``msgctxt``
  376. string, allows specifying a specific message context for the
  377. search.
  378. """
  379. if include_obsolete_entries:
  380. entries = self[:]
  381. else:
  382. entries = [e for e in self if not e.obsolete]
  383. for e in entries:
  384. if getattr(e, by) == st:
  385. if msgctxt is not False and e.msgctxt != msgctxt:
  386. continue
  387. return e
  388. return None
  389. def ordered_metadata(self):
  390. """
  391. Convenience method that returns an ordered version of the metadata
  392. dictionary. The return value is list of tuples (metadata name,
  393. metadata_value).
  394. """
  395. # copy the dict first
  396. metadata = self.metadata.copy()
  397. data_order = [
  398. 'Project-Id-Version',
  399. 'Report-Msgid-Bugs-To',
  400. 'POT-Creation-Date',
  401. 'PO-Revision-Date',
  402. 'Last-Translator',
  403. 'Language-Team',
  404. 'MIME-Version',
  405. 'Content-Type',
  406. 'Content-Transfer-Encoding',
  407. 'Language',
  408. 'Plural-Forms'
  409. ]
  410. ordered_data = []
  411. for data in data_order:
  412. try:
  413. value = metadata.pop(data)
  414. ordered_data.append((data, value))
  415. except KeyError:
  416. pass
  417. # the rest of the metadata will be alphabetically ordered since there
  418. # are no specs for this AFAIK
  419. for data in sorted(metadata.keys()):
  420. value = metadata[data]
  421. ordered_data.append((data, value))
  422. return ordered_data
  423. def to_binary(self):
  424. """
  425. Return the binary representation of the file.
  426. """
  427. offsets = []
  428. entries = self.translated_entries()
  429. # the keys are sorted in the .mo file
  430. def cmp(_self, other):
  431. # msgfmt compares entries with msgctxt if it exists
  432. self_msgid = _self.msgctxt and _self.msgctxt or _self.msgid
  433. other_msgid = other.msgctxt and other.msgctxt or other.msgid
  434. if self_msgid > other_msgid:
  435. return 1
  436. elif self_msgid < other_msgid:
  437. return -1
  438. else:
  439. return 0
  440. # add metadata entry
  441. entries.sort(key=lambda o: o.msgctxt or o.msgid)
  442. mentry = self.metadata_as_entry()
  443. #mentry.msgstr = mentry.msgstr.replace('\\n', '').lstrip()
  444. entries = [mentry] + entries
  445. entries_len = len(entries)
  446. ids, strs = b(''), b('')
  447. for e in entries:
  448. # For each string, we need size and file offset. Each string is
  449. # NUL terminated; the NUL does not count into the size.
  450. msgid = b('')
  451. if e.msgctxt:
  452. # Contexts are stored by storing the concatenation of the
  453. # context, a <EOT> byte, and the original string
  454. msgid = self._encode(e.msgctxt + '\4')
  455. if e.msgid_plural:
  456. msgstr = []
  457. for index in sorted(e.msgstr_plural.keys()):
  458. msgstr.append(e.msgstr_plural[index])
  459. msgid += self._encode(e.msgid + '\0' + e.msgid_plural)
  460. msgstr = self._encode('\0'.join(msgstr))
  461. else:
  462. msgid += self._encode(e.msgid)
  463. msgstr = self._encode(e.msgstr)
  464. offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
  465. ids += msgid + b('\0')
  466. strs += msgstr + b('\0')
  467. # The header is 7 32-bit unsigned integers.
  468. keystart = 7 * 4 + 16 * entries_len
  469. # and the values start after the keys
  470. valuestart = keystart + len(ids)
  471. koffsets = []
  472. voffsets = []
  473. # The string table first has the list of keys, then the list of values.
  474. # Each entry has first the size of the string, then the file offset.
  475. for o1, l1, o2, l2 in offsets:
  476. koffsets += [l1, o1 + keystart]
  477. voffsets += [l2, o2 + valuestart]
  478. offsets = koffsets + voffsets
  479. output = struct.pack(
  480. "Iiiiiii",
  481. # Magic number
  482. MOFile.MAGIC,
  483. # Version
  484. 0,
  485. # number of entries
  486. entries_len,
  487. # start of key index
  488. 7 * 4,
  489. # start of value index
  490. 7 * 4 + entries_len * 8,
  491. # size and offset of hash table, we don't use hash tables
  492. 0, keystart
  493. )
  494. if PY3 and sys.version_info.minor > 1: # python 3.2 or superior
  495. output += array.array("i", offsets).tobytes()
  496. else:
  497. output += array.array("i", offsets).tostring()
  498. output += ids
  499. output += strs
  500. return output
  501. def _encode(self, mixed):
  502. """
  503. Encodes the given ``mixed`` argument with the file encoding if and
  504. only if it's an unicode string and returns the encoded string.
  505. """
  506. if isinstance(mixed, text_type):
  507. mixed = mixed.encode(self.encoding)
  508. return mixed
  509. # }}}
  510. # class POFile {{{
  511. class POFile(_BaseFile):
  512. """
  513. Po (or Pot) file reader/writer.
  514. This class inherits the :class:`~polib._BaseFile` class and, by extension,
  515. the python ``list`` type.
  516. """
  517. def __unicode__(self):
  518. """
  519. Returns the unicode representation of the po file.
  520. """
  521. ret, headers = '', self.header.split('\n')
  522. for header in headers:
  523. if not len(header):
  524. ret += "#\n"
  525. elif header[:1] in [',', ':']:
  526. ret += '#%s\n' % header
  527. else:
  528. ret += '# %s\n' % header
  529. if not isinstance(ret, text_type):
  530. ret = ret.decode(self.encoding)
  531. return ret + _BaseFile.__unicode__(self)
  532. def save_as_mofile(self, fpath):
  533. """
  534. Saves the binary representation of the file to given ``fpath``.
  535. Keyword argument:
  536. ``fpath``
  537. string, full or relative path to the mo file.
  538. """
  539. _BaseFile.save(self, fpath, 'to_binary')
  540. def percent_translated(self):
  541. """
  542. Convenience method that returns the percentage of translated
  543. messages.
  544. """
  545. total = len([e for e in self if not e.obsolete])
  546. if total == 0:
  547. return 100
  548. translated = len(self.translated_entries())
  549. return int(translated * 100 / float(total))
  550. def translated_entries(self):
  551. """
  552. Convenience method that returns the list of translated entries.
  553. """
  554. return [e for e in self if e.translated()]
  555. def untranslated_entries(self):
  556. """
  557. Convenience method that returns the list of untranslated entries.
  558. """
  559. return [e for e in self if not e.translated() and not e.obsolete
  560. and not 'fuzzy' in e.flags]
  561. def fuzzy_entries(self):
  562. """
  563. Convenience method that returns the list of fuzzy entries.
  564. """
  565. return [e for e in self if 'fuzzy' in e.flags]
  566. def obsolete_entries(self):
  567. """
  568. Convenience method that returns the list of obsolete entries.
  569. """
  570. return [e for e in self if e.obsolete]
  571. def merge(self, refpot):
  572. """
  573. Convenience method that merges the current pofile with the pot file
  574. provided. It behaves exactly as the gettext msgmerge utility:
  575. * comments of this file will be preserved, but extracted comments and
  576. occurrences will be discarded;
  577. * any translations or comments in the file will be discarded, however,
  578. dot comments and file positions will be preserved;
  579. * the fuzzy flags are preserved.
  580. Keyword argument:
  581. ``refpot``
  582. object POFile, the reference catalog.
  583. """
  584. # Store entries in dict/set for faster access
  585. self_entries = dict((entry.msgid, entry) for entry in self)
  586. refpot_msgids = set(entry.msgid for entry in refpot)
  587. # Merge entries that are in the refpot
  588. for entry in refpot:
  589. e = self_entries.get(entry.msgid)
  590. if e is None:
  591. e = POEntry()
  592. self.append(e)
  593. e.merge(entry)
  594. # ok, now we must "obsolete" entries that are not in the refpot anymore
  595. for entry in self:
  596. if entry.msgid not in refpot_msgids:
  597. entry.obsolete = True
  598. # }}}
  599. # class MOFile {{{
  600. class MOFile(_BaseFile):
  601. """
  602. Mo file reader/writer.
  603. This class inherits the :class:`~polib._BaseFile` class and, by
  604. extension, the python ``list`` type.
  605. """
  606. MAGIC = 0x950412de
  607. MAGIC_SWAPPED = 0xde120495
  608. def __init__(self, *args, **kwargs):
  609. """
  610. Constructor, accepts all keywords arguments accepted by
  611. :class:`~polib._BaseFile` class.
  612. """
  613. _BaseFile.__init__(self, *args, **kwargs)
  614. self.magic_number = None
  615. self.version = 0
  616. def save_as_pofile(self, fpath):
  617. """
  618. Saves the mofile as a pofile to ``fpath``.
  619. Keyword argument:
  620. ``fpath``
  621. string, full or relative path to the file.
  622. """
  623. _BaseFile.save(self, fpath)
  624. def save(self, fpath=None):
  625. """
  626. Saves the mofile to ``fpath``.
  627. Keyword argument:
  628. ``fpath``
  629. string, full or relative path to the file.
  630. """
  631. _BaseFile.save(self, fpath, 'to_binary')
  632. def percent_translated(self):
  633. """
  634. Convenience method to keep the same interface with POFile instances.
  635. """
  636. return 100
  637. def translated_entries(self):
  638. """
  639. Convenience method to keep the same interface with POFile instances.
  640. """
  641. return self
  642. def untranslated_entries(self):
  643. """
  644. Convenience method to keep the same interface with POFile instances.
  645. """
  646. return []
  647. def fuzzy_entries(self):
  648. """
  649. Convenience method to keep the same interface with POFile instances.
  650. """
  651. return []
  652. def obsolete_entries(self):
  653. """
  654. Convenience method to keep the same interface with POFile instances.
  655. """
  656. return []
  657. # }}}
  658. # class _BaseEntry {{{
  659. class _BaseEntry(object):
  660. """
  661. Base class for :class:`~polib.POEntry` and :class:`~polib.MOEntry` classes.
  662. This class should **not** be instantiated directly.
  663. """
  664. def __init__(self, *args, **kwargs):
  665. """
  666. Constructor, accepts the following keyword arguments:
  667. ``msgid``
  668. string, the entry msgid.
  669. ``msgstr``
  670. string, the entry msgstr.
  671. ``msgid_plural``
  672. string, the entry msgid_plural.
  673. ``msgstr_plural``
  674. list, the entry msgstr_plural lines.
  675. ``msgctxt``
  676. string, the entry context (msgctxt).
  677. ``obsolete``
  678. bool, whether the entry is "obsolete" or not.
  679. ``encoding``
  680. string, the encoding to use, defaults to ``default_encoding``
  681. global variable (optional).
  682. """
  683. self.msgid = kwargs.get('msgid', '')
  684. self.msgstr = kwargs.get('msgstr', '')
  685. self.msgid_plural = kwargs.get('msgid_plural', '')
  686. self.msgstr_plural = kwargs.get('msgstr_plural', {})
  687. self.msgctxt = kwargs.get('msgctxt', None)
  688. self.obsolete = kwargs.get('obsolete', False)
  689. self.encoding = kwargs.get('encoding', default_encoding)
  690. def __unicode__(self, wrapwidth=78):
  691. """
  692. Returns the unicode representation of the entry.
  693. """
  694. if self.obsolete:
  695. delflag = '#~ '
  696. else:
  697. delflag = ''
  698. ret = []
  699. # write the msgctxt if any
  700. if self.msgctxt is not None:
  701. ret += self._str_field("msgctxt", delflag, "", self.msgctxt,
  702. wrapwidth)
  703. # write the msgid
  704. ret += self._str_field("msgid", delflag, "", self.msgid, wrapwidth)
  705. # write the msgid_plural if any
  706. if self.msgid_plural:
  707. ret += self._str_field("msgid_plural", delflag, "",
  708. self.msgid_plural, wrapwidth)
  709. if self.msgstr_plural:
  710. # write the msgstr_plural if any
  711. msgstrs = self.msgstr_plural
  712. keys = list(msgstrs)
  713. keys.sort()
  714. for index in keys:
  715. msgstr = msgstrs[index]
  716. plural_index = '[%s]' % index
  717. ret += self._str_field("msgstr", delflag, plural_index, msgstr,
  718. wrapwidth)
  719. else:
  720. # otherwise write the msgstr
  721. ret += self._str_field("msgstr", delflag, "", self.msgstr,
  722. wrapwidth)
  723. ret.append('')
  724. ret = u('\n').join(ret)
  725. return ret
  726. if PY3:
  727. def __str__(self):
  728. return self.__unicode__()
  729. else:
  730. def __str__(self):
  731. """
  732. Returns the string representation of the entry.
  733. """
  734. return unicode(self).encode(self.encoding)
  735. def __eq__(self, other):
  736. return str(self) == str(other)
  737. def _str_field(self, fieldname, delflag, plural_index, field,
  738. wrapwidth=78):
  739. lines = field.splitlines(True)
  740. if len(lines) > 1:
  741. lines = [''] + lines # start with initial empty line
  742. else:
  743. escaped_field = escape(field)
  744. specialchars_count = 0
  745. for c in ['\\', '\n', '\r', '\t', '"']:
  746. specialchars_count += field.count(c)
  747. # comparison must take into account fieldname length + one space
  748. # + 2 quotes (eg. msgid "<string>")
  749. flength = len(fieldname) + 3
  750. if plural_index:
  751. flength += len(plural_index)
  752. real_wrapwidth = wrapwidth - flength + specialchars_count
  753. if wrapwidth > 0 and len(field) > real_wrapwidth:
  754. # Wrap the line but take field name into account
  755. lines = [''] + [unescape(item) for item in wrap(
  756. escaped_field,
  757. wrapwidth - 2, # 2 for quotes ""
  758. drop_whitespace=False,
  759. break_long_words=False
  760. )]
  761. else:
  762. lines = [field]
  763. if fieldname.startswith('previous_'):
  764. # quick and dirty trick to get the real field name
  765. fieldname = fieldname[9:]
  766. ret = ['%s%s%s "%s"' % (delflag, fieldname, plural_index,
  767. escape(lines.pop(0)))]
  768. for line in lines:
  769. ret.append('%s"%s"' % (delflag, escape(line)))
  770. return ret
  771. # }}}
  772. # class POEntry {{{
  773. class POEntry(_BaseEntry):
  774. """
  775. Represents a po file entry.
  776. """
  777. def __init__(self, *args, **kwargs):
  778. """
  779. Constructor, accepts the following keyword arguments:
  780. ``comment``
  781. string, the entry comment.
  782. ``tcomment``
  783. string, the entry translator comment.
  784. ``occurrences``
  785. list, the entry occurrences.
  786. ``flags``
  787. list, the entry flags.
  788. ``previous_msgctxt``
  789. string, the entry previous context.
  790. ``previous_msgid``
  791. string, the entry previous msgid.
  792. ``previous_msgid_plural``
  793. string, the entry previous msgid_plural.
  794. ``linenum``
  795. integer, the line number of the entry
  796. """
  797. _BaseEntry.__init__(self, *args, **kwargs)
  798. self.comment = kwargs.get('comment', '')
  799. self.tcomment = kwargs.get('tcomment', '')
  800. self.occurrences = kwargs.get('occurrences', [])
  801. self.flags = kwargs.get('flags', [])
  802. self.previous_msgctxt = kwargs.get('previous_msgctxt', None)
  803. self.previous_msgid = kwargs.get('previous_msgid', None)
  804. self.previous_msgid_plural = kwargs.get('previous_msgid_plural', None)
  805. self.linenum = kwargs.get('linenum', None)
  806. def __unicode__(self, wrapwidth=78):
  807. """
  808. Returns the unicode representation of the entry.
  809. """
  810. ret = []
  811. # comments first, if any (with text wrapping as xgettext does)
  812. if self.obsolete:
  813. comments = [('tcomment', '# ')]
  814. else:
  815. comments = [('comment', '#. '), ('tcomment', '# ')]
  816. for c in comments:
  817. val = getattr(self, c[0])
  818. if val:
  819. for comment in val.split('\n'):
  820. if wrapwidth > 0 and len(comment) + len(c[1]) > wrapwidth:
  821. ret += wrap(
  822. comment,
  823. wrapwidth,
  824. initial_indent=c[1],
  825. subsequent_indent=c[1],
  826. break_long_words=False
  827. )
  828. else:
  829. ret.append('%s%s' % (c[1], comment))
  830. # occurrences (with text wrapping as xgettext does)
  831. if not self.obsolete and self.occurrences:
  832. filelist = []
  833. for fpath, lineno in self.occurrences:
  834. if lineno:
  835. filelist.append('%s:%s' % (fpath, lineno))
  836. else:
  837. filelist.append(fpath)
  838. filestr = ' '.join(filelist)
  839. if wrapwidth > 0 and len(filestr) + 3 > wrapwidth:
  840. # textwrap split words that contain hyphen, this is not
  841. # what we want for filenames, so the dirty hack is to
  842. # temporally replace hyphens with a char that a file cannot
  843. # contain, like "*"
  844. ret += [l.replace('*', '-') for l in wrap(
  845. filestr.replace('-', '*'),
  846. wrapwidth,
  847. initial_indent='#: ',
  848. subsequent_indent='#: ',
  849. break_long_words=False
  850. )]
  851. else:
  852. ret.append('#: ' + filestr)
  853. # flags (TODO: wrapping ?)
  854. if self.flags:
  855. ret.append('#, %s' % ', '.join(self.flags))
  856. # previous context and previous msgid/msgid_plural
  857. fields = ['previous_msgctxt', 'previous_msgid',
  858. 'previous_msgid_plural']
  859. if self.obsolete:
  860. prefix = "#~| "
  861. else:
  862. prefix = "#| "
  863. for f in fields:
  864. val = getattr(self, f)
  865. if val:
  866. ret += self._str_field(f, prefix, "", val, wrapwidth)
  867. ret.append(_BaseEntry.__unicode__(self, wrapwidth))
  868. ret = u('\n').join(ret)
  869. return ret
  870. def __cmp__(self, other):
  871. """
  872. Called by comparison operations if rich comparison is not defined.
  873. """
  874. # First: Obsolete test
  875. if self.obsolete != other.obsolete:
  876. if self.obsolete:
  877. return -1
  878. else:
  879. return 1
  880. # Work on a copy to protect original
  881. occ1 = sorted(self.occurrences[:])
  882. occ2 = sorted(other.occurrences[:])
  883. pos = 0
  884. for entry1 in occ1:
  885. try:
  886. entry2 = occ2[pos]
  887. except IndexError:
  888. return 1
  889. pos = pos + 1
  890. if entry1[0] != entry2[0]:
  891. if entry1[0] > entry2[0]:
  892. return 1
  893. else:
  894. return -1
  895. if entry1[1] != entry2[1]:
  896. if entry1[1] > entry2[1]:
  897. return 1
  898. else:
  899. return -1
  900. # Compare msgid_plural if set
  901. if self.msgid_plural:
  902. if not other.msgid_plural:
  903. return 1
  904. for pos in self.msgid_plural:
  905. if pos not in other.msgid_plural:
  906. return 1
  907. if self.msgid_plural[pos] > other.msgid_plural[pos]:
  908. return 1
  909. if self.msgid_plural[pos] < other.msgid_plural[pos]:
  910. return -1
  911. # Finally: Compare message ID
  912. if self.msgid > other.msgid:
  913. return 1
  914. elif self.msgid < other.msgid:
  915. return -1
  916. return 0
  917. def __gt__(self, other):
  918. return self.__cmp__(other) > 0
  919. def __lt__(self, other):
  920. return self.__cmp__(other) < 0
  921. def __ge__(self, other):
  922. return self.__cmp__(other) >= 0
  923. def __le__(self, other):
  924. return self.__cmp__(other) <= 0
  925. def __eq__(self, other):
  926. return self.__cmp__(other) == 0
  927. def __ne__(self, other):
  928. return self.__cmp__(other) != 0
  929. def translated(self):
  930. """
  931. Returns ``True`` if the entry has been translated or ``False``
  932. otherwise.
  933. """
  934. if self.obsolete or 'fuzzy' in self.flags:
  935. return False
  936. if self.msgstr != '':
  937. return True
  938. if self.msgstr_plural:
  939. for pos in self.msgstr_plural:
  940. if self.msgstr_plural[pos] == '':
  941. return False
  942. return True
  943. return False
  944. def merge(self, other):
  945. """
  946. Merge the current entry with the given pot entry.
  947. """
  948. self.msgid = other.msgid
  949. self.msgctxt = other.msgctxt
  950. self.occurrences = other.occurrences
  951. self.comment = other.comment
  952. fuzzy = 'fuzzy' in self.flags
  953. self.flags = other.flags[:] # clone flags
  954. if fuzzy:
  955. self.flags.append('fuzzy')
  956. self.msgid_plural = other.msgid_plural
  957. self.obsolete = other.obsolete
  958. self.previous_msgctxt = other.previous_msgctxt
  959. self.previous_msgid = other.previous_msgid
  960. self.previous_msgid_plural = other.previous_msgid_plural
  961. if other.msgstr_plural:
  962. for pos in other.msgstr_plural:
  963. try:
  964. # keep existing translation at pos if any
  965. self.msgstr_plural[pos]
  966. except KeyError:
  967. self.msgstr_plural[pos] = ''
  968. def __hash__(self):
  969. return hash((self.msgid, self.msgstr))
  970. # }}}
  971. # class MOEntry {{{
  972. class MOEntry(_BaseEntry):
  973. """
  974. Represents a mo file entry.
  975. """
  976. def __init__(self, *args, **kwargs):
  977. """
  978. Constructor, accepts the following keyword arguments,
  979. for consistency with :class:`~polib.POEntry`:
  980. ``comment``
  981. ``tcomment``
  982. ``occurrences``
  983. ``flags``
  984. ``previous_msgctxt``
  985. ``previous_msgid``
  986. ``previous_msgid_plural``
  987. Note: even though these keyword arguments are accepted,
  988. they hold no real meaning in the context of MO files
  989. and are simply ignored.
  990. """
  991. _BaseEntry.__init__(self, *args, **kwargs)
  992. self.comment = ''
  993. self.tcomment = ''
  994. self.occurrences = []
  995. self.flags = []
  996. self.previous_msgctxt = None
  997. self.previous_msgid = None
  998. self.previous_msgid_plural = None
  999. def __hash__(self):
  1000. return hash((self.msgid, self.msgstr))
  1001. # }}}
  1002. # class _POFileParser {{{
  1003. class _POFileParser(object):
  1004. """
  1005. A finite state machine to parse efficiently and correctly po
  1006. file format.
  1007. """
  1008. def __init__(self, pofile, *args, **kwargs):
  1009. """
  1010. Constructor.
  1011. Keyword arguments:
  1012. ``pofile``
  1013. string, path to the po file or its content
  1014. ``encoding``
  1015. string, the encoding to use, defaults to ``default_encoding``
  1016. global variable (optional).
  1017. ``check_for_duplicates``
  1018. whether to check for duplicate entries when adding entries to the
  1019. file (optional, default: ``False``).
  1020. """
  1021. enc = kwargs.get('encoding', default_encoding)
  1022. if _is_file(pofile):
  1023. try:
  1024. self.fhandle = io.open(pofile, 'rt', encoding=enc)
  1025. except LookupError:
  1026. enc = default_encoding
  1027. self.fhandle = io.open(pofile, 'rt', encoding=enc)
  1028. else:
  1029. self.fhandle = pofile.splitlines()
  1030. klass = kwargs.get('klass')
  1031. if klass is None:
  1032. klass = POFile
  1033. self.instance = klass(
  1034. pofile=pofile,
  1035. encoding=enc,
  1036. check_for_duplicates=kwargs.get('check_for_duplicates', False)
  1037. )
  1038. self.transitions = {}
  1039. self.current_line = 0
  1040. self.current_entry = POEntry(linenum=self.current_line)
  1041. self.current_state = 'st'
  1042. self.current_token = None
  1043. # two memo flags used in handlers
  1044. self.msgstr_index = 0
  1045. self.entry_obsolete = 0
  1046. # Configure the state machine, by adding transitions.
  1047. # Signification of symbols:
  1048. # * ST: Beginning of the file (start)
  1049. # * HE: Header
  1050. # * TC: a translation comment
  1051. # * GC: a generated comment
  1052. # * OC: a file/line occurrence
  1053. # * FL: a flags line
  1054. # * CT: a message context
  1055. # * PC: a previous msgctxt
  1056. # * PM: a previous msgid
  1057. # * PP: a previous msgid_plural
  1058. # * MI: a msgid
  1059. # * MP: a msgid plural
  1060. # * MS: a msgstr
  1061. # * MX: a msgstr plural
  1062. # * MC: a msgid or msgstr continuation line
  1063. all = ['st', 'he', 'gc', 'oc', 'fl', 'ct', 'pc', 'pm', 'pp', 'tc',
  1064. 'ms', 'mp', 'mx', 'mi']
  1065. self.add('tc', ['st', 'he'], 'he')
  1066. self.add('tc', ['gc', 'oc', 'fl', 'tc', 'pc', 'pm', 'pp', 'ms',
  1067. 'mp', 'mx', 'mi'], 'tc')
  1068. self.add('gc', all, 'gc')
  1069. self.add('oc', all, 'oc')
  1070. self.add('fl', all, 'fl')
  1071. self.add('pc', all, 'pc')
  1072. self.add('pm', all, 'pm')
  1073. self.add('pp', all, 'pp')
  1074. self.add('ct', ['st', 'he', 'gc', 'oc', 'fl', 'tc', 'pc', 'pm',
  1075. 'pp', 'ms', 'mx'], 'ct')
  1076. self.add('mi', ['st', 'he', 'gc', 'oc', 'fl', 'ct', 'tc', 'pc',
  1077. 'pm', 'pp', 'ms', 'mx'], 'mi')
  1078. self.add('mp', ['tc', 'gc', 'pc', 'pm', 'pp', 'mi'], 'mp')
  1079. self.add('ms', ['mi', 'mp', 'tc'], 'ms')
  1080. self.add('mx', ['mi', 'mx', 'mp', 'tc'], 'mx')
  1081. self.add('mc', ['ct', 'mi', 'mp', 'ms', 'mx', 'pm', 'pp', 'pc'], 'mc')
  1082. def parse(self):
  1083. """
  1084. Run the state machine, parse the file line by line and call process()
  1085. with the current matched symbol.
  1086. """
  1087. keywords = {
  1088. 'msgctxt': 'ct',
  1089. 'msgid': 'mi',
  1090. 'msgstr': 'ms',
  1091. 'msgid_plural': 'mp',
  1092. }
  1093. prev_keywords = {
  1094. 'msgid_plural': 'pp',
  1095. 'msgid': 'pm',
  1096. 'msgctxt': 'pc',
  1097. }
  1098. tokens = []
  1099. for line in self.fhandle:
  1100. self.current_line += 1
  1101. line = line.strip()
  1102. if line == '':
  1103. continue
  1104. tokens = line.split(None, 2)
  1105. nb_tokens = len(tokens)
  1106. if tokens[0] == '#~|':
  1107. continue
  1108. if tokens[0] == '#~' and nb_tokens > 1:
  1109. line = line[3:].strip()
  1110. tokens = tokens[1:]
  1111. nb_tokens -= 1
  1112. self.entry_obsolete = 1
  1113. else:
  1114. self.entry_obsolete = 0
  1115. # Take care of keywords like
  1116. # msgid, msgid_plural, msgctxt & msgstr.
  1117. if tokens[0] in keywords and nb_tokens > 1:
  1118. line = line[len(tokens[0]):].lstrip()
  1119. if re.search(r'([^\\]|^)"', line[1:-1]):
  1120. raise IOError('Syntax error in po file %s (line %s): '
  1121. 'unescaped double quote found' %
  1122. (self.instance.fpath, self.current_line))
  1123. self.current_token = line
  1124. self.process(keywords[tokens[0]])
  1125. continue
  1126. self.current_token = line
  1127. if tokens[0] == '#:':
  1128. if nb_tokens <= 1:
  1129. continue
  1130. # we are on a occurrences line
  1131. self.process('oc')
  1132. elif line[:1] == '"':
  1133. # we are on a continuation line
  1134. if re.search(r'([^\\]|^)"', line[1:-1]):
  1135. raise IOError('Syntax error in po file %s (line %s): '
  1136. 'unescaped double quote found' %
  1137. (self.instance.fpath, self.current_line))
  1138. self.process('mc')
  1139. elif line[:7] == 'msgstr[':
  1140. # we are on a msgstr plural
  1141. self.process('mx')
  1142. elif tokens[0] == '#,':
  1143. if nb_tokens <= 1:
  1144. continue
  1145. # we are on a flags line
  1146. self.process('fl')
  1147. elif tokens[0] == '#' or tokens[0].startswith('##'):
  1148. if line == '#':
  1149. line += ' '
  1150. # we are on a translator comment line
  1151. self.process('tc')
  1152. elif tokens[0] == '#.':
  1153. if nb_tokens <= 1:
  1154. continue
  1155. # we are on a generated comment line
  1156. self.process('gc')
  1157. elif tokens[0] == '#|':
  1158. if nb_tokens <= 1:
  1159. raise IOError('Syntax error in po file %s (line %s)' %
  1160. (self.instance.fpath, self.current_line))
  1161. # Remove the marker and any whitespace right after that.
  1162. line = line[2:].lstrip()
  1163. self.current_token = line
  1164. if tokens[1].startswith('"'):
  1165. # Continuation of previous metadata.
  1166. self.process('mc')
  1167. continue
  1168. if nb_tokens == 2:
  1169. # Invalid continuation line.
  1170. raise IOError('Syntax error in po file %s (line %s): '
  1171. 'invalid continuation line' %
  1172. (self.instance.fpath, self.current_line))
  1173. # we are on a "previous translation" comment line,
  1174. if tokens[1] not in prev_keywords:
  1175. # Unknown keyword in previous translation comment.
  1176. raise IOError('Syntax error in po file %s (line %s): '
  1177. 'unknown keyword %s' %
  1178. (self.instance.fpath, self.current_line,
  1179. tokens[1]))
  1180. # Remove the keyword and any whitespace
  1181. # between it and the starting quote.
  1182. line = line[len(tokens[1]):].lstrip()
  1183. self.current_token = line
  1184. self.process(prev_keywords[tokens[1]])
  1185. else:
  1186. raise IOError('Syntax error in po file %s (line %s)' %
  1187. (self.instance.fpath, self.current_line))
  1188. if self.current_entry and len(tokens) > 0 and \
  1189. not tokens[0].startswith('#'):
  1190. # since entries are added when another entry is found, we must add
  1191. # the last entry here (only if there are lines). Trailing comments
  1192. # are ignored
  1193. self.instance.append(self.current_entry)
  1194. # before returning the instance, check if there's metadata and if
  1195. # so extract it in a dict
  1196. metadataentry = self.instance.find('')
  1197. if metadataentry: # metadata found
  1198. # remove the entry
  1199. self.instance.remove(metadataentry)
  1200. self.instance.metadata_is_fuzzy = metadataentry.flags
  1201. key = None
  1202. for msg in metadataentry.msgstr.splitlines():
  1203. try:
  1204. key, val = msg.split(':', 1)
  1205. self.instance.metadata[key] = val.strip()
  1206. except (ValueError, KeyError):
  1207. if key is not None:
  1208. self.instance.metadata[key] += '\n' + msg.strip()
  1209. # close opened file
  1210. if not isinstance(self.fhandle, list): # must be file
  1211. self.fhandle.close()
  1212. return self.instance
  1213. def add(self, symbol, states, next_state):
  1214. """
  1215. Add a transition to the state machine.
  1216. Keywords arguments:
  1217. ``symbol``
  1218. string, the matched token (two chars symbol).
  1219. ``states``
  1220. list, a list of states (two chars symbols).
  1221. ``next_state``
  1222. the next state the fsm will have after the action.
  1223. """
  1224. for state in states:
  1225. action = getattr(self, 'handle_%s' % next_state)
  1226. self.transitions[(symbol, state)] = (action, next_state)
  1227. def process(self, symbol):
  1228. """
  1229. Process the transition corresponding to the current state and the
  1230. symbol provided.
  1231. Keywords arguments:
  1232. ``symbol``
  1233. string, the matched token (two chars symbol).
  1234. ``linenum``
  1235. integer, the current line number of the parsed file.
  1236. """
  1237. try:
  1238. (action, state) = self.transitions[(symbol, self.current_state)]
  1239. if action():
  1240. self.current_state = state
  1241. except Exception:
  1242. raise IOError('Syntax error in po file (line %s)' %
  1243. self.current_line)
  1244. # state handlers
  1245. def handle_he(self):
  1246. """Handle a header comment."""
  1247. if self.instance.header != '':
  1248. self.instance.header += '\n'
  1249. self.instance.header += self.current_token[2:]
  1250. return 1
  1251. def handle_tc(self):
  1252. """Handle a translator comment."""
  1253. if self.current_state in ['mc', 'ms', 'mx']:
  1254. self.instance.append(self.current_entry)
  1255. self.current_entry = POEntry(linenum=self.current_line)
  1256. if self.current_entry.tcomment != '':
  1257. self.current_entry.tcomment += '\n'
  1258. tcomment = self.current_token.lstrip('#')
  1259. if tcomment.startswith(' '):
  1260. tcomment = tcomment[1:]
  1261. self.current_entry.tcomment += tcomment
  1262. return True
  1263. def handle_gc(self):
  1264. """Handle a generated comment."""
  1265. if self.current_state in ['mc', 'ms', 'mx']:
  1266. self.instance.append(self.current_entry)
  1267. self.current_entry = POEntry(linenum=self.current_line)
  1268. if self.current_entry.comment != '':
  1269. self.current_entry.comment += '\n'
  1270. self.current_entry.comment += self.current_token[3:]
  1271. return True
  1272. def handle_oc(self):
  1273. """Handle a file:num occurrence."""
  1274. if self.current_state in ['mc', 'ms', 'mx']:
  1275. self.instance.append(self.current_entry)
  1276. self.current_entry = POEntry(linenum=self.current_line)
  1277. occurrences = self.current_token[3:].split()
  1278. for occurrence in occurrences:
  1279. if occurrence != '':
  1280. try:
  1281. fil, line = occurrence.rsplit(':', 1)
  1282. if not line.isdigit():
  1283. fil = fil + line
  1284. line = ''
  1285. self.current_entry.occurrences.append((fil, line))
  1286. except (ValueError, AttributeError):
  1287. self.current_entry.occurrences.append((occurrence, ''))
  1288. return True
  1289. def handle_fl(self):
  1290. """Handle a flags line."""
  1291. if self.current_state in ['mc', 'ms', 'mx']:
  1292. self.instance.append(self.current_entry)
  1293. self.current_entry = POEntry(linenum=self.current_line)
  1294. self.current_entry.flags += [c.strip() for c in
  1295. self.current_token[3:].split(',')]
  1296. return True
  1297. def handle_pp(self):
  1298. """Handle a previous msgid_plural line."""
  1299. if self.current_state in ['mc', 'ms', 'mx']:
  1300. self.instance.append(self.current_entry)
  1301. self.current_entry = POEntry(linenum=self.current_line)
  1302. self.current_entry.previous_msgid_plural = \
  1303. unescape(self.current_token[1:-1])
  1304. return True
  1305. def handle_pm(self):
  1306. """Handle a previous msgid line."""
  1307. if self.current_state in ['mc', 'ms', 'mx']:
  1308. self.instance.append(self.current_entry)
  1309. self.current_entry = POEntry(linenum=self.current_line)
  1310. self.current_entry.previous_msgid = \
  1311. unescape(self.current_token[1:-1])
  1312. return True
  1313. def handle_pc(self):
  1314. """Handle a previous msgctxt line."""
  1315. if self.current_state in ['mc', 'ms', 'mx']:
  1316. self.instance.append(self.current_entry)
  1317. self.current_entry = POEntry(linenum=self.current_line)
  1318. self.current_entry.previous_msgctxt = \
  1319. unescape(self.current_token[1:-1])
  1320. return True
  1321. def handle_ct(self):
  1322. """Handle a msgctxt."""
  1323. if self.current_state in ['mc', 'ms', 'mx']:
  1324. self.instance.append(self.current_entry)
  1325. self.current_entry = POEntry(linenum=self.current_line)
  1326. self.current_entry.msgctxt = unescape(self.current_token[1:-1])
  1327. return True
  1328. def handle_mi(self):
  1329. """Handle a msgid."""
  1330. if self.current_state in ['mc', 'ms', 'mx']:
  1331. self.instance.append(self.current_entry)
  1332. self.current_entry = POEntry(linenum=self.current_line)
  1333. self.current_entry.obsolete = self.entry_obsolete
  1334. self.current_entry.msgid = unescape(self.current_token[1:-1])
  1335. return True
  1336. def handle_mp(self):
  1337. """Handle a msgid plural."""
  1338. self.current_entry.msgid_plural = unescape(self.current_token[1:-1])
  1339. return True
  1340. def handle_ms(self):
  1341. """Handle a msgstr."""
  1342. self.current_entry.msgstr = unescape(self.current_token[1:-1])
  1343. return True
  1344. def handle_mx(self):
  1345. """Handle a msgstr plural."""
  1346. index = self.current_token[7]
  1347. value = self.current_token[self.current_token.find('"') + 1:-1]
  1348. self.current_entry.msgstr_plural[int(index)] = unescape(value)
  1349. self.msgstr_index = int(index)
  1350. return True
  1351. def handle_mc(self):
  1352. """Handle a msgid or msgstr continuation line."""
  1353. token = unescape(self.current_token[1:-1])
  1354. if self.current_state == 'ct':
  1355. self.current_entry.msgctxt += token
  1356. elif self.current_state == 'mi':
  1357. self.current_entry.msgid += token
  1358. elif self.current_state == 'mp':
  1359. self.current_entry.msgid_plural += token
  1360. elif self.current_state == 'ms':
  1361. self.current_entry.msgstr += token
  1362. elif self.current_state == 'mx':
  1363. self.current_entry.msgstr_plural[self.msgstr_index] += token
  1364. elif self.current_state == 'pp':
  1365. self.current_entry.previous_msgid_plural += token
  1366. elif self.current_state == 'pm':
  1367. self.current_entry.previous_msgid += token
  1368. elif self.current_state == 'pc':
  1369. self.current_entry.previous_msgctxt += token
  1370. # don't change the current state
  1371. return False
  1372. # }}}
  1373. # class _MOFileParser {{{
  1374. class _MOFileParser(object):
  1375. """
  1376. A class to parse binary mo files.
  1377. """
  1378. def __init__(self, mofile, *args, **kwargs):
  1379. """
  1380. Constructor.
  1381. Keyword arguments:
  1382. ``mofile``
  1383. string, path to the mo file or its content
  1384. ``encoding``
  1385. string, the encoding to use, defaults to ``default_encoding``
  1386. global variable (optional).
  1387. ``check_for_duplicates``
  1388. whether to check for duplicate entries when adding entries to the
  1389. file (optional, default: ``False``).
  1390. """
  1391. self.fhandle = open(mofile, 'rb')
  1392. klass = kwargs.get('klass')
  1393. if klass is None:
  1394. klass = MOFile
  1395. self.instance = klass(
  1396. fpath=mofile,
  1397. encoding=kwargs.get('encoding', default_encoding),
  1398. check_for_duplicates=kwargs.get('check_for_duplicates', False)
  1399. )
  1400. def __del__(self):
  1401. """
  1402. Make sure the file is closed, this prevents warnings on unclosed file
  1403. when running tests with python >= 3.2.
  1404. """
  1405. if self.fhandle:
  1406. self.fhandle.close()
  1407. def parse(self):
  1408. """
  1409. Build the instance with the file handle provided in the
  1410. constructor.
  1411. """
  1412. # parse magic number
  1413. magic_number = self._readbinary('<I', 4)
  1414. if magic_number == MOFile.MAGIC:
  1415. ii = '<II'
  1416. elif magic_number == MOFile.MAGIC_SWAPPED:
  1417. ii = '>II'
  1418. else:
  1419. raise IOError('Invalid mo file, magic number is incorrect !')
  1420. self.instance.magic_number = magic_number
  1421. # parse the version number and the number of strings
  1422. version, numofstrings = self._readbinary(ii, 8)
  1423. # from MO file format specs: "A program seeing an unexpected major
  1424. # revision number should stop reading the MO file entirely"
  1425. if version not in (0, 1):
  1426. raise IOError('Invalid mo file, unexpected major revision number')
  1427. self.instance.version = version
  1428. # original strings and translation strings hash table offset
  1429. msgids_hash_offset, msgstrs_hash_offset = self._readbinary(ii, 8)
  1430. # move to msgid hash table and read length and offset of msgids
  1431. self.fhandle.seek(msgids_hash_offset)
  1432. msgids_index = []
  1433. for i in range(numofstrings):
  1434. msgids_index.append(self._readbinary(ii, 8))
  1435. # move to msgstr hash table and read length and offset of msgstrs
  1436. self.fhandle.seek(msgstrs_hash_offset)
  1437. msgstrs_index = []
  1438. for i in range(numofstrings):
  1439. msgstrs_index.append(self._readbinary(ii, 8))
  1440. # build entries
  1441. encoding = self.instance.encoding
  1442. for i in range(numofstrings):
  1443. self.fhandle.seek(msgids_index[i][1])
  1444. msgid = self.fhandle.read(msgids_index[i][0])
  1445. self.fhandle.seek(msgstrs_index[i][1])
  1446. msgstr = self.fhandle.read(msgstrs_index[i][0])
  1447. if i == 0 and not msgid: # metadata
  1448. raw_metadata, metadata = msgstr.split(b('\n')), {}
  1449. for line in raw_metadata:
  1450. tokens = line.split(b(':'), 1)
  1451. if tokens[0] != b(''):
  1452. try:
  1453. k = tokens[0].decode(encoding)
  1454. v = tokens[1].decode(encoding)
  1455. metadata[k] = v.strip()
  1456. except IndexError:
  1457. metadata[k] = u('')
  1458. self.instance.metadata = metadata
  1459. continue
  1460. # test if we have a plural entry
  1461. msgid_tokens = msgid.split(b('\0'))
  1462. if len(msgid_tokens) > 1:
  1463. entry = self._build_entry(
  1464. msgid=msgid_tokens[0],
  1465. msgid_plural=msgid_tokens[1],
  1466. msgstr_plural=dict((k, v) for k, v in
  1467. enumerate(msgstr.split(b('\0'))))
  1468. )
  1469. else:
  1470. entry = self._build_entry(msgid=msgid, msgstr=msgstr)
  1471. self.instance.append(entry)
  1472. # close opened file
  1473. self.fhandle.close()
  1474. return self.instance
  1475. def _build_entry(self, msgid, msgstr=None, msgid_plural=None,
  1476. msgstr_plural=None):
  1477. msgctxt_msgid = msgid.split(b('\x04'))
  1478. encoding = self.instance.encoding
  1479. if len(msgctxt_msgid) > 1:
  1480. kwargs = {
  1481. 'msgctxt': msgctxt_msgid[0].decode(encoding),
  1482. 'msgid': msgctxt_msgid[1].decode(encoding),
  1483. }
  1484. else:
  1485. kwargs = {'msgid': msgid.decode(encoding)}
  1486. if msgstr:
  1487. kwargs['msgstr'] = msgstr.decode(encoding)
  1488. if msgid_plural:
  1489. kwargs['msgid_plural'] = msgid_plural.decode(encoding)
  1490. if msgstr_plural:
  1491. for k in msgstr_plural:
  1492. msgstr_plural[k] = msgstr_plural[k].decode(encoding)
  1493. kwargs['msgstr_plural'] = msgstr_plural
  1494. return MOEntry(**kwargs)
  1495. def _readbinary(self, fmt, numbytes):
  1496. """
  1497. Private method that unpack n bytes of data using format <fmt>.
  1498. It returns a tuple or a mixed value if the tuple length is 1.
  1499. """
  1500. bytes = self.fhandle.read(numbytes)
  1501. tup = struct.unpack(fmt, bytes)
  1502. if len(tup) == 1:
  1503. return tup[0]
  1504. return tup
  1505. # }}}
  1506. # class TextWrapper {{{
  1507. class TextWrapper(textwrap.TextWrapper):
  1508. """
  1509. Subclass of textwrap.TextWrapper that backport the
  1510. drop_whitespace option.
  1511. """
  1512. def __init__(self, *args, **kwargs):
  1513. drop_whitespace = kwargs.pop('drop_whitespace', True)
  1514. textwrap.TextWrapper.__init__(self, *args, **kwargs)
  1515. self.drop_whitespace = drop_whitespace
  1516. def _wrap_chunks(self, chunks):
  1517. """_wrap_chunks(chunks : [string]) -> [string]
  1518. Wrap a sequence of text chunks and return a list of lines of
  1519. length 'self.width' or less. (If 'break_long_words' is false,
  1520. some lines may be longer than this.) Chunks correspond roughly
  1521. to words and the whitespace between them: each chunk is
  1522. indivisible (modulo 'break_long_words'), but a line break can
  1523. come between any two chunks. Chunks should not have internal
  1524. whitespace; ie. a chunk is either all whitespace or a "word".
  1525. Whitespace chunks will be removed from the beginning and end of
  1526. lines, but apart from that whitespace is preserved.
  1527. """
  1528. lines = []
  1529. if self.width <= 0:
  1530. raise ValueError("invalid width %r (must be > 0)" % self.width)
  1531. # Arrange in reverse order so items can be efficiently popped
  1532. # from a stack of chucks.
  1533. chunks.reverse()
  1534. while chunks:
  1535. # Start the list of chunks that will make up the current line.
  1536. # cur_len is just the length of all the chunks in cur_line.
  1537. cur_line = []
  1538. cur_len = 0
  1539. # Figure out which static string will prefix this line.
  1540. if lines:
  1541. indent = self.subsequent_indent
  1542. else:
  1543. indent = self.initial_indent
  1544. # Maximum width for this line.
  1545. width = self.width - len(indent)
  1546. # First chunk on line is whitespace -- drop it, unless this
  1547. # is the very beginning of the text (ie. no lines started yet).
  1548. if self.drop_whitespace and chunks[-1].strip() == '' and lines:
  1549. del chunks[-1]
  1550. while chunks:
  1551. l = len(chunks[-1])
  1552. # Can at least squeeze this chunk onto the current line.
  1553. if cur_len + l <= width:
  1554. cur_line.append(chunks.pop())
  1555. cur_len += l
  1556. # Nope, this line is full.
  1557. else:
  1558. break
  1559. # The current line is full, and the next chunk is too big to
  1560. # fit on *any* line (not just this one).
  1561. if chunks and len(chunks[-1]) > width:
  1562. self._handle_long_word(chunks, cur_line, cur_len, width)
  1563. # If the last chunk on this line is all whitespace, drop it.
  1564. if self.drop_whitespace and cur_line and not cur_line[-1].strip():
  1565. del cur_line[-1]
  1566. # Convert current line back to a string and store it in list
  1567. # of all lines (return value).
  1568. if cur_line:
  1569. lines.append(indent + ''.join(cur_line))
  1570. return lines
  1571. # }}}
  1572. # function wrap() {{{
  1573. def wrap(text, width=70, **kwargs):
  1574. """
  1575. Wrap a single paragraph of text, returning a list of wrapped lines.
  1576. """
  1577. if sys.version_info < (2, 6):
  1578. return TextWrapper(width=width, **kwargs).wrap(text)
  1579. return textwrap.wrap(text, width=width, **kwargs)
  1580. # }}}