Skip to content

feat: allow plugins to define their own settings - #11292

Open
Surri757 wants to merge 3 commits into
python-poetry:mainfrom
Surri757:fix/9695-plugin-settings
Open

Surri757 wants to merge 3 commits into
python-poetry:mainfrom
Surri757:fix/9695-plugin-settings

Conversation

@Surri757

@Surri757 Surri757 commented Nov 28, 2026 •

Copy link
Copy Markdown

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 had
to 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:

class MyPlugin(Plugin):
    def declare_settings(self, config: PluginConfig) -> None:
        config.define_setting("mirror-url", "https://pypi.org/simple")
        config.define_setting(
            "retries", 3, validator=int_validator, normalizer=int_normalizer
        )

    def activate(self, poetry: Poetry, io: IO) -> None:
        config = poetry.config.register_plugin(self)
        url = config.get("mirror-url")

Declared settings are scoped to plugins.<plugin name>.<setting key> and behave
like 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 implements
this (I searched the open PR list for 9695 and for plugin settings; neither
matched).

Gap and value

  • Today: a plugin cannot declare settings, so poetry config does not know
    they exist. Each plugin validates and normalizes values itself, and users edit
    config files by hand.
  • Who benefits and what changes: every plugin that needs configuration
    (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, and
    POETRY_PLUGINS_<NAME>_<KEY> environment variables, with the plugin's own
    validator/normalizer applied. Values from config files keep working unchanged.
  • What it adds: a new plugin API entry point — BasePlugin.declare_settings,
    PluginConfig.define_setting, Config.register_plugin — that did not exist
    before. Core settings are untouched.
  • Direction: follows the interface proposed by the issue author in Allow plugins to define settings #9695 and
    the plugin API roadmap statement by @Secrus.

Implementation

  • src/poetry/plugins/base_plugin.py: new optional hook
    BasePlugin.declare_settings(), called when a plugin is loaded.
  • src/poetry/plugins/plugin_config.py (new): PluginConfig, the per-plugin
    configuration view returned by Config.register_plugin(), with
    define_setting(key, default, validator=None, normalizer=None, secret=False)
    and get(key).
  • src/poetry/plugins/plugin_manager.py: load_plugins() rebuilds the
    settings of its plugin group from scratch (so settings of plugins that are
    no longer available do not linger on a cached Config) and declares the
    settings of each loaded plugin.
  • src/poetry/config/config.py:
    • Config.register_plugin(plugin, name=None) returns a PluginConfig scoped
      to 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 per
      instance and applies the default value (deep-copied) only if the setting
      is not configured already, so user configuration (global config.toml or
      project poetry.toml, both merged before plugins are loaded) always wins
      over plugin defaults. A failed registration does not register the setting.
    • Config.has_setting() reports whether a setting exists (core or
      plugin-declared); Config.is_secret_setting() reports whether a setting
      holds a secret.
    • Config.reset_plugin_settings(group) drops the settings (registry entries
      and inserted defaults) of a plugin group.
    • get_normalizer() and get_validator() became instance methods (they were
      classmethods used only internally and by the config command) so that
      plugin settings participate in validation and normalization, e.g. for
      POETRY_PLUGINS_* environment variables and poetry config. Values from
      environment variables are rejected if they do not pass the validator of
      the setting.
  • src/poetry/console/commands/config.py: the config command resolves
    settings via the Config instance (has_setting, get_validator,
    get_normalizer, is_secret_setting), so get/set/unset/list work for
    plugin settings, including validation of entered values. Settings marked as
    secret are treated like http-basic/pypi-token: they are not listed by
    --list and cannot be read without a value. Without a project, the command
    loads the regular plugins so that their settings are known.
  • docs/plugins.md: new "Plugin settings" section.
  • Tests: tests/plugins/test_plugin_config.py (new) plus plugin-setting cases
    in 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:

$ .venv/Scripts/python.exe -m pytest tests/plugins/test_plugin_config.py tests/console/commands/test_config.py tests/config/test_config.py -n 0 -q
207 passed in 8.90s

$ .venv/Scripts/python.exe -m pytest tests/config tests/plugins tests/console/commands -n 0 -q
1071 passed, 2 skipped in 113.22s (0:01:53)

$ .venv/Scripts/python.exe -m pytest tests/console -n 0 -q
1021 passed, 2 skipped in 131.52s (0:02:11)

$ .venv/Scripts/python.exe -m mypy <8 changed files>
Success: no issues found in 8 source files

$ .venv/Scripts/ruff.exe check <8 changed files>
All checks passed!

$ .venv/Scripts/ruff.exe format --check <8 changed files>
8 files already formatted

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 not
exist outside a project), then pass after the implementation.

