File tree Expand file tree Collapse file tree
src/poetry/console/commands Expand file tree Collapse file tree Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments