为 Ruby Thor CLI 添加一个 --version 选项

16
3个回答

35

我用这种方法有些幸运:

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

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

前导下划线确保没有像yourapp version这样的命令,强制使用yourapp --versionyourapp -vdesc内容将允许显示为-v, --version,而不会暴露__print_version


1
这有点类似于 bundler 所做的事情。只不过他们把任务称作版本,并允许人们使用 bundler version 命令来调用它(因为为什么不能呢?) https://github.com/bundler/bundler/blob/6afa89217cf052c58316da1f2be7bf54749ff9de/lib/bundler/cli.rb#L312-L316 - ZombieDev
4
应提交给Thor开发人员进行文档修正。 - Rob Kinyon
1
只是一个提醒,你需要重新安装 gem 才能获得新的操作。如果你想动态测试它,可以运行:bundle exec bin/gem_name - konyak

3
我不喜欢现有的解决方案:它将version列为命令,将--version--no-version列为全局选项,如果该脚本没有任何选项运行,则没有帮助信息输出。最好的方法是在Thor之外进行处理:
class CLI < Thor
   .
   .
   .
end

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

CLI.start

这个方法的小缺陷在于 --version 没有被记录在文档中。


3
“我并不喜欢被接受的解决方案” - 仅供纪念,原指摩根的回答(https://dev59.com/TmEh5IYBdhLWcg3wGwKO#22809973)。 - Adam Prescott

1
到目前为止,我想到的最好的选择是创建一个布尔类选项,它不属于任何任务,可以被其他任务引用。常用的类选项示例是-v详细模式,因为所有任务都可以使用它来确定输出信息的详细程度。
然后创建一个“版本”任务并将其设置为默认任务,这样当没有定义任务时,版本任务将运行,并且可以响应--version标志(类选项)。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接