Repository navigation
Conversation
Plugins can now declare their own settings with default values and optional validators and normalizers via poetry.config.register_plugin(). Declared settings are scoped to "plugins.<plugin name>.<setting key>" and behave like core settings: they are listed by "poetry config --list", can be configured with "poetry config" (with validation) and via POETRY_PLUGINS_* environment variables, and the default value is only used if the setting is not configured already, e.g. in the user's or the project's configuration file. Relates-to: python-poetry#9695
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/poetry/config/config.py" line_range="528" />
<code_context>
+ def _get_setting(self, name: str | Sequence[str]) -> ConfigSetting | None:
if not isinstance(name, str):
name = ".".join(name)
+ if name in self._plugin_settings:
+ return self._plugin_settings[name]
if name.startswith("installer.build-config-settings."):
</code_context>
<issue_to_address>
**Invalid plugin values reach callers**
When a plugin setting has a validator, uses a normalizer other than `int_normalizer`, and its environment variable contains a value rejected by the validator, `Config.get()` skips the validator for these environment values, normalizes or returns them, and passes invalid plugin configuration to the caller.
Apply the setting's validator to environment values for every normalizer, rejecting values that fail before returning them.
Also at `src/poetry/config/config.py:529`, `src/poetry/plugins/plugin_config.py:66-68`.
</issue_to_address>
### Comment 2
<location path="src/poetry/config/config.py" line_range="317" />
<code_context>
+ """
+ setting_key = f"{PLUGIN_SETTINGS_SECTION}.{canonicalize_name(name)}.{key}"
+ self._plugin_settings[setting_key] = setting
+ self._set_default_config_value(setting_key, default)
+
+ def has_setting(self, name: str | Sequence[str]) -> bool:
</code_context>
<issue_to_address>
**Plugin secrets appear in config output**
When a plugin declares a setting for a secret, such as an API token, and a user runs `poetry config --list` or captures its output in logs, a user or process that runs `poetry config --list` exposes any plugin setting containing a credential: the setting is added to the ordinary configuration tree, and the listing redacts only the core `http-basic` and `pypi-token` paths.
Provide a way to mark plugin settings as sensitive and redact them in listing and individual-value output.
</issue_to_address>
### Comment 3
<location path="src/poetry/config/config.py" line_range="264" />
<code_context>
self._use_environment = use_environment
self._config_source: ConfigSource = DictConfigSource()
self._auth_config_source: ConfigSource = DictConfigSource()
+ self._plugin_settings: dict[str, ConfigSetting] = {}
@property
</code_context>
<issue_to_address>
**Inactive plugin settings remain available**
When a process reuses a cached `Config` after a plugin was registered but is no longer active, the cached `Config` retains the plugin's registry entries and defaults, so `has_setting()` still recognizes them and `poetry config` exposes and accepts settings for an inactive plugin.
Clear or rebuild plugin registrations and their defaults when a cached `Config` is reused without those plugins.
Also at `src/poetry/config/config.py:316-317`.
</issue_to_address>
### Comment 4
<location path="src/poetry/config/config.py" line_range="316" />
<code_context>
+ the user's or the project's configuration file.
+ """
+ setting_key = f"{PLUGIN_SETTINGS_SECTION}.{canonicalize_name(name)}.{key}"
+ self._plugin_settings[setting_key] = setting
+ self._set_default_config_value(setting_key, default)
+
</code_context>
<issue_to_address>
**Failed registration leaves settings available**
When a plugin setting path crosses a non-table configuration value and the caller catches the registration error, `_set_default_config_value()` raises after the setting is inserted into `_plugin_settings`, so `has_setting()` reports a setting as registered even though its default was not installed.
Add the setting to `_plugin_settings` only after `_set_default_config_value()` succeeds, or roll back the registry entry when it fails.
</issue_to_address>
### Comment 5
<location path="src/poetry/config/config.py" line_range="347" />
<code_context>
A plugin **must not** remove or modify in any way the core commands of Poetry.
{{% /warning %}}
+### Plugin settings
+
</code_context>
<issue_to_address>
**Mutable defaults leak across configs**
When a plugin declares a mutable default such as a list or dictionary and that value is mutated through the returned configuration value, `table.setdefault(leaf, default)` stores a mutable default object by reference, so mutating the value returned by `PluginConfig.get()` also mutates the object supplied by the plugin and any other config instance given that same default.
Deep-copy plugin defaults when inserting them into a Config instance.
</issue_to_address>
### Comment 6
<location path="src/poetry/console/commands/config.py" line_range="155" />
<code_context>
self.line(str(value))
else:
- if setting_key not in Config.settings:
+ if not config.has_setting(setting_key):
raise ValueError(f"There is no {setting_key} setting.")
</code_context>
<issue_to_address>
**Plugin settings unavailable outside projects**
When `poetry config` is run outside a valid project, `config.has_setting()` finds no plugin declaration, so get, set, and unset report the setting as unknown; `--list` also omits plugin defaults because they were never registered.
Load and activate regular plugins for the config command even when no project is available, registering their settings on the `Config` instance used by the command.
Also at `src/poetry/console/commands/config.py:169`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 6 findings to address first, and a plugin setting written through poetry config is persisted and may change that plugin’s behavior; if validation or normalization stores the wrong value, reverting the code does not remove it. The value is bounded and can be unset or corrected in the configuration.
Blocking findings: src/poetry/config/config.py:528, src/poetry/config/config.py:317, src/poetry/config/config.py:264, src/poetry/config/config.py:316, src/poetry/config/config.py:347, and 1 more
Address the review findings on the plugin settings API: - Declare plugin settings when a plugin is loaded (new optional BasePlugin.declare_settings hook) instead of when it is activated, so that settings are known even when Poetry runs outside of a project. PluginManager.load_plugins() rebuilds the settings of its group so that settings of plugins that are no longer available do not linger on a cached Config instance. - Enforce the validator of a plugin setting for values that come from environment variables, not only for integer settings. - Allow marking plugin settings as secret. Secret settings are not shown by "poetry config --list" and cannot be read without a value, like http-basic and pypi-token. - Register a plugin setting only after its default value could be applied so that a failed registration does not leave the setting behind. - Deep-copy mutable default values so that they are not shared between the plugin and Config instances. - The config command loads the regular plugins when there is no project so that plugin settings can be configured globally.
f725030 to
5223092
Compare
The previous text suggested that a different name can be passed to register_plugin() to scope a plugin's settings. Settings are declared when a plugin is loaded, i.e. scoped to the canonicalized name of the package the plugin is defined in, so a configuration view created with an explicit name does not know any declared settings and "poetry config plugins.<name>.<key>" cannot find them. Describe the actual scoping and fix the examples to use the package-derived name.
|
Independent review of this PR (maintainer's perspective), plus one documentation fix I re-reviewed the complete diff independently, verifying each of the six Sourcery findings against the code itself rather than trusting the "Addressed" markers, and checked backward compatibility, the public API contract, cross-group caching, exception paths, and whether the new tests actually pin behavior. One real defect was found; it is fixed in 3402393 (documentation only). Everything else checks out. Verified as correctly fixed:
Backward compatibility: Defect found and fixed (3402393, documentation only) docs/plugins.md claimed that "a different name can be passed to Verification on this branch (project $ pytest tests/plugins/test_plugin_config.py tests/console/commands/test_config.py tests/config/test_config.py -n 0 -q
207 passed in 6.50s
$ pytest tests/config tests/plugins -n 0 -q
170 passed in 2.90s
$ pytest tests/console/commands -n 0 -q
901 passed, 2 skipped in 175.03s
$ mypy src/poetry/config/config.py src/poetry/console/commands/config.py src/poetry/plugins/base_plugin.py src/poetry/plugins/plugin_config.py src/poetry/plugins/plugin_manager.py
Success: no issues found in 5 source files
$ ruff check <5 changed source files + 3 changed test files>
All checks passed!
$ ruff format --check <same 8 files>
8 files already formattedWith this correction I consider the PR ready for maintainer review. Disclosure: this review and the documentation fix were prepared with assistance from MiniMax Code (MCode). |
Linked issuesChecked at commit 3402393 #9695 Allow plugins to define settings · 3 of 3 met
|
Summary
Resolves: #9695
Plugins had no way to declare their own settings: settings that are not part of
Poetry's hardcoded list cannot be configured with
poetry config, so plugins hadto read their settings from config files directly and each plugin had to implement
its own validation and normalization (see the
pypi-mirror plugin
referenced in the issue). Maintainer @Secrus confirmed that this is
"on the roadmap for the plugin API",
so this PR implements the interface proposed in the issue:
Declared settings are scoped to
plugins.<plugin name>.<setting key>and behavelike core settings. Settings are declared when the plugin is loaded (not when
it is activated) so that they are known even when Poetry runs outside of a
project, which is the primary use case from the issue: configuring global
plugin settings with
poetry config. No open PR in this repository implementsthis (I searched the open PR list for 9695 and for plugin settings; neither
matched).
Gap and value
poetry configdoes not knowthey exist. Each plugin validates and normalizes values itself, and users edit
config files by hand.
(e.g. a private PyPI mirror) can expose its settings with a native interface:
poetry config plugins.<name>.<key> <value>,poetry config --unset plugins.<name>.<key>,poetry config --list, andPOETRY_PLUGINS_<NAME>_<KEY>environment variables, with the plugin's ownvalidator/normalizer applied. Values from config files keep working unchanged.
BasePlugin.declare_settings,PluginConfig.define_setting,Config.register_plugin— that did not existbefore. Core settings are untouched.
the plugin API roadmap statement by @Secrus.
Implementation
src/poetry/plugins/base_plugin.py: new optional hookBasePlugin.declare_settings(), called when a plugin is loaded.src/poetry/plugins/plugin_config.py(new):PluginConfig, the per-pluginconfiguration view returned by
Config.register_plugin(), withdefine_setting(key, default, validator=None, normalizer=None, secret=False)and
get(key).src/poetry/plugins/plugin_manager.py:load_plugins()rebuilds thesettings of its plugin group from scratch (so settings of plugins that are
no longer available do not linger on a cached
Config) and declares thesettings of each loaded plugin.
src/poetry/config/config.py:Config.register_plugin(plugin, name=None)returns aPluginConfigscopedto the canonicalized name of the package the plugin is defined in, or to
an explicitly given name.
Config.add_plugin_setting()registers the validator/normalizer perinstance and applies the default value (deep-copied) only if the setting
is not configured already, so user configuration (global
config.tomlorproject
poetry.toml, both merged before plugins are loaded) always winsover plugin defaults. A failed registration does not register the setting.
Config.has_setting()reports whether a setting exists (core orplugin-declared);
Config.is_secret_setting()reports whether a settingholds a secret.
Config.reset_plugin_settings(group)drops the settings (registry entriesand inserted defaults) of a plugin group.
get_normalizer()andget_validator()became instance methods (they wereclassmethods used only internally and by the
configcommand) so thatplugin settings participate in validation and normalization, e.g. for
POETRY_PLUGINS_*environment variables andpoetry config. Values fromenvironment variables are rejected if they do not pass the validator of
the setting.
src/poetry/console/commands/config.py: theconfigcommand resolvessettings via the
Configinstance (has_setting,get_validator,get_normalizer,is_secret_setting), so get/set/unset/list work forplugin settings, including validation of entered values. Settings marked as
secret are treated like
http-basic/pypi-token: they are not listed by--listand cannot be read without a value. Without a project, the commandloads the regular plugins so that their settings are known.
docs/plugins.md: new "Plugin settings" section.tests/plugins/test_plugin_config.py(new) plus plugin-setting casesin
tests/console/commands/test_config.py.Value precedence (consistent with core settings): environment variable >
user/project configuration file > plugin default.
Verification
All commands were run in the repository checkout with the project
.venv:The tests for the changes were written before the implementation and verified
to fail first (e.g.
AttributeError: 'Config' object has no attribute 'is_secret_setting',ValueError: Setting plugins.tests.retries does notexistoutside a project), then pass after the implementation.Impact
Config.default_configandConfig.settingsare untouched; plugin settings live in a per-instanceregistry under the new
pluginssection and only exist while the declaringplugin is installed. The existing test asserting that
Config.settingsstays in sync with
default_configstill passes.Config.get_normalizer()/Config.get_validator()changed fromclassmethods to instance methods. They are internal APIs (not part of the
documented plugin API); all in-repo call sites are updated.
integer settings reject invalid values); the validator is enforced for
plugin settings because plugins declare their own validator.
PluginManager.load_plugins()now touchesConfig(it rebuilds the pluginsettings of its group and declares the settings of loaded plugins).
AI disclosure
This contribution was prepared with assistance from MiniMax Code (MCode), an AI
coding assistant, authorized by the account owner: the
implementation, tests, documentation and the verification runs above were
produced and executed with it; no line-by-line human code review is claimed.
Checklist