Class: Homebrew::CLI::Parser

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
cli/parser.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ void

FIXME: Block should be T.nilable(T.proc.bind(Parser).void). See https://github.com/sorbet/sorbet/issues/498.

Parameters:

  • block (T.proc.bind(Parser).void)


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'cli/parser.rb', line 112

def initialize(&block)
  @parser = OptionParser.new

  @parser.summary_indent = " " * 2

  # Disable default handling of `--version` switch.
  @parser.base.long.delete("version")

  # Disable default handling of `--help` switch.
  @parser.base.long.delete("help")

  @args = Homebrew::CLI::Args.new

  @command_name = caller_locations(2, 1).first.label.chomp("_args").tr("_", "-")

  @constraints = []
  @conflicts = []
  @switch_sources = {}
  @processed_options = []
  @non_global_processed_options = []
  @named_args_type = nil
  @max_named_args = nil
  @min_named_args = nil
  @description = nil
  @usage_banner = nil
  @hide_from_man_page = false
  @formula_options = false
  @cask_options = false

  self.class.global_options.each do |short, long, desc|
    switch short, long, description: desc, env: option_to_name(long), method: :on_tail
  end

  instance_eval(&block) if block

  generate_banner
end

Instance Attribute Details

#hide_from_man_pageObject (readonly)

Returns the value of attribute hide_from_man_page.



19
20
21
# File 'cli/parser.rb', line 19

def hide_from_man_page
  @hide_from_man_page
end

#named_args_typeObject (readonly)

Returns the value of attribute named_args_type.



19
20
21
# File 'cli/parser.rb', line 19

def named_args_type
  @named_args_type
end

#processed_optionsObject (readonly)

Returns the value of attribute processed_options.



19
20
21
# File 'cli/parser.rb', line 19

def processed_options
  @processed_options
end

Class Method Details

.from_cmd_path(cmd_path) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'cli/parser.rb', line 21

def self.from_cmd_path(cmd_path)
  cmd_args_method_name = Commands.args_method_name(cmd_path)

  begin
    Homebrew.send(cmd_args_method_name) if require?(cmd_path)
  rescue NoMethodError => e
    raise if e.name != cmd_args_method_name

    nil
  end
end

.global_cask_optionsObject



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
92
93
94
95
96
97
# File 'cli/parser.rb', line 33

def self.global_cask_options
  [
    [:flag, "--appdir=", {
      description: "Target location for Applications " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:appdir]}`).",
    }],
    [:flag, "--colorpickerdir=", {
      description: "Target location for Color Pickers " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:colorpickerdir]}`).",
    }],
    [:flag, "--prefpanedir=", {
      description: "Target location for Preference Panes " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:prefpanedir]}`).",
    }],
    [:flag, "--qlplugindir=", {
      description: "Target location for QuickLook Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:qlplugindir]}`).",
    }],
    [:flag, "--mdimporterdir=", {
      description: "Target location for Spotlight Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:mdimporterdir]}`).",
    }],
    [:flag, "--dictionarydir=", {
      description: "Target location for Dictionaries " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:dictionarydir]}`).",
    }],
    [:flag, "--fontdir=", {
      description: "Target location for Fonts " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:fontdir]}`).",
    }],
    [:flag, "--servicedir=", {
      description: "Target location for Services " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:servicedir]}`).",
    }],
    [:flag, "--input-methoddir=", {
      description: "Target location for Input Methods " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:input_methoddir]}`).",
    }],
    [:flag, "--internet-plugindir=", {
      description: "Target location for Internet Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:internet_plugindir]}`).",
    }],
    [:flag, "--audio-unit-plugindir=", {
      description: "Target location for Audio Unit Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:audio_unit_plugindir]}`).",
    }],
    [:flag, "--vst-plugindir=", {
      description: "Target location for VST Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:vst_plugindir]}`).",
    }],
    [:flag, "--vst3-plugindir=", {
      description: "Target location for VST3 Plugins " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:vst3_plugindir]}`).",
    }],
    [:flag, "--screen-saverdir=", {
      description: "Target location for Screen Savers " \
                   "(default: `#{Cask::Config::DEFAULT_DIRS[:screen_saverdir]}`).",
    }],
    [:comma_array, "--language", {
      description: "Comma-separated list of language codes to prefer for cask installation. " \
                   "The first matching language is used, otherwise it reverts to the cask's " \
                   "default language. The default value is the language of your system.",
    }],
  ]
end

.global_optionsArray<Array(String, String, String)>

Returns:



100
101
102
103
104
105
106
107
# File 'cli/parser.rb', line 100

def self.global_options
  [
    ["-d", "--debug",   "Display any debugging information."],
    ["-q", "--quiet",   "Make some output more quiet."],
    ["-v", "--verbose", "Make some output more verbose."],
    ["-h", "--help",    "Show this message."],
  ]
end

Instance Method Details

#cask_optionsObject



358
359
360
361
362
363
364
# File 'cli/parser.rb', line 358

def cask_options
  self.class.global_cask_options.each do |method, *args, **options|
    send(method, *args, **options)
    conflicts "--formula", args.last
  end
  @cask_options = true
end

#comma_array(name, description: nil) ⇒ Object



201
202
203
204
205
206
207
208
# File 'cli/parser.rb', line 201

def comma_array(name, description: nil)
  name = name.chomp "="
  description = option_to_description(name) if description.nil?
  process_option(name, description, type: :comma_array)
  @parser.on(name, OptionParser::REQUIRED_ARGUMENT, Array, *wrap_option_desc(description)) do |list|
    @args[option_to_name(name)] = list
  end
end

#conflicts(*options) ⇒ Object



236
237
238
# File 'cli/parser.rb', line 236

def conflicts(*options)
  @conflicts << options.map { |option| option_to_name(option) }
end

#description(text = nil) ⇒ Object



187
188
189
190
191
# File 'cli/parser.rb', line 187

def description(text = nil)
  return @description if text.blank?

  @description = text.chomp
end

#env?(env) ⇒ Boolean

Returns:

  • (Boolean)


181
182
183
184
185
# File 'cli/parser.rb', line 181

def env?(env)
  return if env.blank?

  Homebrew::EnvConfig.try(:"#{env}?")
end

#flag(*names, description: nil, replacement: nil, required_for: nil, depends_on: nil, hidden: false) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'cli/parser.rb', line 210

def flag(*names, description: nil, replacement: nil, required_for: nil,
         depends_on: nil, hidden: false)
  required, flag_type = if names.any? { |name| name.end_with? "=" }
    [OptionParser::REQUIRED_ARGUMENT, :required_flag]
  else
    [OptionParser::OPTIONAL_ARGUMENT, :optional_flag]
  end
  names.map! { |name| name.chomp "=" }
  description = option_to_description(*names) if description.nil?
  if replacement.nil?
    process_option(*names, description, type: flag_type, hidden: hidden)
  else
    description += " (disabled#{"; replaced by #{replacement}" if replacement.present?})"
  end
  @parser.on(*names, *wrap_option_desc(description), required) do |option_value|
    odisabled "the `#{names.first}` flag", replacement unless replacement.nil?
    names.each do |name|
      @args[option_to_name(name)] = option_value
    end
  end

  names.each do |name|
    set_constraints(name, required_for: required_for, depends_on: depends_on)
  end
end

#formula_optionsvoid

This method returns an undefined value.



367
368
369
# File 'cli/parser.rb', line 367

def formula_options
  @formula_options = true
end

#generate_help_textObject



348
349
350
351
352
353
354
355
356
# File 'cli/parser.rb', line 348

def generate_help_text
  Formatter.wrap(@parser.to_s, COMMAND_DESC_WIDTH)
           .sub(/^/, "#{Tty.bold}Usage: brew#{Tty.reset} ")
           .gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}")
           .gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) }
           .gsub(/\*(.*?)\*|<(.*?)>/m) do |underlined|
             underlined[1...-1].gsub(/^(\s*)(.*?)$/, "\\1#{Tty.underline}\\2#{Tty.reset}")
           end
end

#hide_from_man_page!void

This method returns an undefined value.



413
414
415
# File 'cli/parser.rb', line 413

def hide_from_man_page!
  @hide_from_man_page = true
end

#max_named(_count) ⇒ Object



400
401
402
# File 'cli/parser.rb', line 400

def max_named(_count)
  odisabled "`max_named`", "`named_args max:`"
end

#min_named(_count_or_type) ⇒ Object



404
405
406
# File 'cli/parser.rb', line 404

def min_named(_count_or_type)
  odisabled "`min_named`", "`named_args min:`"
end

#name_to_option(name) ⇒ Object



246
247
248
249
250
251
252
# File 'cli/parser.rb', line 246

def name_to_option(name)
  if name.length == 1
    "-#{name}"
  else
    "--#{name.tr("_", "-")}"
  end
end

#named(_count_or_type) ⇒ Object



408
409
410
# File 'cli/parser.rb', line 408

def named(_count_or_type)
  odisabled "`named`", "`named_args`"
end

#named_args(type = nil, number: nil, min: nil, max: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • type (Symbol, Array<String>, Array<Symbol>) (defaults to: nil)
  • number (Integer, nil) (defaults to: nil)
  • min (Integer, nil) (defaults to: nil)
  • max (Integer, nil) (defaults to: nil)


379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'cli/parser.rb', line 379

def named_args(type = nil, number: nil, min: nil, max: nil)
  if number.present? && (min.present? || max.present?)
    raise ArgumentError, "Do not specify both `number` and `min` or `max`"
  end

  if type == :none && (number.present? || min.present? || max.present?)
    raise ArgumentError, "Do not specify both `number`, `min` or `max` with `named_args :none`"
  end

  @named_args_type = type

  if type == :none
    @max_named_args = 0
  elsif number.present?
    @min_named_args = @max_named_args = number
  elsif min.present? || max.present?
    @min_named_args = min
    @max_named_args = max
  end
end

#option_to_description(*names) ⇒ Object



254
255
256
# File 'cli/parser.rb', line 254

def option_to_description(*names)
  names.map { |name| name.to_s.sub(/\A--?/, "").tr("-", " ") }.max
end

#option_to_name(option) ⇒ Object



240
241
242
243
244
# File 'cli/parser.rb', line 240

def option_to_name(option)
  option.sub(/\A--?(\[no-\])?/, "")
        .tr("-", "_")
        .delete("=")
end

#parse(argv = ARGV.freeze, ignore_invalid_options: false) ⇒ Args

Parameters:

  • argv (Array<String>) (defaults to: ARGV.freeze)
  • ignore_invalid_options (Boolean) (defaults to: false)

Returns:



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'cli/parser.rb', line 293

def parse(argv = ARGV.freeze, ignore_invalid_options: false)
  raise "Arguments were already parsed!" if @args_parsed

  # If we accept formula options, parse once allowing invalid options
  # so we can get the remaining list containing formula names.
  if @formula_options
    remaining, non_options = parse_remaining(argv, ignore_invalid_options: true)

    argv = [*remaining, "--", *non_options]

    formulae(argv).each do |f|
      next if f.options.empty?

      f.options.each do |o|
        name = o.flag
        description = "`#{f.name}`: #{o.description}"
        if name.end_with? "="
          flag   name, description: description
        else
          switch name, description: description
        end

        conflicts "--cask", name
      end
    end
  end

  remaining, non_options = parse_remaining(argv, ignore_invalid_options: ignore_invalid_options)

  named_args = if ignore_invalid_options
    []
  else
    remaining + non_options
  end

  unless ignore_invalid_options
    check_constraint_violations
    check_named_args(named_args)
  end

  @args.freeze_named_args!(named_args, cask_options: @cask_options)
  @args.freeze_remaining_args!(non_options.empty? ? remaining : [*remaining, "--", non_options])
  @args.freeze_processed_options!(@processed_options)
  @args.freeze

  @args_parsed = true

  if !ignore_invalid_options && @args.help?
    puts generate_help_text
    exit
  end

  @args
end

#parse_remaining(argv, ignore_invalid_options: false) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'cli/parser.rb', line 258

def parse_remaining(argv, ignore_invalid_options: false)
  i = 0
  remaining = []

  argv, non_options = split_non_options(argv)

  while i < argv.count
    begin
      begin
        arg = argv[i]

        remaining << arg unless @parser.parse([arg]).empty?
      rescue OptionParser::MissingArgument
        raise if i + 1 >= argv.count

        args = argv[i..(i + 1)]
        @parser.parse(args)
        i += 1
      end
    rescue OptionParser::InvalidOption
      if ignore_invalid_options
        remaining << arg
      else
        $stderr.puts generate_help_text
        raise
      end
    end

    i += 1
  end

  [remaining, non_options]
end

#switch(*names, description: nil, replacement: nil, env: nil, required_for: nil, depends_on: nil, method: :on) ⇒ Object Also known as: switch_option



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'cli/parser.rb', line 150

def switch(*names, description: nil, replacement: nil, env: nil, required_for: nil, depends_on: nil,
           method: :on)
  global_switch = names.first.is_a?(Symbol)
  return if global_switch

  description = option_to_description(*names) if description.nil?
  if replacement.nil?
    process_option(*names, description, type: :switch)
  else
    description += " (disabled#{"; replaced by #{replacement}" if replacement.present?})"
  end
  @parser.public_send(method, *names, *wrap_option_desc(description)) do |value|
    odisabled "the `#{names.first}` switch", replacement unless replacement.nil?
    value = if names.any? { |name| name.start_with?("--[no-]") }
      value
    else
      true
    end

    set_switch(*names, value: value, from: :args)
  end

  names.each do |name|
    set_constraints(name, required_for: required_for, depends_on: depends_on)
  end

  env_value = env?(env)
  set_switch(*names, value: env_value, from: :env) unless env_value.nil?
end

#usage_banner(text) ⇒ Object



193
194
195
# File 'cli/parser.rb', line 193

def usage_banner(text)
  @usage_banner, @description = text.chomp.split("\n\n", 2)
end

#usage_banner_textObject



197
198
199
# File 'cli/parser.rb', line 197

def usage_banner_text
  @parser.banner
end