yugui (owner)

Revisions

gist: 30428 Download_button fork
public
Description:
helper methods to generate mdoc from OptionParser in Ruby
Public Clone URL: git://gist.github.com/30428.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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