Class: Legion::TTY::Background::Scanner

Inherits:
Object
  • Object
show all
Includes:
Logging::Helper
Defined in:
lib/legion/tty/background/scanner.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

MAX_DEPTH =
3
SERVICES =
{
  rabbitmq: 5672,
  redis: 6379,
  memcached: 11_211,
  vault: 8200,
  postgres: 5432
}.freeze
CONFIG_FILES =
%w[.env Gemfile package.json Dockerfile].freeze
LANGUAGE_MAP =
{
  '.rb' => 'Ruby',
  '.py' => 'Python',
  '.js' => 'JavaScript',
  '.ts' => 'TypeScript',
  '.go' => 'Go',
  '.java' => 'Java',
  '.rs' => 'Rust',
  '.tf' => 'Terraform',
  '.sh' => 'Shell'
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(base_dirs: nil, logger: nil) ⇒ Scanner

Returns a new instance of Scanner.



38
39
40
41
# File 'lib/legion/tty/background/scanner.rb', line 38

def initialize(base_dirs: nil, logger: nil)
  @base_dirs = base_dirs || [File.expand_path('~')]
  @boot_log = logger
end

Instance Method Details

#run_async(queue) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/legion/tty/background/scanner.rb', line 77

def run_async(queue)
  Thread.new do
    @boot_log&.log('scanner', "starting scan of #{@base_dirs.join(', ')}")
    t0 = Time.now
    data = scan_all
    elapsed = ((Time.now - t0) * 1000).round
    @boot_log&.log('scanner', "scan complete in #{elapsed}ms")
    queue.push({ type: :scan_complete, data: data })
  rescue StandardError => e
    @boot_log&.log('scanner', "ERROR: #{e.class}: #{e.message}")
    queue.push({ type: :scan_error, error: e.message })
  end
end

#scan_allObject



64
65
66
67
# File 'lib/legion/tty/background/scanner.rb', line 64

def scan_all
  { services: scan_services, repos: scan_git_repos, tools: scan_shell_history,
    configs: scan_config_files, dotfiles: scan_dotfiles }
end

#scan_config_filesObject



58
59
60
61
62
# File 'lib/legion/tty/background/scanner.rb', line 58

def scan_config_files
  @base_dirs.flat_map do |base|
    CONFIG_FILES.map { |name| File.join(base, name) }.select { |p| File.exist?(p) }
  end
end

#scan_dotfilesObject



69
70
71
72
73
74
75
# File 'lib/legion/tty/background/scanner.rb', line 69

def scan_dotfiles
  {
    git: scan_gitconfig,
    jfrog: scan_jfrog,
    terraform: scan_terraform
  }
end

#scan_git_reposObject



49
50
51
# File 'lib/legion/tty/background/scanner.rb', line 49

def scan_git_repos
  @base_dirs.flat_map { |base| collect_repos(base) }
end

#scan_servicesObject



43
44
45
46
47
# File 'lib/legion/tty/background/scanner.rb', line 43

def scan_services
  SERVICES.each_with_object({}) do |(name, port), result|
    result[name] = { name: name.to_s, port: port, running: port_open?('127.0.0.1', port) }
  end
end

#scan_shell_historyObject



53
54
55
56
# File 'lib/legion/tty/background/scanner.rb', line 53

def scan_shell_history
  lines = read_history_lines
  tally_commands(lines).sort_by { |_, v| -v }.first(20).to_h
end