Coverage for src/somesy/julia/writer.py: 97%

38 statements  

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

1"""Julia writer.""" 

2 

3import logging 

4from pathlib import Path 

5 

6import tomlkit 

7from rich.pretty import pretty_repr 

8 

9from somesy.core.models import Entity, Person, ProjectMetadata, parse_name_email 

10from somesy.core.writer import ProjectMetadataWriter, format_toml_data 

11 

12from .models import JuliaConfig 

13 

14logger = logging.getLogger("somesy") 

15 

16 

17class Julia(ProjectMetadataWriter): 

18 """Julia config file handler parsed from Project.toml.""" 

19 

20 def __init__( 

21 self, 

22 path: Path, 

23 pass_validation: bool | None = False, 

24 ): 

25 """Julia config file handler parsed from Project.toml. 

26 

27 See [somesy.core.writer.ProjectMetadataWriter.__init__][]. 

28 """ 

29 super().__init__( 

30 path, 

31 create_if_not_exists=False, 

32 pass_validation=pass_validation, 

33 ) 

34 

35 def _load(self) -> None: 

36 """Load Project.toml file.""" 

37 with open(self.path, encoding="utf-8") as f: 

38 self._data = tomlkit.load(f) 

39 

40 def _validate(self) -> None: 

41 """Validate poetry config using pydantic class. 

42 

43 In order to preserve toml comments and structure, tomlkit library is used. 

44 Pydantic class only used for validation. 

45 """ 

46 if self.pass_validation: 

47 return 

48 config = dict(self._get_property([])) 

49 logger.debug( 

50 f"Validating config using {JuliaConfig.__name__}: {pretty_repr(config)}" 

51 ) 

52 JuliaConfig(**config) 

53 

54 def save(self, path: Path | None = None) -> None: 

55 """Save the julia file.""" 

56 path = path or self.path 

57 format_toml_data(self._data) 

58 

59 with open(path, "w", encoding="utf-8") as f: 

60 tomlkit.dump(self._data, f) 

61 

62 @staticmethod 

63 def _from_person(person: Person | Entity): 

64 """Convert project metadata person object to a name+email string.""" 

65 return person.to_name_email_string() 

66 

67 @staticmethod 

68 def _to_person(person_obj: str) -> Person | Entity | None: 

69 """Convert from free string to person or entity object.""" 

70 return parse_name_email(person_obj) 

71 

72 def sync(self, metadata: ProjectMetadata) -> None: 

73 """Sync output file with other metadata files.""" 

74 # overridden to not sync fields that are not present in the Project.toml file 

75 if metadata.name is not None: 

76 self.name = metadata.name 

77 if metadata.version: 

78 self.version = metadata.version 

79 

80 if metadata.authors(): 

81 self._sync_authors(metadata)