Run a CLI Thor app without arguments or task name

感情迁移 提交于 2019-12-03 01:14:54

It seems the proper Thor-way to do this is using default_task:

class Commands < Thor
  desc "whatever", "The default task to run when no command is given"
  def whatever
    ...
  end
  default_task :whatever
end
Commands.start

If for whatever reason that isn't what you need, you should be able to do something like

class Commands < Thor
  ...
end

if ARGV.empty?
  # Perform the default, it doesn't have to be a Thor task
  Commands.new.whatever
else
  # Start Thor as usual
  Commands.start
end

Kind of hackish, but where there's only one defined action anyway, I just prepended the action name to the ARGV array that gets passed in:

class GitTranslate < Thor
  desc "translate <repo-name>", "Obtain a full url given only a repo name"
  option :bitbucket, type: :boolean, aliases: 'b' 
  def translate(repo)
    if options[:bitbucket]
      str = "freedomben/#{repo}.git"
      puts "SSH:   git@bitbucket.org:#{str}"
      puts "HTTPS: https://freedomben@bitbucket.org/#{str}"
    else
      str = "FreedomBen/#{repo}.git"
      puts "SSH:   git@github.com:#{str}"
      puts "HTTPS: https://github.com/#{str}"
    end 
  end 
end

Then where I start the class by passing in ARGV:

GitTranslate.start(ARGV.dup.unshift("translate"))

While it is a little hackish, I solved a similar problem by catching the option as the argument itself:

argument :name

def init
 if name === '--init'
   file_name = ".blam"
   template('templates/blam.tt', file_name) unless File.exists?(file_name)
   exit(0)
 end
end

When running in a Thor::Group this method is executed before others and lets me trick the program into responding to an option like argument.

This code is from https://github.com/neverstopbuilding/blam.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!