Class: Solargraph::Shell

Inherits:
Thor
  • Object
show all
Includes:
ApiMap::SourceToYard, ServerMethods
Defined in:
lib/solargraph/shell.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ApiMap::SourceToYard

#code_object_at, #code_object_paths, #rake_yard

Methods included from ServerMethods

#available_port

Class Method Details

.exit_on_failure?Boolean

Tell Thor to ensure the process exits with status 1 if any error happens.

Returns:

  • (Boolean)


17
18
19
# File 'lib/solargraph/shell.rb', line 17

def self.exit_on_failure?
  true
end

Instance Method Details

#cache(gem, version = nil) ⇒ void

This method returns an undefined value.

Parameters:

  • gem (String)
  • version (String, nil) (defaults to: nil)


111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/solargraph/shell.rb', line 111

def cache gem, version = nil
  gemspec = Gem::Specification.find_by_name(gem, version)

  if options[:rebuild] || !PinCache.has_yard?(gemspec)
    pins = GemPins.build_yard_pins(['yard-activesupport-concern'], gemspec)
    PinCache.serialize_yard_gem(gemspec, pins)
  end

  workspace = Solargraph::Workspace.new(Dir.pwd) if File.exist?('rbs_collection.yaml')
  rbs_map = RbsMap.from_gemspec(gemspec, workspace&.rbs_collection_path, workspace&.rbs_collection_config_path)
  if options[:rebuild] || !PinCache.has_rbs_collection?(gemspec, rbs_map.cache_key)
    PinCache.serialize_rbs_collection_gem(gemspec, rbs_map.cache_key, rbs_map.pins)
  end
rescue Gem::MissingSpecError
  warn "Gem '#{gem}' not found"
end

#clearvoid

This method returns an undefined value.



99
100
101
102
# File 'lib/solargraph/shell.rb', line 99

def clear
  puts 'Deleting all cached documentation (gems, core and stdlib)'
  Solargraph::PinCache.clear
end

#config(directory = '.') ⇒ void

This method returns an undefined value.

Parameters:

  • directory (String) (defaults to: '.')


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/solargraph/shell.rb', line 71

def config directory = '.'
  matches = []
  if options[:extensions]
    Gem::Specification.each do |g|
      if g.name.match(/^solargraph-[A-Za-z0-9_-]*?-ext/)
        require g.name
        matches.push g.name
      end
    end
  end
  conf = Solargraph::Workspace::Config.new.raw_data
  unless matches.empty?
    matches.each do |m|
      conf['extensions'].push m
    end
  end
  # @param file [File]
  File.open(File.join(directory, '.solargraph.yml'), 'w') do |file|
    file.puts conf.to_yaml
  end
  $stdout.puts 'Configuration file initialized.'
end

#gems(*names) ⇒ void

This method returns an undefined value.

Parameters:

  • names (Array<String>)


181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/solargraph/shell.rb', line 181

def gems *names
  # print time with ms
  workspace = Solargraph::Workspace.new('.')

  if names.empty?
    Gem::Specification.to_a.each { |spec| do_cache spec, rebuild: options[:rebuild] }
    $stderr.puts "Documentation cached for all #{Gem::Specification.count} gems."
  else
    warn("Caching these gems: #{names}")
    names.each do |name|
      if name == 'core'
        # @sg-ignore cache_core and core? are dynamically defined
        PinCache.cache_core(out: $stdout) # if !PinCache.core? || options[:rebuild]
        next
      end

      gemspec = workspace.find_gem(*name.split('='))
      if gemspec.nil?
        warn "Gem '#{name}' not found"
      else
        if options[:rebuild] || !PinCache.has_yard?(gemspec)
          pins = GemPins.build_yard_pins(['yard-activesupport-concern'], gemspec)
          PinCache.serialize_yard_gem(gemspec, pins)
        end

        workspace = Solargraph::Workspace.new(Dir.pwd)
        rbs_map = RbsMap.from_gemspec(gemspec, workspace.rbs_collection_path, workspace.rbs_collection_config_path)
        if options[:rebuild] || !PinCache.has_rbs_collection?(gemspec, rbs_map.cache_key)
          # cache pins even if result is zero, so we don't retry building pins
          pins = rbs_map.pins || []
          PinCache.serialize_rbs_collection_gem(gemspec, rbs_map.cache_key, pins)
        end
      end
    rescue Gem::MissingSpecError
      warn "Gem '#{name}' not found"
    rescue Gem::Requirement::BadRequirementError => e
      warn "Gem '#{name}' failed while loading"
      warn e.message
      # @sg-ignore Need to add nil check here
      warn e.backtrace.join("\n")
    end
    warn "Documentation cached for #{names.count} gems."
  end
