pygettext.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. #! /usr/bin/env python3
  2. # -*- coding: iso-8859-1 -*-
  3. # Originally written by Barry Warsaw <barry@python.org>
  4. #
  5. # Minimally patched to make it even more xgettext compatible
  6. # by Peter Funk <pf@artcom-gmbh.de>
  7. #
  8. # 2002-11-22 Jürgen Hermann <jh@web.de>
  9. # Added checks that _() only contains string literals, and
  10. # command line args are resolved to module lists, i.e. you
  11. # can now pass a filename, a module or package name, or a
  12. # directory (including globbing chars, important for Win32).
  13. # Made docstring fit in 80 chars wide displays using pydoc.
  14. #
  15. # for selftesting
  16. try:
  17. import fintl
  18. _ = fintl.gettext
  19. except ImportError:
  20. _ = lambda s: s
  21. __doc__ = _("""pygettext -- Python equivalent of xgettext(1)
  22. Many systems (Solaris, Linux, Gnu) provide extensive tools that ease the
  23. internationalization of C programs. Most of these tools are independent of
  24. the programming language and can be used from within Python programs.
  25. Martin von Loewis' work[1] helps considerably in this regard.
  26. There's one problem though; xgettext is the program that scans source code
  27. looking for message strings, but it groks only C (or C++). Python
  28. introduces a few wrinkles, such as dual quoting characters, triple quoted
  29. strings, and raw strings. xgettext understands none of this.
  30. Enter pygettext, which uses Python's standard tokenize module to scan
  31. Python source code, generating .pot files identical to what GNU xgettext[2]
  32. generates for C and C++ code. From there, the standard GNU tools can be
  33. used.
  34. A word about marking Python strings as candidates for translation. GNU
  35. xgettext recognizes the following keywords: gettext, dgettext, dcgettext,
  36. and gettext_noop. But those can be a lot of text to include all over your
  37. code. C and C++ have a trick: they use the C preprocessor. Most
  38. internationalized C source includes a #define for gettext() to _() so that
  39. what has to be written in the source is much less. Thus these are both
  40. translatable strings:
  41. gettext("Translatable String")
  42. _("Translatable String")
  43. Python of course has no preprocessor so this doesn't work so well. Thus,
  44. pygettext searches only for _() by default, but see the -k/--keyword flag
  45. below for how to augment this.
  46. [1] http://www.python.org/workshops/1997-10/proceedings/loewis.html
  47. [2] http://www.gnu.org/software/gettext/gettext.html
  48. NOTE: pygettext attempts to be option and feature compatible with GNU
  49. xgettext where ever possible. However some options are still missing or are
  50. not fully implemented. Also, xgettext's use of command line switches with
  51. option arguments is broken, and in these cases, pygettext just defines
  52. additional switches.
  53. Usage: pygettext [options] inputfile ...
  54. Options:
  55. -a
  56. --extract-all
  57. Extract all strings.
  58. -d name
  59. --default-domain=name
  60. Rename the default output file from messages.pot to name.pot.
  61. -E
  62. --escape
  63. Replace non-ASCII characters with octal escape sequences.
  64. -D
  65. --docstrings
  66. Extract module, class, method, and function docstrings. These do
  67. not need to be wrapped in _() markers, and in fact cannot be for
  68. Python to consider them docstrings. (See also the -X option).
  69. -h
  70. --help
  71. Print this help message and exit.
  72. -k word
  73. --keyword=word
  74. Keywords to look for in addition to the default set, which are:
  75. %(DEFAULTKEYWORDS)s
  76. You can have multiple -k flags on the command line.
  77. -K
  78. --no-default-keywords
  79. Disable the default set of keywords (see above). Any keywords
  80. explicitly added with the -k/--keyword option are still recognized.
  81. --no-location
  82. Do not write filename/lineno location comments.
  83. -n
  84. --add-location
  85. Write filename/lineno location comments indicating where each
  86. extracted string is found in the source. These lines appear before
  87. each msgid. The style of comments is controlled by the -S/--style
  88. option. This is the default.
  89. -o filename
  90. --output=filename
  91. Rename the default output file from messages.pot to filename. If
  92. filename is `-' then the output is sent to standard out.
  93. -p dir
  94. --output-dir=dir
  95. Output files will be placed in directory dir.
  96. -S stylename
  97. --style stylename
  98. Specify which style to use for location comments. Two styles are
  99. supported:
  100. Solaris # File: filename, line: line-number
  101. GNU #: filename:line
  102. The style name is case insensitive. GNU style is the default.
  103. -v
  104. --verbose
  105. Print the names of the files being processed.
  106. -V
  107. --version
  108. Print the version of pygettext and exit.
  109. -w columns
  110. --width=columns
  111. Set width of output to columns.
  112. -x filename
  113. --exclude-file=filename
  114. Specify a file that contains a list of strings that are not be
  115. extracted from the input files. Each string to be excluded must
  116. appear on a line by itself in the file.
  117. -X filename
  118. --no-docstrings=filename
  119. Specify a file that contains a list of files (one per line) that
  120. should not have their docstrings extracted. This is only useful in
  121. conjunction with the -D option above.
  122. If `inputfile' is -, standard input is read.
  123. """)
  124. import os
  125. import importlib.machinery
  126. import importlib.util
  127. import sys
  128. import glob
  129. import time
  130. import getopt
  131. import token
  132. import tokenize
  133. __version__ = '1.5'
  134. default_keywords = ['_']
  135. DEFAULTKEYWORDS = ', '.join(default_keywords)
  136. EMPTYSTRING = ''
  137. # The normal pot-file header. msgmerge and Emacs's po-mode work better if it's
  138. # there.
  139. pot_header = _('''\
  140. # SOME DESCRIPTIVE TITLE.
  141. # Copyright (C) YEAR ORGANIZATION
  142. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
  143. #
  144. msgid ""
  145. msgstr ""
  146. "Project-Id-Version: PACKAGE VERSION\\n"
  147. "POT-Creation-Date: %(time)s\\n"
  148. "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
  149. "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
  150. "Language-Team: LANGUAGE <LL@li.org>\\n"
  151. "MIME-Version: 1.0\\n"
  152. "Content-Type: text/plain; charset=%(charset)s\\n"
  153. "Content-Transfer-Encoding: %(encoding)s\\n"
  154. "Generated-By: pygettext.py %(version)s\\n"
  155. ''')
  156. def usage(code, msg=''):
  157. print(__doc__ % globals(), file=sys.stderr)
  158. if msg:
  159. print(msg, file=sys.stderr)
  160. sys.exit(code)
  161. def make_escapes(pass_nonascii):
  162. global escapes, escape
  163. if pass_nonascii:
  164. # Allow non-ascii characters to pass through so that e.g. 'msgid
  165. # "Höhe"' would result not result in 'msgid "H\366he"'. Otherwise we
  166. # escape any character outside the 32..126 range.
  167. mod = 128
  168. escape = escape_ascii
  169. else:
  170. mod = 256
  171. escape = escape_nonascii
  172. escapes = [r"\%03o" % i for i in range(mod)]
  173. for i in range(32, 127):
  174. escapes[i] = chr(i)
  175. escapes[ord('\\')] = r'\\'
  176. escapes[ord('\t')] = r'\t'
  177. escapes[ord('\r')] = r'\r'
  178. escapes[ord('\n')] = r'\n'
  179. escapes[ord('\"')] = r'\"'
  180. def escape_ascii(s, encoding):
  181. return ''.join(escapes[ord(c)] if ord(c) < 128 else c for c in s)
  182. def escape_nonascii(s, encoding):
  183. return ''.join(escapes[b] for b in s.encode(encoding))
  184. def is_literal_string(s):
  185. return s[0] in '\'"' or (s[0] in 'rRuU' and s[1] in '\'"')
  186. def safe_eval(s):
  187. # unwrap quotes, safely
  188. return eval(s, {'__builtins__':{}}, {})
  189. def normalize(s, encoding):
  190. # This converts the various Python string types into a format that is
  191. # appropriate for .po files, namely much closer to C style.
  192. lines = s.split('\n')
  193. if len(lines) == 1:
  194. s = '"' + escape(s, encoding) + '"'
  195. else:
  196. if not lines[-1]:
  197. del lines[-1]
  198. lines[-1] = lines[-1] + '\n'
  199. for i in range(len(lines)):
  200. lines[i] = escape(lines[i], encoding)
  201. lineterm = '\\n"\n"'
  202. s = '""\n"' + lineterm.join(lines) + '"'
  203. return s
  204. def containsAny(str, set):
  205. """Check whether 'str' contains ANY of the chars in 'set'"""
  206. return 1 in [c in str for c in set]
  207. def getFilesForName(name):
  208. """Get a list of module files for a filename, a module or package name,
  209. or a directory.
  210. """
  211. if not os.path.exists(name):
  212. # check for glob chars
  213. if containsAny(name, "*?[]"):
  214. files = glob.glob(name)
  215. list = []
  216. for file in files:
  217. list.extend(getFilesForName(file))
  218. return list
  219. # try to find module or package
  220. try:
  221. spec = importlib.util.find_spec(name)
  222. name = spec.origin
  223. except ImportError:
  224. name = None
  225. if not name:
  226. return []
  227. if os.path.isdir(name):
  228. # find all python files in directory
  229. list = []
  230. # get extension for python source files
  231. _py_ext = importlib.machinery.SOURCE_SUFFIXES[0]
  232. for root, dirs, files in os.walk(name):
  233. # don't recurse into CVS directories
  234. if 'CVS' in dirs:
  235. dirs.remove('CVS')
  236. # add all *.py files to list
  237. list.extend(
  238. [os.path.join(root, file) for file in files
  239. if os.path.splitext(file)[1] == _py_ext]
  240. )
  241. return list
  242. elif os.path.exists(name):
  243. # a single file
  244. return [name]
  245. return []
  246. class TokenEater:
  247. def __init__(self, options):
  248. self.__options = options
  249. self.__messages = {}
  250. self.__state = self.__waiting
  251. self.__data = []
  252. self.__lineno = -1
  253. self.__freshmodule = 1
  254. self.__curfile = None
  255. self.__enclosurecount = 0
  256. def __call__(self, ttype, tstring, stup, etup, line):
  257. # dispatch
  258. ## import token
  259. ## print('ttype:', token.tok_name[ttype], 'tstring:', tstring,
  260. ## file=sys.stderr)
  261. self.__state(ttype, tstring, stup[0])
  262. def __waiting(self, ttype, tstring, lineno):
  263. opts = self.__options
  264. # Do docstring extractions, if enabled
  265. if opts.docstrings and not opts.nodocstrings.get(self.__curfile):
  266. # module docstring?
  267. if self.__freshmodule:
  268. if ttype == tokenize.STRING and is_literal_string(tstring):
  269. self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
  270. self.__freshmodule = 0
  271. elif ttype not in (tokenize.COMMENT, tokenize.NL):
  272. self.__freshmodule = 0
  273. return
  274. # class or func/method docstring?
  275. if ttype == tokenize.NAME and tstring in ('class', 'def'):
  276. self.__state = self.__suiteseen
  277. return
  278. if ttype == tokenize.NAME and tstring in opts.keywords:
  279. self.__state = self.__keywordseen
  280. def __suiteseen(self, ttype, tstring, lineno):
  281. # skip over any enclosure pairs until we see the colon
  282. if ttype == tokenize.OP:
  283. if tstring == ':' and self.__enclosurecount == 0:
  284. # we see a colon and we're not in an enclosure: end of def
  285. self.__state = self.__suitedocstring
  286. elif tstring in '([{':
  287. self.__enclosurecount += 1
  288. elif tstring in ')]}':
  289. self.__enclosurecount -= 1
  290. def __suitedocstring(self, ttype, tstring, lineno):
  291. # ignore any intervening noise
  292. if ttype == tokenize.STRING and is_literal_string(tstring):
  293. self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
  294. self.__state = self.__waiting
  295. elif ttype not in (tokenize.NEWLINE, tokenize.INDENT,
  296. tokenize.COMMENT):
  297. # there was no class docstring
  298. self.__state = self.__waiting
  299. def __keywordseen(self, ttype, tstring, lineno):
  300. if ttype == tokenize.OP and tstring == '(':
  301. self.__data = []
  302. self.__lineno = lineno
  303. self.__state = self.__openseen
  304. else:
  305. self.__state = self.__waiting
  306. def __openseen(self, ttype, tstring, lineno):
  307. if ttype == tokenize.OP and tstring == ')':
  308. # We've seen the last of the translatable strings. Record the
  309. # line number of the first line of the strings and update the list
  310. # of messages seen. Reset state for the next batch. If there
  311. # were no strings inside _(), then just ignore this entry.
  312. if self.__data:
  313. self.__addentry(EMPTYSTRING.join(self.__data))
  314. self.__state = self.__waiting
  315. elif ttype == tokenize.STRING and is_literal_string(tstring):
  316. self.__data.append(safe_eval(tstring))
  317. elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
  318. token.NEWLINE, tokenize.NL]:
  319. # warn if we see anything else than STRING or whitespace
  320. print(_(
  321. '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
  322. ) % {
  323. 'token': tstring,
  324. 'file': self.__curfile,
  325. 'lineno': self.__lineno
  326. }, file=sys.stderr)
  327. self.__state = self.__waiting
  328. def __addentry(self, msg, lineno=None, isdocstring=0):
  329. if lineno is None:
  330. lineno = self.__lineno
  331. if not msg in self.__options.toexclude:
  332. entry = (self.__curfile, lineno)
  333. self.__messages.setdefault(msg, {})[entry] = isdocstring
  334. def set_filename(self, filename):
  335. self.__curfile = filename
  336. self.__freshmodule = 1
  337. def write(self, fp):
  338. options = self.__options
  339. timestamp = time.strftime('%Y-%m-%d %H:%M%z')
  340. encoding = fp.encoding if fp.encoding else 'UTF-8'
  341. print(pot_header % {'time': timestamp, 'version': __version__,
  342. 'charset': encoding,
  343. 'encoding': '8bit'}, file=fp)
  344. # Sort the entries. First sort each particular entry's keys, then
  345. # sort all the entries by their first item.
  346. reverse = {}
  347. for k, v in self.__messages.items():
  348. keys = sorted(v.keys())
  349. reverse.setdefault(tuple(keys), []).append((k, v))
  350. rkeys = sorted(reverse.keys())
  351. for rkey in rkeys:
  352. rentries = reverse[rkey]
  353. rentries.sort()
  354. for k, v in rentries:
  355. # If the entry was gleaned out of a docstring, then add a
  356. # comment stating so. This is to aid translators who may wish
  357. # to skip translating some unimportant docstrings.
  358. isdocstring = any(v.values())
  359. # k is the message string, v is a dictionary-set of (filename,
  360. # lineno) tuples. We want to sort the entries in v first by
  361. # file name and then by line number.
  362. v = sorted(v.keys())
  363. if not options.writelocations:
  364. pass
  365. # location comments are different b/w Solaris and GNU:
  366. elif options.locationstyle == options.SOLARIS:
  367. for filename, lineno in v:
  368. d = {'filename': filename, 'lineno': lineno}
  369. print(_(
  370. '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
  371. elif options.locationstyle == options.GNU:
  372. # fit as many locations on one line, as long as the
  373. # resulting line length doesn't exceed 'options.width'
  374. locline = '#:'
  375. for filename, lineno in v:
  376. d = {'filename': filename, 'lineno': lineno}
  377. s = _(' %(filename)s:%(lineno)d') % d
  378. if len(locline) + len(s) <= options.width:
  379. locline = locline + s
  380. else:
  381. print(locline, file=fp)
  382. locline = "#:" + s
  383. if len(locline) > 2:
  384. print(locline, file=fp)
  385. if isdocstring:
  386. print('#, docstring', file=fp)
  387. print('msgid', normalize(k, encoding), file=fp)
  388. print('msgstr ""\n', file=fp)
  389. def main():
  390. global default_keywords
  391. try:
  392. opts, args = getopt.getopt(
  393. sys.argv[1:],
  394. 'ad:DEhk:Kno:p:S:Vvw:x:X:',
  395. ['extract-all', 'default-domain=', 'escape', 'help',
  396. 'keyword=', 'no-default-keywords',
  397. 'add-location', 'no-location', 'output=', 'output-dir=',
  398. 'style=', 'verbose', 'version', 'width=', 'exclude-file=',
  399. 'docstrings', 'no-docstrings',
  400. ])
  401. except getopt.error as msg:
  402. usage(1, msg)
  403. # for holding option values
  404. class Options:
  405. # constants
  406. GNU = 1
  407. SOLARIS = 2
  408. # defaults
  409. extractall = 0 # FIXME: currently this option has no effect at all.
  410. escape = 0
  411. keywords = []
  412. outpath = ''
  413. outfile = 'messages.pot'
  414. writelocations = 1
  415. locationstyle = GNU
  416. verbose = 0
  417. width = 78
  418. excludefilename = ''
  419. docstrings = 0
  420. nodocstrings = {}
  421. options = Options()
  422. locations = {'gnu' : options.GNU,
  423. 'solaris' : options.SOLARIS,
  424. }
  425. # parse options
  426. for opt, arg in opts:
  427. if opt in ('-h', '--help'):
  428. usage(0)
  429. elif opt in ('-a', '--extract-all'):
  430. options.extractall = 1
  431. elif opt in ('-d', '--default-domain'):
  432. options.outfile = arg + '.pot'
  433. elif opt in ('-E', '--escape'):
  434. options.escape = 1
  435. elif opt in ('-D', '--docstrings'):
  436. options.docstrings = 1
  437. elif opt in ('-k', '--keyword'):
  438. options.keywords.append(arg)
  439. elif opt in ('-K', '--no-default-keywords'):
  440. default_keywords = []
  441. elif opt in ('-n', '--add-location'):
  442. options.writelocations = 1
  443. elif opt in ('--no-location',):
  444. options.writelocations = 0
  445. elif opt in ('-S', '--style'):
  446. options.locationstyle = locations.get(arg.lower())
  447. if options.locationstyle is None:
  448. usage(1, _('Invalid value for --style: %s') % arg)
  449. elif opt in ('-o', '--output'):
  450. options.outfile = arg
  451. elif opt in ('-p', '--output-dir'):
  452. options.outpath = arg
  453. elif opt in ('-v', '--verbose'):
  454. options.verbose = 1
  455. elif opt in ('-V', '--version'):
  456. print(_('pygettext.py (xgettext for Python) %s') % __version__)
  457. sys.exit(0)
  458. elif opt in ('-w', '--width'):
  459. try:
  460. options.width = int(arg)
  461. except ValueError:
  462. usage(1, _('--width argument must be an integer: %s') % arg)
  463. elif opt in ('-x', '--exclude-file'):
  464. options.excludefilename = arg
  465. elif opt in ('-X', '--no-docstrings'):
  466. fp = open(arg)
  467. try:
  468. while 1:
  469. line = fp.readline()
  470. if not line:
  471. break
  472. options.nodocstrings[line[:-1]] = 1
  473. finally:
  474. fp.close()
  475. # calculate escapes
  476. make_escapes(not options.escape)
  477. # calculate all keywords
  478. options.keywords.extend(default_keywords)
  479. # initialize list of strings to exclude
  480. if options.excludefilename:
  481. try:
  482. fp = open(options.excludefilename)
  483. options.toexclude = fp.readlines()
  484. fp.close()
  485. except IOError:
  486. print(_(
  487. "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
  488. sys.exit(1)
  489. else:
  490. options.toexclude = []
  491. # resolve args to module lists
  492. expanded = []
  493. for arg in args:
  494. if arg == '-':
  495. expanded.append(arg)
  496. else:
  497. expanded.extend(getFilesForName(arg))
  498. args = expanded
  499. # slurp through all the files
  500. eater = TokenEater(options)
  501. for filename in args:
  502. if filename == '-':
  503. if options.verbose:
  504. print(_('Reading standard input'))
  505. fp = sys.stdin.buffer
  506. closep = 0
  507. else:
  508. if options.verbose:
  509. print(_('Working on %s') % filename)
  510. fp = open(filename, 'rb')
  511. closep = 1
  512. try:
  513. eater.set_filename(filename)
  514. try:
  515. tokens = tokenize.tokenize(fp.readline)
  516. for _token in tokens:
  517. eater(*_token)
  518. except tokenize.TokenError as e:
  519. print('%s: %s, line %d, column %d' % (
  520. e.args[0], filename, e.args[1][0], e.args[1][1]),
  521. file=sys.stderr)
  522. finally:
  523. if closep:
  524. fp.close()
  525. # write the output
  526. if options.outfile == '-':
  527. fp = sys.stdout
  528. closep = 0
  529. else:
  530. if options.outpath:
  531. options.outfile = os.path.join(options.outpath, options.outfile)
  532. fp = open(options.outfile, 'w')
  533. closep = 1
  534. try:
  535. eater.write(fp)
  536. finally:
  537. if closep:
  538. fp.close()
  539. if __name__ == '__main__':
  540. main()
  541. # some more test strings
  542. # this one creates a warning
  543. _('*** Seen unexpected token "%(token)s"') % {'token': 'test'}
  544. _('more' 'than' 'one' 'string')