70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
import sys
|
|
import argparse
|
|
from pathlib import Path
|
|
from ..configuration import Config
|
|
from ..glossary import Glossary
|
|
|
|
|
|
class GlossaryCmdError(Exception):
|
|
pass
|
|
|
|
|
|
def get_glossary_file(name: str, config: Config) -> Path:
|
|
"""
|
|
Get the complete filename for a glossary with the given path.
|
|
"""
|
|
if not config.glossaries:
|
|
raise GlossaryCmdError("Can't create glossary name without a glossary directory")
|
|
return Path(config.glossaries, name).with_suffix(Glossary.file_suffix).absolute()
|
|
|
|
|
|
def list_glossaries(args: argparse.Namespace, config: Config) -> None:
|
|
"""
|
|
List existing glossaries in the 'glossaries' directory.
|
|
"""
|
|
if not config.glossaries:
|
|
raise GlossaryCmdError("Glossaries directory missing in the configuration file")
|
|
glossaries = Path(config.glossaries).glob(f'*.{Glossary.file_suffix}')
|
|
for glo in glossaries:
|
|
print(Glossary.from_file(glo).to_str(args.entries))
|
|
|
|
|
|
def create_glossary(args: argparse.Namespace, config: Config) -> None:
|
|
"""
|
|
Create a new glossary and write it either to the glossaries directory
|
|
or the given file.
|
|
"""
|
|
# we need to know where the glossary should be stored
|
|
if config.glossaries is None and args.file is None:
|
|
raise GlossaryCmdError("Glossaries directory missing in the configuration file")
|
|
# sanity checks
|
|
if args.name is None:
|
|
print("Error: please specify the glossary name.")
|
|
sys.exit(1)
|
|
if args.source_lang is None:
|
|
print("Error: please specify the source language.")
|
|
sys.exit(1)
|
|
if args.target_lang is None:
|
|
print("Error: please specify the target language.")
|
|
sys.exit(1)
|
|
# create file or use the given one
|
|
glo_file = Path(args.file) if args.file else get_glossary_file(args.name, config)
|
|
if glo_file.exists():
|
|
print(f"Error: glossary '{glo_file}' already exists!")
|
|
sys.exit(1)
|
|
glo = Glossary(name=args.name,
|
|
source_lang=args.source_lang,
|
|
target_lang=args.target_lang,
|
|
desc=args.description,
|
|
file_path=glo_file)
|
|
glo.to_file()
|
|
print(f"Successfully created new glossary '{glo_file}'.")
|
|
|
|
|
|
def glossary_cmd(args: argparse.Namespace, config: Config) -> None:
|
|
"""
|
|
Handler for the 'glossary' command.
|
|
"""
|
|
if args.create:
|
|
create_glossary(args, config)
|