|
1 | 1 | """Module with some simple functions, e.g. for parsing for YAML into RMS |
2 | 2 | """ |
3 | 3 |
|
| 4 | +from yaml.loader import Loader |
| 5 | + |
4 | 6 | # for ordered dicts! |
5 | 7 | from fmu.config import oyaml as yaml |
| 8 | +from fmu.config._loader import ConstructorError, FmuLoader |
6 | 9 |
|
7 | 10 |
|
8 | | -def yaml_load(filename, safe=True, tool=None): |
| 11 | +def yaml_load(filename, safe=True, tool=None, loader="standard"): |
9 | 12 | """Load as YAML file, return a dictionary of type OrderedDict which is the config. |
10 | 13 |
|
11 | 14 | Returning an ordered dictionary is a main feature of this loader. It makes it much |
12 | | - easier to compare the dictionaries returned. |
| 15 | + easier to compare the dictionaries returned. In addition, it allows for reading the |
| 16 | + input (extended) YAML format, if key ``allow_extended`` is True. |
13 | 17 |
|
14 | 18 | Args: |
15 | 19 | filename (str): Name of file (YAML formatted) |
16 | | - safe (bool): If True (default), then use `safe_load` |
| 20 | + safe (bool): If True (default), then use `safe_load` when allow_extended is |
| 21 | + set to False. Not applied if loader is "fmu". |
17 | 22 | tool (str): Refers to a particular main section in the config. |
18 | | - Default is None, which measn 'all'. |
| 23 | + Default is None, which means 'all'. |
| 24 | + loader (str): If "fmu", the in-house FMU extended YAML loader that allows |
| 25 | + use of e.g. `!include` is applied; otherwise the default is "standard" YAML. |
19 | 26 |
|
20 | 27 | Example:: |
21 | 28 | >>> import fmu.config.utilities as utils |
22 | 29 | >>> cfg = utils.yaml_load('somefile.yml') |
23 | 30 |
|
24 | 31 | """ |
25 | 32 |
|
| 33 | + useloader = FmuLoader if loader.lower() == "fmu" else Loader |
| 34 | + |
26 | 35 | with open(filename, "r", encoding="utf-8") as stream: |
27 | | - if safe: |
28 | | - cfg = yaml.safe_load(stream) |
29 | | - else: |
30 | | - cfg = yaml.load(stream) |
| 36 | + try: |
| 37 | + if safe and loader.lower() != "fmu": |
| 38 | + cfg = yaml.safe_load(stream) |
| 39 | + else: |
| 40 | + cfg = yaml.load(stream, Loader=useloader) |
| 41 | + except ConstructorError as cerr: |
| 42 | + if "!include" in str(cerr): |
| 43 | + print( |
| 44 | + "\n*** Consider setting loader='fmu' to read fmu.config " |
| 45 | + "input style ***\n" |
| 46 | + ) |
| 47 | + raise |
31 | 48 |
|
32 | 49 | if tool is not None: |
33 | 50 | try: |
34 | 51 | newcfg = cfg[tool] |
35 | 52 | cfg = newcfg |
36 | 53 | except Exception as exc: # pylint: disable=broad-except |
37 | | - print("Cannot import: {}".format(exc)) |
| 54 | + print(f"Cannot import: {exc}") |
38 | 55 | return None |
39 | 56 |
|
40 | 57 | return cfg |
|
0 commit comments