Debian Codegraph @

doc/tasks.rst

raw
1 .. meta::
2 :description: pydoit guide - core concepts: tasks, actions, dependencies and targets.
3 :keywords: python, doit, documentation, guide, introduction, task, actions, dependencies, targets, cmd action
4
5 .. title:: Introduction to Tasks, basic metadata and operations
6
7 ========
8 Tasks
9 ========
10
11 Intro
12 -------
13
14 `doit` is all about automating task dependency management and execution.
15 Tasks can execute external shell commands/scripts or python functions
16 (actually any callable).
17 So a task can be anything you can code :)
18
19 Tasks are defined in plain `python <http://python.org/>`_ module with some
20 conventions.
21
22 .. note::
23
24 You should be comfortable with python basics. If you don't know python yet
25 check `Python tutorial <http://docs.python.org/tut/>`_.
26
27
28 A function that starts with the name `task_` defines a *task-creator* recognized
29 by `doit`.
30 These functions must return (or yield) dictionaries representing a *task*.
31 A python module/file that defines *tasks* for `doit` is called **dodo** file
32 (that is something like a `Makefile` for `make`).
33
34 Take a look at this example (file dodo.py):
35
36 .. literalinclude:: samples/hello.py
37
38 When `doit` is executed without any parameters it will look for tasks in a
39 file named `dodo.py` in the current folder and execute its tasks.
40
41
42 .. code-block:: console
43
44 $ doit
45 . hello
46
47 On the output it displays which tasks were executed.
48 In this case the `dodo` file has only one task, `hello`.
49
50
51 Actions
52 --------
53
54 Every *task* must define `actions`.
55 It can optionally define other attributes like `targets`, `file_dep`,
56 `verbosity`, `doc` ...
57
58 `actions` define what the task actually does.
59 `actions` is always a list that can have any number of elements.
60 The actions of a task are always run sequentially.
61 There are 2 basic kinds of `actions`: *cmd-action* and *python-action*.
62 The action "result" is used to determine if task execution was successful or not.
63
64
65 python-action
66 ^^^^^^^^^^^^^^
67
68 If `action` is a python callable or a tuple `(callable, *args, **kwargs)`
69 - only `callable` is required.
70 The callable must be a function, method or callable object.
71 Classes and built-in functions are not allowed.
72 ``args`` is a sequence and ``kwargs`` is a dictionary that will be used
73 as positional and keywords arguments for the callable.
74 See `Keyword Arguments <http://docs.python.org/tutorial/controlflow.html#keyword-arguments>`_.
75
76 The result of the task is given by the returned value of the
77 ``action`` function.
78
79 For **successful** completion it must return one of:
80
81 * `True`
82 * `None`
83 * a dictionary
84 * a string
85
86 For **unsuccessful** completion it must return one of:
87
88 * `False` indicates the task generally failed
89 * if it raises any exception, it will be considered an error
90 * it can also explicitly return an instance of :py:class:`TaskFailed`
91 or :py:class:`TaskError`
92
93 If the action returns a type other than the types already discussed, the action
94 will be considered a failure, although this behavior might change in future
95 versions.
96
97 .. literalinclude:: samples/tutorial_02.py
98
99 The function `task_hello` is a *task-creator*, not the task itself.
100 The body of the task-creator function is always executed when the dodo
101 file is loaded.
102
103 .. topic:: task-creators vs actions
104
105 The body of task-creators are executed even if the task is not going
106 to be executed.
107 The body of task-creators should be used to create task metadata only,
108 not execute tasks!
109 From now on when the documentation says that a *task* is executed,
110 read "the task's actions are executed".
111
112
113 `action` parameters can be passed as ``kwargs``.
114
115 .. literalinclude:: samples/task_kwargs.py
116
117
118 cmd-action
119 ^^^^^^^^^^^
120
121 CmdAction's are executed in a subprocess (using python
122 `subprocess.Popen <http://docs.python.org/library/subprocess.html#popen-constructor>`_).
123
124 If `action` is a string, the command will be executed through the shell.
125 (Popen argument shell=True).
126
127 It is easy to include dynamic (on-the-fly) behavior to your tasks with
128 python code from the `dodo` file. Let's take a look at another example:
129
130
131 .. literalinclude:: samples/cmd_actions.py
132
133 .. note::
134
135 The body of the *task-creator* is always executed,
136 so in this example the line `msg = 3 * "hi! "` will always be executed.
137
138
139 If `action` is a list of strings and instances of any Path class from
140 `pathlib <https://docs.python.org/3/library/pathlib.html>`_, by default it will
141 be executed **without the shell** (Popen argument shell=False).
142
143 .. literalinclude:: samples/cmd_actions_list.py
144
145
146 For complex commands it is also possible to pass a callable that returns
147 the command string. In this case you must explicit import CmdAction.
148
149 .. literalinclude:: samples/cmd_from_callable.py
150
151
152 You might also explicitly import ``CmdAction`` in case you want to pass extra
153 parameters to ``Popen`` like ``cwd``.
154 All keyword parameter from ``Popen`` can be used on ``CmdAction`` (except
155 ``stdout`` and ``stderr``).
156
157 .. note::
158
159 Different from `subprocess.Popen`, `CmdAction` `shell` argument defaults to
160 `True`. All other `Popen` arguments can also be passed in `CmdAction` except
161 `stdout` and `stderr`
162
163
164
165 The result of the task follows the shell convention.
166 If the process exits with the value `0` it is successful.
167 Any other value means the task failed.
168
169
170 .. _custom-actions:
171
172 custom actions
173 ^^^^^^^^^^^^^^^^^^^
174
175 It is possible to create other type of actions,
176 check :ref:`tools.LongRunning<tools.LongRunning>` as an example.
177
178
179
180 task name
181 ------------
182
183 By default a task name is taken from the name of the python function
184 that generates the task.
185 For example a `def task_hello` would create a task named ``hello``.
186
187 It is possible to explicitly set a task name with the parameter ``basename``.
188
189 .. literalinclude:: samples/task_name.py
190
191
192 .. code-block:: console
193
194 $ doit
195 . hello
196 . hello2
197
198
199 When explicit using ``basename`` the task-creator is not limited
200 to create only one task.
201 Using ``yield`` it can generate several tasks at once.
202 It is also possible to ``yield`` a generator that generate tasks.
203 This is useful to write some generic/reusable task-creators.
204
205 .. literalinclude:: samples/task_reusable.py
206
207 .. code-block:: console
208
209 $ doit
210 . t2
211 . t1
212
213
214 listing tasks
215 -------------
216
217 ``doit`` has built-in sub-command that can be used to list/print all tasks.
218
219 .. code-block:: console
220
221 $ doit list
222 hello say hello
223 hello2 say hello again
224
225
226 doc
227 ---
228
229 Every task has an associated documentation.
230 By default this documentation is taken from the task-creator function's docstring.
231 It can also be set by the ``doc`` attribute.
232
233 .. literalinclude:: samples/task_doc.py
234
235 .. code-block:: console
236
237 $ doit list
238 . hello say hello
239
240
241
242 sub-tasks
243 ---------
244
245 Most of the time we want to apply the same task several times
246 in different contexts.
247
248 The task function can return a python-generator that yields dictionaries.
249 Since each sub-task must be uniquely identified it requires an
250 additional field ``name``.
251
252 .. literalinclude:: samples/subtasks.py
253
254
255 .. code-block:: console
256
257 $ doit
258 . create_file:file0.txt
259 . create_file:file1.txt
260 . create_file:file2.txt
261
262
263
264 avoiding empty sub-tasks
265 ^^^^^^^^^^^^^^^^^^^^^^^^^^
266
267 If you are not sure sub-tasks will be created for a given ``basename``
268 but you want to make sure that a task exists,
269 you can yield a sub-task with ``name`` equal to ``None``.
270 This can also be used to set the task ``doc`` and ``watch`` attributes.
271
272 .. literalinclude:: samples/empty_subtasks.py
273
274 .. code-block:: console
275
276 $ doit
277 $ doit list
278 do_x docs for X
279
280
281
282 Dependencies & Targets
283 -------------------------
284
285 One of the main ideas of `doit` (and other build-tools) is to check if the
286 tasks/targets are **up-to-date**. In case there is no modification in the
287 dependencies and the targets already exist, it skips the task execution to
288 save time, as it would produce the same output from the previous run.
289
290 Dependency
291 A dependency indicates an input to the task execution.
292
293 Target
294 A *target* is the result/output file produced by the task execution.
295
296
297 i.e. In a compilation task the source file is a *file_dep*,
298 the object file is a *target*.
299
300 .. literalinclude:: samples/compile.py
301
302
303 `doit` automatically keeps track of file dependencies. It saves the
304 signature (MD5) of the dependencies every time the task is completed successfully.
305
306 So if there are no modifications to the dependencies and you run `doit` again.
307 The execution of the task's actions is skipped.
308
309
310 .. code-block:: console
311
312 $ doit
313 . compile
314 $ doit
315 -- compile
316
317 Note the ``--`` (2 dashes, one space) on the command output on the second
318 time it is executed. It means, this task was up-to-date and not executed.
319
320
321 .. _file-dep:
322
323 file_dep (file dependency)
324 -----------------------------
325
326 Different from most build-tools dependencies are on tasks, not on targets.
327 So `doit` can take advantage of the "execute only if not up-to-date" feature
328 even for tasks that don't define targets.
329
330 Let's say you work with a dynamic language (python in this example).
331 You don't need to compile anything but you probably want to apply a lint-like
332 tool (i.e. `pyflakes <http://pypi.python.org/pypi/pyflakes>`_) to your
333 source code files. You can define the source code as a dependency to the task.
334
335 Every dependency in file_dep list should be a string or an instance of any
336 Path class from `pathlib <https://docs.python.org/3/library/pathlib.html>`_.
337
338
339 .. literalinclude:: samples/checker.py
340
341 .. code-block:: console
342
343 $ doit
344 . checker
345 $ doit
346 -- checker
347
348
349 `doit` checks if `file_dep` was modified or not
350 (by comparing the file content's MD5). If there are no changes the action
351 is not executed again as it would produce the same result.
352
353 Note the ``--`` again to indicate the execution was skipped.
354
355 Traditional build-tools can only handle files as "dependencies".
356 `doit` has several ways to check for dependencies, those will be introduced later.
357
358
359 .. note::
360
361 `doit` saves the MD5 of a `file_dep` after the actions are executed.
362 Be careful about editing a `file_dep` while a task is running because
363 `doit` might save the MD5 of a version of the file that is different
364 than it actually used to execute the task.
365
366
367 targets
368 -------
369
370 Targets can be any file path (a file or folder). If a target does not exist
371 the task will be executed. There is no limitation on the number of targets
372 a task may define. Two different tasks can not have the same target. Target
373 can be specified as a string or as an instance of any Path class from
374 `pathlib <https://docs.python.org/3/library/pathlib.html>`_.
375
376 Lets take the compilation example again.
377
378 .. literalinclude:: samples/compile.py
379
380 * If there are no changes in the dependency the task execution is skipped.
381 * But if the target is removed the task is executed again.
382 * But only if it does not exist. If the target is modified but the dependencies
383 do not change the task is not executed again.
384
385 .. code-block:: console
386
387 $ doit
388 . compile
389 $ doit
390 -- compile
391 $ rm main.o
392 $ doit
393 . compile
394 $ echo xxx > main.o
395 $ doit
396 -- compile
397
398
399
400 execution order
401 -----------------
402
403 If your tasks interact in a way where the target (output) of one task is a
404 file_dep (input) of another task, `doit` will make sure your tasks are
405 executed in the correct order.
406
407 .. literalinclude:: samples/taskorder.py
408
409 .. code-block:: console
410
411 $ doit
412 . create
413 . modify
414
415
416 .. note::
417
418 `doit` compares the path (string) of the file of `file_dep` and `targets`.
419 So although `my_file` and `./my_file` are actually the same file, `doit`
420 will think they are different files.
421
422
423 .. _task-selection:
424
425 Task selection
426 ----------------
427
428
429 By default all tasks are executed in the same order as they were defined (the order may change to satisfy dependencies). You can control which tasks will run in 2 ways.
430
431 Another example
432
433 .. literalinclude:: samples/selecttasks.py
434
435 DOIT_CONFIG -> default_tasks
436 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
437
438 *dodo* file defines a dictionary ``DOIT_CONFIG`` with ``default_tasks``, a list of strings where each element is a task name.
439
440 .. code-block:: console
441
442 $ doit
443 . t1
444 . t3
445
446 Note that only the task *t3* was specified to be executed by default.
447 But its dependencies include a target of another task (t1).
448 So that task was automatically executed also.
449
450
451 command line selection
452 ^^^^^^^^^^^^^^^^^^^^^^^
453
454 From the command line you can control which tasks are going to be execute by passing its task name. Any number of tasks can be passed as positional arguments.
455
456 .. code-block:: console
457
458 $ doit t2
459 . t2
460
461
462 You can also specify which task to execute by its target:
463
464 .. code-block:: console
465
466 $ doit task1
467 . t1
468
469
470 sub-task selection
471 ^^^^^^^^^^^^^^^^^^^^^
472
473 You can select sub-tasks from the command line specifying its full name.
474
475 .. literalinclude:: samples/subtasks.py
476
477
478 .. code-block:: console
479
480 $ doit create_file:file2.txt
481 . create_file:file2.txt
482
483
484 wildcard selection
485 ^^^^^^^^^^^^^^^^^^^^
486
487 You can also select tasks to be executed using a `glob <http://docs.python.org/library/glob.html>`_ like syntax (it must contains a ``*``).
488
489 .. code-block:: console
490
491 $ doit "create_file:file*"
492 . create_file:file1.txt
493 . create_file:file2.txt
494 . create_file:file3.txt
495
496
497
498 parameters on actions
499 ---------------------
500
501 Actions may take optional parameters provided as function keywords arguments for *python-action*. Or values for *printf-style* formatting on *cmd-action*.
502
503 There are three sources of parameter values:
504
505 - specified on action's `kwargs` definition
506 - keywords with task metadata such as `dependencies`, `changed`, `targets` and `task`
507 - values computed in other tasks. :ref:`getargs` describes, how a task can calculate and store values and how other tasks can refer to them.
508
509
510 keywords with task metadata
511 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
512
513 These values are automatically calculated by `doit`:
514
515 - `dependencies`: list of `file_dep`
516 - `changed`: list of `file_dep` that changed since last
517 successful execution
518 - `targets`: list of `targets`
519 - `task`: only available to *python-action*.
520 Note: the value is a `Task` object instance, not the metadata *dict*.
521
522
523 .. _keywords-on-cmd-action-string:
524
525 keywords on cmd-action string
526 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
527
528 For *cmd-action* you can take advantage of implicit keyword
529 substitution on *cmd-action* strings using python formatting.
530
531 Both format-string-syntax_ and old-string-formatting_ are available and
532 are controlled by ``DOIT_CONFIG`` value of ``action_string_formatting``.
533 It can be:
534
535 * ``'old'`` uses old-string-formatting_ (``%``)
536 * ``'new'`` uses format-string-syntax_ (``{{}}``)
537 * ``'both'`` both old and new style
538
539 The keyword value is a string containing all respective
540 file names separated by a space (" ").
541
542 .. _format-string-syntax: https://docs.python.org/3/library/string.html#format-string-syntax
543 .. _old-string-formatting: http://docs.python.org/3/library/stdtypes.html#old-string-formatting
544
545
546 .. literalinclude:: samples/report_deps.py
547
548 .. warning:: ``action_string_formatting`` default value (as of `doit` version **0.32**) is ``'old'``. This default value might change in future versions, it is advised to always explicitly state a value.
549
550 Before the string is actually executed, it is always formatted using
551 the formatters specified in `DOIT_CONFIG`. Make sure to escape your formatters
552 control characters, namely `{` and `}` for format-string-syntax_ and `%` for
553 old-string-formatting_. This is done by doubling them, so `%` becomes `%%` and so on.
554
555 .. note:: *cmd-action* may have the form of a string (as `"echo hello world"`)
556 or list of arguments (as `["echo", "hello", "world"]`).
557 Implicit keywords substitution applies only to the string form
558 and does not affect the list form. This means `{}` and `%`
559 need not be escaped when using this form.
560
561
562
563 keywords on *python-action*
564 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
565
566 For *python-action* add a keyword parameter in the function,
567 `doit` will take care of passing the value when the function is called.
568 `dependencies`, `changed`, `targets` are passed as list of strings.
569
570
571 .. literalinclude:: samples/hello.py
572
573
574 You can also pass the keyword `task` to have a reference to all task
575 metadata.
576
577 .. literalinclude:: samples/meta.py
578
579
580 .. note::
581
582 It is possible not only to retrieve task's attributes but also to
583 modify them while the action is running!
584
585
586
587
588 private/hidden tasks
589 ---------------------
590
591 If task name starts with an underscore '_', it will not be included in the output.
592
593
594 title
595 -------
596
597 By default when you run `doit` only the task name is printed out on the output.
598 You can customize the output passing a ``title`` function to the task:
599
600 .. literalinclude:: samples/title.py
601
602 .. code-block:: console
603
604 $ doit
605 . executing... Cmd: echo abc efg
606
607
608
609 .. _verbosity:
610
611
612 verbosity
613 -----------
614
615 By default the stdout from a task is captured and its stderr is sent to the
616 console. If the task fails or there is an error the stdout and a traceback
617 (if any) is displayed.
618
619 There are 3 levels of verbosity:
620
621 0:
622 capture (do not print) stdout/stderr from task.
623
624 1 (default):
625 capture stdout only.
626
627 2:
628 do not capture anything (print everything immediately).
629
630
631 You can control the verbosity by:
632
633 * task attribute verbosity
634
635 .. literalinclude:: samples/verbosity.py
636
637 .. code-block:: console
638
639 $ doit
640 . print
641 hello
642
643 * from command line, see :ref:`verbosity option<verbosity_option>`.
644
645
646 meta
647 ----
648
649 You can pass *extra* metadata (dict) to a task through the **meta** attribute.
650 This could be used by custom commands or plugins.
651
652 .. literalinclude:: samples/metadata.py
653
654
655 pathlib
656 --------
657
658 `doit` supports `pathlib <https://docs.python.org/3/library/pathlib.html>`_:
659 file_dep, targets and CmdAction specified as a list can take as elements not
660 only strings but also instances of any Path class from pathlib.
661
662 Lets take the compilation example and modify it to work with any number
663 of header and source files in current directory using pathlib.
664
665 .. literalinclude:: samples/compile_pathlib.py