pytex/PyTeX/format/dict_formatter.py

95 lines
3.6 KiB
Python

import csv
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from .constants import *
from .pytex_formatter import PyTeXFormatter
from ..logger import logger
from .formatting_config import FormattingConfig
class DictFormatter(PyTeXFormatter):
def __init__(self, *args, **kwargs):
super(DictFormatter, self).__init__(*args, **kwargs)
with open(self.input_file, 'r') as file:
line = file.readline()
parts = [entry.strip() for entry in line.split(',')]
if not len(parts) >= 1:
raise NotImplementedError
if not parts[0] == DICTIONARY_KEY_COLUMN_NAME:
raise NotImplementedError
self._languages = parts[1:]
self._dict_name = self.input_file.name.split('.')[0]
self._translations = None
@property
def dependencies(self) -> List[str]:
return [] # No dependencies for dictionaries
@property
def translations(self) -> Dict:
if self._translations is None:
self._translations = self.parse()
return self._translations
@property
def output_files(self) -> List[str]:
return [
DICTIONARY_NAMING_PATTERN.format(
dict_name=self._dict_name,
language=language
)
for language in self._languages
]
def parse(self) -> Dict:
with open(self.input_file, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
next(spamreader) # Skip languages line
translations: Dict = {}
for language in self._languages:
translations[language] = {}
for line in spamreader:
if not len(line) == len(self._languages) + 1:
raise NotImplementedError # Invalid file format
for n in range(1, len(line)):
translations[self._languages[n-1]][line[0]] = line[n]
return translations
def format(self, build_dir: Path, overwrite: bool = False) -> List[Tuple[str, FormattingConfig]]:
build_dir.mkdir(parents=True, exist_ok=True)
self.make_header() # TODO: add kwargs
for language in self._languages:
lines: List[str] = [self.make_header(), '']
lines += r'\ProvidesDictionary{{{dict_name}}}{{{language}}}'.format(
dict_name=self._dict_name,
language=language
)
lines += ['\n'] * 2
for key in self.translations[language].keys():
if self.translations[language][key].strip() != '':
lines += r'\providetranslation{{{key}}}{{{translation}}}'.format(
key=key.strip(),
translation=self.translations[language][key].strip()
)
lines += '\n'
else:
logger.warning(
'Empty translation key found in {filename}'.format(
filename=self.input_file.name
)
)
output_file = build_dir / DICTIONARY_NAMING_PATTERN.format(
language=language,
dict_name=self._dict_name
)
if not overwrite and output_file.exists():
raise NotImplementedError
else:
output_file.write_text(
''.join(lines)
)
logger.info(
f'Successfully wrote dictionary file {output_file.name}.'
)
return [] # No future configuration needed