6

pyinvoke supports so called "pre" tasks, that have to be executed before running a task:

@task(pre=[required_precondition])
def mytask(c, param1=False):
    pass

Is it possible to add a condition to a "pre" task (i.e. run "required_precondition" only if param1 is True)?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
mrh1997
  • 922
  • 7
  • 18

1 Answers1

4

As far as I have seen no, the pre and post conditions are created at "compile time", which means they won't have access to a parameter. Alternatively, it is part from perfect, but you can use the fact that you can call one task from another (it is not explained in the docs) to manually do your pretask condition.

from invoke import Collection, task

@task
def hello(c):
    print("hello")

@task
def goodbye(c, a=False):
    if a:
        col = Collection()
        col.add_task(hello)
        col['hello'](c)

    print('goodbye')

Outputs

> invoke goodbye
goodbye

> invoke goodbye -a
hello
goodbye

It does feel "hacky", but as far as I can this is the easier way.

Note: If for any reason your tasks are already part of a namespace or ns variable, you don't need to create a new collection, just call them from the namespace itself as in namespace['hello'](c)

Jordi Nonell
  • 81
  • 2
  • 4
  • 1
    Instead of creating a collection, adding a task and call it, one could also call the task directly: "hello(c)". But in both cases deduplication does not work, which is an essential part of invoke. – mrh1997 Oct 16 '19 at 20:56