Class: CliUtils

Inherits:
Object
  • Object
show all
Includes:
Errors
Defined in:
lib/cli_utils.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(commands_filepath = nil, config_filepath = nil, suggestions_count = nil) ⇒ CliUtils

Returns a new instance of CliUtils.



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
# File 'lib/cli_utils.rb', line 21

def initialize(commands_filepath=nil, config_filepath=nil, suggestions_count=nil)
  @s_count = suggestions_count || 4

  begin
    init_commands(commands_filepath)
    init_config(config_filepath)
    parse_options

    if @command
      @eval = @commands[@command]['eval']
    end

  rescue ParseError => e
    render_error e
  rescue ArgumentError => e
    render_error e
  rescue MissingFileError => e
    render_error e
  rescue MissingCommandError => e
    err = "#{e.message} is not a command. Did you mean:\n\n"
    alts = CliUtils::top_matches(e.message, @commands.keys, @s_count).map{|m| usage(m)}.uniq.join("\n")
    $stderr.puts("#{err}#{alts}")
    exit 1
  end
end

Instance Attribute Details

#commandObject

Returns the value of attribute command.



19
20
21
# File 'lib/cli_utils.rb', line 19

def command
  @command
end

#commandsObject

Returns the value of attribute commands.



19
20
21
# File 'lib/cli_utils.rb', line 19

def commands
  @commands
end

#configObject

Returns the value of attribute config.



19
20
21
# File 'lib/cli_utils.rb', line 19

def config
  @config
end

#evalObject

Returns the value of attribute eval.



19
20
21
# File 'lib/cli_utils.rb', line 19

def eval
  @eval
end

#optionalObject

Returns the value of attribute optional.



19
20
21
# File 'lib/cli_utils.rb', line 19

def optional
  @optional
end

#requiredObject

Returns the value of attribute required.



19
20
21
# File 'lib/cli_utils.rb', line 19

def required
  @required
end

Class Method Details

.levenshtein_distance(s, t) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cli_utils.rb', line 47

def self.levenshtein_distance(s, t)
  return 0 if s == t
  return t.length if s.length == 0
  return s.length if t.length == 0

  a0 = (0..t.length + 1).to_a
  a1 = []

  (0..s.length - 1).each{|i|
    a1[0] = i + 1

    (0..t.length - 1).each{|j|
      cost = (s[i] == t[j]) ? 0 : 1
      a1[j + 1] = [a1[j] + 1, a0[j + 1] + 1, a0[j] + cost].min
    }
    a0 = a1.clone
  }

  return a1[t.length]
end

.test_levObject



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/cli_utils.rb', line 68

def self.test_lev
  ts = [ [''    , 'abc', 3],
         ['aaa' , 'aab', 1],
         ['aa'  , 'aab', 1],
         ['aaaa', 'aab', 2],
         ['aaa' , 'aaa', 0],
       ]

  ts.each_with_index{|arr,i|
    condition = levenshtein_distance(arr[0],arr[1]) == arr[2]
    puts "Test #{i}: #{(condition ? 'success' : 'failure')}"
  }
end

.top_matches(str, candidates, top = 4) ⇒ Object

TODO can return duplicates if the long and short commands are similar



83
84
85
# File 'lib/cli_utils.rb', line 83

def self.top_matches(str, candidates, top=4)
  candidates.sort_by{|a| levenshtein_distance(str, a)}[0...top]
end

Instance Method Details

#dangling?(command_index, current_index, arg) ⇒ Boolean

Returns:

  • (Boolean)


169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/cli_utils.rb', line 169

def dangling?(command_index, current_index, arg)
  num_req = (@commands[@command]['required'] || []).length if @command
  is_required =
    command_index &&
    (command_index + 1 + num_req) > current_index &&
    current_index > command_index

  is_value = current_index > 0 && ARGV[current_index - 1].start_with?('--')
  is_first_command = is_command?(arg) && !@command

  !(is_value || is_required || is_first_command)
end

#format_json(struct) ⇒ Object



93
94
95
96
97
98
99
# File 'lib/cli_utils.rb', line 93

