diff --git a/fromtext.py b/fromtext.py index b229358..40723c2 100755 --- a/fromtext.py +++ b/fromtext.py @@ -11,17 +11,29 @@ def _sanitize_line(l: str) -> str: return l[1:-1].replace('""', '"') return l +def _get_path(basepath: pathlib.Path, deckname: str) -> pathlib.Path: + for p in basepath.iterdir(): + if p.name == deckname: + return p + if p.name.startswith(f'{deckname}.'): + return p + p = basepath / deckname + p.mkdir() + return p + def process_line( *, columns: list[str], columns_indices: list[int], + deck_index: int, target_dir: pathlib.Path, ) -> None: columns = [_sanitize_line(l) for l in columns] + deckpath = _get_path(target_dir, columns[deck_index]) columns = [columns[i] for i in columns_indices] slug = ''.join(c for c in columns[0].lower() if c.isalnum() or c == ' ') slug = slug.replace(' ', '-') - base_filename = target_dir / slug + base_filename = deckpath / slug for i, c in enumerate(columns): with (base_filename.parent / (base_filename.name + f'.{i}.md')).open('w') as fp: fp.write(c) @@ -30,6 +42,7 @@ def main( *, target_column_count: int = 6, columns_indices: list[int] = [3, 4], + deck_index: int = 2, sep: str = '\t', ): target_dir = pathlib.Path(next(iter(sys.argv[1:] or ['.']))) @@ -43,7 +56,12 @@ def main( buff += l split_ = buff.split(sep) if len(split_) == target_column_count: - process_line(columns=split_, columns_indices=columns_indices, target_dir=target_dir) + process_line( + columns=split_, + columns_indices=columns_indices, + deck_index=deck_index, + target_dir=target_dir, + ) buff = '' if __name__ == '__main__':