File: parsing.py

package info (click to toggle)
python-ical 12.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,776 kB
  • sloc: python: 15,157; sh: 9; makefile: 5
file content (42 lines) | stat: -rw-r--r-- 1,381 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""Library for parsing rfc5545 types."""

from __future__ import annotations

import logging
from typing import Any, get_origin

from pydantic import BaseModel
from pydantic.fields import FieldInfo

from ical.util import get_field_type

_LOGGER = logging.getLogger(__name__)


def _all_fields(cls: type[BaseModel]) -> dict[str, FieldInfo]:
    all_fields: dict[str, FieldInfo] = {}
    for name, model_field in cls.model_fields.items():
        all_fields[name] = model_field
        if model_field.alias is not None:
            all_fields[model_field.alias] = model_field
    return all_fields


def parse_parameter_values(
    cls: type[BaseModel], values: dict[str, Any]
) -> dict[str, Any]:
    """Convert property parameters to pydantic fields."""
    _LOGGER.debug("parse_parameter_values=%s", values)
    if params := values.get("params"):
        all_fields = _all_fields(cls)
        for param in params:
            if not (field := all_fields.get(param["name"])):
                continue
            annotation = get_field_type(field.annotation)
            if get_origin(annotation) is list:
                values[param["name"]] = param["values"]
            else:
                if len(param["values"]) > 1:
                    raise ValueError("Unexpected repeated property parameter")
                values[param["name"]] = param["values"][0]
    return values