pyinvoke / invoke

Pythonic task management & command execution.
http://pyinvoke.org
BSD 2-Clause "Simplified" License
4.39k stars 367 forks source link

Get name for context aware task #195

Open darfink opened 9 years ago

darfink commented 9 years ago

Is it possible to get the name of the currently running task, if the task is context aware? I can give an example of by describing my current situation.

I want to have one task for each of my application installations, but the logic of these tasks are all identical. That means a lot of boilerplate code.

@task(cask)
def alfred():
  if application_exists('alfred'):
    return
  install('alfred')

@task(cask)
def asepsis():
  if application_exists('asepsis'):
    return
  install('asepsis')

What I would prefer would be to do something like this:

@task(cask)
def install_app(ctx):
  if application_exists(ctx.name):
    return
  install(ctx.name)

ns = Collection()
ns.add_task(install_app, name='alfred')
ns.add_task(install_app, name='asepsis')

Is this possible, or is there any workaround?

sophacles commented 9 years ago

Looking at the code for Task, you should be able to do this, or something similar:

def install_app(name):
  if application_exists(name):
    return
  install(name)

class MyTask(Task):
   def __call__(self, ctx, *args, **kw):
     return self.body(self.name)

ns = Collection()
ns.add_task(MyTask(install_app, name = "alfred"))
ns.add_atask(MyTask(install_app, name="asepsis"))

Although this in my mind brings up a couple thoughts for @bitprophet -

  1. Can we get a kwarg to the @task decorators to point at custom subclasses of Task? (this may be done or covered by another ticket already....)
  2. Should the Context object point to the specific Task instance being used - so we could do something like ctx.task.name in the above - this gets a bit hairy with all the other stuff being discussed, but it might be useful/needed.
bitprophet commented 9 years ago

Hi!

haydenflinner commented 6 years ago

Think you can close this thanks to klass. Very handy feature!