Skip to content

Commit 4cbf4b6

Browse files
committed
fix(init): validate version constraint in interactive prompt
Resolves #8797
1 parent 050a405 commit 4cbf4b6

2 files changed

Lines changed: 47 additions & 1 deletion

File tree

src/poetry/console/commands/init.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ def _determine_requirements(
382382
"(or leave blank to use the latest version):"
383383
)
384384
question.set_max_attempts(3)
385-
question.set_validator(lambda x: (x or "").strip() or None)
385+
question.set_validator(self._validate_version_constraint)
386386

387387
package_constraint = self.ask(question)
388388

@@ -521,6 +521,21 @@ def _validate_package(package: str | None) -> str | None:
521521

522522
return package
523523

524+
@staticmethod
525+
def _validate_version_constraint(constraint: str | None) -> str | None:
526+
from poetry.core.constraints.version import parse_constraint
527+
528+
constraint = (constraint or "").strip() or None
529+
if constraint is None:
530+
return None
531+
532+
try:
533+
parse_constraint(constraint)
534+
except ValueError as e:
535+
raise ValueError(f"Invalid version constraint: {constraint}") from e
536+
537+
return constraint
538+
524539
def _get_pool(self) -> RepositoryPool:
525540
from poetry.config.config import Config
526541
from poetry.repositories import RepositoryPool

tests/console/commands/test_init.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1217,3 +1217,34 @@ def test_init_does_not_add_readme_key_when_readme_missing(
12171217
# Assert
12181218
pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
12191219
assert "readme =" not in pyproject
1220+
1221+
1222+
@pytest.mark.parametrize(
1223+
("constraint", "expected"),
1224+
[
1225+
("^1.0", "^1.0"),
1226+
("==1.2.3", "==1.2.3"),
1227+
(">=1,<2", ">=1,<2"),
1228+
("", None),
1229+
(None, None),
1230+
(" ", None),
1231+
],
1232+
)
1233+
def test_validate_version_constraint_accepts_valid_inputs(
1234+
constraint: str | None, expected: str | None
1235+
) -> None:
1236+
assert InitCommand._validate_version_constraint(constraint) == expected
1237+
1238+
1239+
@pytest.mark.parametrize(
1240+
"invalid",
1241+
[
1242+
"latest",
1243+
"isort",
1244+
"==1.,",
1245+
"not-a-version",
1246+
],
1247+
)
1248+
def test_validate_version_constraint_rejects_invalid_inputs(invalid: str) -> None:
1249+
with pytest.raises(ValueError, match="Invalid version constraint"):
1250+
InitCommand._validate_version_constraint(invalid)

0 commit comments

Comments
 (0)