Debian Codegraph @

babel/messages/frontend.py

raw
1 """
2 babel.messages.frontend
3 ~~~~~~~~~~~~~~~~~~~~~~~
4
5 Frontends for the message extraction functionality.
6
7 :copyright: (c) 2013-2026 by the Babel Team.
8 :license: BSD, see LICENSE for more details.
9 """
10
11 from __future__ import annotations
12
13 import datetime
14 import fnmatch
15 import logging
16 import optparse
17 import os
18 import pathlib
19 import re
20 import shutil
21 import sys
22 import tempfile
23 import warnings
24 from configparser import RawConfigParser
25 from io import StringIO
26 from typing import Any, BinaryIO, Iterable, Literal
27
28 from babel import Locale, localedata
29 from babel import __version__ as VERSION
30 from babel.core import UnknownLocaleError
31 from babel.messages.catalog import DEFAULT_HEADER, Catalog
32 from babel.messages.extract import (
33 DEFAULT_KEYWORDS,
34 DEFAULT_MAPPING,
35 check_and_call_extract_file,
36 extract_from_dir,
37 )
38 from babel.messages.mofile import write_mo
39 from babel.messages.pofile import read_po, write_po
40 from babel.util import LOCALTZ
41
42 log = logging.getLogger('babel')
43
44
45 class BaseError(Exception):
46 pass
47
48
49 class OptionError(BaseError):
50 pass
51
52
53 class SetupError(BaseError):
54 pass
55
56
57 class ConfigurationError(BaseError):
58 """
59 Raised for errors in configuration files.
60 """
61
62
63 def listify_value(arg, split=None):
64 """
65 Make a list out of an argument.
66
67 Values from `distutils` argument parsing are always single strings;
68 values from `optparse` parsing may be lists of strings that may need
69 to be further split.
70
71 No matter the input, this function returns a flat list of whitespace-trimmed
72 strings, with `None` values filtered out.
73
74 >>> listify_value("foo bar")
75 ['foo', 'bar']
76 >>> listify_value(["foo bar"])
77 ['foo', 'bar']
78 >>> listify_value([["foo"], "bar"])
79 ['foo', 'bar']
80 >>> listify_value([["foo"], ["bar", None, "foo"]])
81 ['foo', 'bar', 'foo']
82 >>> listify_value("foo, bar, quux", ",")
83 ['foo', 'bar', 'quux']
84
85 :param arg: A string or a list of strings
86 :param split: The argument to pass to `str.split()`.
87 :return:
88 """
89 out = []
90
91 if not isinstance(arg, (list, tuple)):
92 arg = [arg]
93
94 for val in arg:
95 if val is None:
96 continue
97 if isinstance(val, (list, tuple)):
98 out.extend(listify_value(val, split=split))
99 continue
100 out.extend(s.strip() for s in str(val).split(split))
101 assert all(isinstance(val, str) for val in out)
102 return out
103
104
105 class CommandMixin:
106 # This class is a small shim between Distutils commands and
107 # optparse option parsing in the frontend command line.
108
109 #: Option name to be input as `args` on the script command line.
110 as_args = None
111
112 #: Options which allow multiple values.
113 #: This is used by the `optparse` transmogrification code.
114 multiple_value_options = ()
115
116 #: Options which are booleans.
117 #: This is used by the `optparse` transmogrification code.
118 # (This is actually used by distutils code too, but is never
119 # declared in the base class.)
120 boolean_options = ()
121
122 #: Option aliases, to retain standalone command compatibility.
123 #: Distutils does not support option aliases, but optparse does.
124 #: This maps the distutils argument name to an iterable of aliases
125 #: that are usable with optparse.
126 option_aliases = {}
127
128 #: Choices for options that needed to be restricted to specific
129 #: list of choices.
130 option_choices = {}
131
132 #: Log object. To allow replacement in the script command line runner.
133 log = log
134
135 def __init__(self, dist=None):
136 # A less strict version of distutils' `__init__`.
137 self.distribution = dist
138 self.initialize_options()
139 self._dry_run = None
140 self.verbose = False
141 self.force = None
142 self.help = 0
143 self.finalized = 0
144
145 def initialize_options(self):
146 pass
147
148 def ensure_finalized(self):
149 if not self.finalized:
150 self.finalize_options()
151 self.finalized = 1
152
153 def finalize_options(self):
154 raise RuntimeError(
155 f"abstract method -- subclass {self.__class__} must override",
156 )
157
158
159 class CompileCatalog(CommandMixin):
160 description = 'compile message catalogs to binary MO files'
161 user_options = [
162 ('domain=', 'D',
163 "domains of PO files (space separated list, default 'messages')"),
164 ('directory=', 'd',
165 'path to base directory containing the catalogs'),
166 ('input-file=', 'i',
167 'name of the input file'),
168 ('output-file=', 'o',
169 "name of the output file (default "
170 "'<output_dir>/<locale>/LC_MESSAGES/<domain>.mo')"),
171 ('locale=', 'l',
172 'locale of the catalog to compile'),
173 ('use-fuzzy', 'f',
174 'also include fuzzy translations'),
175 ('statistics', None,
176 'print statistics about translations'),
177 ] # fmt: skip
178 boolean_options = ['use-fuzzy', 'statistics']
179
180 def initialize_options(self):
181 self.domain = 'messages'
182 self.directory = None
183 self.input_file = None
184 self.output_file = None
185 self.locale = None
186 self.use_fuzzy = False
187 self.statistics = False
188
189 def finalize_options(self):
190 self.domain = listify_value(self.domain)
191 if not self.input_file and not self.directory:
192 raise OptionError('you must specify either the input file or the base directory')
193 if not self.output_file and not self.directory:
194 raise OptionError('you must specify either the output file or the base directory')
195
196 def run(self):
197 n_errors = 0
198 for domain in self.domain:
199 for errors in self._run_domain(domain).values():
200 n_errors += len(errors)
201 if n_errors:
202 self.log.error('%d errors encountered.', n_errors)
203 return 1 if n_errors else 0
204
205 def _get_po_mo_triples(self, domain: str):
206 if not self.input_file:
207 dir_path = pathlib.Path(self.directory)
208 if self.locale:
209 lc_messages_path = dir_path / self.locale / "LC_MESSAGES"
210 po_file = lc_messages_path / f"{domain}.po"
211 yield self.locale, po_file, po_file.with_suffix(".mo")
212 else:
213 for locale_path in dir_path.iterdir():
214 po_file = locale_path / "LC_MESSAGES" / f"{domain}.po"
215 if po_file.exists():
216 yield locale_path.name, po_file, po_file.with_suffix(".mo")
217 else:
218 po_file = pathlib.Path(self.input_file)
219 if self.output_file:
220 mo_file = pathlib.Path(self.output_file)
221 else:
222 mo_file = (
223 pathlib.Path(self.directory) / self.locale / "LC_MESSAGES" / f"{domain}.mo"
224 )
225 yield self.locale, po_file, mo_file
226
227 def _run_domain(self, domain):
228 locale_po_mo_triples = list(self._get_po_mo_triples(domain))
229 if not locale_po_mo_triples:
230 raise OptionError(f'no message catalogs found for domain {domain!r}')
231
232 catalogs_and_errors = {}
233
234 for locale, po_file, mo_file in locale_po_mo_triples:
235 with open(po_file, 'rb') as infile:
236 catalog = read_po(infile, locale)
237
238 if self.statistics:
239 translated = 0
240 for message in list(catalog)[1:]:
241 if message.string:
242 translated += 1
243 percentage = 0
244 if len(catalog):
245 percentage = translated * 100 // len(catalog)
246 self.log.info(
247 '%d of %d messages (%d%%) translated in %s',
248 translated,
249 len(catalog),
250 percentage,
251 po_file,
252 )
253
254 if catalog.fuzzy and not self.use_fuzzy:
255 self.log.info('catalog %s is marked as fuzzy, skipping', po_file)
256 continue
257
258 catalogs_and_errors[catalog] = catalog_errors = list(catalog.check())
259 for message, errors in catalog_errors:
260 for error in errors:
261 self.log.error('error: %s:%d: %s', po_file, message.lineno, error)
262
263 self.log.info('compiling catalog %s to %s', po_file, mo_file)
264
265 with open(mo_file, 'wb') as outfile:
266 write_mo(outfile, catalog, use_fuzzy=self.use_fuzzy)
267
268 return catalogs_and_errors
269
270
271 def _make_directory_filter(ignore_patterns):
272 """
273 Build a directory_filter function based on a list of ignore patterns.
274 """
275
276 def cli_directory_filter(dirname):
277 basename = os.path.basename(dirname)
278 return not any(
279 fnmatch.fnmatch(basename, ignore_pattern) for ignore_pattern in ignore_patterns
280 )
281
282 return cli_directory_filter
283
284
285 class ExtractMessages(CommandMixin):
286 description = 'extract localizable strings from the project code'
287 user_options = [
288 ('charset=', None,
289 'charset to use in the output file (default "utf-8")'),
290 ('keywords=', 'k',
291 'space-separated list of keywords to look for in addition to the '
292 'defaults (may be repeated multiple times)'),
293 ('no-default-keywords', None,
294 'do not include the default keywords'),
295 ('mapping-file=', 'F',
296 'path to the mapping configuration file'),
297 ('no-location', None,
298 'do not include location comments with filename and line number'),
299 ('add-location=', None,
300 'location lines format. If it is not given or "full", it generates '
301 'the lines with both file name and line number. If it is "file", '
302 'the line number part is omitted. If it is "never", it completely '
303 'suppresses the lines (same as --no-location).'),
304 ('omit-header', None,
305 'do not include msgid "" entry in header'),
306 ('output-file=', 'o',
307 'name of the output file'),
308 ('width=', 'w',
309 'set output line width (default 76)'),
310 ('no-wrap', None,
311 'do not break long message lines, longer than the output line width, '
312 'into several lines'),
313 ('sort-output', None,
314 'generate sorted output (default False)'),
315 ('sort-by-file', None,
316 'sort output by file location (default False)'),
317 ('msgid-bugs-address=', None,
318 'set report address for msgid'),
319 ('copyright-holder=', None,
320 'set copyright holder in output'),
321 ('project=', None,
322 'set project name in output'),
323 ('version=', None,
324 'set project version in output'),
325 ('add-comments=', 'c',
326 'place comment block with TAG (or those preceding keyword lines) in '
327 'output file. Separate multiple TAGs with commas(,)'), # TODO: Support repetition of this argument
328 ('strip-comments', 's',
329 'strip the comment TAGs from the comments.'),
330 ('input-paths=', None,
331 'files or directories that should be scanned for messages. Separate multiple '
332 'files or directories with commas(,)'), # TODO: Support repetition of this argument
333 ('input-dirs=', None, # TODO (3.x): Remove me.
334 'alias for input-paths (does allow files as well as directories).'),
335 ('ignore-dirs=', None,
336 'Patterns for directories to ignore when scanning for messages. '
337 'Separate multiple patterns with spaces (default ".* ._")'),
338 ('header-comment=', None,
339 'header comment for the catalog'),
340 ('last-translator=', None,
341 'set the name and email of the last translator in output'),
342 ] # fmt: skip
343 boolean_options = [
344 'no-default-keywords',
345 'no-location',
346 'omit-header',
347 'no-wrap',
348 'sort-output',
349 'sort-by-file',
350 'strip-comments',
351 ]
352 as_args = 'input-paths'
353 multiple_value_options = (
354 'add-comments',
355 'keywords',
356 'ignore-dirs',
357 )
358 option_aliases = {
359 'keywords': ('--keyword',),
360 'mapping-file': ('--mapping',),
361 'output-file': ('--output',),
362 'strip-comments': ('--strip-comment-tags',),
363 'last-translator': ('--last-translator',),
364 }
365 option_choices = {
366 'add-location': ('full', 'file', 'never'),
367 }
368
369 def initialize_options(self):
370 self.charset = 'utf-8'
371 self.keywords = None
372 self.no_default_keywords = False
373 self.mapping_file = None
374 self.no_location = False
375 self.add_location = None
376 self.omit_header = False
377 self.output_file = None
378 self.input_dirs = None
379 self.input_paths = None
380 self.width = None
381 self.no_wrap = False
382 self.sort_output = False
383 self.sort_by_file = False
384 self.msgid_bugs_address = None
385 self.copyright_holder = None
386 self.project = None
387 self.version = None
388 self.add_comments = None
389 self.strip_comments = False
390 self.include_lineno = True
391 self.ignore_dirs = None
392 self.header_comment = None
393 self.last_translator = None
394
395 def finalize_options(self):
396 if self.input_dirs:
397 if not self.input_paths:
398 self.input_paths = self.input_dirs
399 else:
400 raise OptionError(
401 'input-dirs and input-paths are mutually exclusive',
402 )
403
404 keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy()
405
406 keywords.update(parse_keywords(listify_value(self.keywords)))
407
408 self.keywords = keywords
409
410 if not self.keywords:
411 raise OptionError(
412 'you must specify new keywords if you disable the default ones',
413 )
414
415 if not self.output_file:
416 raise OptionError('no output file specified')
417 if self.no_wrap and self.width:
418 raise OptionError(
419 "'--no-wrap' and '--width' are mutually exclusive",
420 )
421 if not self.no_wrap and not self.width:
422 self.width = 76
423 elif self.width is not None:
424 self.width = int(self.width)
425
426 if self.sort_output and self.sort_by_file:
427 raise OptionError(
428 "'--sort-output' and '--sort-by-file' are mutually exclusive",
429 )
430
431 if self.input_paths:
432 if isinstance(self.input_paths, str):
433 self.input_paths = re.split(r',\s*', self.input_paths)
434 elif self.distribution is not None:
435 self.input_paths = list(
436 {k.split('.', 1)[0] for k in (self.distribution.packages or ())},
437 )
438 else:
439 self.input_paths = []
440
441 if not self.input_paths:
442 raise OptionError("no input files or directories specified")
443
444 for path in self.input_paths:
445 if not os.path.exists(path):
446 raise OptionError(f"Input path: {path} does not exist")
447
448 self.add_comments = listify_value(self.add_comments or (), ",")
449
450 if self.distribution:
451 if not self.project:
452 self.project = self.distribution.get_name()
453 if not self.version:
454 self.version = self.distribution.get_version()
455
456 if self.add_location == 'never':
457 self.no_location = True
458 elif self.add_location == 'file':
459 self.include_lineno = False
460
461 ignore_dirs = listify_value(self.ignore_dirs)
462 if ignore_dirs:
463 self.directory_filter = _make_directory_filter(ignore_dirs)
464 else:
465 self.directory_filter = None
466
467 def _build_callback(self, path: str):
468 def callback(filename: str, method: str, options: dict):
469 if method == 'ignore':
470 return
471
472 # If we explicitly provide a full filepath, just use that.
473 # Otherwise, path will be the directory path and filename
474 # is the relative path from that dir to the file.
475 # So we can join those to get the full filepath.
476 if os.path.isfile(path):
477 filepath = path
478 else:
479 filepath = os.path.normpath(os.path.join(path, filename))
480
481 optstr = ''
482 if options:
483 opt_values = ", ".join(f'{k}="{v}"' for k, v in options.items())
484 optstr = f" ({opt_values})"
485 self.log.info('extracting messages from %s%s', filepath, optstr)
486
487 return callback
488
489 def run(self):
490 mappings = self._get_mappings()
491 with open(self.output_file, 'wb') as outfile:
492 catalog = Catalog(
493 project=self.project,
494 version=self.version,
495 msgid_bugs_address=self.msgid_bugs_address,
496 copyright_holder=self.copyright_holder,
497 charset=self.charset,
498 header_comment=(self.header_comment or DEFAULT_HEADER),
499 last_translator=self.last_translator,
500 )
501
502 for path, method_map, options_map in mappings:
503 callback = self._build_callback(path)
504 if os.path.isfile(path):
505 current_dir = os.getcwd()
506 extracted = check_and_call_extract_file(
507 path,
508 method_map,
509 options_map,
510 callback=callback,
511 comment_tags=self.add_comments,
512 dirpath=current_dir,
513 keywords=self.keywords,
514 strip_comment_tags=self.strip_comments,
515 )
516 else:
517 extracted = extract_from_dir(
518 path,
519 method_map,
520 options_map,
521 callback=callback,
522 comment_tags=self.add_comments,
523 directory_filter=self.directory_filter,
524 keywords=self.keywords,
525 strip_comment_tags=self.strip_comments,
526 )
527 for filename, lineno, message, comments, context in extracted:
528 if os.path.isfile(path):
529 filepath = filename # already normalized
530 else:
531 filepath = os.path.normpath(os.path.join(path, filename))
532
533 catalog.add(
534 message,
535 None,
536 [(filepath, lineno)],
537 auto_comments=comments,
538 context=context,
539 )
540
541 self.log.info('writing PO template file to %s', self.output_file)
542 write_po(
543 outfile,
544 catalog,
545 include_lineno=self.include_lineno,
546 no_location=self.no_location,
547 omit_header=self.omit_header,
548 sort_by_file=self.sort_by_file,
549 sort_output=self.sort_output,
550 width=self.width,
551 )
552
553 def _get_mappings(self):
554 mappings = []
555
556 if self.mapping_file:
557 if self.mapping_file.endswith(".toml"):
558 with open(self.mapping_file, "rb") as fileobj:
559 file_style = (
560 "pyproject.toml"
561 if os.path.basename(self.mapping_file) == "pyproject.toml"
562 else "standalone"
563 )
564 method_map, options_map = _parse_mapping_toml(
565 fileobj,
566 filename=self.mapping_file,
567 style=file_style,
568 )
569 else:
570 with open(self.mapping_file) as fileobj:
571 method_map, options_map = parse_mapping_cfg(
572 fileobj,
573 filename=self.mapping_file,
574 )
575 for path in self.input_paths:
576 mappings.append((path, method_map, options_map))
577
578 elif getattr(self.distribution, 'message_extractors', None):
579 message_extractors = self.distribution.message_extractors
580 for path, mapping in message_extractors.items():
581 if isinstance(mapping, str):
582 method_map, options_map = parse_mapping_cfg(StringIO(mapping))
583 else:
584 method_map, options_map = [], {}
585 for pattern, method, options in mapping:
586 method_map.append((pattern, method))
587 options_map[pattern] = _parse_string_options(options or {})
588 mappings.append((path, method_map, options_map))
589
590 else:
591 for path in self.input_paths:
592 mappings.append((path, DEFAULT_MAPPING, {}))
593
594 return mappings
595
596
597 def _init_catalog(*, input_file, output_file, locale: Locale, width: int) -> None:
598 with open(input_file, 'rb') as infile:
599 # Although reading from the catalog template, read_po must be fed
600 # the locale in order to correctly calculate plurals
601 catalog = read_po(infile, locale=locale)
602
603 catalog.locale = locale
604 catalog.revision_date = datetime.datetime.now(LOCALTZ)
605 catalog.fuzzy = False
606
607 if dirname := os.path.dirname(output_file):
608 os.makedirs(dirname, exist_ok=True)
609
610 with open(output_file, 'wb') as outfile:
611 write_po(outfile, catalog, width=width)
612
613
614 class InitCatalog(CommandMixin):
615 description = 'create a new catalog based on a POT file'
616 user_options = [
617 ('domain=', 'D',
618 "domain of PO file (default 'messages')"),
619 ('input-file=', 'i',
620 'name of the input file'),
621 ('output-dir=', 'd',
622 'path to output directory'),
623 ('output-file=', 'o',
624 "name of the output file (default "
625 "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"),
626 ('locale=', 'l',
627 'locale for the new localized catalog'),
628 ('width=', 'w',
629 'set output line width (default 76)'),
630 ('no-wrap', None,
631 'do not break long message lines, longer than the output line width, '
632 'into several lines'),
633 ] # fmt: skip
634 boolean_options = ['no-wrap']
635
636 def initialize_options(self):
637 self.output_dir = None
638 self.output_file = None
639 self.input_file = None
640 self.locale = None
641 self.domain = 'messages'
642 self.no_wrap = False
643 self.width = None
644
645 def finalize_options(self):
646 if not self.input_file:
647 raise OptionError('you must specify the input file')
648
649 if not self.locale:
650 raise OptionError('you must provide a locale for the new catalog')
651 try:
652 self._locale = Locale.parse(self.locale)
653 except UnknownLocaleError as e:
654 raise OptionError(e) from e
655
656 if not self.output_file and not self.output_dir:
657 raise OptionError('you must specify the output directory')
658 if not self.output_file:
659 lc_messages_path = pathlib.Path(self.output_dir) / self.locale / "LC_MESSAGES"
660 self.output_file = str(lc_messages_path / f"{self.domain}.po")
661
662 if self.no_wrap and self.width:
663 raise OptionError("'--no-wrap' and '--width' are mutually exclusive")
664 if not self.no_wrap and not self.width:
665 self.width = 76
666 elif self.width is not None:
667 self.width = int(self.width)
668
669 def run(self):
670 self.log.info(
671 'creating catalog %s based on %s',
672 self.output_file,
673 self.input_file,
674 )
675 _init_catalog(
676 input_file=self.input_file,
677 output_file=self.output_file,
678 locale=self._locale,
679 width=self.width,
680 )
681
682
683 class UpdateCatalog(CommandMixin):
684 description = 'update message catalogs from a POT file'
685 user_options = [
686 ('domain=', 'D',
687 "domain of PO file (default 'messages')"),
688 ('input-file=', 'i',
689 'name of the input file'),
690 ('output-dir=', 'd',
691 'path to base directory containing the catalogs'),
692 ('output-file=', 'o',
693 "name of the output file (default "
694 "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"),
695 ('omit-header', None,
696 "do not include msgid "" entry in header"),
697 ('locale=', 'l',
698 'locale of the catalog to compile'),
699 ('width=', 'w',
700 'set output line width (default 76)'),
701 ('no-wrap', None,
702 'do not break long message lines, longer than the output line width, '
703 'into several lines'),
704 ('ignore-obsolete=', None,
705 'whether to omit obsolete messages from the output'),
706 ('init-missing=', None,
707 'if any output files are missing, initialize them first'),
708 ('no-fuzzy-matching', 'N',
709 'do not use fuzzy matching'),
710 ('update-header-comment', None,
711 'update target header comment'),
712 ('previous', None,
713 'keep previous msgids of translated messages'),
714 ('check=', None,
715 'don\'t update the catalog, just return the status. Return code 0 '
716 'means nothing would change. Return code 1 means that the catalog '
717 'would be updated'),
718 ('ignore-pot-creation-date=', None,
719 'ignore changes to POT-Creation-Date when updating or checking'),
720 ] # fmt: skip
721 boolean_options = [
722 'omit-header',
723 'no-wrap',
724 'ignore-obsolete',
725 'init-missing',
726 'no-fuzzy-matching',
727 'previous',
728 'update-header-comment',
729 'check',
730 'ignore-pot-creation-date',
731 ]
732
733 def initialize_options(self):
734 self.domain = 'messages'
735 self.input_file = None
736 self.output_dir = None
737 self.output_file = None
738 self.omit_header = False
739 self.locale = None
740 self.width = None
741 self.no_wrap = False
742 self.ignore_obsolete = False
743 self.init_missing = False
744 self.no_fuzzy_matching = False
745 self.update_header_comment = False
746 self.previous = False
747 self.check = False
748 self.ignore_pot_creation_date = False
749
750 def finalize_options(self):
751 if not self.input_file:
752 raise OptionError('you must specify the input file')
753 if not self.output_file and not self.output_dir:
754 raise OptionError('you must specify the output file or directory')
755 if self.output_file and not self.locale:
756 raise OptionError('you must specify the locale')
757
758 if self.init_missing:
759 if not self.locale:
760 raise OptionError(
761 'you must specify the locale for the init-missing option to work',
762 )
763
764 try:
765 self._locale = Locale.parse(self.locale)
766 except UnknownLocaleError as e:
767 raise OptionError(e) from e
768 else:
769 self._locale = None
770
771 if self.no_wrap and self.width:
772 raise OptionError("'--no-wrap' and '--width' are mutually exclusive")
773 if not self.no_wrap and not self.width:
774 self.width = 76
775 elif self.width is not None:
776 self.width = int(self.width)
777 if self.no_fuzzy_matching and self.previous:
778 self.previous = False
779
780 def _get_locale_po_file_tuples(self):
781 if not self.output_file:
782 output_path = pathlib.Path(self.output_dir)
783 if self.locale:
784 lc_messages_path = output_path / self.locale / "LC_MESSAGES"
785 yield self.locale, str(lc_messages_path / f"{self.domain}.po")
786 else:
787 for locale_path in output_path.iterdir():
788 po_file = locale_path / "LC_MESSAGES" / f"{self.domain}.po"
789 if po_file.exists():
790 yield locale_path.stem, po_file
791 else:
792 yield self.locale, self.output_file
793
794 def run(self):
795 domain = self.domain
796 if not domain:
797 domain = os.path.splitext(os.path.basename(self.input_file))[0]
798
799 check_status = {}
800 locale_po_file_tuples = list(self._get_locale_po_file_tuples())
801
802 if not locale_po_file_tuples:
803 raise OptionError(f'no message catalogs found for domain {domain!r}')
804
805 with open(self.input_file, 'rb') as infile:
806 template = read_po(infile)
807
808 for locale, filename in locale_po_file_tuples:
809 if self.init_missing and not os.path.exists(filename):
810 if self.check:
811 check_status[filename] = False
812 continue
813 self.log.info(
814 'creating catalog %s based on %s',
815 filename,
816 self.input_file,
817 )
818
819 _init_catalog(
820 input_file=self.input_file,
821 output_file=filename,
822 locale=self._locale,
823 width=self.width,
824 )
825
826 self.log.info('updating catalog %s based on %s', filename, self.input_file)
827 with open(filename, 'rb') as infile:
828 catalog = read_po(infile, locale=locale, domain=domain)
829
830 catalog.update(
831 template,
832 no_fuzzy_matching=self.no_fuzzy_matching,
833 update_header_comment=self.update_header_comment,
834 update_creation_date=not self.ignore_pot_creation_date,
835 )
836
837 tmpname = os.path.join(
838 os.path.dirname(filename),
839 tempfile.gettempprefix() + os.path.basename(filename),
840 )
841 try:
842 with open(tmpname, 'wb') as tmpfile:
843 write_po(
844 tmpfile,
845 catalog,
846 ignore_obsolete=self.ignore_obsolete,
847 include_previous=self.previous,
848 omit_header=self.omit_header,
849 width=self.width,
850 )
851 except Exception:
852 os.remove(tmpname)
853 raise
854
855 if self.check:
856 with open(filename, "rb") as origfile:
857 original_catalog = read_po(origfile)
858 with open(tmpname, "rb") as newfile:
859 updated_catalog = read_po(newfile)
860 updated_catalog.revision_date = original_catalog.revision_date
861 check_status[filename] = updated_catalog.is_identical(original_catalog)
862 os.remove(tmpname)
863 continue
864
865 try:
866 os.rename(tmpname, filename)
867 except OSError:
868 # We're probably on Windows, which doesn't support atomic
869 # renames, at least not through Python
870 # If the error is in fact due to a permissions problem, that
871 # same error is going to be raised from one of the following
872 # operations
873 os.remove(filename)
874 shutil.copy(tmpname, filename)
875 os.remove(tmpname)
876
877 if self.check:
878 for filename, up_to_date in check_status.items():
879 if up_to_date:
880 self.log.info('Catalog %s is up to date.', filename)
881 else:
882 self.log.warning('Catalog %s is out of date.', filename)
883 if not all(check_status.values()):
884 raise BaseError("Some catalogs are out of date.")
885 else:
886 self.log.info("All the catalogs are up-to-date.")
887 return
888
889
890 class CommandLineInterface:
891 """Command-line interface.
892
893 This class provides a simple command-line interface to the message
894 extraction and PO file generation functionality.
895 """
896
897 usage = '%%prog %s [options] %s'
898 version = f'%prog {VERSION}'
899 commands = {
900 'compile': 'compile message catalogs to MO files',
901 'extract': 'extract messages from source files and generate a POT file',
902 'init': 'create new message catalogs from a POT file',
903 'update': 'update existing message catalogs from a POT file',
904 }
905
906 command_classes = {
907 'compile': CompileCatalog,
908 'extract': ExtractMessages,
909 'init': InitCatalog,
910 'update': UpdateCatalog,
911 }
912
913 log = None # Replaced on instance level
914
915 def run(self, argv=None):
916 """Main entry point of the command-line interface.
917
918 :param argv: list of arguments passed on the command-line
919 """
920
921 if argv is None:
922 argv = sys.argv
923
924 self.parser = optparse.OptionParser(
925 usage=self.usage % ('command', '[args]'),
926 version=self.version,
927 )
928 self.parser.disable_interspersed_args()
929 self.parser.print_help = self._help
930 self.parser.add_option(
931 "--list-locales",
932 dest="list_locales",
933 action="store_true",
934 help="print all known locales and exit",
935 )
936 self.parser.add_option(
937 "-v",
938 "--verbose",
939 action="store_const",
940 dest="loglevel",
941 const=logging.DEBUG,
942 help="print as much as possible",
943 )
944 self.parser.add_option(
945 "-q",
946 "--quiet",
947 action="store_const",
948 dest="loglevel",
949 const=logging.ERROR,
950 help="print as little as possible",
951 )
952 self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)
953
954 options, args = self.parser.parse_args(argv[1:])
955
956 self._configure_logging(options.loglevel)
957 if options.list_locales:
958 identifiers = localedata.locale_identifiers()
959 id_width = max(len(identifier) for identifier in identifiers) + 1
960 for identifier in sorted(identifiers):
961 locale = Locale.parse(identifier)
962 print(f"{identifier:<{id_width}} {locale.english_name}")
963 return 0
964
965 if not args:
966 self.parser.error(
967 "no valid command or option passed. "
968 "Try the -h/--help option for more information.",
969 )
970
971 cmdname = args[0]
972 if cmdname not in self.commands:
973 self.parser.error(f'unknown command "{cmdname}"')
974
975 cmdinst = self._configure_command(cmdname, args[1:])
976 return cmdinst.run()
977
978 def _configure_logging(self, loglevel):
979 self.log = log
980 self.log.setLevel(loglevel)
981 # Don't add a new handler for every instance initialization (#227), this
982 # would cause duplicated output when the CommandLineInterface as an
983 # normal Python class.
984 if self.log.handlers:
985 handler = self.log.handlers[0]
986 else:
987 handler = logging.StreamHandler()
988 self.log.addHandler(handler)
989 handler.setLevel(loglevel)
990 formatter = logging.Formatter('%(message)s')
991 handler.setFormatter(formatter)
992
993 def _help(self):
994 print(self.parser.format_help())
995 print("commands:")
996 cmd_width = max(8, max(len(command) for command in self.commands) + 1)
997 for name, description in sorted(self.commands.items()):
998 print(f" {name:<{cmd_width}} {description}")
999
1000 def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin:
1001 cmdclass = self.command_classes[cmdname]
1002 cmdinst = cmdclass()
1003 if self.log:
1004 cmdinst.log = self.log # Use our logger, not distutils'.
1005 assert isinstance(cmdinst, CommandMixin)
1006 cmdinst.initialize_options()
1007
1008 parser = optparse.OptionParser(
1009 usage=self.usage % (cmdname, ''),
1010 description=self.commands[cmdname],
1011 )
1012 as_args: str | None = getattr(cmdclass, "as_args", None)
1013 for long, short, help in cmdclass.user_options:
1014 name = long.strip("=")
1015 default = getattr(cmdinst, name.replace("-", "_"))
1016 strs = [f"--{name}"]
1017 if short:
1018 strs.append(f"-{short}")
1019 strs.extend(cmdclass.option_aliases.get(name, ()))
1020 choices = cmdclass.option_choices.get(name, None)
1021 if name == as_args:
1022 parser.usage += f"<{name}>"
1023 elif name in cmdclass.boolean_options:
1024 parser.add_option(*strs, action="store_true", help=help)
1025 elif name in cmdclass.multiple_value_options:
1026 parser.add_option(*strs, action="append", help=help, choices=choices)
1027 else:
1028 parser.add_option(*strs, help=help, default=default, choices=choices)
1029 options, args = parser.parse_args(argv)
1030
1031 if as_args:
1032 setattr(options, as_args.replace('-', '_'), args)
1033
1034 for key, value in vars(options).items():
1035 setattr(cmdinst, key, value)
1036
1037 try:
1038 cmdinst.ensure_finalized()
1039 except OptionError as err:
1040 parser.error(str(err))
1041
1042 return cmdinst
1043
1044
1045 def main():
1046 return CommandLineInterface().run(sys.argv)
1047
1048
1049 def parse_mapping(fileobj, filename=None):
1050 warnings.warn(
1051 "parse_mapping is deprecated, use parse_mapping_cfg instead",
1052 DeprecationWarning,
1053 stacklevel=2,
1054 )
1055 return parse_mapping_cfg(fileobj, filename)
1056
1057
1058 def parse_mapping_cfg(fileobj, filename=None):
1059 """Parse an extraction method mapping from a file-like object.
1060
1061 :param fileobj: a readable file-like object containing the configuration
1062 text to parse
1063 :param filename: the name of the file being parsed, for error messages
1064 """
1065 extractors = {}
1066 method_map = []
1067 options_map = {}
1068
1069 parser = RawConfigParser()
1070 parser.read_file(fileobj, filename)
1071
1072 for section in parser.sections():
1073 if section == 'extractors':
1074 extractors = dict(parser.items(section))
1075 else:
1076 method, pattern = (part.strip() for part in section.split(':', 1))
1077 method_map.append((pattern, method))
1078 options_map[pattern] = _parse_string_options(dict(parser.items(section)))
1079
1080 if extractors:
1081 for idx, (pattern, method) in enumerate(method_map):
1082 if method in extractors:
1083 method = extractors[method]
1084 method_map[idx] = (pattern, method)
1085
1086 return method_map, options_map
1087
1088
1089 def _parse_string_options(options: dict[str, str]) -> dict[str, Any]:
1090 """
1091 Parse string-formatted options from a mapping configuration.
1092
1093 The `keywords` and `add_comments` options are parsed into a canonical
1094 internal format, so they can be merged with global keywords/comment tags
1095 during extraction.
1096 """
1097 options: dict[str, Any] = options.copy()
1098
1099 if keywords_val := options.pop("keywords", None):
1100 options['keywords'] = parse_keywords(listify_value(keywords_val))
1101
1102 if comments_val := options.pop("add_comments", None):
1103 options['add_comments'] = listify_value(comments_val)
1104
1105 return options
1106
1107
1108 def _parse_config_object(config: dict, *, filename="(unknown)"):
1109 extractors = {}
1110 method_map = []
1111 options_map = {}
1112
1113 extractors_read = config.get("extractors", {})
1114 if not isinstance(extractors_read, dict):
1115 raise ConfigurationError(
1116 f"{filename}: extractors: Expected a dictionary, got {type(extractors_read)!r}",
1117 )
1118 for method, callable_spec in extractors_read.items():
1119 if not isinstance(method, str):
1120 # Impossible via TOML, but could happen with a custom object.
1121 raise ConfigurationError(
1122 f"{filename}: extractors: Extraction method must be a string, got {method!r}",
1123 )
1124 if not isinstance(callable_spec, str):
1125 raise ConfigurationError(
1126 f"{filename}: extractors: Callable specification must be a string, got {callable_spec!r}",
1127 )
1128 extractors[method] = callable_spec
1129
1130 if "mapping" in config:
1131 raise ConfigurationError(
1132 f"{filename}: 'mapping' is not a valid key, did you mean 'mappings'?",
1133 )
1134
1135 mappings_read = config.get("mappings", [])
1136 if not isinstance(mappings_read, list):
1137 raise ConfigurationError(
1138 f"{filename}: mappings: Expected a list, got {type(mappings_read)!r}",
1139 )
1140 for idx, entry in enumerate(mappings_read):
1141 if not isinstance(entry, dict):
1142 raise ConfigurationError(
1143 f"{filename}: mappings[{idx}]: Expected a dictionary, got {type(entry)!r}",
1144 )
1145 entry = entry.copy()
1146
1147 method = entry.pop("method", None)
1148 if not isinstance(method, str):
1149 raise ConfigurationError(
1150 f"{filename}: mappings[{idx}]: 'method' must be a string, got {method!r}",
1151 )
1152 method = extractors.get(method, method) # Map the extractor name to the callable now
1153
1154 pattern = entry.pop("pattern", None)
1155 if not isinstance(pattern, (list, str)):
1156 raise ConfigurationError(
1157 f"{filename}: mappings[{idx}]: 'pattern' must be a list or a string, got {pattern!r}",
1158 )
1159 if not isinstance(pattern, list):
1160 pattern = [pattern]
1161
1162 if keywords_val := entry.pop("keywords", None):
1163 if isinstance(keywords_val, str):
1164 entry["keywords"] = parse_keywords(listify_value(keywords_val))
1165 elif isinstance(keywords_val, list):
1166 entry["keywords"] = parse_keywords(keywords_val)
1167 else:
1168 raise ConfigurationError(
1169 f"{filename}: mappings[{idx}]: 'keywords' must be a string or list, got {keywords_val!r}",
1170 )
1171
1172 if comments_val := entry.pop("add_comments", None):
1173 if isinstance(comments_val, str):
1174 entry["add_comments"] = [comments_val]
1175 elif isinstance(comments_val, list):
1176 entry["add_comments"] = comments_val
1177 else:
1178 raise ConfigurationError(
1179 f"{filename}: mappings[{idx}]: 'add_comments' must be a string or list, got {comments_val!r}",
1180 )
1181
1182 for pat in pattern:
1183 if not isinstance(pat, str):
1184 raise ConfigurationError(
1185 f"{filename}: mappings[{idx}]: 'pattern' elements must be strings, got {pat!r}",
1186 )
1187 method_map.append((pat, method))
1188 options_map[pat] = entry
1189
1190 return method_map, options_map
1191
1192
1193 def _parse_mapping_toml(
1194 fileobj: BinaryIO,
1195 filename: str = "(unknown)",
1196 style: Literal["standalone", "pyproject.toml"] = "standalone",
1197 ):
1198 """Parse an extraction method mapping from a binary file-like object.
1199
1200 .. warning: As of this version of Babel, this is a private API subject to changes.
1201
1202 :param fileobj: a readable binary file-like object containing the configuration TOML to parse
1203 :param filename: the name of the file being parsed, for error messages
1204 :param style: whether the file is in the style of a `pyproject.toml` file, i.e. whether to look for `tool.babel`.
1205 """
1206 try:
1207 import tomllib
1208 except ImportError:
1209 try:
1210 import tomli as tomllib
1211 except ImportError as ie: # pragma: no cover
1212 raise ImportError("tomli or tomllib is required to parse TOML files") from ie
1213
1214 try:
1215 parsed_data = tomllib.load(fileobj)
1216 except tomllib.TOMLDecodeError as e:
1217 raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e
1218
1219 if style == "pyproject.toml":
1220 try:
1221 babel_data = parsed_data["tool"]["babel"]
1222 except (TypeError, KeyError) as e:
1223 raise ConfigurationError(
1224 f"{filename}: No 'tool.babel' section found in file",
1225 ) from e
1226 elif style == "standalone":
1227 babel_data = parsed_data
1228 if "babel" in babel_data:
1229 raise ConfigurationError(
1230 f"{filename}: 'babel' should not be present in a stand-alone configuration file",
1231 )
1232 else: # pragma: no cover
1233 raise ValueError(f"Unknown TOML style {style!r}")
1234
1235 return _parse_config_object(babel_data, filename=filename)
1236
1237
1238 def _parse_spec(s: str) -> tuple[int | None, tuple[int | tuple[int, str], ...]]:
1239 inds = []
1240 number = None
1241 for x in s.split(','):
1242 if x[-1] == 't':
1243 number = int(x[:-1])
1244 elif x[-1] == 'c':
1245 inds.append((int(x[:-1]), 'c'))
1246 else:
1247 inds.append(int(x))
1248 return number, tuple(inds)
1249
1250
1251 def parse_keywords(strings: Iterable[str] = ()):
1252 """Parse keywords specifications from the given list of strings.
1253
1254 >>> import pprint
1255 >>> keywords = ['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2',
1256 ... 'polymorphic:1', 'polymorphic:2,2t', 'polymorphic:3c,3t']
1257 >>> pprint.pprint(parse_keywords(keywords))
1258 {'_': None,
1259 'dgettext': (2,),
1260 'dngettext': (2, 3),
1261 'pgettext': ((1, 'c'), 2),
1262 'polymorphic': {None: (1,), 2: (2,), 3: ((3, 'c'),)}}
1263
1264 The input keywords are in GNU Gettext style; see :doc:`cmdline` for details.
1265
1266 The output is a dictionary mapping keyword names to a dictionary of specifications.
1267 Keys in this dictionary are numbers of arguments, where ``None`` means that all numbers
1268 of arguments are matched, and a number means only calls with that number of arguments
1269 are matched (which happens when using the "t" specifier). However, as a special
1270 case for backwards compatibility, if the dictionary of specifications would
1271 be ``{None: x}``, i.e., there is only one specification and it matches all argument
1272 counts, then it is collapsed into just ``x``.
1273
1274 A specification is either a tuple or None. If a tuple, each element can be either a number
1275 ``n``, meaning that the nth argument should be extracted as a message, or the tuple
1276 ``(n, 'c')``, meaning that the nth argument should be extracted as context for the
1277 messages. A ``None`` specification is equivalent to ``(1,)``, extracting the first
1278 argument.
1279 """
1280 keywords = {}
1281 for string in strings:
1282 if ':' in string:
1283 funcname, spec_str = string.split(':')
1284 number, spec = _parse_spec(spec_str)
1285 else:
1286 funcname = string
1287 number = None
1288 spec = None
1289 keywords.setdefault(funcname, {})[number] = spec
1290
1291 # For best backwards compatibility, collapse {None: x} into x.
1292 for k, v in keywords.items():
1293 if set(v) == {None}:
1294 keywords[k] = v[None]
1295
1296 return keywords
1297
1298
1299 def __getattr__(name: str):
1300 # Re-exports for backwards compatibility;
1301 # `setuptools_frontend` is the canonical import location.
1302 if name in {
1303 'check_message_extractors',
1304 'compile_catalog',
1305 'extract_messages',
1306 'init_catalog',
1307 'update_catalog',
1308 }:
1309 from babel.messages import setuptools_frontend
1310
1311 return getattr(setuptools_frontend, name)
1312
1313 raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
1314
1315
1316 if __name__ == '__main__':
1317 main()