end

#listvoid

This method returns an undefined value.



324
325
326
327
328
# File 'lib/solargraph/shell.rb', line 324

def list
  workspace = Solargraph::Workspace.new(options[:directory])
  puts workspace.filenames unless options[:count]
  puts "#{workspace.filenames.length} files total."
end

#pin(path) ⇒ void

This method returns an undefined value.

Parameters:

  • path (String)

    The path to the method pin, e.g. ‘Class#method’ or ‘Class.method’



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/solargraph/shell.rb', line 341

def pin path
  api_map = Solargraph::ApiMap.load_with_cache('.', $stderr)
  is_method = path.include?('#') || path.include?('.')
  if is_method && options[:stack]
    scope, ns, meth = if path.include? '#'
                        [:instance, *path.split('#', 2)]
                      else
                        [:class, *path.split('.', 2)]
                      end

    # @sg-ignore Wrong argument type for
    #   Solargraph::ApiMap#get_method_stack: rooted_tag
    #   expected String, received Array<String>
    pins = api_map.get_method_stack(ns, meth, scope: scope)
  else
    pins = api_map.get_path_pins path
  end
  # @type [Hash{Symbol => Pin::Base}]
  references = {}
  pin = pins.first
  case pin
  when nil
    warn "Pin not found for path '#{path}'"
    exit 1
  when Pin::Namespace
    if options[:references]
      # @sg-ignore Need to add nil check here
      superclass_tag = api_map.qualify_superclass(pin.return_type.tag)
      superclass_pin = api_map.get_path_pins(superclass_tag).first if superclass_tag
      references[:superclass] = superclass_pin if superclass_pin
    end
  end

  pins.each do |pin|
    if options[:typify] || options[:probe]
      type = ComplexType::UNDEFINED
      type = pin.typify(api_map) if options[:typify]
      type = pin.probe(api_map) if options[:probe] && type.undefined?
      print_type(type)
      next
    end

    print_pin(pin)
  end
  references.each do |key, refpin|
    puts "\n# #{key.to_s.capitalize}:\n\n"
    print_pin(refpin)
  end
end

#profile(file = nil) ⇒ void

This method returns an undefined value.

Parameters:

  • file (String, nil) (defaults to: nil)


399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/solargraph/shell.rb', line 399

