from pathlib import Path from typing import List, Dict, Tuple, Optional import csv from .pytex_formatter import PyTeXFormatter from .constants import * from ..logger import logger 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 translations(self) -> Dict: if self._translations is None: self._translations = self.parse() return self._translations 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 = {} 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]][line[0]] = line[n] return translations def format(self, build_dir: Path, overwrite: bool = False) -> Optional[List[Tuple[str, Dict]]]: build_dir.mkdir(parents=True, exist_ok=True) self.make_header() for language in self._languages: lines = [self.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( '\n'.join(lines) ) logger.info( f'Successfully wrote dictionary file {output_file.name}.' ) return None # No future configuration needed