Completed
Pull Request — master (#2842)
by Edward
05:19
created

search_pack_index()   D

Complexity

Conditions 9

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
dl 0
loc 23
rs 4.0465
c 1
b 0
f 0
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
from oslo_config import cfg
17
import requests
18
19
from st2common.persistence.pack import Pack
20
21
__all__ = [
22
    'get_pack_by_ref',
23
    'fetch_pack_index',
24
    'search_pack_index'
25
]
26
27
28
def get_pack_by_ref(pack_ref):
29
    """
30
    Retrieve PackDB by the provided reference.
31
    """
32
    pack_db = Pack.get_by_ref(pack_ref)
33
    return pack_db
34
35
36
def fetch_pack_index(index_url=None):
37
    """
38
    Fetch the pack indexes (either from the config or provided as an argument)
39
    and return the object.
40
    """
41
    if not index_url:
42
        index_urls = cfg.CONF.content.index_url
43
    elif isinstance(index_url, str):
44
        index_urls = [index_url]
45
    elif hasattr(index_url, '__iter__'):
46
        index_urls = index_url
47
    else:
48
        raise TypeError('"index_url" should either be a string or an iterable object.')
49
50
    result = {}
51
    for index_url in index_urls:
52
        result.update(requests.get(index_url).json())
53
    return result
54
55
56
def search_pack_index(query=None, pack=None):
57
    """
58
    Search the pack index either by pack name or by query.
59
    Returns a pack object if the pack name is specified, otherwise returns
60
    a list of matches for a query.
61
    """
62
    if (not query and not pack) or (query and pack):
63
        raise ValueError("Either a query or a pack name must be specified.")
64
65
    index = fetch_pack_index()
66
67
    if pack:
68
        return index.get(pack, None)
69
70
    pack_list = index.values()
71
    matches = []
72
    for pack in pack_list:
73
        for value in pack.values():
74
            if query in value:
75
                matches.append(pack)
76
                break
77
78
    return matches
79