开发者

How to use or add subcommand feature with thor?

I am creating a CLI app using thor. Its going well but now I'm stuck with the sub-command feature.

There ain't anything in its github wiki and googled around, but nothing helpful.

So, can someone show or point me out how to implement the s开发者_StackOverflow社区ubcommand feature?


Check out: http://whatisthor.com/

From that site (edited a bit to save space and highlight subcommand usage):

module GitCLI
  class Remote  ", "Adds a remote named  for the repository at "
    option :t, :banner => ""
    option :m, :banner => ""
    options :f => :boolean, :tags => :boolean, :mirror => :string
    def add(name, url)
      # implement git remote add
    end

    desc "rename  ", "Rename the remote named  to "
    def rename(old, new)
    end
  end

  class Git  [...]", "Download objects and refs from another repository"
    options :all => :boolean, :multiple => :boolean
    option :append, :type => :boolean, :aliases => :a
    def fetch(respository, *refspec)
      # implement git fetch here
    end

    desc "remote SUBCOMMAND ...ARGS", "manage set of tracked repositories"
    subcommand "remote", Remote  ### SUBCOMMAND USED HERE...
  end
end

hth...


Try something like this (file test.rb):

#!/usr/bin/env ruby

require 'rubygems'
require 'thor'
require 'thor/group'  # This is required -- it's not a bug, it's a feature!

class Bar < Thor
  desc "baz", "Whatever"
  def baz
    puts "Hello from Bar"
  end
end

class Foo < Thor
  desc "go", "Do something"
  def go
    puts "Hello there!"
  end

  register Bar, :bar, "bar", "Do something else"
end

if __FILE__ == $0
  Foo.start
end

This behaves as follows:

> test.rb
Tasks:
  test.rb bar          # Do something else
  test.rb go           # Do something
  test.rb help [TASK]  # Describe available tasks or one specific task

> test.rb go
Hello there!
> test.rb bar
Tasks:
  test.rb baz             # Whatever
  test.rb help [COMMAND]  # Describe subcommands or one specific subcommand

> test.rb bar baz
Hello from Bar
> test.rb baz
Could not find task "baz".
>

(This mostly works as expected, except the help information for "test.rb bar" isn't quite right, IMHO. I think it should say "test.rb bar baz ...", instead of "test.rb baz ...".)

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