def build_hook_params()

in kitsune/sumo/parser.py [0:0]


def build_hook_params(string, locale, allowed_params=[], allowed_param_values={}):
    """Parses a string of the form 'some-title|opt1|opt2=arg2|opt3...'

    Builds a list of items and returns relevant parameters in a dict.

    """
    if "|" not in string:  # No params? Simple and easy.
        string = string.strip()
        return (string, {"alt": string})

    items = [i.strip() for i in string.split("|")]
    title = items.pop(0)
    params = {}

    last_item = ""
    for item in items:  # this splits by = or assigns the dict key to True
        if "=" in item:
            param, value = item.split("=", 1)
            params[param] = value
        else:
            params[item] = True
            last_item = item

    if "caption" in allowed_params:
        params["caption"] = title
        # Allowed parameters are not caption. All else is.
        if last_item and last_item not in allowed_params:
            params["caption"] = items.pop()
            del params[last_item]
        elif last_item == "caption":
            params["caption"] = last_item

    # Validate params allowed
    for p in list(params.keys()):
        if p not in allowed_params:
            del params[p]

    # Validate params with limited # of values
    for p in allowed_param_values:
        if p in params and params[p] not in allowed_param_values[p]:
            del params[p]

    # Handle page as a special case
    if "page" in params and params["page"] is not True:
        link = _get_wiki_link(params["page"], locale)
        params["link"] = link["url"]
        params["found"] = link["found"]

    return (title, params)