Impact

  • Core configuration behavior is unchanged: Config.default_config and
    Config.settings are untouched; plugin settings live in a per-instance
    registry under the new plugins section and only exist while the declaring
    plugin is installed. The existing test asserting that Config.settings
    stays in sync with default_config still passes.
  • Config.get_normalizer() / Config.get_validator() changed from
    classmethods to instance methods. They are internal APIs (not part of the
    documented plugin API); all in-repo call sites are updated.
  • Core settings keep their previous environment variable behavior (only
    integer settings reject invalid values); the validator is enforced for
    plugin settings because plugins declare their own validator.
  • PluginManager.load_plugins() now touches Config (it rebuilds the plugin
    settings 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

  • Added tests for changed code.
  • Updated documentation for changed code.

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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/poetry/config/config.py Resolved
Comment thread src/poetry/config/config.py Resolved
Comment thread src/poetry/config/config.py Resolved
Comment thread src/poetry/config/config.py Resolved
Comment thread src/poetry/config/config.py Resolved
Comment thread src/poetry/console/commands/config.py Resolved
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.
@Surri757
Surri757 force-pushed the fix/9695-plugin-settings branch from f725030 to 5223092 Compare November 28, 2026 05:49
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.
@Surri757

Copy link
Copy Markdown
Author

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:

  1. Environment values validated for every normalizer - src/poetry/config/config.py:547-553: the validator is now enforced when the joined key is a registered plugin setting, for any normalizer; core settings keep the previous behavior (only int_normalizer rejects). Pinned by test_invalid_plugin_setting_environment_variable_is_rejected_for_any_normalizer (tests/plugins/test_plugin_config.py), which also asserts that a valid value still passes.
  2. Secret plugin settings - ConfigSetting.secret (src/poetry/config/config.py:164), Config.is_secret_setting() (src/poetry/config/config.py:340), redaction in --list and the read rejection (src/poetry/console/commands/config.py:126,360). Same mechanism as http-basic/pypi-token: not listed, and reading without a value raises "Expected a value for ... setting."
  3. Stale settings of unavailable plugins - Config.reset_plugin_settings() (src/poetry/config/config.py:349) is called per group in PluginManager.load_plugins() (src/poetry/plugins/plugin_manager.py:74-84). The reset only drops the names registered for that group (_plugin_groups), so reloading the plugin group cannot clear settings declared by application plugins, which the Application loads separately (src/poetry/console/application.py:642-643).
  4. Failed registration leaves nothing behind - src/poetry/config/config.py:326-329: the default is installed first and the registry entry is only written afterwards. I also verified that _set_default_config_value() cannot leave a partially created table behind when it raises: a non-table ancestor aborts before any new table is created, and once a missing parent has been created all deeper parents are missing too, so no raise can follow a mutation.
  5. Mutable defaults deep-copied - src/poetry/config/config.py:397. _plugin_setting_defaults keeps the original only as a reset marker; its value is never read back, so the stored reference cannot leak.
  6. Settings known outside a project - src/poetry/console/commands/config.py:93-100: the config command loads the regular plugins in the no-project branch and honors --no-plugins. The two new tests pin this with a fresh per-test Config (tests/conftest.py mocks Config.create), so they cannot pass through cross-test pollution.

Backward compatibility: Config.default_config and Config.settings are untouched and core normalizer/validator behavior is unchanged - the golden --list output test (test_list_displays_default_value_if_not_set) still passes without modification. get_normalizer()/get_validator() changed from classmethods to instance methods; all in-repo call sites are updated (verified by grep: only config.py, the config command and the tests use them).

Defect found and fixed (3402393, documentation only)

docs/plugins.md claimed that "a different name can be passed to register_plugin()" to scope a plugin's settings. But settings are declared when a plugin is loaded, under the canonicalized name of the package the plugin is defined in, so a configuration view created with an explicit name knows no declared settings: following the documented example, config.get("mirror-url") returns None, and poetry config plugins.my-plugin.mirror-url <value> fails with "Setting plugins.my-plugin.mirror-url does not exist" (reproduced with a scratch test against this branch, then removed). The paragraph now describes the actual scoping, and the CLI and environment variable examples use the package-derived name (poetry-demo-plugin), matching the entry point used earlier in the same document.

Verification on this branch (project .venv, -n 0):

$ 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 formatted

With 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).

@sourcery-ai

sourcery-ai Bot commented Nov 28, 2026

Copy link
Copy Markdown

Linked issues

Checked at commit 3402393

#9695 Allow plugins to define settings · 3 of 3 met

# Requirement Status Notes
1 Define plugin settings with defaults and read them at runtime. ✅ Met Plugins declare settings through the optional load-time hook, and PluginConfig.get() reads them.
2 Configure plugin settings using poetry config. ✅ Met The config command supports setting, reading, unsetting, and listing declared plugin settings, including when no project is available.
3 Support validators and normalizers for plugin settings. ✅ Met PluginConfig.define_setting() accepts both, and they are used when values are entered through the config command or environment variables.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow plugins to define settings

1 participant