|
| 1 | +"""Julia writer.""" |
| 2 | +import logging |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import tomlkit |
| 8 | +from rich.pretty import pretty_repr |
| 9 | + |
| 10 | +from somesy.core.models import Person, ProjectMetadata |
| 11 | +from somesy.core.writer import ProjectMetadataWriter |
| 12 | + |
| 13 | +from .models import JuliaConfig |
| 14 | + |
| 15 | +logger = logging.getLogger("somesy") |
| 16 | + |
| 17 | + |
| 18 | +class 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 poetry string for person format "full name <email>.""" |
| 54 | + return f"{person.full_name} <{person.email}>" |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def _to_person(person_obj: str) -> Person: |
| 58 | + """Parse poetry person string to a Person.""" |
| 59 | + m = re.match(r"\s*([^<]+)<([^>]+)>", person_obj) |
| 60 | + names, mail = ( |
| 61 | + list(map(lambda s: s.strip(), m.group(1).split())), |
| 62 | + m.group(2).strip(), |
| 63 | + ) |
| 64 | + # NOTE: for our purposes, does not matter what are given or family names, |
| 65 | + # we only compare on full_name anyway. |
| 66 | + return Person( |
| 67 | + **{ |
| 68 | + "given-names": " ".join(names[:-1]), |
| 69 | + "family-names": names[-1], |
| 70 | + "email": mail, |
| 71 | + } |
| 72 | + ) |
| 73 | + |
| 74 | + def sync(self, metadata: ProjectMetadata) -> None: |
| 75 | + """Sync output file with other metadata files.""" |
| 76 | + self.name = metadata.name |
| 77 | + |
| 78 | + if metadata.version: |
| 79 | + self.version = metadata.version |
| 80 | + |
| 81 | + self._sync_authors(metadata) |
0 commit comments