Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/attributes.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
6 import re
7
8
9 def attrmatch(attributes, **kwargs):
10 """Determine whether the given set of task attributes matches.
11
12 The conditions are given as keyword arguments, where each keyword names an
13 attribute. The keyword value can be a literal, a set, or a callable:
14
15 * A literal must match the attribute exactly.
16 * Given a set or list, the attribute value must be contained within it.
17 * A callable is called with the attribute value and returns a boolean.
18
19 If an attribute is specified as a keyword argument but not present in the
20 task's attributes, the result is False.
21
22 Args:
23 attributes (dict): The task's attributes object.
24 kwargs (dict): The conditions the task's attributes must satisfy in
25 order to match.
26 Returns:
27 bool: Whether the task's attributes match the conditions or not.
28 """
29 for kwkey, kwval in kwargs.items():
30 if kwkey not in attributes:
31 return False
32 attval = attributes[kwkey]
33 if isinstance(kwval, (set, list)):
34 if attval not in kwval:
35 return False
36 elif callable(kwval):
37 if not kwval(attval):
38 return False
39 elif kwval != attributes[kwkey]:
40 return False
41 return True
42
43
44 def keymatch(attributes, target):
45 """Determine if any keys in attributes are a match to target, then return
46 a list of matching values. First exact matches will be checked. Failing
47 that, regex matches and finally a default key.
48 """
49 # exact match
50 if target in attributes:
51 return [attributes[target]]
52
53 # regular expression match
54 matches = [v for k, v in attributes.items() if re.match(k + "$", target)]
55 if matches:
56 return matches
57
58 # default
59 if "default" in attributes:
60 return [attributes["default"]]
61
62 return []
63
64
65 def _match_run_on(key, run_on):
66 """
67 Determine whether the given parameter is included in the corresponding `run-on-attribute`.
68 """
69 if "all" in run_on:
70 return True
71 return key in run_on
72
73
74 match_run_on_projects = _match_run_on
75 match_run_on_tasks_for = _match_run_on
76
77
78 def match_run_on_git_branches(git_branch, run_on_git_branches):
79 """
80 Determine whether the given project is included in the `run-on-git-branches` parameter.
81 Allows 'all'.
82 """
83 if "all" in run_on_git_branches:
84 return True
85
86 for expected_git_branch_pattern in run_on_git_branches:
87 if re.match(expected_git_branch_pattern, git_branch):
88 return True
89
90 return False
91
92
93 def sorted_unique_list(*args):
94 """Join one or more lists, and return a sorted list of unique members"""
95 combined = set().union(*args)
96 return sorted(combined)