Source code for ini2toml.plugins.profile_independent_tasks
"""Profile-independent tasks implemented via *profile augmentation*."""importrefromfunctoolsimportwrapsfromtypingimportCallablefrom..typesimportProfile,TranslatorDUPLICATED_NEWLINES=re.compile(r"\n+",re.M)TABLE_START=re.compile(r"^\[(.*)\]",re.M)EMPTY_TABLES=re.compile(r"^\[(.*)\]\n+\[(\1\.(?:.*))\]",re.M)MISSING_TERMINATING_LINE=re.compile(r"(?<!\n)\Z",re.M)# ^ POSIX tools will not play nicely with text files without a terminating new line# https://unix.stackexchange.com/questions/18743/whats-the-point-in-adding-a-new-line-to-the-end-of-a-file
defpost_process(fn:Callable[[str],str]):@wraps(fn)def_augmentation(profile:Profile):profile.post_processors.append(fn)return_augmentationdefnormalise_newlines(text:str)->str:"""Make sure every table is preceded by an empty newline, but remove them elsewhere in the output TOML document. Also ensure a terminating newline is present for best POSIX tool compatibility. """text=DUPLICATED_NEWLINES.sub(r"\n",text)text=TABLE_START.sub(r"\n[\1]",text)returnMISSING_TERMINATING_LINE.sub("\n",text)defremove_empty_table_headers(text:str)->str:"""Remove empty TOML table headers"""prev_text=""whiletext!=prev_text:prev_text=texttext=EMPTY_TABLES.sub(r"[\2]",text).strip()returntextdefensure_terminating_newlines(text:str)->str:returntext.strip()+"\n"