Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/dependencies.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 from typing import Dict, Iterator, Optional
6
7 from taskgraph.task import Task
8 from taskgraph.transforms.base import TransformConfig
9 from taskgraph.util.schema import Schema
10
11 # Define a collection of group_by functions
12 GROUP_BY_MAP = {}
13
14
15 def group_by(name, schema=None):
16 def wrapper(func):
17 assert name not in GROUP_BY_MAP, (
18 f"duplicate group_by function name {name} ({func} and {GROUP_BY_MAP[name]})"
19 )
20 GROUP_BY_MAP[name] = func
21 func.schema = schema
22 return func
23
24 return wrapper
25
26
27 @group_by("single")
28 def group_by_single(config, tasks):
29 for task in tasks:
30 yield [task]
31
32
33 @group_by("all")
34 def group_by_all(config, tasks):
35 return [[task for task in tasks]]
36
37
38 @group_by("attribute", schema=Schema(str))
39 def group_by_attribute(config, tasks, attr):
40 groups = {}
41 for task in tasks:
42 val = task.attributes.get(attr)
43 if not val:
44 continue
45 groups.setdefault(val, []).append(task)
46
47 return groups.values()
48
49
50 def get_dependencies(config: TransformConfig, task: Dict) -> Iterator[Task]:
51 """Iterate over all dependencies as ``Task`` objects.
52
53 Args:
54 config (TransformConfig): The ``TransformConfig`` object associated
55 with the kind.
56 task (Dict): The task dictionary to retrieve dependencies from.
57
58 Returns:
59 Iterator[Task]: Returns a generator that iterates over the ``Task``
60 objects associated with each dependency.
61 """
62 if "dependencies" not in task:
63 return []
64
65 for label, dep in config.kind_dependencies_tasks.items():
66 if label in task["dependencies"].values():
67 yield dep
68
69
70 def get_primary_dependency(config: TransformConfig, task: Dict) -> Optional[Task]:
71 """Return the ``Task`` object associated with the primary dependency.
72
73 This uses the task's ``primary-kind-dependency`` attribute to find the primary
74 dependency, or returns ``None`` if the attribute is unset.
75
76 Args:
77 config (TransformConfig): The ``TransformConfig`` object associated
78 with the kind.
79 task (Dict): The task dictionary to retrieve the primary dependency from.
80
81 Returns:
82 Optional[Task]: The ``Task`` object associated with the
83 primary dependency or ``None``.
84 """
85 try:
86 primary_kind = task["attributes"]["primary-kind-dependency"]
87 except KeyError:
88 return None
89
90 for dep in get_dependencies(config, task):
91 if dep.kind == primary_kind:
92 return dep