Changeset aab2f5e in rtems-central


Ignore:
Timestamp:
May 6, 2020, 8:13:03 AM (6 months ago)
Author:
Sebastian Huber <sebastian.huber@…>
Branches:
master
Children:
6772014
Parents:
4fc185c
git-author:
Sebastian Huber <sebastian.huber@…> (05/06/20 08:13:03)
git-committer:
Sebastian Huber <sebastian.huber@…> (05/28/20 08:37:29)
Message:

items: Rework item mapper

Rename Item.get() in Item.get_by_key_path() since it may conflict with a
future dict-like get() method.

In Item.get_by_key_path() first call the get_value() callable to get the
value. This allows a context-sensitive formatting of values.

Location:
rtemsqual
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • rtemsqual/interface.py

    r4fc185c raab2f5e  
    2727from contextlib import contextmanager
    2828import os
    29 from typing import Any, Callable, Dict, Iterator, List, Union
     29from typing import Any, Callable, Dict, Iterator, List, Optional, Union
    3030
    3131from rtemsqual.content import CContent
     
    126126        return value
    127127
    128     def interface_name(self, item: Item, _value: Any):
    129         """ Returns the interface name of a forward declaration. """
     128    def get_value(self, item: Item, _path: str, _value: Any, key: str,
     129                  _index: Optional[int]) -> Any:
     130        """ Gets a value by key and optional index. """
    130131        # pylint: disable=no-self-use
    131         return _forward_declaration(item)
     132        if key == "interface-name" and item["type"] == "interface" and item[
     133                "interface-type"] == "forward-declaration":
     134            return _forward_declaration(item)
     135        raise KeyError
    132136
    133137
  • rtemsqual/items.py

    r4fc185c raab2f5e  
    3030import string
    3131import stat
    32 from typing import Any, Callable, Dict, Iterator, List, Mapping, Tuple
     32from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, \
     33    Tuple
    3334import yaml
    3435
     
    3637
    3738ItemMap = Dict[str, "Item"]
    38 KeyMapper = Callable[["Item", Any, str], Any]
     39ItemGetValue = Callable[["Item", str, Any, str, Optional[int]], Any]
    3940
    4041
     
    111112
    112113
    113 def _key_error(_item: "Item", _value: Any, _key: str) -> str:
    114     raise KeyError
     114def _get_value(_item: "Item", _path: str, value: Any, key: str,
     115               index: Optional[int]) -> str:
     116    value = value[key]
     117    if index is not None:
     118        value = value[index]
     119    return value
    115120
    116121
     
    130135        return self._data[name]
    131136
    132     def get(self,
    133             key_path: str,
    134             prefix: str = "",
    135             mapper: KeyMapper = _key_error) -> Any:
     137    def get_by_key_path(self,
     138                        key_path: str,
     139                        prefix: str = "",
     140                        get_value: ItemGetValue = _get_value) -> Any:
    136141        """ Gets the attribute value corresponding to the key path. """
    137142        if not os.path.isabs(key_path):
    138143            key_path = os.path.join(prefix, key_path)
    139144        key_path = os.path.normpath(key_path)
     145        path = "/"
    140146        value = self._data
    141147        for key in key_path.strip("/").split("/"):
    142148            parts = key.split("[")
    143149            try:
    144                 value = value[parts[0]]
     150                index = int(parts[1].split("]")[0])  # type: Optional[int]
     151            except IndexError:
     152                index = None
     153            try:
     154                value = get_value(self, path, value, parts[0], index)
    145155            except KeyError:
    146                 value = mapper(self, value, parts[0])
    147             try:
    148                 value = value[int(parts[1].split("]")[0])]
    149             except IndexError:
    150                 pass
     156                value = _get_value(self, path, value, parts[0], index)
     157            path = os.path.join(path, key)
    151158        return value
    152159
     
    277284            item = self._item.map(uid)
    278285            prefix = ""
    279         value = item.get(key_path, prefix, self._key_mapper)
     286        value = item.get_by_key_path(key_path, prefix, self.get_value)
    280287        for func in parts[1:]:
    281288            value = getattr(self, func)(value)
     
    295302        return ItemTemplate(text).substitute(self)
    296303
    297     def _key_mapper(self, item: Item, value: Any, key: str) -> Any:
    298         return getattr(self, key.replace("-", "_"))(item, value)
     304    def get_value(self, _item: Item, _path: str, _value: Any, _key: str,
     305                  _index: Optional[int]) -> Any:
     306        """ Gets a value by key and optional index. """
     307        # pylint: disable=no-self-use
     308        raise KeyError
    299309
    300310
  • rtemsqual/tests/test_items_item.py

    r4fc185c raab2f5e  
    5858
    5959
    60 def test_get():
     60def test_get_key_path():
    6161    data = {}
    6262    data["a"] = {"b": "c", "d": [1, 2, 3]}
    6363    data["x"] = "y"
    6464    item = Item(EmptyCache(), "z", data)
    65     assert item.get("x") == "y"
    66     assert item.get("a/d[2]") == 3
    67     assert item.get("a/b/../d[0]") == 1
    68     assert item.get("/a/b/../d[0]") == 1
    69     assert item.get("../d[0]", "a/b") == 1
     65    assert item.get_by_key_path("x") == "y"
     66    assert item.get_by_key_path("a/d[2]") == 3
     67    assert item.get_by_key_path("a/b/../d[0]") == 1
     68    assert item.get_by_key_path("/a/b/../d[0]") == 1
     69    assert item.get_by_key_path("../d[0]", "a/b") == 1
    7070    with pytest.raises(KeyError):
    71         assert item.get("y")
    72     with pytest.raises(KeyError):
    73         assert item.get("[")
     71        assert item.get_by_key_path("y")
    7472    with pytest.raises(ValueError):
    75         assert item.get("x[y]")
     73        assert item.get_by_key_path("[")
     74    with pytest.raises(ValueError):
     75        assert item.get_by_key_path("x[y]")
    7676
    7777
  • rtemsqual/tests/test_items_itemcache.py

    r4fc185c raab2f5e  
    8787        return value + value
    8888
    89     def x_to_b(self, item, value):
    90         return value["b"]
     89    def get_value(self, item, path, value, key, index):
     90        if key == "x-to-b":
     91            return value["b"]
     92        raise KeyError
    9193
    9294
     
    9597    item_cache = ItemCache(config)
    9698    item = item_cache["/p"]
     99    base_mapper = ItemMapper(item)
     100    assert base_mapper["d/c:v"] == "c"
    97101    mapper = Mapper(item)
    98102    with mapper.prefix("v"):
Note: See TracChangeset for help on using the changeset viewer.