Coverage for src/somesy/commands/set_value.py: 90%

29 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-11-09 13:08 +0000

1"""Update scalar project metadata in a somesy.toml file.""" 

2 

3from pathlib import Path 

4 

5import tomlkit 

6from pydantic import ValidationError 

7 

8from somesy.core.core import atomic_write, get_input_content 

9from somesy.core.models import PartialProjectMetadata, SomesyInput 

10 

11SETTABLE_FIELDS = { 

12 "name", 

13 "description", 

14 "abstract", 

15 "version", 

16 "license", 

17 "homepage", 

18 "repository", 

19 "documentation", 

20} 

21 

22 

23def set_project_value(input_file: Path, field: str, value: str) -> None: 

24 """Set one scalar project-metadata value in a somesy.toml file.""" 

25 if field not in SETTABLE_FIELDS: 

26 allowed = ", ".join(sorted(SETTABLE_FIELDS)) 

27 raise ValueError(f"Unknown project field '{field}'. Choose one of: {allowed}.") 

28 if not SomesyInput.is_somesy_file_path(input_file): 

29 raise ValueError("The input file must be a somesy.toml file.") 

30 

31 content = get_input_content(input_file, no_unwrap=True) 

32 if "project" not in content: 

33 raise ValueError( 

34 f"No [project] table found in {input_file}; add one before using 'set'." 

35 ) 

36 try: 

37 # only the changed field must be valid, the file may be incomplete 

38 PartialProjectMetadata.model_validate({**content["project"], field: value}) 

39 except ValidationError as error: 

40 first = error.errors()[0] 

41 if first["type"] in ("enum", "literal_error"): 

42 reason = f"{first['input']!r} is not an allowed value" 

43 if field == "license": 

44 reason = f"{first['input']!r} is not a known SPDX license identifier" 

45 else: 

46 reason = first["msg"] 

47 if len(reason) > 200: 

48 reason = reason[:197] + "..." 

49 raise ValueError(f"Invalid value for '{field}': {reason}") from None 

50 content["project"][field] = value 

51 atomic_write(input_file, tomlkit.dumps(content))