|
| 1 | +import os |
| 2 | +from argparse import Namespace |
| 3 | +from typing import Sequence, Tuple, Union |
| 4 | + |
| 5 | +cfg_file_vldtor = Tuple[str, str, bool, Union[str, None]] |
| 6 | + |
| 7 | + |
| 8 | +def _validate_config_file_paths(args: Namespace, cfg_files_to_validate: Sequence[cfg_file_vldtor]) -> None: |
| 9 | + """Validate the CLI config files. |
| 10 | +
|
| 11 | + Args: |
| 12 | + args (argparse.Namespace): The parsed arguments from the CLI. |
| 13 | + cfg_files_to_validate (list[tuple[str, str, bool, str | None]]): config files to validate. |
| 14 | + Tuple is (config filename, CLI flag, is filepath required, default config file location). |
| 15 | +
|
| 16 | + Raises: |
| 17 | + ValueError: If a path to a required config file is not provided. |
| 18 | + FileNotFoundError: If a config file is provided but does not exist. |
| 19 | + """ |
| 20 | + for filename, cli_flag, required, default_loc in cfg_files_to_validate: |
| 21 | + |
| 22 | + attr_name = f"{filename}_file" |
| 23 | + file_path = getattr(args, attr_name) |
| 24 | + |
| 25 | + # args.config_dir defaults to '.' if not specified |
| 26 | + file_in_config_dir = os.path.join(args.config_dir, f"my_{filename}.yaml") |
| 27 | + if file_path is None and os.path.exists(file_in_config_dir): |
| 28 | + setattr(args, attr_name, file_in_config_dir) |
| 29 | + elif file_path is None: |
| 30 | + setattr(args, attr_name, default_loc) |
| 31 | + |
| 32 | + file_path = getattr(args, attr_name, None) |
| 33 | + |
| 34 | + # throw on missing config files |
| 35 | + if file_path is None and required: |
| 36 | + raise ValueError( |
| 37 | + f"No path specified for {attr_name}. Use the {cli_flag} flag to specify or check the value " |
| 38 | + f"of CONFIG_FILE_DIR and make sure it points at where all your config files are." |
| 39 | + ) |
| 40 | + if file_path is not None and not os.path.exists(file_path): |
| 41 | + raise FileNotFoundError(f"{attr_name} '{file_path}' does not exist!") |
0 commit comments