Debian Codegraph @

tasks/_inv/tasks.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2018 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Task management
19 ~~~~~~~~~~~~~~~
20
21 """
22 __all__ = ["by_name", "execute", "exists", "new_context"]
23
24 import collections as _collections
25 import importlib as _importlib
26 import os as _os
27 import re as _re
28
29 import invoke as _invoke
30
31 from . import shell as _shell
32 from . import util as _util
33
34 _TASKS = None
35 _SETTINGS = None
36
37
38 def exists(name):
39 """
40 Check if a task exists
41
42 Parameters:
43 name (str):
44 The fully qualified task name
45
46 Returns:
47 bool: Does the task exist?
48 """
49 assert _TASKS is not None
50
51 return name in _TASKS
52
53
54 def by_name(name):
55 """
56 Find task by name
57
58 Parameters:
59 name (str):
60 The fully qualified task name
61
62 Returns:
63 invoke.Task: The task
64
65 Raises:
66 KeyError: Task not found
67 """
68 assert _TASKS is not None
69
70 return _TASKS[name]
71
72
73 def execute(*args, **kwargs): # pylint: disable = invalid-name
74 """
75 execute(ctx, name, **kwargs)
76
77 Execute a task like invoke does (including pre + post).
78
79 All arguments have to be given via kwargs.
80
81 Parameters:
82 *args:
83 List of (task-name, kwargs) tuples. If there's no kwargs for a task,
84 the task-name only is sufficient. If there's only one task-name given,
85 kwargs is applied to that task. Otherwise kwargs must be empty.
86
87 **kwargs:
88 Arguments if a single task is given
89
90 Returns:
91 dict: A dict mapping task objects to their return values (as returned
92 from ``invoke.Exceutor().execute()``)
93 """
94 assert _TASKS is not None
95
96 ctx, tasks = args[0], list(args[1:])
97 if len(tasks) == 1 and isinstance(tasks[0], _util.basestring_):
98 tasks = [(tasks[0], kwargs)]
99 elif kwargs:
100 raise AssertionError("Multiple tasks cannot share the same kwargs")
101
102 for idx, task in enumerate(tasks):
103 if isinstance(task, _util.basestring_):
104 tasks[idx] = (task, {})
105
106 return _invoke.Executor(_TASKS, ctx.config).execute(*tasks)
107
108
109 def new_context():
110 """
111 Create a new context
112
113 Typically only needed if a function is run "independent" from invoke.
114
115 Returns:
116 invoke.Context: The new context
117 """
118 assert _TASKS is not None
119
120 config = _invoke.Config()
121 collection_config = _TASKS.configuration()
122 config.load_collection(collection_config)
123 config.load_shell_env()
124 return _invoke.context.Context(config)
125
126
127 def optional(collection, featureflag=None):
128 """
129 Decorator for optional task
130
131 Parameters:
132 collection (list):
133 Collection to append the task name to if the task is enabled. Can be
134 ``None`` if no collection is desired.
135
136 featureflag (callable):
137 Feature flag function. If it's not None, it's called without
138 arguments. The return value is treated as a bool. If true, the task
139 will be returned by the decorator and the task name will be added to
140 the collection. Otherwise ``None`` will be returned.
141
142 If featureflag is ``None``, the collection will be checked as a bool.
143 If true the task will be returned, ``None`` otherwise.
144
145 Returns:
146 callable: inner function accepting the task and taking the decision.
147 """
148
149 def inner(func):
150 """
151 Inner proxy, taking the return decision
152
153 Parameters:
154 func (Task):
155 The optional task
156
157 Returns:
158 callable: The task or ``None``
159 """
160 if featureflag is None:
161 if collection:
162 return func
163
164 elif featureflag(_SETTINGS):
165 if collection is not None:
166 collection.append(func.name)
167 return func
168
169 return None
170
171 return inner
172
173
174 def setup_tasks(env):
175 """
176 Find available tasks (cached)
177
178 Parameters:
179 env (dict-like):
180 The settings
181
182 Returns:
183 invoke.Collection: The tasks
184 """
185 global _SETTINGS, _TASKS # pylint: disable = global-statement
186 if _TASKS is not None:
187 return _TASKS
188 _SETTINGS = env
189
190 path = _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))
191 pkg = _os.path.basename(path)
192 torepair, space = [], _collections.defaultdict(dict)
193
194 for module in _find_modules():
195 name = getattr(module, "NAMESPACE", None)
196 if not name:
197 name = module.__name__[len(pkg) + 1 :] # noqa
198
199 for item in vars(module).values():
200 if not isinstance(item, _invoke.Task):
201 continue
202
203 torepair.append((name, item))
204 space[name][item.name] = item
205
206 result = _invoke.Collection(
207 **{
208 name: _invoke.Collection(*tasks.values())
209 for name, tasks in space.items()
210 }
211 )
212 result.configure(env)
213
214 # pre and post can be passed as string - map them here
215 for name, task in torepair:
216 for attr in ("pre", "post"):
217 res = []
218 for dep in getattr(task, attr):
219 if not isinstance(dep, _util.basestring_):
220 res.append(dep)
221 continue
222
223 if "." in dep:
224 depspace, dep = dep.rsplit(".", 1)
225 else:
226 depspace = name
227 res.append(space[depspace][dep])
228 setattr(task, attr, res)
229
230 _TASKS = result
231 return result
232
233
234 def _find_modules():
235 """
236 Find modules with tasks
237
238 Returns:
239 iterable: Modules found
240 """
241 path, prune = _os.path.split(_os.path.dirname(_os.path.abspath(__file__)))
242 pkg = _os.path.basename(path)
243 pkg_path = pkg + "/"
244
245 is_valid_file = _re.compile(r"^[a-zA-Z_]+[a-zA-Z0-9_]*\.py$").match
246 is_valid_dir = _re.compile(r"^[a-zA-Z_]+[a-zA-Z0-9_]*$").match
247 init = "__init__.py"
248
249 for filename in _shell.files(path, "[!.]*.py", prune=[prune]):
250 assert filename.startswith(pkg_path)
251 filename = filename[len(pkg_path) :] # noqa
252 dirname, basename = _os.path.split(filename)
253 odirname = dirname
254
255 # Skip root __init__.py or non-id names
256 if filename == init or not is_valid_file(basename):
257 continue
258
259 # Check all sub-path parts if any
260 while dirname:
261 if not is_valid_dir(_os.path.basename(dirname)):
262 break
263 if not _os.path.exists(_os.path.join(path, dirname, init)):
264 break
265 dirname = _os.path.dirname(dirname)
266
267 # import module/package and yield if there are any tasks
268 else:
269 modname = filename[:-3] if basename != init else odirname
270 modname = ".".join(_shell.pathparts(modname))
271 qname = "%s.%s" % (pkg, modname)
272
273 module = _importlib.import_module(qname)
274 for item in vars(module).values():
275 if isinstance(item, _invoke.Task):
276 yield module
277 break