Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a --version option to a Ruby Thor CLI

Tags:

ruby

thor

How do I add a --version option to my Ruby Thor command line interface application.

For example I want to be able to run

$ thor_app --version
> thor_app version 1.0.0

This question is related to Run a CLI Thor app without arguments or task name, but specifically to add a --version option which does not require a task.

Note
This was written following the self-answer format. Addition answers and updates are encouraged

like image 594
Morgan Avatar asked Apr 02 '14 11:04

Morgan


3 Answers

I had some luck with this approach:

class CLI < Thor
  map %w[--version -v] => :__print_version

  desc "--version, -v", "print the version"
  def __print_version
    puts FooBar::VERSION
  end
end

The leading underscores ensures there isn't a command like yourapp version, and forces yourapp --version or yourapp -v. The desc content will allow it to show up as -v, --version without exposing __print_version.

like image 181
Adam Prescott Avatar answered Oct 22 '22 18:10

Adam Prescott


I didn't love the accepted solution; it ends up listing version as a command, listing --version and --no-version as global options, and if the script is run with no options it's silent rather than giving help.

The best I've been able to come up with is to do it outside Thor:

class CLI < Thor
   .
   .
   .
end

if ARGV[0] == "--version"
    puts "MyApp #{MyApp::VERSION}"
    exit
end

CLI.start

This has the minor drawback that --version isn't documented anywhere.

like image 3
ronen Avatar answered Oct 22 '22 20:10

ronen


So far the best option I have come up with is to create a boolean class option, which does not belong to a task, which can be referenced by other tasks. The often used example for a class option is -v verbose, as all tasks can use this to determine how noisy they should be.

Then create a 'version' task and make it the default task, so when no task is defined the version task is ran and can react to the --version flag (class option).

class CLI < Thor
  #include Thor::Actions
  class_option :version, :type => :boolean

  desc "version", "Show thor_app version"
  def version
    if options[:version]
      puts "thor_app version #{find_version}"
    end
  end
  default_task :version

  no_tasks do
    def find_version
      ## Method can be replaced to look up VERSION
      '1.0.0'
    end
  end
end
like image 1
Morgan Avatar answered Oct 22 '22 18:10

Morgan