def format_json(struct)
  if (@config['defaults'] || {})['pretty_print'].to_s.downcase == 'true'
    return Json.pretty_generate(struct, {'max_nesting' => 100})
  else
    return Json.generate(struct, {'max_nesting' => 100})
  end
end

#init_commands(commands_filepath) ⇒ Object

Raises:



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/cli_utils.rb', line 101

def init_commands(commands_filepath)
  @commands ={}
  return unless commands_filepath

  unless File.exist?(commands_filepath)
    raise MissingFileError.new("Commands File not found: #{commands_filepath}")
  end

  begin
    commands = JSON.parse(File.open(commands_filepath,'r').read)
  rescue JSON::ParserError => e
    raise ArgumentError.new("#{commands_filepath} contents is not valid JSON")
  end

  raise ArgumentError.new("#{commands_filepath} is not an array") unless commands.is_a?(Array)

  commands.each{|c|
    mb_long = c['long']
    mb_short = c['short']
    @commands[mb_long] = c if mb_long
    @commands[mb_short] = c if mb_short
  }
end

#init_config(config_filepath) ⇒ Object



201
202
203
204
# File 'lib/cli_utils.rb', line 201

def init_config(config_filepath)
  #TODO
  @config = {}
end

#is_command?(str) ⇒ Boolean

Returns:

  • (Boolean)


193
194
195
# File 'lib/cli_utils.rb', line 193

def is_command?(str)
  (@commands || {}).has_key?(str)
end

#parse_optionsObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/cli_utils.rb', line 125

def parse_options
  @optional = {}
  command_index = nil
  ARGV.each_with_index {|arg, i|
    next_arg = ARGV[i + 1]

    if arg[0] == '-'
      if arg[1] == '-'
        raise ParseError.new("Missing argument to: #{arg}") unless next_arg
        @optional[arg[2..-1]] = processValue(next_arg)
      else
        @optional[tail(arg)] = true
      end
    else
      if dangling?(command_index, i, arg)
        if ARGV.find{|e| @commands.has_key?(e)}
          raise ParseError.new("Dangling command line element: #{arg}")
        else
          raise MissingCommandError.new(arg)
        end
      end

      next if @command

      if is_command?(arg)
        @command = arg
        command_index = i
        req_keys = (@commands[@command]['required'] || [])
        req_vals = ARGV[i + 1, req_keys.length]

        err_str1 = 'Missing required arguments'
        raise ParseError.new(err_str1) unless req_keys.length == req_vals.length

        err_str2 = 'Required arguments may not begin with "-"'
        raise ParseError.new(err_str2) if req_vals.map{|v| v.chr}.include?('-')

        @required = {}
        #old versions of ruby do not have a to_h array method
        req_keys.zip(req_vals).each{|(k,v)| @required[k] = processValue(v)}
      end
    end
  }
end

#processValue(val) ⇒ Object



206
207
208
209
210
211
212
213
# File 'lib/cli_utils.rb', line 206

def processValue(val)
  if val.start_with? '@'
    fn = tail(val)
    raise ArgumentError.new("File not found: #{fn}") unless File.exist?(fn)
    return File.open(fn,'r').read
  end
  val
end

#render_error(err) ⇒ Object



87
88
89
90
91
# File 'lib/cli_utils.rb', line 87

def render_error(err)
  $stderr.puts err.message
  $stderr.puts usage(@command) if @command
  exit 1
end

#tail(arr) ⇒ Object



197
198
199
# File 'lib/cli_utils.rb', line 197

def tail(arr)
  arr[1..-1]
end

#usage(command) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/cli_utils.rb', line 182

def usage(command)
  c        = @commands[command]
  long     = c['long'] || ''
  short    = c['short'] ? "(#{c['short']})" : ''
  required = (c['required'] || []).map{|r| "<#{r}>"}.join(' ')

  optional = (c['optional'] || []).map{|o| "[#{o}#{o.start_with?('--') ? ' foo' : ''}]"}.join(' ')

  "#{long} #{short} #{required} #{optional}".gsub(/ +/,' ')
end