From 263665bd708b59d81486f9608de3428b91497faa Mon Sep 17 00:00:00 2001 From: Maximilian Moser Date: Tue, 7 Jul 2026 00:27:12 +0200 Subject: [PATCH 1/9] Implement parsing of command configuration from pyproject.toml If present, use a "pyproject.toml" file for default configuration of `pybabel` commands. Co-authored-by: Aarni Koskela --- babel/messages/frontend.py | 167 ++++++++++++++++++----- tests/messages/frontend/test_cli.py | 84 ++++++++++++ tests/messages/frontend/test_frontend.py | 4 +- tests/messages/test_toml_config.py | 30 +++- 4 files changed, 246 insertions(+), 39 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index e642a1a08..ed3933201 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -47,6 +47,116 @@ log = logging.getLogger('babel') +def _parse_toml( + fileobj: BinaryIO, + *, + style: Literal["standalone", "pyproject.toml"], + filename: str = "(unknown)", + allow_missing_sections: bool = False, +) -> dict[str, Any]: + """Parse the Babel configuration from the given binary file object. + + :param fileobj: a readable file-like object containing the configuration text + to parse. + :param style: whether the file is in the style of a `pyproject.toml` file, + i.e. whether to look for `tool.babel`. + :param filename: the name of the file being parsed, for error messages. + :param allow_missing_sections: decides if a missing ``[tool.babel]`` section + results in an empty dictionary being returned or a + ``ConfigurationError`` being raised. + """ + try: + import tomllib + except ImportError: + try: + import tomli as tomllib + except ImportError as ie: # pragma: no cover + raise ImportError( + "tomli or tomllib is required to parse TOML files", + ) from ie + + try: + parsed_data = tomllib.load(fileobj) + except tomllib.TOMLDecodeError as e: + raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e + + if style == "pyproject.toml": + try: + babel_data = parsed_data["tool"]["babel"] + except (TypeError, KeyError) as e: + if not allow_missing_sections: + raise ConfigurationError( + f"{filename}: No 'tool.babel' section found in file", + ) from e + else: + return {} + + elif style == "standalone": + babel_data = parsed_data + if "babel" in babel_data: + raise ConfigurationError( + f"{filename}: 'babel' should not be present in a stand-alone configuration file", + ) + else: # pragma: no cover + raise ValueError(f"Unknown TOML style {style!r}") + + return babel_data + + +def _find_pyproject_toml( + path: pathlib.Path | None, max_depth: int = 10, +) -> pathlib.Path | None: + """Find the closest "pyproject.toml" file to the specified path. + + If the given path's directory contains a ``pyproject.toml``, return that. + Otherwise, walk up the directory hierarchy until one has been found or the + maximum search depth has been exhausted. + + :param path: The path to start the search for ``pyproject.toml`` from. + If set to ``None``, the current working directory will be used. + :param max_depth: The maximum number of steps up the file system for the search. + """ + if path is None: + path = pathlib.Path.cwd() + + path = path.resolve() # resolve symlinks and remove ".." components + if path.is_file(): + return path + + tries = 0 + while tries < max_depth: + pyproject_file = path / "pyproject.toml" + if pyproject_file.is_file(): + return pyproject_file + + parent = path.parent + if path == parent: + return None + + path = parent + tries += 1 + + return None + + +def _parse_pyproject_toml_config(path: pathlib.Path | None, table_name: str | None) -> dict: + """Parse the Babel config from a "pyproject.toml" file near the specified path.""" + if table_name is None: + return {} + + if path := _find_pyproject_toml(path): + with path.open("rb") as file_fd: + babel_data = _parse_toml( + file_fd, + style="pyproject.toml", + filename=path.name, + allow_missing_sections=True, + ) + return babel_data.get(table_name, {}) + else: + return {} + + class BaseError(Exception): pass @@ -134,6 +244,10 @@ class CommandMixin: #: list of choices. option_choices = {} + #: The name of the table containing the command's configuration in + #: a TOML file. + toml_config_table = None + #: Log object. To allow replacement in the script command line runner. log = log @@ -193,6 +307,7 @@ class CompileCatalog(CommandMixin): 'print statistics about translations'), ] # fmt: skip boolean_options = ['use-fuzzy', 'statistics'] + toml_config_table = "compile_catalog" def initialize_options(self): self.domain = 'messages' @@ -382,6 +497,7 @@ class ExtractMessages(CommandMixin): option_choices = { 'add-location': ('full', 'file', 'never'), } + toml_config_table = "extract_messages" def initialize_options(self): self.charset = 'utf-8' @@ -571,7 +687,7 @@ def _get_mappings(self): if os.path.basename(self.mapping_file) == "pyproject.toml" else "standalone" ) - method_map, options_map = _parse_mapping_toml( + method_map, options_map = _parse_mappings_from_toml( fileobj, filename=self.mapping_file, style=file_style, @@ -642,6 +758,7 @@ class InitCatalog(CommandMixin): 'into several lines'), ] # fmt: skip boolean_options = ['no-wrap'] + toml_config_table = "init_catalog" def initialize_options(self): self.output_dir = None @@ -734,6 +851,7 @@ class UpdateCatalog(CommandMixin): 'check', 'ignore-pot-creation-date', ] + toml_config_table = "update_catalog" def initialize_options(self): self.domain = 'messages' @@ -1220,6 +1338,7 @@ def run(self, argv=None): if cmdname not in self.commands: self.parser.error(f'unknown command "{cmdname}"') + # TODO add possibility to turn TOML config parsing off, e.g. new option above? cmdinst = self._configure_command(cmdname, args[1:]) return cmdinst.run() @@ -1253,6 +1372,7 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: assert isinstance(cmdinst, CommandMixin) cmdinst.initialize_options() + toml_config = _parse_pyproject_toml_config(None, cmdinst.toml_config_table) parser = optparse.OptionParser( usage=self.usage % (cmdname, ''), description=self.commands[cmdname], @@ -1260,7 +1380,8 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: as_args: str | None = getattr(cmdclass, "as_args", None) for long, short, help in cmdclass.user_options: name = long.strip("=") - default = getattr(cmdinst, name.replace("-", "_")) + normalized_name = name.replace("-", "_") + default = toml_config.get(normalized_name, getattr(cmdinst, normalized_name)) strs = [f"--{name}"] if short: strs.append(f"-{short}") @@ -1269,14 +1390,18 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: if name == as_args: parser.usage += f"<{name}>" elif name in cmdclass.boolean_options: - parser.add_option(*strs, action="store_true", help=help) + parser.add_option(*strs, action="store_true", default=default, help=help) elif name in cmdclass.multiple_value_options: - parser.add_option(*strs, action="append", help=help, choices=choices) + parser.add_option(*strs, action="append", default=listify_value(default), help=help, choices=choices) else: parser.add_option(*strs, help=help, default=default, choices=choices) + options, args = parser.parse_args(argv) if as_args: + # Read `args` from TOML; `as_args` is the key name, e.g. + # `input_paths = ...` in `[tool.babel.extract_messages]` + args = args or listify_value(toml_config.get(as_args.replace("-", "_"), args)) setattr(options, as_args.replace('-', '_'), args) for key, value in vars(options).items(): @@ -1438,7 +1563,7 @@ def _parse_config_object(config: dict, *, filename="(unknown)"): return method_map, options_map -def _parse_mapping_toml( +def _parse_mappings_from_toml( fileobj: BinaryIO, filename: str = "(unknown)", style: Literal["standalone", "pyproject.toml"] = "standalone", @@ -1451,36 +1576,8 @@ def _parse_mapping_toml( :param filename: the name of the file being parsed, for error messages :param style: whether the file is in the style of a `pyproject.toml` file, i.e. whether to look for `tool.babel`. """ - try: - import tomllib - except ImportError: - try: - import tomli as tomllib - except ImportError as ie: # pragma: no cover - raise ImportError("tomli or tomllib is required to parse TOML files") from ie - - try: - parsed_data = tomllib.load(fileobj) - except tomllib.TOMLDecodeError as e: - raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e - - if style == "pyproject.toml": - try: - babel_data = parsed_data["tool"]["babel"] - except (TypeError, KeyError) as e: - raise ConfigurationError( - f"{filename}: No 'tool.babel' section found in file", - ) from e - elif style == "standalone": - babel_data = parsed_data - if "babel" in babel_data: - raise ConfigurationError( - f"{filename}: 'babel' should not be present in a stand-alone configuration file", - ) - else: # pragma: no cover - raise ValueError(f"Unknown TOML style {style!r}") - - return _parse_config_object(babel_data, filename=filename) + parsed_data = _parse_toml(fileobj, style=style, filename=filename) + return _parse_config_object(parsed_data, filename=filename) def _parse_spec(s: str) -> tuple[int | None, tuple[int | tuple[int, str], ...]]: diff --git a/tests/messages/frontend/test_cli.py b/tests/messages/frontend/test_cli.py index a2b85bfba..30b592b8f 100644 --- a/tests/messages/frontend/test_cli.py +++ b/tests/messages/frontend/test_cli.py @@ -14,6 +14,7 @@ import logging import os +import pathlib import shutil import sys import time @@ -44,6 +45,17 @@ def cli(monkeypatch, capsys): _remove_log_handlers() +@pytest.fixture +def pyproject_toml_file(): + """ + Fixture to create ``${data_dir}/pyproject.toml`` and clean it after the test. + """ + pyproject_toml = (pathlib.Path(data_dir) / "pyproject.toml") + pyproject_toml.touch() + yield pyproject_toml + pyproject_toml.unlink() + + def _remove_log_handlers(): # Logging handlers will be reused if possible (#227). This breaks the # implicit assumption that our newly created StringIO for sys.stderr @@ -219,6 +231,78 @@ def test_extract_with_mapping_file(formatted_frozen_time, cli, pot_file): assert expected_content == pot_file.read_text() +def test_extract_with_mapping_file_from_pyproject_toml_config( + formatted_frozen_time, cli, pot_file, pyproject_toml_file, +): + """ + Test the same as ``test_extract_with_mapping_file()`` but with ``pyproject.toml`` + as the configuration source instead of args purely coming from the CLI. + """ + pyproject_toml_file.write_text( + '[tool.babel.extract_messages]\n' + 'copyright_holder = "FooBar, Inc."\n' + 'project = "TestProject"\n' + 'version = "0.1"\n' + 'msgid_bugs_address = "bugs.address@email.tld"\n' + f"mapping_file = '{os.path.join(data_dir, 'mapping.cfg')}'\n" + 'add_comments = "TRANSLATOR,TRANSLATORS:"\n' + f"output_file = '{pot_file}'\n", + ) + cli.run(['pybabel', 'extract', 'project']) + + expected_content = rf"""# Translations template for TestProject. +# Copyright (C) {time.strftime('%Y')} FooBar, Inc. +# This file is distributed under the same license as the TestProject +# project. +# FIRST AUTHOR , {time.strftime('%Y')}. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: TestProject 0.1\n" +"Report-Msgid-Bugs-To: bugs.address@email.tld\n" +"POT-Creation-Date: {formatted_frozen_time}\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel {VERSION}\n" + +#. TRANSLATOR: This will be a translator coment, +#. that will include several lines +#: project/file1.py:8 +msgid "bar" +msgstr "" + +#: project/file2.py:9 +msgid "foobar" +msgid_plural "foobars" +msgstr[0] "" +msgstr[1] "" + +""" + assert expected_content == pot_file.read_text() + + # Second round, reusing the `expected_content` from above; + # specify `input_paths` as (listified) value from pyproject.toml instead of the CLI + # and specify multiple (listified) comments via pyproject.toml and CLI + pyproject_toml_file.write_text( + '[tool.babel.extract_messages]\n' + 'copyright_holder = "FooBar, Inc."\n' + 'project = "TestProject"\n' + 'version = "0.1"\n' + 'msgid_bugs_address = "bugs.address@email.tld"\n' + f"mapping_file = '{os.path.join(data_dir, 'mapping.cfg')}'\n" + 'add_comments = "TRANSLATOR"\n' + 'input_paths = "project"\n' + f"output_file = '{pot_file}'\n", + ) + cli.run(['pybabel', 'extract', '-c', 'TRANSLATORS:']) + assert expected_content == pot_file.read_text() + + def test_extract_with_exact_file(formatted_frozen_time, cli, pot_file): """Tests that we can call extract with a particular file and only strings from that file get extracted. (Note the absence of strings from file1.py) diff --git a/tests/messages/frontend/test_frontend.py b/tests/messages/frontend/test_frontend.py index c8b8d17d5..366357741 100644 --- a/tests/messages/frontend/test_frontend.py +++ b/tests/messages/frontend/test_frontend.py @@ -97,13 +97,13 @@ ), ( mapping_toml, - frontend._parse_mapping_toml, + frontend._parse_mappings_from_toml, None, True, ), ( mapping_toml, - partial(frontend._parse_mapping_toml, style="pyproject.toml"), + partial(frontend._parse_mappings_from_toml, style="pyproject.toml"), lambda s: re.sub(r"^(\[+)", r"\1tool.babel.", s, flags=re.MULTILINE), True, ), diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index 682728490..0ad58ee57 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -14,7 +14,7 @@ def parse_toml(cfg: bytes | str): if isinstance(cfg, str): cfg = cfg.encode("utf-8") - return frontend._parse_mapping_toml(BytesIO(cfg)) + return frontend._parse_mappings_from_toml(BytesIO(cfg)) def test_toml_mapping_multiple_patterns(): @@ -78,8 +78,34 @@ def test_bad_toml_test_case(test_case: pathlib.Path): """ with pytest.raises(frontend.ConfigurationError): with test_case.open("rb") as f: - frontend._parse_mapping_toml( + frontend._parse_mappings_from_toml( f, filename=test_case.name, style="pyproject.toml" if "pyproject" in test_case.name else "standalone", ) + + +def test_parse_pyproject_toml_config_without_pyproject_toml_file(tmp_path): + """ + Test that trying to parse the config from a missing ``pyproject.toml`` doesn't crash. + """ + assert frontend._parse_pyproject_toml_config(tmp_path, "extract_messages") == {} + + +@pytest.mark.parametrize( + ("pyproject_toml_content", "expected"), + [ + ('[project]\nname = "test"\n', {}), # no [tool.babel] section + ('[tool.babel.compile_catalog]\ndomain = "test"\n', {}), # different command + ( + '[tool.babel.extract_messages]\noutput_file = "test.pot"\n', + {"output_file": "test.pot"}, + ), + ], +) +def test_parse_pyproject_toml_config(tmp_path, pyproject_toml_content, expected): + """ + Test different cases of Babel configuration in ``pyproject.toml``. + """ + (tmp_path / "pyproject.toml").write_text(pyproject_toml_content) + assert frontend._parse_pyproject_toml_config(tmp_path, "extract_messages") == expected From 0b713d9549b7795d332b103cf09142da4c7736a0 Mon Sep 17 00:00:00 2001 From: Maximilian Moser Date: Thu, 5 Nov 2026 14:10:35 +0100 Subject: [PATCH 2/9] Allow specifying an alternative pyproject.toml location and disabling it The environment variable `BABEL_PYPROJECT_TOML` can be used to set an alternative search path for a "pyproject.toml" file for configuration parsing by setting it to a path. If set to "skip" or "none", the config parsing from pyproject.toml will be disabled altogether. Co-authored-by: Aarni Koskela --- babel/messages/frontend.py | 15 ++++++++++-- tests/messages/frontend/test_cli.py | 37 +++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index ed3933201..884b5ef9a 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -1338,7 +1338,6 @@ def run(self, argv=None): if cmdname not in self.commands: self.parser.error(f'unknown command "{cmdname}"') - # TODO add possibility to turn TOML config parsing off, e.g. new option above? cmdinst = self._configure_command(cmdname, args[1:]) return cmdinst.run() @@ -1364,6 +1363,18 @@ def _help(self): for name, description in sorted(self.commands.items()): print(f" {name:<{cmd_width}} {description}") + def _parse_config_from_pyproject_toml(self, cmdinst) -> dict: + pyproject_toml_path_override = os.getenv("BABEL_PYPROJECT_TOML", None) + + if pyproject_toml_path_override in ["none", "skip"]: + return {} + elif pyproject_toml_path_override is None: + path = None + else: + path = pathlib.Path(pyproject_toml_path_override) + + return _parse_pyproject_toml_config(path, cmdinst.toml_config_table) + def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: cmdclass = self.command_classes[cmdname] cmdinst = cmdclass() @@ -1372,7 +1383,7 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: assert isinstance(cmdinst, CommandMixin) cmdinst.initialize_options() - toml_config = _parse_pyproject_toml_config(None, cmdinst.toml_config_table) + toml_config = self._parse_config_from_pyproject_toml(cmdinst) parser = optparse.OptionParser( usage=self.usage % (cmdname, ''), description=self.commands[cmdname], diff --git a/tests/messages/frontend/test_cli.py b/tests/messages/frontend/test_cli.py index 30b592b8f..ccf82eda8 100644 --- a/tests/messages/frontend/test_cli.py +++ b/tests/messages/frontend/test_cli.py @@ -46,14 +46,14 @@ def cli(monkeypatch, capsys): @pytest.fixture -def pyproject_toml_file(): +def pyproject_toml_file(tmp_path, monkeypatch) -> pathlib.Path: """ - Fixture to create ``${data_dir}/pyproject.toml`` and clean it after the test. + Fixture to create ``${tmp_path}/pyproject.toml`` and clean it after the test. """ - pyproject_toml = (pathlib.Path(data_dir) / "pyproject.toml") + pyproject_toml = (tmp_path / "pyproject.toml") pyproject_toml.touch() - yield pyproject_toml - pyproject_toml.unlink() + monkeypatch.setenv("BABEL_PYPROJECT_TOML", str(pyproject_toml)) + return pyproject_toml def _remove_log_handlers(): @@ -303,6 +303,33 @@ def test_extract_with_mapping_file_from_pyproject_toml_config( assert expected_content == pot_file.read_text() +def test_extract_with_mapping_file_with_disabled_pyproject_toml_config( + formatted_frozen_time, cli, pot_file, pyproject_toml_file, monkeypatch, +): + """ + Test the same as ``test_extract_with_mapping_file()`` but with ``pyproject.toml`` + as the configuration source instead of CLI arguments. + """ + pyproject_toml_file.write_text( + '[tool.babel.extract_messages]\n' + 'copyright_holder = "FooBar, Inc."\n' + 'project = "TestProject"\n' + 'version = "0.1"\n' + 'msgid_bugs_address = "bugs.address@email.tld"\n' + f"mapping_file = '{os.path.join(data_dir, 'mapping.cfg')}'\n" + 'add_comments = "TRANSLATOR,TRANSLATORS:"\n' + f"output_file = '{pot_file}'\n", + ) + + # disable the pyproject.toml parsing + monkeypatch.setenv("BABEL_PYPROJECT_TOML", "skip") + + # optparse is expected to exit with code 2, since output-file is required + # but not provided (it's defined in pyproject.toml but that's disabled) + with pytest.raises(SystemExit, match="2"): + cli.run(['pybabel', 'extract', 'project']) + + def test_extract_with_exact_file(formatted_frozen_time, cli, pot_file): """Tests that we can call extract with a particular file and only strings from that file get extracted. (Note the absence of strings from file1.py) From 75392926761db86860b537162dd0371f2775e82c Mon Sep 17 00:00:00 2001 From: Maximilian Moser Date: Thu, 5 Nov 2026 16:17:11 +0100 Subject: [PATCH 3/9] Handle pyproject.toml ConfigurationErrors more gracefully by default If the user explicitly specified a path for searching pyproject.toml, we assume that they know what they're doing, and we crash loudly. --- babel/messages/frontend.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 884b5ef9a..4a793af9e 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -1368,12 +1368,28 @@ def _parse_config_from_pyproject_toml(self, cmdinst) -> dict: if pyproject_toml_path_override in ["none", "skip"]: return {} + elif pyproject_toml_path_override is None: - path = None + # The user is relying on default behavior; + # let's handle config parsing errors gracefully (by logging) + try: + return _parse_pyproject_toml_config(None, cmdinst.toml_config_table) + + except ImportError as ie: + self.log.error("Could not load TOML parsing library: %s", ie) + return {} + + except ConfigurationError as ce: + self.log.error("Unable to parse configuration: %s", ce) + return {} + else: - path = pathlib.Path(pyproject_toml_path_override) + # The user specified a pyproject.toml path explicitly; + # let's crash loudly in case of errors + return _parse_pyproject_toml_config( + pathlib.Path(pyproject_toml_path_override), cmdinst.toml_config_table, + ) - return _parse_pyproject_toml_config(path, cmdinst.toml_config_table) def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: cmdclass = self.command_classes[cmdname] From 51f6096bcf3678e980e3b92ef1653991b13c5df0 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 17:29:31 +0200 Subject: [PATCH 4/9] Only read pyproject.toml from the current directory Relative paths in the configuration are resolved relative to the current working directory, so picking up a pyproject.toml from a parent directory could make them point to the wrong place. --- babel/messages/frontend.py | 33 +++++++---------------- tests/messages/test_toml_config.py | 43 +++++++++++++++++------------- 2 files changed, 35 insertions(+), 41 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 4a793af9e..ae265a818 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -103,44 +103,31 @@ def _parse_toml( return babel_data -def _find_pyproject_toml( - path: pathlib.Path | None, max_depth: int = 10, -) -> pathlib.Path | None: - """Find the closest "pyproject.toml" file to the specified path. +def _find_pyproject_toml(path: pathlib.Path | None) -> pathlib.Path | None: + """Find the "pyproject.toml" file to read configuration from. - If the given path's directory contains a ``pyproject.toml``, return that. - Otherwise, walk up the directory hierarchy until one has been found or the - maximum search depth has been exhausted. + The directory hierarchy is presently deliberately *not* searched upwards, + since relative paths in the configuration are resolved relative to the + current working directory. This may change in a future version. - :param path: The path to start the search for ``pyproject.toml`` from. + :param path: A path to a file, or a directory containing a ``pyproject.toml``. If set to ``None``, the current working directory will be used. - :param max_depth: The maximum number of steps up the file system for the search. """ if path is None: path = pathlib.Path.cwd() - path = path.resolve() # resolve symlinks and remove ".." components if path.is_file(): return path - tries = 0 - while tries < max_depth: - pyproject_file = path / "pyproject.toml" - if pyproject_file.is_file(): - return pyproject_file - - parent = path.parent - if path == parent: - return None - - path = parent - tries += 1 + pyproject_file = path / "pyproject.toml" + if pyproject_file.is_file(): + return pyproject_file return None def _parse_pyproject_toml_config(path: pathlib.Path | None, table_name: str | None) -> dict: - """Parse the Babel config from a "pyproject.toml" file near the specified path.""" + """Parse the Babel config from a "pyproject.toml" file at the specified path.""" if table_name is None: return {} diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index 0ad58ee57..00bedaf0a 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -85,27 +85,34 @@ def test_bad_toml_test_case(test_case: pathlib.Path): ) -def test_parse_pyproject_toml_config_without_pyproject_toml_file(tmp_path): - """ - Test that trying to parse the config from a missing ``pyproject.toml`` doesn't crash. - """ - assert frontend._parse_pyproject_toml_config(tmp_path, "extract_messages") == {} +@pytest.fixture +def in_tmp_path(tmp_path, monkeypatch) -> pathlib.Path: + monkeypatch.delenv("BABEL_PYPROJECT_TOML", raising=False) + monkeypatch.chdir(tmp_path) + return tmp_path + + +def _parse_cli_config(command="extract"): + cli = frontend.CommandLineInterface() + cli.log = frontend.log + cmdinst = cli.command_classes[command]() + return cli._parse_config_from_pyproject_toml(cmdinst) @pytest.mark.parametrize( - ("pyproject_toml_content", "expected"), + ("path", "content", "expected"), [ - ('[project]\nname = "test"\n', {}), # no [tool.babel] section - ('[tool.babel.compile_catalog]\ndomain = "test"\n', {}), # different command - ( - '[tool.babel.extract_messages]\noutput_file = "test.pot"\n', - {"output_file": "test.pot"}, - ), + ("pyproject.toml", '[project]\nname = "test"\n', {}), + ("pyproject.toml", '[tool.babel.compile_catalog]\ndomain = "test"\n', {}), + ("pyproject.toml", '[tool.babel.extract_messages]\noutput_file = "x.pot"\n', {"output_file": "x.pot"}), + ("../pyproject.toml", '[tool.babel.extract_messages]\noutput_file = "x.pot"\n', {}), # no upward search + (None, None, {}), # no file ], ) -def test_parse_pyproject_toml_config(tmp_path, pyproject_toml_content, expected): - """ - Test different cases of Babel configuration in ``pyproject.toml``. - """ - (tmp_path / "pyproject.toml").write_text(pyproject_toml_content) - assert frontend._parse_pyproject_toml_config(tmp_path, "extract_messages") == expected +def test_cli_pyproject_toml_lookup(in_tmp_path, monkeypatch, path, content, expected): + sub = in_tmp_path / "sub" + sub.mkdir() + monkeypatch.chdir(sub) + if path: + (sub / path).write_text(content) + assert _parse_cli_config() == expected From e849f27814d4db886840a3050cd29b28f8e1c01d Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 17:30:24 +0200 Subject: [PATCH 5/9] Skip or at least don't crash on bad pyproject.tomls * If unreadable or malformed, don't crash * Skip parsing pyproject.toml files that can't contain Babel configuration altogether --- babel/messages/frontend.py | 47 ++++++++++++++++++++---------- tests/messages/test_toml_config.py | 17 +++++++++++ 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index ae265a818..a105c17a0 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -24,7 +24,7 @@ from collections import Counter, defaultdict from collections.abc import Iterable from configparser import RawConfigParser -from io import StringIO +from io import BytesIO, StringIO from typing import TYPE_CHECKING, Any, BinaryIO, Literal if TYPE_CHECKING: @@ -77,7 +77,7 @@ def _parse_toml( try: parsed_data = tomllib.load(fileobj) - except tomllib.TOMLDecodeError as e: + except (tomllib.TOMLDecodeError, UnicodeDecodeError) as e: raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e if style == "pyproject.toml": @@ -91,6 +91,11 @@ def _parse_toml( else: return {} + if not isinstance(babel_data, dict): + raise ConfigurationError( + f"{filename}: 'tool.babel' should be a table, got {type(babel_data).__name__}", + ) + elif style == "standalone": babel_data = parsed_data if "babel" in babel_data: @@ -131,18 +136,30 @@ def _parse_pyproject_toml_config(path: pathlib.Path | None, table_name: str | No if table_name is None: return {} - if path := _find_pyproject_toml(path): - with path.open("rb") as file_fd: - babel_data = _parse_toml( - file_fd, - style="pyproject.toml", - filename=path.name, - allow_missing_sections=True, - ) - return babel_data.get(table_name, {}) - else: + path = _find_pyproject_toml(path) + if not path: + return {} + + data = path.read_bytes() + if b"babel" not in data: + # Can't possibly contain a `tool.babel` table, + # so don't bother parsing at all (or require a TOML library) return {} + babel_data = _parse_toml( + BytesIO(data), + style="pyproject.toml", + filename=str(path), + allow_missing_sections=True, + ) + + table = babel_data.get(table_name, {}) + if not isinstance(table, dict): + raise ConfigurationError( + f"{path}: 'tool.babel.{table_name}' should be a table, got {type(table).__name__}", + ) + return table + class BaseError(Exception): pass @@ -1363,11 +1380,11 @@ def _parse_config_from_pyproject_toml(self, cmdinst) -> dict: return _parse_pyproject_toml_config(None, cmdinst.toml_config_table) except ImportError as ie: - self.log.error("Could not load TOML parsing library: %s", ie) + self.log.warning("Could not load TOML parsing library: %s", ie) return {} - except ConfigurationError as ce: - self.log.error("Unable to parse configuration: %s", ce) + except (ConfigurationError, OSError) as e: + self.log.warning("Ignoring pyproject.toml configuration: %s", e) return {} else: diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index 00bedaf0a..da6e06791 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import pathlib from io import BytesIO @@ -116,3 +117,19 @@ def test_cli_pyproject_toml_lookup(in_tmp_path, monkeypatch, path, content, expe if path: (sub / path).write_text(content) assert _parse_cli_config() == expected + + +@pytest.mark.parametrize( + "content", + [ + pytest.param(b"[tool.babel]\nx = [", id="malformed"), + pytest.param(b'[tool.babel]\nx = "\xff"\n', id="non-utf8"), + pytest.param(b'[tool]\nbabel = "x"\n', id="babel-not-a-table"), + pytest.param(b'[tool.babel]\nextract_messages = "x"\n', id="command-not-a-table"), + ], +) +def test_cli_ignores_bad_pyproject_toml_by_default(in_tmp_path, caplog, content): + (in_tmp_path / "pyproject.toml").write_bytes(content) + with caplog.at_level(logging.WARNING, logger="babel"): + assert _parse_cli_config() == {} + assert "Ignoring pyproject.toml configuration" in caplog.text From ef3fe77c144b4d7c0f786ea906d9785cf60ffdda Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 17:31:24 +0200 Subject: [PATCH 6/9] Be strict about an explicitly specified BABEL_PYPROJECT_TOML A path that isn't a file is now an error instead of silently falling back to searching from it. --- babel/messages/frontend.py | 15 +++++++-------- tests/messages/frontend/test_cli.py | 27 --------------------------- tests/messages/test_toml_config.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 35 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index a105c17a0..e68872964 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -1373,7 +1373,7 @@ def _parse_config_from_pyproject_toml(self, cmdinst) -> dict: if pyproject_toml_path_override in ["none", "skip"]: return {} - elif pyproject_toml_path_override is None: + elif not pyproject_toml_path_override: # The user is relying on default behavior; # let's handle config parsing errors gracefully (by logging) try: @@ -1387,13 +1387,12 @@ def _parse_config_from_pyproject_toml(self, cmdinst) -> dict: self.log.warning("Ignoring pyproject.toml configuration: %s", e) return {} - else: - # The user specified a pyproject.toml path explicitly; - # let's crash loudly in case of errors - return _parse_pyproject_toml_config( - pathlib.Path(pyproject_toml_path_override), cmdinst.toml_config_table, - ) - + # The user specified a pyproject.toml path explicitly; + # let's crash loudly in case of errors + path = pathlib.Path(pyproject_toml_path_override) + if not path.is_file(): + raise ConfigurationError(f"BABEL_PYPROJECT_TOML: {pyproject_toml_path_override} is not a file") + return _parse_pyproject_toml_config(path, cmdinst.toml_config_table) def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: cmdclass = self.command_classes[cmdname] diff --git a/tests/messages/frontend/test_cli.py b/tests/messages/frontend/test_cli.py index ccf82eda8..bda034368 100644 --- a/tests/messages/frontend/test_cli.py +++ b/tests/messages/frontend/test_cli.py @@ -303,33 +303,6 @@ def test_extract_with_mapping_file_from_pyproject_toml_config( assert expected_content == pot_file.read_text() -def test_extract_with_mapping_file_with_disabled_pyproject_toml_config( - formatted_frozen_time, cli, pot_file, pyproject_toml_file, monkeypatch, -): - """ - Test the same as ``test_extract_with_mapping_file()`` but with ``pyproject.toml`` - as the configuration source instead of CLI arguments. - """ - pyproject_toml_file.write_text( - '[tool.babel.extract_messages]\n' - 'copyright_holder = "FooBar, Inc."\n' - 'project = "TestProject"\n' - 'version = "0.1"\n' - 'msgid_bugs_address = "bugs.address@email.tld"\n' - f"mapping_file = '{os.path.join(data_dir, 'mapping.cfg')}'\n" - 'add_comments = "TRANSLATOR,TRANSLATORS:"\n' - f"output_file = '{pot_file}'\n", - ) - - # disable the pyproject.toml parsing - monkeypatch.setenv("BABEL_PYPROJECT_TOML", "skip") - - # optparse is expected to exit with code 2, since output-file is required - # but not provided (it's defined in pyproject.toml but that's disabled) - with pytest.raises(SystemExit, match="2"): - cli.run(['pybabel', 'extract', 'project']) - - def test_extract_with_exact_file(formatted_frozen_time, cli, pot_file): """Tests that we can call extract with a particular file and only strings from that file get extracted. (Note the absence of strings from file1.py) diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index da6e06791..bd360cf42 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -133,3 +133,32 @@ def test_cli_ignores_bad_pyproject_toml_by_default(in_tmp_path, caplog, content) with caplog.at_level(logging.WARNING, logger="babel"): assert _parse_cli_config() == {} assert "Ignoring pyproject.toml configuration" in caplog.text + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("", {"output_file": "x.pot"}), + ("skip", {}), + ], +) +def test_cli_pyproject_toml_env_disable_or_default(in_tmp_path, monkeypatch, value, expected): + (in_tmp_path / "pyproject.toml").write_text('[tool.babel.extract_messages]\noutput_file = "x.pot"\n') + monkeypatch.setenv("BABEL_PYPROJECT_TOML", value) + assert _parse_cli_config() == expected + + +@pytest.mark.parametrize( + ("filename", "content", "match"), + [ + ("pyproject.tml", None, "is not a file"), + ("config.toml", "[tool.babel.extract_messages]\nx = [", "Error parsing TOML"), + ], +) +def test_cli_pyproject_toml_env_errors_are_raised(in_tmp_path, monkeypatch, filename, content, match): + (in_tmp_path / "pyproject.toml").write_text('[tool.babel.extract_messages]\noutput_file = "x.pot"\n') + if content: + (in_tmp_path / filename).write_text(content) + monkeypatch.setenv("BABEL_PYPROJECT_TOML", str(in_tmp_path / filename)) + with pytest.raises(frontend.ConfigurationError, match=match): + _parse_cli_config() From e61e7a2056a5f8fae14e141690099dbf0ec8154c Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 17:34:16 +0200 Subject: [PATCH 7/9] Allow dashed option names in pyproject.toml E.g. `output-file` is now treated the same as `output_file`, matching the command line option names. --- babel/messages/frontend.py | 3 ++- tests/messages/test_toml_config.py | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index e68872964..377545f6f 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -158,7 +158,8 @@ def _parse_pyproject_toml_config(path: pathlib.Path | None, table_name: str | No raise ConfigurationError( f"{path}: 'tool.babel.{table_name}' should be a table, got {type(table).__name__}", ) - return table + # Allow spelling keys like the command line options, e.g. `output-file` + return {key.replace("-", "_"): value for key, value in table.items()} class BaseError(Exception): diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index bd360cf42..6fbcb7378 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -106,6 +106,7 @@ def _parse_cli_config(command="extract"): ("pyproject.toml", '[project]\nname = "test"\n', {}), ("pyproject.toml", '[tool.babel.compile_catalog]\ndomain = "test"\n', {}), ("pyproject.toml", '[tool.babel.extract_messages]\noutput_file = "x.pot"\n', {"output_file": "x.pot"}), + ("pyproject.toml", '[tool.babel.extract_messages]\noutput-file = "x.pot"\n', {"output_file": "x.pot"}), ("../pyproject.toml", '[tool.babel.extract_messages]\noutput_file = "x.pot"\n', {}), # no upward search (None, None, {}), # no file ], From 6472a70150fb786f35dfea2ebf5463d5681d8fa2 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 18:26:32 +0200 Subject: [PATCH 8/9] Briefly document CLI pyproject.toml support --- docs/cmdline.rst | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/cmdline.rst b/docs/cmdline.rst index 672bbfe70..bc9899152 100644 --- a/docs/cmdline.rst +++ b/docs/cmdline.rst @@ -32,6 +32,32 @@ When properly installed, Babel provides a script called ``pybabel``:: The ``pybabel`` script provides a number of sub-commands that do the actual work. Those sub-commands are described below. +Configuration in ``pyproject.toml`` +=================================== + +The ``extract``, ``init``, ``update`` and ``compile`` sub-commands read option +defaults from ``[tool.babel.]`` in ``pyproject.toml`` in the current +directory. A future version of Babel may extend this to look in parent directories. + +Keys are long option names (dashes or underscores), but command line options +take precedence:: + + [tool.babel.extract_messages] + output_file = "locale/messages.pot" + input_paths = ["src"] + add_comments = ["TRANSLATORS:"] + mapping_file = "pyproject.toml" + + [tool.babel.compile_catalog] + directory = "locale" + use_fuzzy = true + +The table names are ``extract_messages``, ``init_catalog``, ``update_catalog`` +and ``compile_catalog``. Relative paths are relative to the current directory. + +Set ``BABEL_PYPROJECT_TOML`` to read a different file instead, +or to ``skip`` to not read any. + compile ======= From 7f06a48aebc9b177751a5cae72f730c41823718a Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 24 Nov 2026 18:54:21 +0200 Subject: [PATCH 9/9] Do not whitespace-split values from TOML --- babel/messages/frontend.py | 6 ++++-- tests/messages/test_toml_config.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 377545f6f..2492747c6 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -1423,7 +1423,8 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: elif name in cmdclass.boolean_options: parser.add_option(*strs, action="store_true", default=default, help=help) elif name in cmdclass.multiple_value_options: - parser.add_option(*strs, action="append", default=listify_value(default), help=help, choices=choices) + default_list = [default] if isinstance(default, str) else default + parser.add_option(*strs, action="append", default=default_list, help=help, choices=choices) else: parser.add_option(*strs, help=help, default=default, choices=choices) @@ -1432,7 +1433,8 @@ def _configure_command(self, cmdname: str, argv: list[str]) -> CommandMixin: if as_args: # Read `args` from TOML; `as_args` is the key name, e.g. # `input_paths = ...` in `[tool.babel.extract_messages]` - args = args or listify_value(toml_config.get(as_args.replace("-", "_"), args)) + toml_args = toml_config.get(as_args.replace("-", "_"), []) + args = args or ([toml_args] if isinstance(toml_args, str) else toml_args) setattr(options, as_args.replace('-', '_'), args) for key, value in vars(options).items(): diff --git a/tests/messages/test_toml_config.py b/tests/messages/test_toml_config.py index 6fbcb7378..f6e139c8c 100644 --- a/tests/messages/test_toml_config.py +++ b/tests/messages/test_toml_config.py @@ -163,3 +163,18 @@ def test_cli_pyproject_toml_env_errors_are_raised(in_tmp_path, monkeypatch, file monkeypatch.setenv("BABEL_PYPROJECT_TOML", str(in_tmp_path / filename)) with pytest.raises(frontend.ConfigurationError, match=match): _parse_cli_config() + + +def test_cli_pyproject_toml_list_values_not_split(in_tmp_path): + (in_tmp_path / "a b.py").touch() + (in_tmp_path / "pyproject.toml").write_text( + '[tool.babel.extract_messages]\n' + 'output_file = "x.pot"\n' + 'add_comments = ["NOTE TO TRANSLATORS:"]\n' + 'input_paths = ["a b.py"]\n', + ) + cli = frontend.CommandLineInterface() + cli.log = frontend.log + cmdinst = cli._configure_command("extract", []) + assert cmdinst.add_comments == ["NOTE TO TRANSLATORS:"] + assert cmdinst.input_paths == ["a b.py"]