# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_yaml.ipynb.

# %% auto 0
__all__ = ['fmt', 'yaml2d', 'Section', 'YamlModel', 'QuartoDoc']

# %% ../nbs/00_yaml.ipynb 2
import sys
from pydantic import BaseModel, ValidationError
import yaml
from typing import List, Dict
from fastcore.test import test_fail

# %% ../nbs/00_yaml.ipynb 4
def fmt(err:dict):
    "format error messages from pydantic."
    msg = ""
    if err['type'] == 'value_error.missing':
        msg += 'Missing field'
    else:
        msg += err['msg'] + ':'
        
    if 'loc' in err:
        if len(err['loc']) == 1:
            msg += f" from root level: `{err['loc'][0]}`"
        elif len(err['loc']) == 3:
            msg += f" `{err['loc'][2]}` for element {err['loc'][1]} in the list for `{err['loc'][0]}`"
                
    else:
        msg += str(err['msg'])
    return msg

# %% ../nbs/00_yaml.ipynb 5
def yaml2d(yml:str) -> dict:
    "Turn a yaml string into a dict"
    return yaml.safe_load(yml)

# %% ../nbs/00_yaml.ipynb 6
class Section(BaseModel):
    title: str
    desc: str
    contents: List[str]


class YamlModel(BaseModel):
    @classmethod
    def from_dict(cls, ymldict:dict, f:callable=fmt):
        sys.tracebacklimit = 0
        try:
            return cls.parse_obj(ymldict)
        except ValidationError as e:
            if f:
                msg = 'Configuration error(s) for YAML:\n - '
                msg += '\n - '.join(f(err) for err in e.errors())           
                raise ValueError(msg) from None
            else: 
                raise e

class QuartoDoc(YamlModel):
    style: str
    dir: str
    package: str
    sidebar: str
    sections: List[Section]
