davetron5000 / gli

Make awesome command-line applications the easy way
http://davetron5000.github.io/gli
Apache License 2.0
1.26k stars 102 forks source link

RFE: pre/post blocks for subcommands #312

Closed np422 closed 3 years ago

np422 commented 3 years ago

I'm working on a an app with a lot of subcommands.

It would be great if a pre block could be specified inside a command to define a pre-block that is executed for all subcommands of that command.

desc "manage remotes"
command :remote do |c|
  c.command :repo do |repo|
    # do something
  end
  c.command :other_subcommand do |other|
    # do something else
  end
  pre do |global,command,options,args|
    # This gets done for both app remote repo and and app remote other_subcommand
    true
  end 
end
davetron5000 commented 3 years ago

You could mimic this by using the passed command object in the pre. It has a parent attribute which is either the parent command or the GLI App if the command is a top level subcommand, so you could do something like:

def find_top_level_command(command)
  if command.parent.kind_of?(GLI::Command)
    find_top_level_command(command.parent)
  else
    command
  end
end

pre do |global,command,options,args|
  top_level_command = find_top_level_command(command)
  if top_level_command.name == "foo"
    # do whatever common stuff is needed for "foo" commands
  end
end

Hack-ish, but would work.

np422 commented 3 years ago

Thank you! This gets the job done!