def profile file = nil
  begin
    require 'vernier'
  rescue LoadError
    $stderr.puts 'vernier gem not found. Please install this dependency:'
    $stderr.puts
    $stderr.puts "  gem 'vernier', '>1.0', '<2'"

    return
  end

  hooks = []
  hooks << :memory_usage if options[:memory]

  directory = File.realpath(options[:directory])
  FileUtils.mkdir_p(options[:output_dir])

  host = Solargraph::LanguageServer::Host.new
  host.client_capabilities.merge!({ 'window' => { 'workDoneProgress' => true } })
  # @param method [String] The message method
  # @param params [Hash] The method parameters
  # @return [void]
  def host.send_notification method, params
    puts "Notification: #{method} - #{params}"
  end

  parse_path = File.join(options[:output_dir], 'parse_benchmark.json.gz')
  catalog_path = File.join(options[:output_dir], 'catalog_benchmark.json.gz')
  definition_path = File.join(options[:output_dir], 'definition_benchmark.json.gz')

  prepare_time = catalog_time = definition_time = nil

  # Trap CTRL-C so the in-progress Vernier.profile block can unwind through
  # its ensure clause and still write its output file. A second CTRL-C
  # restores default handling for a hard exit.
  interrupted = false
  previous_int_trap = Signal.trap('INT') do
    if interrupted
      Signal.trap('INT', 'DEFAULT')
      Process.kill('INT', Process.pid)
    else
      interrupted = true
      puts "\nInterrupted. Finishing current profile (CTRL-C again to force exit)..."
      raise Interrupt
    end
  end

  begin
    puts 'Parsing and mapping source files...'
    prepare_start = Time.now
    Vernier.profile(out: parse_path, hooks: hooks) do
      puts 'Mapping libraries'
      host.prepare(directory)
      sleep 0.2 until host.libraries.all?(&:mapped?)
    end
    prepare_time = Time.now - prepare_start

    puts 'Building the catalog...'
    catalog_start = Time.now
    Vernier.profile(out: catalog_path, hooks: hooks) do
      host.catalog
    end
    catalog_time = Time.now - catalog_start

    # Determine test file
    if file
      test_file = File.join(directory, file)
    else
      test_file = File.join(directory, 'lib', 'other.rb')
      unless File.exist?(test_file)
        # Fallback to any Ruby file in the workspace
        workspace = Solargraph::Workspace.new(directory)
        test_file = workspace.filenames.find { |f| f.end_with?('.rb') }
        unless test_file
          puts 'No Ruby files found in workspace'
          return
        end
      end
    end

    file_uri = Solargraph::LanguageServer::UriHelpers.file_to_uri(File.absolute_path(test_file))

    puts "Profiling go-to-definition for #{test_file}"
    puts "Position: line #{options[:line]}, column #{options[:column]}"

    definition_start = Time.now
    Vernier.profile(out: definition_path, hooks: hooks) do
      message = Solargraph::LanguageServer::Message::TextDocument::Definition.new(
        host, {
          'params' => {
            'textDocument' => { 'uri' => file_uri },
            'position' => { 'line' => options[:line], 'character' => options[:column] }
          }
        }
      )
      puts 'Processing go-to-definition request...'
      result = message.process

      puts "Result: #{result.inspect}"
    end
    definition_time = Time.now - definition_start
  rescue Interrupt
    puts "\nProfile run interrupted; partial profile(s) have been written."
  ensure
    Signal.trap('INT', previous_int_trap || 'DEFAULT')

    puts "\n=== Timing Results ==="
    puts "Parsing & mapping: #{(prepare_time * 1000).round(2)}ms" if prepare_time
    puts "Catalog building: #{(catalog_time * 1000).round(2)}ms" if catalog_time
    puts "Go-to-definition: #{(definition_time * 1000).round(2)}ms" if definition_time
    if prepare_time && catalog_time && definition_time
      total_time = prepare_time + catalog_time + definition_time
      puts "Total time: #{(total_time * 1000).round(2)}ms"
    end

    saved = [parse_path, catalog_path, definition_path].select { |p| File.exist?(p) }
    unless saved.empty?
      puts "\nProfiles saved to:"
      saved.each { |p| puts "  - #{File.expand_path(p)}" }

      puts "\nUpload the JSON files to https://vernier.prof/ to view the profiles."
      puts 'Or use https://rubygems.org/gems/profile-viewer to view them locally.'
    end
  end
end

#rbsObject



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/solargraph/shell.rb', line 528

def rbs
  api_map = Solargraph::ApiMap.load('.')
  pins = api_map.source_maps.flat_map(&:pins)
  store = Solargraph::ApiMap::Store.new(pins)
  if options[:inference]
    puts 'Inferring untyped methods...'
    store.method_pins.each do |pin|
      next unless pin.return_type.undefined?
      type = pin.typify(api_map)
      type = pin.probe(api_map) if type.undefined?
      pin.docstring.add_tag YARD::Tags::Tag.new('return', nil, type.items.map(&:to_s))
      pin.instance_variable_set(:@return_type, type)
    end
  end
  puts 'Generating yardocs...'
  rake_yard(store)
  work_dir = Dir.pwd
  Dir.mktmpdir do |tmpdir|
    Dir.chdir tmpdir do
      yardoc = File.join(tmpdir, '.yardoc')
      YARD::Registry.save(false, yardoc)
      YARD::Registry.load(yardoc)
      rel_dir = File.join('sig', options[:filename])
      puts "Writing #{rel_dir}..."
      target = File.join(work_dir, rel_dir)
      FileUtils.mkdir_p(File.join(work_dir, 'sig'))
      `sord #{target} --rbs --no-regenerate`
    end
  end
  puts 'Done.'
end

#reportersvoid

This method returns an undefined value.



228
229
230
# File 'lib/solargraph/shell.rb', line 228

def reporters
  puts Solargraph::Diagnostics.reporters
end

#scanvoid

This method returns an undefined value.



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
# File 'lib/solargraph/shell.rb', line 292

