Run a CLI Thor app without arguments or task name
Asked Answered
C

3

34

I'm looking for a way to create a command-line thor app that will run a default method without any arguments. I fiddled with Thor's default_method option, but still requires that I pass in an argument. I found a similar case where someone wanted to run a CLI Thor task with arguments but without a task name.

I'd like to run a task with no task name and no arguments. Is such a thing possible?

Canning answered 31/8, 2011 at 6:37 Comment(1)
I think you can also use Thor::Group, see hereTressietressure
I
68

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
Imbrication answered 31/8, 2011 at 7:1 Comment(0)
T
5

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:   [email protected]:#{str}"
      puts "HTTPS: https://[email protected]/#{str}"
    else
      str = "FreedomBen/#{repo}.git"
      puts "SSH:   [email protected]:#{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"))
Theoretical answered 19/4, 2015 at 18:51 Comment(1)
No reason to become hackish :) Jacob's answer is the way to go. Just set a default_task :translate and you are done.Accelerate
V
0

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.

Vodka answered 2/12, 2013 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.