Debian Codegraph @

sites/docs/getting-started.rst

raw
1 ===============
2 Getting started
3 ===============
4
5 This document presents a whirlwind tour of Invoke's feature set. Please see the
6 links throughout for detailed conceptual & API docs. For installation help, see
7 the project's `installation page <https://www.pyinvoke.org/installing.html>`_.
8
9 .. _defining-and-running-task-functions:
10
11 Defining and running task functions
12 ===================================
13
14 The core use case for Invoke is setting up a collection of task functions and
15 executing them. This is pretty easy -- all you need is to make a file called
16 ``tasks.py`` importing the `.task` decorator and decorating one or more
17 functions. You will also need to add an arbitrarily-named context argument
18 (convention is to use ``c``, ``ctx`` or ``context``) as the first positional
19 arg. Don't worry about using this context parameter yet.
20
21 Let's start with a dummy Sphinx docs building task::
22
23 from invoke import task
24
25 @task
26 def build(c):
27 print("Building!")
28
29 You can then execute that new task by telling Invoke's command line runner,
30 ``invoke``, that you want it to run::
31
32 $ invoke build
33 Building!
34
35 The function body can be any Python you want -- anything at all.
36
37
38 Task parameters
39 ===============
40
41 Functions can have arguments, and thus so can tasks. By default, your task
42 functions' args/kwargs are mapped automatically to both long and short CLI
43 flags, as per :ref:`the CLI docs <task-arguments>`. For example, if we add a
44 ``clean`` argument and give it a boolean default, it will show up as a set of
45 toggle flags, ``--clean`` and ``-c``::
46
47 @task
48 def build(c, clean=False):
49 if clean:
50 print("Cleaning!")
51 print("Building!")
52
53 Invocations::
54
55 $ invoke build -c
56 $ invoke build --clean
57
58 Naturally, other default argument values will allow giving string or integer
59 values. Arguments with no default values are assumed to take strings, and can
60 also be given as positional arguments. Take this incredibly contrived snippet
61 for example::
62
63 @task
64 def hi(c, name):
65 print("Hi {}!".format(name))
66
67 It can be invoked in the following ways, all resulting in "Hi Name!"::
68
69 $ invoke hi Name
70 $ invoke hi --name Name
71 $ invoke hi --name=Name
72 $ invoke hi -n Name
73 $ invoke hi -nName
74
75 Adding metadata via `@task <.task>`
76 -----------------------------------
77
78 `@task <.task>` can be used without any arguments, as above, but it's also a
79 convenient vector for additional metadata about the task function it decorates.
80 One common example is describing the task's arguments, via the ``help``
81 parameter (in addition to optionally giving task-level help via the
82 docstring)::
83
84 @task(help={'name': "Name of the person to say hi to."})
85 def hi(c, name):
86 """
87 Say hi to someone.
88 """
89 print("Hi {}!".format(name))
90
91 This description will show up when invoking ``--help``::
92
93 $ invoke --help hi
94 Usage: inv[oke] [--core-opts] hi [--options] [other tasks here ...]
95
96 Docstring:
97 Say hi to someone.
98
99 Options:
100 -n STRING, --name=STRING Name of the person to say hi to.
101
102 More details on task parameterization and metadata can be found in
103 :doc:`/concepts/invoking-tasks` (for the command-line & parsing side of things)
104 and in the `.task` API documentation (for the declaration side).
105
106
107 Listing tasks
108 =============
109
110 You'll sometimes want to see what tasks are available in a given
111 ``tasks.py`` -- ``invoke`` can be told to list them instead of executing
112 something::
113
114 $ invoke --list
115 Available tasks:
116
117 build
118
119 This will also print the first line of each task’s docstring, if it has one. To
120 see what else is available besides ``--list``, say ``invoke --help``.
121
122
123 Running shell commands
124 ======================
125
126 Many use cases for Invoke involve running local shell commands, similar to
127 programs like Make or Rake. This is done via the `~.Context.run` function::
128
129 from invoke import task
130
131 @task
132 def build(c):
133 c.run("sphinx-build docs docs/_build")
134
135 You'll see the command's output in your terminal as it runs::
136
137 $ invoke build
138 Running Sphinx v1.1.3
139 loading pickled environment... done
140 ...
141 build succeeded, 2 warnings.
142
143 `~.Context.run` has a number of arguments controlling its behavior, such as
144 activation of pseudo-terminals for complex programs requiring them, suppression
145 of exit-on-error behavior, hiding of subprocess' output (while still capturing
146 it for later review), and more. See `its API docs <.Context.run>` for details.
147
148 `~.Context.run` always returns a useful `.Result` object providing access to
149 the captured output, exit code, and other information.
150
151 .. _why-context:
152
153 Aside: what exactly is this 'context' arg anyway?
154 -------------------------------------------------
155
156 A common problem task runners face is transmission of "global" data - values
157 loaded from :doc:`configuration files </concepts/configuration>` or :ref:`other
158 configuration vectors <collection-configuration>`, given via CLI flags,
159 generated in 'setup' tasks, etc.
160
161 Some libraries (such as `Fabric <https://fabfile.org>`_ 1.x) implement this via
162 module-level attributes, which makes testing difficult and error prone, limits
163 concurrency, and increases implementation complexity.
164
165 Invoke encapsulates state in explicit `~.Context` objects, handed to tasks when
166 they execute . The context is the primary API endpoint, offering methods which
167 honor the current state (such as `.Context.run`) as well as access to that
168 state itself.
169
170
171 Declaring pre-tasks
172 ===================
173
174 Tasks may be configured in a number of ways via the `.task` decorator. One of
175 these is to select one or more other tasks you wish to always run prior to
176 execution of your task, indicated by name.
177
178 Let's expand our docs builder with a new cleanup task that runs before every
179 build (but which, of course, can still be executed on its own)::
180
181 from invoke import task
182
183 @task
184 def clean(c):
185 c.run("rm -rf docs/_build")
186
187 @task(clean)
188 def build(c):
189 c.run("sphinx-build docs docs/_build")
190
191 Now when you ``invoke build``, it will automatically run ``clean`` first.
192
193 .. note::
194 If you're not a fan of the implicit "positional arguments are pre-run task
195 names" API, you can instead explicitly give the ``pre`` kwarg:
196 ``@task(pre=[clean])``.
197
198 Details can be found in :ref:`how-tasks-run`.
199
200
201 Creating namespaces
202 ===================
203
204 Right now, our ``tasks.py`` is implicitly for documentation only, but maybe our
205 project needs other non-doc things, like packaging/deploying, testing, etc. At
206 that point, a single flat namespace isn't enough, so Invoke lets you easily
207 build a :doc:`nested namespace <concepts/namespaces>`. Here's a quick example.
208
209 Let's first rename our ``tasks.py`` to be ``docs.py``; no other changes are
210 needed there. Then we create a new ``tasks.py``, and for the sake of brevity
211 populate it with a new, truly top level task called ``deploy``.
212
213 Finally, we can use a new API member, the `.Collection` class, to bind this
214 task and the ``docs`` module into a single explicit namespace. When Invoke
215 loads your task module, if a `.Collection` object bound as ``ns`` or
216 ``namespace`` exists it will get used for the root namespace::
217
218 from invoke import Collection, task
219 import docs
220
221 @task
222 def deploy(c):
223 c.run("python setup.py sdist")
224 c.run("twine upload dist/*")
225
226 namespace = Collection(docs, deploy)
227
228 The result::
229
230 $ invoke --list
231 Available tasks:
232
233 deploy
234 docs.build
235 docs.clean
236
237 For a more detailed breakdown of how namespacing works, please see :doc:`the
238 docs <concepts/namespaces>`.