diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-07-20 22:51:14 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-07-20 22:51:14 -0500 |
| commit | ba5d3e2541670829697d794943322dd5f2a453af (patch) | |
| tree | 507bed499736b71623c4a208a4401ef2da84d68c | |
| parent | Remove parser imports from __init__ (diff) | |
| download | config-file-ba5d3e2541670829697d794943322dd5f2a453af.zip | |
Add toml and yaml parsers
| -rw-r--r-- | config_file/parsers/toml_parser.py | 29 | ||||
| -rw-r--r-- | config_file/parsers/yaml_parser.py | 30 |
2 files changed, 53 insertions, 6 deletions
diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index 4905aec..d369003 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -1,5 +1,28 @@ -from config_file.parsers import AbstractParser +try: + import tomlkit + TOML_AVAILABLE = True +except ImportError: + TOML_AVAILABLE = False -class TomlParser(AbstractParser): - """The TomlParser allows use of toml files with ConfigFile.""" +from config_file.exceptions import MissingDependencyError + +from .base_parser import BaseParser + + +class TomlParser(BaseParser): + def __init__(self, file_contents: str): + if not TOML_AVAILABLE: + raise MissingDependencyError( + "It doesn't appear `toml` is installed, but a toml " + "file was attempted to be used. Install the `toml` " + "extra first with `pip install config-file[toml]`." + ) + + super().__init__( + file_contents=file_contents, + module=tomlkit, + # tomlkit doesn't expose it's exceptions, but + # it's parsing error is a subclass of ValueError + decode_error=ValueError, + ) diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py index a45d7f6..77b59fe 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -1,5 +1,29 @@ -from config_file.parsers import AbstractParser +try: + import yaml + YAML_AVAILABLE = True -class YamlParser(AbstractParser): - pass + # Conform yaml to json and + # toml package syntax + yaml.loads = yaml.load + yaml.dumps = yaml.dump +except ImportError: + YAML_AVAILABLE = False + +from config_file.exceptions import MissingDependencyError + +from .base_parser import BaseParser + + +class YamlParser(BaseParser): + def __init__(self, file_contents: str): + if not YAML_AVAILABLE: + raise MissingDependencyError( + "It doesn't appear `PyYaml` is installed, but a yaml " + "file was attempted to be used. Install the `toml` " + "extra first with `pip install config-file[toml]`." + ) + + super().__init__( + file_contents=file_contents, module=yaml, decode_error=yaml.YAMLError + ) |