def scan
  directory = File.realpath(options[:directory])
  # @type [Solargraph::ApiMap, nil]
  api_map = nil
  time = Benchmark.measure do
    api_map = Solargraph::ApiMap.load_with_cache(directory, $stdout)
    # @sg-ignore flow sensitive typing should be able to handle redefinition
    api_map.pins.each do |pin|
      puts pin_description(pin) if options[:verbose]
      pin.typify api_map
      pin.probe api_map
    rescue StandardError => e
      # @todo to add nil check here
      # @todo should warn on nil dereference below
      warn "Error testing #{pin_description(pin)} #{if pin.location
                                                      "at #{pin.location.filename}:#{pin.location.range.start.line + 1}"
                                                    end}"
      warn "[#{e.class}]: #{e.message}"
      # @todo Need to add nil check here
      # @todo flow sensitive typing should be able to handle redefinition
      warn e.backtrace.join("\n")
      exit 1
    end
  end
  # @sg-ignore Need to add nil check here
  puts "Scanned #{directory} (#{api_map.pins.length} pins) in #{time.real} seconds."
end

#socketvoid

This method returns an undefined value.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/solargraph/shell.rb', line 33

def socket
  require 'backport'
  port = options[:port]
  port = available_port if port.zero?
  Backport.run do
    Signal.trap('INT') do
      Backport.stop
    end
    Signal.trap('TERM') do
      Backport.stop
    end
    # @sg-ignore Wrong argument type for Backport.prepare_tcp_server: adapter expected Backport::Adapter, received Module<Solargraph::LanguageServer::Transport::Adapter>
    Backport.prepare_tcp_server host: options[:host], port: port, adapter: Solargraph::LanguageServer::Transport::Adapter
    $stderr.puts "Solargraph is listening PORT=#{port} PID=#{Process.pid}"
  end
end

#stdiovoid

This method returns an undefined value.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/solargraph/shell.rb', line 52

def stdio
  require 'backport'
  Backport.run do
    Signal.trap('INT') do
      Backport.stop
    end
    Signal.trap('TERM') do
      Backport.stop
    end
    # @sg-ignore Wrong argument type for Backport.prepare_stdio_server: adapter expected Backport::Adapter, received Module<Solargraph::LanguageServer::Transport::Adapter>
    Backport.prepare_stdio_server adapter: Solargraph::LanguageServer::Transport::Adapter
    $stderr.puts "Solargraph is listening on stdio PID=#{Process.pid}"
  end
end

#typecheck(*files) ⇒ void

This method returns an undefined value.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/solargraph/shell.rb', line 242

def typecheck *files
  directory = File.realpath(options[:directory])
  workspace = Solargraph::Workspace.new(directory)
  level = options[:level].to_sym
  rules = workspace.rules(level)
  api_map =
    Solargraph::ApiMap.load_with_cache(directory, $stdout,
                                       loose_unions:
                                         !rules.require_all_unique_types_support_call?)
  probcount = 0
  if files.empty?
    files = api_map.source_maps.map(&:filename)
  else
    files.map! { |file| File.realpath(file) }
  end
  filecount = 0
  time = Benchmark.measure do
    files.each do |file|
      checker = TypeChecker.new(file, api_map: api_map, rules: rules, level: options[:level].to_sym,
                                      workspace: workspace)
      problems = checker.problems
      next if problems.empty?
      problems.sort! { |a, b| a.location.range.start.line <=> b.location.range.start.line }
      puts problems.map { |prob|
        "#{prob.location.filename}:#{prob.location.range.start.line + 1}: #{prob.message}"
      }.join("\n")
      filecount += 1
      probcount += problems.length
    end
  end
  puts "Typecheck finished in #{time.real} seconds."
  puts "#{probcount} problem#{if probcount != 1
                                's'
                              end} found#{if files.length != 1
                                                              " in #{filecount} of #{files.length} files"
                                                            end}."
  # "
  exit 1 if probcount.positive?
end

#uncache(*gems) ⇒ void

This method returns an undefined value.

Parameters:

  • gems (Array<String>)

Raises:

  • (ArgumentError)


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/solargraph/shell.rb', line 136

def uncache *gems
  raise ArgumentError, 'No gems specified.' if gems.empty?
  gems.each do |gem|
    if gem == 'core'
      PinCache.uncache_core
      next
    end

    if gem == 'stdlib'
      PinCache.uncache_stdlib
      next
    end

    spec = Gem::Specification.find_by_name(gem)
    PinCache.uncache_gem(spec, out: $stdout)
  end
end

#versionvoid

This method returns an undefined value.



25
26
27
# File 'lib/solargraph/shell.rb', line 25

def version
  puts Solargraph::VERSION
end