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

37 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2024-07-29 07:50 +0000

1"""Julia writer.""" 

2 

3import logging 

4from pathlib import Path 

5from typing import Optional 

6 

7import tomlkit 

8from rich.pretty import pretty_repr 

9 

10from somesy.core.models import Person, ProjectMetadata 

11from somesy.core.writer import ProjectMetadataWriter 

12 

13from .models import JuliaConfig 

14 

15logger = logging.getLogger("somesy") 

16 

17 

18class Julia(ProjectMetadataWriter): 

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

20 

21 def __init__(self, path: Path): 

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

23 

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

25 """ 

26 super().__init__(path, create_if_not_exists=False) 

27 

28 def _load(self) -> None: 

29 """Load Project.toml file.""" 

30 with open(self.path) as f: 

31 self._data = tomlkit.load(f) 

32 

33 def _validate(self) -> None: 

34 """Validate poetry config using pydantic class. 

35 

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

37 Pydantic class only used for validation. 

38 """ 

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

40 logger.debug( 

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

42 ) 

43 JuliaConfig(**config) 

44 

45 def save(self, path: Optional[Path] = None) -> None: 

46 """Save the julia file.""" 

47 path = path or self.path 

48 with open(path, "w") as f: 

49 tomlkit.dump(self._data, f) 

50 

51 @staticmethod 

52 def _from_person(person: Person): 

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

54 return person.to_name_email_string() 

55 

56 @staticmethod 

57 def _to_person(person_obj) -> Optional[Person]: 

58 """Parse name+email string to a Person.""" 

59 try: 

60 return Person.from_name_email_string(person_obj) 

61 except (ValueError, AttributeError): 

62 logger.warning(f"Cannot convert {person_obj} to Person object.") 

63 return None 

64 

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

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

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

68 self.name = metadata.name 

69 self.version = metadata.version 

70 

71 self._sync_authors(metadata)