Fix: Improve error message for invalid template variables in virtualenvs.prompt#10648
Conversation
Reviewer's GuideImproves handling of invalid template variables in the virtualenv prompt configuration by validating the format string and raising a clearer PoetryRuntimeError, and adds a test to cover this behavior. Sequence diagram for handling invalid virtualenvs.prompt template variablessequenceDiagram
actor User
participant EnvManager
participant PythonVersion
participant PoetryRuntimeError
User->>EnvManager: create_venv(venv_prompt)
alt venv_prompt is not None
EnvManager->>PythonVersion: minor_version.to_string()
PythonVersion-->>EnvManager: python_version
EnvManager->>EnvManager: venv_prompt.format(project_name, python_version)
alt format raises KeyError
EnvManager->>PoetryRuntimeError: construct with invalid template variable message
PoetryRuntimeError-->>EnvManager: PoetryRuntimeError instance
EnvManager-->>User: raise PoetryRuntimeError
else format succeeds
EnvManager-->>User: continue venv creation with formatted prompt
end
else venv_prompt is None
EnvManager-->>User: continue venv creation without custom prompt
end
Class diagram for EnvManager create_venv with improved error handlingclassDiagram
class EnvManager {
+create_venv(venv_prompt, create_venv)
}
class PoetryRuntimeError {
+PoetryRuntimeError(message)
}
class Package {
+name
}
class Poetry {
+package : Package
}
class PythonVersion {
+minor_version : PythonVersion
+to_string() string
}
EnvManager --> Poetry : uses
EnvManager --> PythonVersion : uses
EnvManager --> PoetryRuntimeError : raises
%% Internal logic of create_venv
class CreateVenvFlow {
+if venv_prompt is not None
+try venv_prompt.format(project_name, python_version)
+except KeyError -> raise PoetryRuntimeError
}
EnvManager ..> CreateVenvFlow : implements logic
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey there - I've reviewed your changes - here's some feedback:
- The error message f-string will try to interpolate
project_nameandpython_versionas Python variables; use escaped braces ('{{project_name}}', '{{python_version}}') so the message shows the literal template variables. - Including the raw
KeyErrorobject in the message ({e}) will render as"KeyError('invalid_var')"; consider usinge.args[0]orstr(e)to show just the invalid template variable name. - Importing
PoetryRuntimeErrorinside theexceptblock adds overhead and can obscure dependencies; consider moving this import to the module level unless there is a specific circular import issue.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The error message f-string will try to interpolate `project_name` and `python_version` as Python variables; use escaped braces (`'{{project_name}}', '{{python_version}}'`) so the message shows the literal template variables.
- Including the raw `KeyError` object in the message (`{e}`) will render as `"KeyError('invalid_var')"`; consider using `e.args[0]` or `str(e)` to show just the invalid template variable name.
- Importing `PoetryRuntimeError` inside the `except` block adds overhead and can obscure dependencies; consider moving this import to the module level unless there is a specific circular import issue.
## Individual Comments
### Comment 1
<location> `src/poetry/utils/env/env_manager.py:444-449` </location>
<code_context>
- project_name=self._poetry.package.name or "virtualenv",
- python_version=python.minor_version.to_string(),
- )
+ try:
+ venv_prompt = venv_prompt.format(
+ project_name=self._poetry.package.name or "virtualenv",
+ python_version=python.minor_version.to_string(),
+ )
+ except KeyError as e:
+ from poetry.console.exceptions import PoetryRuntimeError
+
</code_context>
<issue_to_address>
**suggestion:** Formatting errors other than missing keys (e.g. malformed templates) are not handled and will raise unwrapped exceptions.
`str.format` can also fail with `ValueError` (e.g. malformed format string like `"{project_name"`) and other format-related errors. Currently only `KeyError` is wrapped in `PoetryRuntimeError`, so these cases will surface as raw exceptions.
Please also handle `ValueError` (or otherwise validate the template) so all user-facing template/configuration errors are consistently wrapped in `PoetryRuntimeError`.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
|
Hey @JaviMaligno! 👋 I’ve already opened a PR for this issue and am working through the review feedback right now. To avoid overlapping work, it might be easier to tackle another open issue unless the maintainers prefer otherwise. Appreciate the enthusiasm! |
radoering
left a comment
There was a problem hiding this comment.
Please take a look at the separate review comments and the failing pre-commit check.
Shortly after you, someone else created a similar PR to fix the issue (#10649). I tend to prefer your PR (if you address the review feedback) since your were a bit earlier, covered an additional error and added tests.
|
Thanks for the review feedback! I've addressed all the comments: Changes in this commit:
Let me know if there's anything else that needs to be addressed! |
…emove unused parameters - Changed exception type from PoetryRuntimeError to PoetryConsoleError so error messages display in red as requested by reviewer - Removed unused 'mocker' parameter from test functions - Ran ruff to fix formatting and remove unused imports (Config, NullIO, virtualenv)
f81301f to
3741e25
Compare
This PR contains the following updates: | Package | Update | Change | |---|---|---| | [poetry](https://github.com/python-poetry/poetry) ([changelog](https://python-poetry.org/history/)) | minor | ` 2.2.1` -> `2.3.0` | --- ### Release Notes <details> <summary>python-poetry/poetry (poetry)</summary> ### [`v2.3.0`](https://github.com/python-poetry/poetry/blob/HEAD/CHANGELOG.md#230---2026-01-18) [Compare Source](python-poetry/poetry@2.2.1...2.3.0) ##### Added - **Add support for exporting `pylock.toml` files with `poetry-plugin-export`** ([#​10677](python-poetry/poetry#10677)). - Add support for specifying build constraints for dependencies ([#​10388](python-poetry/poetry#10388)). - Add support for publishing artifacts whose version is determined dynamically by the build-backend ([#​10644](python-poetry/poetry#10644)). - Add support for editable project plugins ([#​10661](python-poetry/poetry#10661)). - Check `requires-poetry` before any other validation ([#​10593](python-poetry/poetry#10593)). - Validate the content of `project.readme` when running `poetry check` ([#​10604](python-poetry/poetry#10604)). - Add the option to clear all caches by making the cache name in `poetry cache clear` optional ([#​10627](python-poetry/poetry#10627)). - Automatically update the cache for packages where the locked files differ from cached files ([#​10657](python-poetry/poetry#10657)). - Suggest to clear the cache if running a command with `--no-cache` solves an issue ([#​10585](python-poetry/poetry#10585)). - Propose `poetry init` when trying `poetry new` for an existing directory ([#​10563](python-poetry/poetry#10563)). - Add support for `poetry publish --skip-existing` for new Nexus OSS versions ([#​10603](python-poetry/poetry#10603)). - Show Poetry's own Python's path in `poetry debug info` ([#​10588](python-poetry/poetry#10588)). ##### Changed - **Drop support for Python 3.9** ([#​10634](python-poetry/poetry#10634)). - **Change the default of `installer.re-resolve` from `true` to `false`** ([#​10622](python-poetry/poetry#10622)). - **PEP 735 dependency groups are considered in the lock file hash** ([#​10621](python-poetry/poetry#10621)). - Deprecate `poetry.utils._compat.metadata`, which is sometimes used in plugins, in favor of `importlib.metadata` ([#​10634](python-poetry/poetry#10634)). - Improve managing free-threaded Python versions with `poetry python` ([#​10606](python-poetry/poetry#10606)). - Prefer JSON API to HTML API in legacy repositories ([#​10672](python-poetry/poetry#10672)). - When running `poetry init`, only add the readme field in the `pyproject.toml` if the readme file exists ([#​10679](python-poetry/poetry#10679)). - Raise an error if no hash can be determined for any distribution link of a package ([#​10673](python-poetry/poetry#10673)). - Require `dulwich>=0.25.0` ([#​10674](python-poetry/poetry#10674)). ##### Fixed - Fix an issue where `poetry remove` did not work for PEP 735 dependency groups with `include-group` items ([#​10587](python-poetry/poetry#10587)). - Fix an issue where `poetry remove` caused dangling `include-group` references in PEP 735 dependency groups ([#​10590](python-poetry/poetry#10590)). - Fix an issue where `poetry add` did not work for PEP 735 dependency groups with `include-group` items ([#​10636](python-poetry/poetry#10636)). - Fix an issue where PEP 735 dependency groups were not considered in the lock file hash ([#​10621](python-poetry/poetry#10621)). - Fix an issue where wrong markers were locked for a dependency that was required by several groups with different markers ([#​10613](python-poetry/poetry#10613)). - Fix an issue where non-deterministic markers were created in a method used by `poetry-plugin-export` ([#​10667](python-poetry/poetry#10667)). - Fix an issue where wrong wheels were chosen for installation in free-threaded Python environments if Poetry itself was not installed with free-threaded Python ([#​10614](python-poetry/poetry#10614)). - Fix an issue where `poetry publish` used the metadata of the project instead of the metadata of the build artifact ([#​10624](python-poetry/poetry#10624)). - Fix an issue where `poetry env use` just used another Python version instead of failing when the requested version was not supported by the project ([#​10685](python-poetry/poetry#10685)). - Fix an issue where `poetry env activate` returned the wrong command for `dash` ([#​10696](python-poetry/poetry#10696)). - Fix an issue where `data-dir` and `python.installation-dir` could not be set ([#​10595](python-poetry/poetry#10595)). - Fix an issue where Python and pip executables were not correctly detected on Windows ([#​10645](python-poetry/poetry#10645)). - Fix an issue where invalid template variables in `virtualenvs.prompt` caused an incomprehensible error message ([#​10648](python-poetry/poetry#10648)). ##### Docs - Add a warning about `~/.netrc` for Poetry credential configuration ([#​10630](python-poetry/poetry#10630)). - Clarify that the local configuration takes precedence over the global configuration ([#​10676](python-poetry/poetry#10676)). - Add an explanation in which cases `packages` are automatically detected ([#​10680](python-poetry/poetry#10680)). ##### poetry-core ([`2.3.0`](https://github.com/python-poetry/poetry-core/releases/tag/2.3.0)) - Normalize versions ([#​893](python-poetry/poetry-core#893)). - Fix an issue where unsatisfiable requirements did not raise an error ([#​891](python-poetry/poetry-core#891)). - Fix an issue where the implicit main group did not exist if it was explicitly declared as not having any dependencies ([#​892](python-poetry/poetry-core#892)). - Fix an issue where `python_full_version` markers with pre-release versions were parsed incorrectly ([#​893](python-poetry/poetry-core#893)). </details> --- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MS4xNDYuMCIsInVwZGF0ZWRJblZlciI6IjQxLjE0Ni4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119--> Reviewed-on: https://git.walbeck.it/walbeck-it/docker-python-poetry/pulls/1654 Co-authored-by: renovate-bot <[email protected]> Co-committed-by: renovate-bot <[email protected]>
|
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Fixes #10635
Closes #10649
Summary by Sourcery
Improve validation and error reporting for virtual environment prompt templates when creating virtualenvs.
Bug Fixes:
Tests: