Method: RBS::CLI#run_ancestors

Defined in:
lib/rbs/cli.rb

#run_ancestors(args, options) ⇒ Object



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
291
292
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
# File 'lib/rbs/cli.rb', line 260

def run_ancestors(args, options)
  # @type var kind: :instance | :singleton
  kind = :instance

  OptionParser.new do |opts|
    opts.banner = "Usage: rbs ancestors [options...] [type_name]\n\nShow ancestors of the given class or module.\n\nExamples:\n\n  $ rbs ancestors --instance String\n  $ rbs ancestors --singleton Array\n\nOptions:\n"
    opts.on("--instance", "Ancestors of instance of the given type_name (default)") { kind = :instance }
    opts.on("--singleton", "Ancestors of singleton of the given type_name") { kind = :singleton }
  end.order!(args)

  unless args.size == 1
    stdout.puts "Expected one argument."
    return
  end

  loader = options.loader()

  env = Environment.from_loader(loader).resolve_type_names

  builder = DefinitionBuilder::AncestorBuilder.new(env: env)
  type_name = TypeName.parse(args[0]).absolute!

  case env.constant_entry(type_name)
  when Environment::ClassEntry, Environment::ModuleEntry, Environment::ClassAliasEntry, Environment::ModuleAliasEntry
    type_name = env.normalize_module_name(type_name)

    ancestors = case kind
                when :instance
                  builder.instance_ancestors(type_name)
                when :singleton
                  builder.singleton_ancestors(type_name)
                else
                  raise
                end

    ancestors.ancestors.each do |ancestor|
      case ancestor
      when Definition::Ancestor::Singleton
        stdout.puts "singleton(#{ancestor.name})"
      when Definition::Ancestor::Instance
        if ancestor.args.empty?
          stdout.puts ancestor.name.to_s
        else
          stdout.puts "#{ancestor.name}[#{ancestor.args.join(", ")}]"
        end
      end
    end
  else
    stdout.puts "Cannot find class: #{type_name}"
  end
end