Skip to content

Instantly share code, notes, and snippets.

@yugui
Created November 30, 2008 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yugui/30428 to your computer and use it in GitHub Desktop.
Save yugui/30428 to your computer and use it in GitHub Desktop.
helper methods to generate mdoc from OptionParser in Ruby
require 'optparse'
class OptionParser
def list_opts(prior_opts)
opts = enum_for(:visit, :tap).map(&:list).flatten(1)
prior_opts = opts.select{|opt| opt.long.any?{|name| prior_opts.include?(name)} }
opts -= prior_opts
simple_opts = opts.select{|opt| !opt.short.empty? && opt.arg.nil? }.sort_by{|x| x.short.sort.first}
opts -= simple_opts
arg_opts = opts.select{|opt| !opt.short.empty?}.sort_by{|x| x.short.sort.first}
opts -= arg_opts
opts = opts.sort{|x,y| x.long.sort.first}
return prior_opts, simple_opts, arg_opts, opts
end
private :list_opts
def to_mdoc_synopsis(prior_opts)
prior, simple, arg, long = list_opts(prior_opts)
synopsis = ".Sh SYNOPSIS¥n.Nm¥n"
prior.each do |opt|
synopsis << ".Op Fl " << opt.long.sort.first[1..-1]
if opt.arg =~ /¥[([^¥]]+)¥]/
synopsis << " Op Ar " << $1
elsif opt.arg
synopsis << " Ar " << opt.arg[/¥S+/]
end
synopsis << "¥n"
end
synopsis << ".Op Fl " << simple.map{|x| x.short.first[-1, 1]}.join << "¥n"
(arg + long).each do |opt|
name = opt.short.sort.first || opt.long.sort.first
synopsis << ".Op Fl " << name[1..-1]
if opt.arg =~ /¥[([^¥]]+)¥]/
synopsis << " Op Ar " << $1
elsif opt.arg
synopsis << " Ar " << opt.arg[/¥S+/]
end
synopsis << "¥n"
end
synopsis.chomp
end
def to_mdoc_description(prior_opts)
prior, simple, arg, long = list_opts(prior_opts)
synopsis = <<EOS
.Sh OPTIONS
.Bl -tag -width "1234567890123" -compact
.Pp
EOS
prior.each do |opt|
synopsis << ".It Fl " << opt.long.sort.first[1..-1]
if opt.arg =~ /¥[([^¥]]+)¥]/
synopsis << " Op Ar " << $1
elsif opt.arg
synopsis << " Ar " << opt.arg[/¥S+/]
end
synopsis << "¥n"
synopsis << opt.desc.join << "¥n.Pp¥n"
end
short = (simple + arg).sort_by{|x| x.short.sort.first}
(short + long).each do |opt|
(opt.short.sort + opt.long.sort).each do |name|
synopsis << ".It Fl " << name[1..-1]
if opt.arg =~ /¥[([^¥]]+)¥]/
synopsis << " Op Ar " << $1
elsif opt.arg
synopsis << " Ar " << opt.arg[/¥S+/]
end
synopsis << "¥n"
end
synopsis << opt.desc.join << "¥n.Pp¥n"
end
synopsis << <<'EOS'
.El
.Pp
EOS
synopsis.chomp
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment