From: nobu.nokada@... Date: 2004-11-10T16:38:36+09:00 Subject: Re: From getoptlong to optparse Hi, At Wed, 3 Nov 2004 05:33:48 +0900, Massimiliano Mirra - bard wrote in [ruby-talk:118836]: > I have a command line program invoked like this: > > $ prog --host localhost --port 8000 login --password secret > $ prog --host localhost --port 8000 list --open > > ....and so on. In other words: > > $ command [general options] subcommand [specific options] > > Like darcs or cvs. I had included an example file cmd.rb (and its incidental file cmd-ls.rb), in sole packaged optparse, but they are not bundled now. #! /usr/bin/ruby require 'optparse' require 'pp' @host = @port = nil # general options opt = OptionParser.new do |opt| opt.banner = "Usage: #{$0} [general options] subcommand [specific options]" opt.define(" general options:") opt.define('--host HOST', String) {|host| @host = host} opt.define('--port PORT', Integer) {|port| @port = port} end # specific option initializers specific = { "login" => proc do |opt| @passwd = nil opt.define("--password PASSWORD", String) {|passwd| @passwd = passwd} end, "list" => proc do |opt| @open = false opt.define("--open") {|open| @open = true} end, } missing = proc {|opt| opt.define([" subcommand:", specific.keys.sort].join("\n\t")) } begin cmd = nil opt.order!(ARGV) {|cmd| opt.terminate} opt = OptionParser.new(opt) do |opt| unless cmd abort "#{$0}: command missing\n#{missing[opt]}" end subopt = specific.fetch(cmd) do abort "#{$0}: unknown command: #{cmd}\n#{missing[opt]}" end opt.define(" specific options for #{cmd}:") subopt[opt] end opt.parse!(ARGV) rescue OptionParser::ParseError => e abort "#{e}\n#{opt}" end pp self -- Nobu Nakada