blob: 0f0395a4fcab6c71a23dc7093f0d731bc101004f [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +00002# -*- coding: iso-8859-1 -*-
Benjamin Petersoneaedaec2013-12-22 19:45:38 -06003# Originally written by Barry Warsaw <barry@python.org>
Barry Warsawc8f08922000-02-26 20:56:47 +00004#
Barry Warsawe04ee702003-04-16 18:08:23 +00005# Minimally patched to make it even more xgettext compatible
Barry Warsawc8f08922000-02-26 20:56:47 +00006# by Peter Funk <pf@artcom-gmbh.de>
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +00007#
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#
Barry Warsawe27db5a1999-08-13 20:59:48 +000015
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000016# for selftesting
17try:
18 import fintl
19 _ = fintl.gettext
20except ImportError:
21 _ = lambda s: s
22
23__doc__ = _("""pygettext -- Python equivalent of xgettext(1)
Barry Warsawe27db5a1999-08-13 20:59:48 +000024
25Many systems (Solaris, Linux, Gnu) provide extensive tools that ease the
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000026internationalization of C programs. Most of these tools are independent of
27the programming language and can be used from within Python programs.
Barry Warsawe04ee702003-04-16 18:08:23 +000028Martin von Loewis' work[1] helps considerably in this regard.
Barry Warsawe27db5a1999-08-13 20:59:48 +000029
Barry Warsaw5dbf5261999-11-03 18:47:52 +000030There's one problem though; xgettext is the program that scans source code
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000031looking for message strings, but it groks only C (or C++). Python
32introduces a few wrinkles, such as dual quoting characters, triple quoted
Barry Warsawe04ee702003-04-16 18:08:23 +000033strings, and raw strings. xgettext understands none of this.
Barry Warsawe27db5a1999-08-13 20:59:48 +000034
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000035Enter pygettext, which uses Python's standard tokenize module to scan
36Python source code, generating .pot files identical to what GNU xgettext[2]
37generates for C and C++ code. From there, the standard GNU tools can be
Barry Warsawe04ee702003-04-16 18:08:23 +000038used.
Barry Warsawe27db5a1999-08-13 20:59:48 +000039
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000040A word about marking Python strings as candidates for translation. GNU
41xgettext recognizes the following keywords: gettext, dgettext, dcgettext,
42and gettext_noop. But those can be a lot of text to include all over your
43code. C and C++ have a trick: they use the C preprocessor. Most
44internationalized C source includes a #define for gettext() to _() so that
45what has to be written in the source is much less. Thus these are both
Barry Warsawe04ee702003-04-16 18:08:23 +000046translatable strings:
Barry Warsawe27db5a1999-08-13 20:59:48 +000047
48 gettext("Translatable String")
49 _("Translatable String")
50
51Python of course has no preprocessor so this doesn't work so well. Thus,
52pygettext searches only for _() by default, but see the -k/--keyword flag
53below for how to augment this.
54
55 [1] http://www.python.org/workshops/1997-10/proceedings/loewis.html
56 [2] http://www.gnu.org/software/gettext/gettext.html
57
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000058NOTE: pygettext attempts to be option and feature compatible with GNU
59xgettext where ever possible. However some options are still missing or are
60not fully implemented. Also, xgettext's use of command line switches with
61option arguments is broken, and in these cases, pygettext just defines
Barry Warsawe04ee702003-04-16 18:08:23 +000062additional switches.
Barry Warsawe27db5a1999-08-13 20:59:48 +000063
Barry Warsawa17e0f12000-03-08 15:18:35 +000064Usage: pygettext [options] inputfile ...
Barry Warsawe27db5a1999-08-13 20:59:48 +000065
66Options:
67
68 -a
69 --extract-all
Barry Warsaw63ce5af2001-07-27 16:47:18 +000070 Extract all strings.
Barry Warsawe27db5a1999-08-13 20:59:48 +000071
Barry Warsawc8f08922000-02-26 20:56:47 +000072 -d name
73 --default-domain=name
Barry Warsaw63ce5af2001-07-27 16:47:18 +000074 Rename the default output file from messages.pot to name.pot.
Barry Warsawc8f08922000-02-26 20:56:47 +000075
76 -E
77 --escape
Barry Warsaw08a8a352000-10-27 04:56:28 +000078 Replace non-ASCII characters with octal escape sequences.
79
80 -D
81 --docstrings
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +000082 Extract module, class, method, and function docstrings. These do
83 not need to be wrapped in _() markers, and in fact cannot be for
84 Python to consider them docstrings. (See also the -X option).
Barry Warsawc8f08922000-02-26 20:56:47 +000085
86 -h
87 --help
Barry Warsaw63ce5af2001-07-27 16:47:18 +000088 Print this help message and exit.
Barry Warsawe27db5a1999-08-13 20:59:48 +000089
Barry Warsawa17e0f12000-03-08 15:18:35 +000090 -k word
91 --keyword=word
92 Keywords to look for in addition to the default set, which are:
93 %(DEFAULTKEYWORDS)s
Barry Warsawe27db5a1999-08-13 20:59:48 +000094
Barry Warsawa17e0f12000-03-08 15:18:35 +000095 You can have multiple -k flags on the command line.
96
97 -K
98 --no-default-keywords
99 Disable the default set of keywords (see above). Any keywords
100 explicitly added with the -k/--keyword option are still recognized.
Barry Warsawe27db5a1999-08-13 20:59:48 +0000101
102 --no-location
Barry Warsawa17e0f12000-03-08 15:18:35 +0000103 Do not write filename/lineno location comments.
Barry Warsawe27db5a1999-08-13 20:59:48 +0000104
Barry Warsawa17e0f12000-03-08 15:18:35 +0000105 -n
106 --add-location
Barry Warsawe27db5a1999-08-13 20:59:48 +0000107 Write filename/lineno location comments indicating where each
108 extracted string is found in the source. These lines appear before
Barry Warsawa17e0f12000-03-08 15:18:35 +0000109 each msgid. The style of comments is controlled by the -S/--style
110 option. This is the default.
111
Barry Warsaw08a8a352000-10-27 04:56:28 +0000112 -o filename
113 --output=filename
114 Rename the default output file from messages.pot to filename. If
115 filename is `-' then the output is sent to standard out.
116
117 -p dir
118 --output-dir=dir
119 Output files will be placed in directory dir.
120
Barry Warsawa17e0f12000-03-08 15:18:35 +0000121 -S stylename
122 --style stylename
123 Specify which style to use for location comments. Two styles are
124 supported:
Barry Warsawe27db5a1999-08-13 20:59:48 +0000125
126 Solaris # File: filename, line: line-number
Barry Warsawa17e0f12000-03-08 15:18:35 +0000127 GNU #: filename:line
Barry Warsawe27db5a1999-08-13 20:59:48 +0000128
Barry Warsawa17e0f12000-03-08 15:18:35 +0000129 The style name is case insensitive. GNU style is the default.
Barry Warsawe27db5a1999-08-13 20:59:48 +0000130
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000131 -v
132 --verbose
133 Print the names of the files being processed.
134
Barry Warsawc8f08922000-02-26 20:56:47 +0000135 -V
136 --version
137 Print the version of pygettext and exit.
138
139 -w columns
140 --width=columns
141 Set width of output to columns.
142
143 -x filename
144 --exclude-file=filename
145 Specify a file that contains a list of strings that are not be
146 extracted from the input files. Each string to be excluded must
147 appear on a line by itself in the file.
Barry Warsawe27db5a1999-08-13 20:59:48 +0000148
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000149 -X filename
150 --no-docstrings=filename
151 Specify a file that contains a list of files (one per line) that
152 should not have their docstrings extracted. This is only useful in
153 conjunction with the -D option above.
Barry Warsawa17e0f12000-03-08 15:18:35 +0000154
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000155If `inputfile' is -, standard input is read.
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000156""")
Barry Warsawe27db5a1999-08-13 20:59:48 +0000157
158import os
Victor Stinner328cb1f2016-04-12 18:46:10 +0200159import importlib.machinery
160import importlib.util
Barry Warsawe27db5a1999-08-13 20:59:48 +0000161import sys
Barry Warsawe04ee702003-04-16 18:08:23 +0000162import glob
Barry Warsawe27db5a1999-08-13 20:59:48 +0000163import time
164import getopt
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000165import token
Barry Warsawe27db5a1999-08-13 20:59:48 +0000166import tokenize
167
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000168__version__ = '1.5'
Barry Warsawa17e0f12000-03-08 15:18:35 +0000169
170default_keywords = ['_']
171DEFAULTKEYWORDS = ', '.join(default_keywords)
172
173EMPTYSTRING = ''
Barry Warsawe27db5a1999-08-13 20:59:48 +0000174
175
176
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000177# The normal pot-file header. msgmerge and Emacs's po-mode work better if it's
178# there.
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000179pot_header = _('''\
180# SOME DESCRIPTIVE TITLE.
181# Copyright (C) YEAR ORGANIZATION
182# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
183#
184msgid ""
185msgstr ""
186"Project-Id-Version: PACKAGE VERSION\\n"
Martin v. Löwis0f6b3832001-03-01 22:56:17 +0000187"POT-Creation-Date: %(time)s\\n"
188"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000189"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
190"Language-Team: LANGUAGE <LL@li.org>\\n"
191"MIME-Version: 1.0\\n"
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200192"Content-Type: text/plain; charset=%(charset)s\\n"
193"Content-Transfer-Encoding: %(encoding)s\\n"
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000194"Generated-By: pygettext.py %(version)s\\n"
195
196''')
197
198
Barry Warsawe27db5a1999-08-13 20:59:48 +0000199def usage(code, msg=''):
Collin Winter6afaeb72007-08-03 17:06:41 +0000200 print(__doc__ % globals(), file=sys.stderr)
Barry Warsawe27db5a1999-08-13 20:59:48 +0000201 if msg:
Collin Winter6afaeb72007-08-03 17:06:41 +0000202 print(msg, file=sys.stderr)
Barry Warsawe27db5a1999-08-13 20:59:48 +0000203 sys.exit(code)
204
Barry Warsawc8f08922000-02-26 20:56:47 +0000205
Barry Warsawe27db5a1999-08-13 20:59:48 +0000206
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200207def make_escapes(pass_nonascii):
208 global escapes, escape
209 if pass_nonascii:
210 # Allow non-ascii characters to pass through so that e.g. 'msgid
Barry Warsaw7733e122000-02-27 14:30:48 +0000211 # "Höhe"' would result not result in 'msgid "H\366he"'. Otherwise we
212 # escape any character outside the 32..126 range.
213 mod = 128
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200214 escape = escape_ascii
Barry Warsaw7733e122000-02-27 14:30:48 +0000215 else:
216 mod = 256
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200217 escape = escape_nonascii
218 escapes = [r"\%03o" % i for i in range(mod)]
219 for i in range(32, 127):
220 escapes[i] = chr(i)
221 escapes[ord('\\')] = r'\\'
222 escapes[ord('\t')] = r'\t'
223 escapes[ord('\r')] = r'\r'
224 escapes[ord('\n')] = r'\n'
225 escapes[ord('\"')] = r'\"'
Barry Warsawc8f08922000-02-26 20:56:47 +0000226
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000227
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200228def escape_ascii(s, encoding):
229 return ''.join(escapes[ord(c)] if ord(c) < 128 else c for c in s)
230
231def escape_nonascii(s, encoding):
232 return ''.join(escapes[b] for b in s.encode(encoding))
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000233
234
235def safe_eval(s):
236 # unwrap quotes, safely
237 return eval(s, {'__builtins__':{}}, {})
238
239
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200240def normalize(s, encoding):
Barry Warsawe27db5a1999-08-13 20:59:48 +0000241 # This converts the various Python string types into a format that is
242 # appropriate for .po files, namely much closer to C style.
Barry Warsawa17e0f12000-03-08 15:18:35 +0000243 lines = s.split('\n')
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000244 if len(lines) == 1:
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200245 s = '"' + escape(s, encoding) + '"'
Barry Warsawe27db5a1999-08-13 20:59:48 +0000246 else:
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000247 if not lines[-1]:
248 del lines[-1]
249 lines[-1] = lines[-1] + '\n'
250 for i in range(len(lines)):
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200251 lines[i] = escape(lines[i], encoding)
Barry Warsawa17e0f12000-03-08 15:18:35 +0000252 lineterm = '\\n"\n"'
253 s = '""\n"' + lineterm.join(lines) + '"'
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000254 return s
Barry Warsawe27db5a1999-08-13 20:59:48 +0000255
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000256
257def containsAny(str, set):
Barry Warsawe04ee702003-04-16 18:08:23 +0000258 """Check whether 'str' contains ANY of the chars in 'set'"""
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000259 return 1 in [c in str for c in set]
260
261
262def _visit_pyfiles(list, dirname, names):
Barry Warsawe04ee702003-04-16 18:08:23 +0000263 """Helper for getFilesForName()."""
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000264 # get extension for python source files
Georg Brandlbf82e372008-05-16 17:02:34 +0000265 if '_py_ext' not in globals():
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000266 global _py_ext
Victor Stinner328cb1f2016-04-12 18:46:10 +0200267 _py_ext = importlib.machinery.SOURCE_SUFFIXES[0]
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000268
269 # don't recurse into CVS directories
270 if 'CVS' in names:
271 names.remove('CVS')
272
273 # add all *.py files to list
274 list.extend(
Barry Warsawe04ee702003-04-16 18:08:23 +0000275 [os.path.join(dirname, file) for file in names
276 if os.path.splitext(file)[1] == _py_ext]
277 )
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000278
279
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000280def getFilesForName(name):
Barry Warsawe04ee702003-04-16 18:08:23 +0000281 """Get a list of module files for a filename, a module or package name,
282 or a directory.
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000283 """
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000284 if not os.path.exists(name):
285 # check for glob chars
286 if containsAny(name, "*?[]"):
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000287 files = glob.glob(name)
288 list = []
289 for file in files:
290 list.extend(getFilesForName(file))
291 return list
292
293 # try to find module or package
Victor Stinner328cb1f2016-04-12 18:46:10 +0200294 try:
295 spec = importlib.util.find_spec(name)
296 name = spec.origin
297 except ImportError:
298 name = None
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000299 if not name:
300 return []
301
302 if os.path.isdir(name):
303 # find all python files in directory
304 list = []
Alexandre Vassalotti4e6531e2008-05-09 20:00:17 +0000305 os.walk(name, _visit_pyfiles, list)
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000306 return list
307 elif os.path.exists(name):
308 # a single file
309 return [name]
310
311 return []
Barry Warsawe27db5a1999-08-13 20:59:48 +0000312
313
314class TokenEater:
315 def __init__(self, options):
316 self.__options = options
317 self.__messages = {}
318 self.__state = self.__waiting
319 self.__data = []
320 self.__lineno = -1
Barry Warsaw08a8a352000-10-27 04:56:28 +0000321 self.__freshmodule = 1
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000322 self.__curfile = None
Miss Islington (bot)51d95ff2018-02-26 15:23:26 -0800323 self.__enclosurecount = 0
Barry Warsawe27db5a1999-08-13 20:59:48 +0000324
325 def __call__(self, ttype, tstring, stup, etup, line):
326 # dispatch
Barry Warsaw08a8a352000-10-27 04:56:28 +0000327## import token
328## print >> sys.stderr, 'ttype:', token.tok_name[ttype], \
329## 'tstring:', tstring
Barry Warsawe27db5a1999-08-13 20:59:48 +0000330 self.__state(ttype, tstring, stup[0])
331
332 def __waiting(self, ttype, tstring, lineno):
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000333 opts = self.__options
Barry Warsaw08a8a352000-10-27 04:56:28 +0000334 # Do docstring extractions, if enabled
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000335 if opts.docstrings and not opts.nodocstrings.get(self.__curfile):
Barry Warsaw08a8a352000-10-27 04:56:28 +0000336 # module docstring?
337 if self.__freshmodule:
338 if ttype == tokenize.STRING:
Barry Warsaw16b62c12001-05-21 19:51:26 +0000339 self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
Barry Warsaw08a8a352000-10-27 04:56:28 +0000340 self.__freshmodule = 0
341 elif ttype not in (tokenize.COMMENT, tokenize.NL):
342 self.__freshmodule = 0
343 return
Miss Islington (bot)51d95ff2018-02-26 15:23:26 -0800344 # class or func/method docstring?
Barry Warsaw08a8a352000-10-27 04:56:28 +0000345 if ttype == tokenize.NAME and tstring in ('class', 'def'):
346 self.__state = self.__suiteseen
347 return
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000348 if ttype == tokenize.NAME and tstring in opts.keywords:
Barry Warsawe27db5a1999-08-13 20:59:48 +0000349 self.__state = self.__keywordseen
350
Barry Warsaw08a8a352000-10-27 04:56:28 +0000351 def __suiteseen(self, ttype, tstring, lineno):
Miss Islington (bot)51d95ff2018-02-26 15:23:26 -0800352 # skip over any enclosure pairs until we see the colon
353 if ttype == tokenize.OP:
354 if tstring == ':' and self.__enclosurecount == 0:
355 # we see a colon and we're not in an enclosure: end of def
356 self.__state = self.__suitedocstring
357 elif tstring in '([{':
358 self.__enclosurecount += 1
359 elif tstring in ')]}':
360 self.__enclosurecount -= 1
Barry Warsaw08a8a352000-10-27 04:56:28 +0000361
362 def __suitedocstring(self, ttype, tstring, lineno):
363 # ignore any intervening noise
364 if ttype == tokenize.STRING:
Barry Warsaw16b62c12001-05-21 19:51:26 +0000365 self.__addentry(safe_eval(tstring), lineno, isdocstring=1)
Barry Warsaw08a8a352000-10-27 04:56:28 +0000366 self.__state = self.__waiting
367 elif ttype not in (tokenize.NEWLINE, tokenize.INDENT,
368 tokenize.COMMENT):
369 # there was no class docstring
370 self.__state = self.__waiting
371
Barry Warsawe27db5a1999-08-13 20:59:48 +0000372 def __keywordseen(self, ttype, tstring, lineno):
373 if ttype == tokenize.OP and tstring == '(':
374 self.__data = []
375 self.__lineno = lineno
376 self.__state = self.__openseen
377 else:
378 self.__state = self.__waiting
379
380 def __openseen(self, ttype, tstring, lineno):
381 if ttype == tokenize.OP and tstring == ')':
382 # We've seen the last of the translatable strings. Record the
Barry Warsawe04ee702003-04-16 18:08:23 +0000383 # line number of the first line of the strings and update the list
Barry Warsawe27db5a1999-08-13 20:59:48 +0000384 # of messages seen. Reset state for the next batch. If there
385 # were no strings inside _(), then just ignore this entry.
386 if self.__data:
Barry Warsaw08a8a352000-10-27 04:56:28 +0000387 self.__addentry(EMPTYSTRING.join(self.__data))
Barry Warsawe27db5a1999-08-13 20:59:48 +0000388 self.__state = self.__waiting
389 elif ttype == tokenize.STRING:
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000390 self.__data.append(safe_eval(tstring))
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000391 elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
392 token.NEWLINE, tokenize.NL]:
393 # warn if we see anything else than STRING or whitespace
Collin Winter6afaeb72007-08-03 17:06:41 +0000394 print(_(
Barry Warsawe04ee702003-04-16 18:08:23 +0000395 '*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"'
396 ) % {
397 'token': tstring,
398 'file': self.__curfile,
399 'lineno': self.__lineno
Collin Winter6afaeb72007-08-03 17:06:41 +0000400 }, file=sys.stderr)
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000401 self.__state = self.__waiting
Barry Warsawe27db5a1999-08-13 20:59:48 +0000402
Barry Warsaw16b62c12001-05-21 19:51:26 +0000403 def __addentry(self, msg, lineno=None, isdocstring=0):
Barry Warsaw08a8a352000-10-27 04:56:28 +0000404 if lineno is None:
405 lineno = self.__lineno
406 if not msg in self.__options.toexclude:
407 entry = (self.__curfile, lineno)
Barry Warsaw16b62c12001-05-21 19:51:26 +0000408 self.__messages.setdefault(msg, {})[entry] = isdocstring
Barry Warsaw08a8a352000-10-27 04:56:28 +0000409
Barry Warsawe27db5a1999-08-13 20:59:48 +0000410 def set_filename(self, filename):
411 self.__curfile = filename
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000412 self.__freshmodule = 1
Barry Warsawe27db5a1999-08-13 20:59:48 +0000413
414 def write(self, fp):
415 options = self.__options
R David Murray2b781292015-04-16 12:15:09 -0400416 timestamp = time.strftime('%Y-%m-%d %H:%M%z')
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200417 encoding = fp.encoding if fp.encoding else 'UTF-8'
418 print(pot_header % {'time': timestamp, 'version': __version__,
419 'charset': encoding,
420 'encoding': '8bit'}, file=fp)
Barry Warsaw128c77d2001-05-23 16:59:45 +0000421 # Sort the entries. First sort each particular entry's keys, then
422 # sort all the entries by their first item.
423 reverse = {}
Fred Drake33e2c3e2000-10-26 03:49:15 +0000424 for k, v in self.__messages.items():
Guido van Rossumf7bd9642008-01-15 17:41:38 +0000425 keys = sorted(v.keys())
Barry Warsaw50cf7062001-05-24 23:06:13 +0000426 reverse.setdefault(tuple(keys), []).append((k, v))
Guido van Rossumf7bd9642008-01-15 17:41:38 +0000427 rkeys = sorted(reverse.keys())
Barry Warsaw128c77d2001-05-23 16:59:45 +0000428 for rkey in rkeys:
Barry Warsaw50cf7062001-05-24 23:06:13 +0000429 rentries = reverse[rkey]
430 rentries.sort()
431 for k, v in rentries:
432 # If the entry was gleaned out of a docstring, then add a
433 # comment stating so. This is to aid translators who may wish
434 # to skip translating some unimportant docstrings.
Guido van Rossum89da5d72006-08-22 00:21:25 +0000435 isdocstring = any(v.values())
Barry Warsaw50cf7062001-05-24 23:06:13 +0000436 # k is the message string, v is a dictionary-set of (filename,
437 # lineno) tuples. We want to sort the entries in v first by
438 # file name and then by line number.
Guido van Rossumf7bd9642008-01-15 17:41:38 +0000439 v = sorted(v.keys())
Barry Warsaw50cf7062001-05-24 23:06:13 +0000440 if not options.writelocations:
441 pass
442 # location comments are different b/w Solaris and GNU:
443 elif options.locationstyle == options.SOLARIS:
444 for filename, lineno in v:
445 d = {'filename': filename, 'lineno': lineno}
Collin Winter6afaeb72007-08-03 17:06:41 +0000446 print(_(
447 '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
Barry Warsaw50cf7062001-05-24 23:06:13 +0000448 elif options.locationstyle == options.GNU:
449 # fit as many locations on one line, as long as the
Martin Panter69332c12016-08-04 13:07:31 +0000450 # resulting line length doesn't exceed 'options.width'
Barry Warsaw50cf7062001-05-24 23:06:13 +0000451 locline = '#:'
452 for filename, lineno in v:
453 d = {'filename': filename, 'lineno': lineno}
454 s = _(' %(filename)s:%(lineno)d') % d
455 if len(locline) + len(s) <= options.width:
456 locline = locline + s
457 else:
Collin Winter6afaeb72007-08-03 17:06:41 +0000458 print(locline, file=fp)
Barry Warsaw50cf7062001-05-24 23:06:13 +0000459 locline = "#:" + s
460 if len(locline) > 2:
Collin Winter6afaeb72007-08-03 17:06:41 +0000461 print(locline, file=fp)
Barry Warsaw5c94ce52001-06-20 19:41:40 +0000462 if isdocstring:
Collin Winter6afaeb72007-08-03 17:06:41 +0000463 print('#, docstring', file=fp)
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200464 print('msgid', normalize(k, encoding), file=fp)
Collin Winter6afaeb72007-08-03 17:06:41 +0000465 print('msgstr ""\n', file=fp)
Barry Warsaw08a8a352000-10-27 04:56:28 +0000466
Barry Warsawe27db5a1999-08-13 20:59:48 +0000467
468
469def main():
Barry Warsawa17e0f12000-03-08 15:18:35 +0000470 global default_keywords
Barry Warsawe27db5a1999-08-13 20:59:48 +0000471 try:
472 opts, args = getopt.getopt(
473 sys.argv[1:],
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000474 'ad:DEhk:Kno:p:S:Vvw:x:X:',
Barry Warsaw2b639692001-05-21 19:58:23 +0000475 ['extract-all', 'default-domain=', 'escape', 'help',
Barry Warsawa17e0f12000-03-08 15:18:35 +0000476 'keyword=', 'no-default-keywords',
Barry Warsawc8f08922000-02-26 20:56:47 +0000477 'add-location', 'no-location', 'output=', 'output-dir=',
Barry Warsawa17e0f12000-03-08 15:18:35 +0000478 'style=', 'verbose', 'version', 'width=', 'exclude-file=',
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000479 'docstrings', 'no-docstrings',
Barry Warsawc8f08922000-02-26 20:56:47 +0000480 ])
Guido van Rossumb940e112007-01-10 16:19:56 +0000481 except getopt.error as msg:
Barry Warsawe27db5a1999-08-13 20:59:48 +0000482 usage(1, msg)
483
484 # for holding option values
485 class Options:
486 # constants
487 GNU = 1
488 SOLARIS = 2
489 # defaults
Barry Warsawc8f08922000-02-26 20:56:47 +0000490 extractall = 0 # FIXME: currently this option has no effect at all.
491 escape = 0
Barry Warsawe27db5a1999-08-13 20:59:48 +0000492 keywords = []
Barry Warsawc8f08922000-02-26 20:56:47 +0000493 outpath = ''
Barry Warsawe27db5a1999-08-13 20:59:48 +0000494 outfile = 'messages.pot'
Barry Warsawa17e0f12000-03-08 15:18:35 +0000495 writelocations = 1
496 locationstyle = GNU
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000497 verbose = 0
Barry Warsawc8f08922000-02-26 20:56:47 +0000498 width = 78
499 excludefilename = ''
Barry Warsaw08a8a352000-10-27 04:56:28 +0000500 docstrings = 0
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000501 nodocstrings = {}
Barry Warsawe27db5a1999-08-13 20:59:48 +0000502
503 options = Options()
504 locations = {'gnu' : options.GNU,
505 'solaris' : options.SOLARIS,
506 }
507
508 # parse options
509 for opt, arg in opts:
510 if opt in ('-h', '--help'):
511 usage(0)
Barry Warsawc8f08922000-02-26 20:56:47 +0000512 elif opt in ('-a', '--extract-all'):
513 options.extractall = 1
514 elif opt in ('-d', '--default-domain'):
515 options.outfile = arg + '.pot'
516 elif opt in ('-E', '--escape'):
517 options.escape = 1
Barry Warsaw08a8a352000-10-27 04:56:28 +0000518 elif opt in ('-D', '--docstrings'):
519 options.docstrings = 1
Barry Warsawe27db5a1999-08-13 20:59:48 +0000520 elif opt in ('-k', '--keyword'):
Barry Warsawe27db5a1999-08-13 20:59:48 +0000521 options.keywords.append(arg)
Barry Warsawa17e0f12000-03-08 15:18:35 +0000522 elif opt in ('-K', '--no-default-keywords'):
523 default_keywords = []
Barry Warsawe27db5a1999-08-13 20:59:48 +0000524 elif opt in ('-n', '--add-location'):
Barry Warsawa17e0f12000-03-08 15:18:35 +0000525 options.writelocations = 1
Barry Warsawe27db5a1999-08-13 20:59:48 +0000526 elif opt in ('--no-location',):
Barry Warsawa17e0f12000-03-08 15:18:35 +0000527 options.writelocations = 0
528 elif opt in ('-S', '--style'):
529 options.locationstyle = locations.get(arg.lower())
530 if options.locationstyle is None:
531 usage(1, _('Invalid value for --style: %s') % arg)
Barry Warsawc8f08922000-02-26 20:56:47 +0000532 elif opt in ('-o', '--output'):
533 options.outfile = arg
534 elif opt in ('-p', '--output-dir'):
535 options.outpath = arg
Barry Warsaw5dbf5261999-11-03 18:47:52 +0000536 elif opt in ('-v', '--verbose'):
537 options.verbose = 1
Barry Warsawc8f08922000-02-26 20:56:47 +0000538 elif opt in ('-V', '--version'):
Collin Winter6afaeb72007-08-03 17:06:41 +0000539 print(_('pygettext.py (xgettext for Python) %s') % __version__)
Barry Warsawc8f08922000-02-26 20:56:47 +0000540 sys.exit(0)
541 elif opt in ('-w', '--width'):
542 try:
543 options.width = int(arg)
544 except ValueError:
Barry Warsawa17e0f12000-03-08 15:18:35 +0000545 usage(1, _('--width argument must be an integer: %s') % arg)
Barry Warsawc8f08922000-02-26 20:56:47 +0000546 elif opt in ('-x', '--exclude-file'):
547 options.excludefilename = arg
Barry Warsaw63ce5af2001-07-27 16:47:18 +0000548 elif opt in ('-X', '--no-docstrings'):
549 fp = open(arg)
550 try:
551 while 1:
552 line = fp.readline()
553 if not line:
554 break
555 options.nodocstrings[line[:-1]] = 1
556 finally:
557 fp.close()
Barry Warsawc8f08922000-02-26 20:56:47 +0000558
559 # calculate escapes
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200560 make_escapes(not options.escape)
Barry Warsawe27db5a1999-08-13 20:59:48 +0000561
562 # calculate all keywords
563 options.keywords.extend(default_keywords)
564
Barry Warsawc8f08922000-02-26 20:56:47 +0000565 # initialize list of strings to exclude
566 if options.excludefilename:
567 try:
568 fp = open(options.excludefilename)
569 options.toexclude = fp.readlines()
570 fp.close()
571 except IOError:
Collin Winter6afaeb72007-08-03 17:06:41 +0000572 print(_(
573 "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
Barry Warsawc8f08922000-02-26 20:56:47 +0000574 sys.exit(1)
575 else:
576 options.toexclude = []
577
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000578 # resolve args to module lists
579 expanded = []
580 for arg in args:
581 if arg == '-':
582 expanded.append(arg)
583 else:
584 expanded.extend(getFilesForName(arg))
585 args = expanded
586
Barry Warsawe27db5a1999-08-13 20:59:48 +0000587 # slurp through all the files
588 eater = TokenEater(options)
589 for filename in args:
Barry Warsawa17e0f12000-03-08 15:18:35 +0000590 if filename == '-':
591 if options.verbose:
Collin Winter6afaeb72007-08-03 17:06:41 +0000592 print(_('Reading standard input'))
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200593 fp = sys.stdin.buffer
Barry Warsawa17e0f12000-03-08 15:18:35 +0000594 closep = 0
595 else:
596 if options.verbose:
Collin Winter6afaeb72007-08-03 17:06:41 +0000597 print(_('Working on %s') % filename)
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200598 fp = open(filename, 'rb')
Barry Warsawa17e0f12000-03-08 15:18:35 +0000599 closep = 1
600 try:
601 eater.set_filename(filename)
Barry Warsaw75ee8f52001-02-26 04:46:53 +0000602 try:
Serhiy Storchakab6ed1732013-02-09 22:37:22 +0200603 tokens = tokenize.tokenize(fp.readline)
Trent Nelson428de652008-03-18 22:41:35 +0000604 for _token in tokens:
605 eater(*_token)
Guido van Rossumb940e112007-01-10 16:19:56 +0000606 except tokenize.TokenError as e:
Collin Winter6afaeb72007-08-03 17:06:41 +0000607 print('%s: %s, line %d, column %d' % (
Georg Brandl6464d472007-10-22 16:16:13 +0000608 e.args[0], filename, e.args[1][0], e.args[1][1]),
609 file=sys.stderr)
Barry Warsawa17e0f12000-03-08 15:18:35 +0000610 finally:
611 if closep:
612 fp.close()
Barry Warsawe27db5a1999-08-13 20:59:48 +0000613
Barry Warsawa17e0f12000-03-08 15:18:35 +0000614 # write the output
615 if options.outfile == '-':
616 fp = sys.stdout
617 closep = 0
618 else:
619 if options.outpath:
620 options.outfile = os.path.join(options.outpath, options.outfile)
621 fp = open(options.outfile, 'w')
622 closep = 1
623 try:
624 eater.write(fp)
625 finally:
626 if closep:
627 fp.close()
Barry Warsawe27db5a1999-08-13 20:59:48 +0000628
629
630if __name__ == '__main__':
631 main()
Barry Warsaw75a6e672000-05-02 19:28:30 +0000632 # some more test strings
Barry Warsawe04ee702003-04-16 18:08:23 +0000633 # this one creates a warning
634 _('*** Seen unexpected token "%(token)s"') % {'token': 'test'}
Martin v. Löwis0d1fdea2002-11-22 08:36:54 +0000635 _('more' 'than' 'one' 'string')