theforeman/foreman_maintain

View on GitHub
bin/foreman-maintain-complete

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
require 'English'
project_root = File.expand_path('..', __dir__)
$LOAD_PATH.unshift(File.join(project_root, 'lib'))
CONFIG_FILE = '/etc/foreman-maintain/foreman_maintain.yml'.freeze
system('which foreman_maintain > /dev/null 2>&1')
found = $CHILD_STATUS.success?
FOREMAN_MAINTAIN = found ? 'foreman-maintain' : File.join(project_root, 'bin/foreman-maintain')

require 'yaml'
require 'foreman_maintain/utils/bash'

# rubocop:disable Lint/SuppressedException
def cache_file(config_file)
  config = YAML.load(File.open(config_file))
  config.fetch(:completion_cache_file,
    "#{ENV['HOME'] || '/root'}/.cache/foreman_maintain_completion.yml")
rescue StandardError
end
# rubocop:enable Lint/SuppressedException

config_file = if File.exist?(CONFIG_FILE)
                CONFIG_FILE
              else
                File.join(project_root, 'config/foreman_maintain.yml')
              end
completion_cache_file = cache_file(config_file)
completion_cache_file = File.expand_path(completion_cache_file)

# build the cache if it does not exist
`#{FOREMAN_MAINTAIN} advanced prebuild-bash-completion` unless File.exist?(completion_cache_file)

dict = ForemanMaintain::Utils::Bash::Completion.load_description(completion_cache_file)

# regenerate and reload cache if it expired
sha1sum = `sha1sum #{dict[:expire][:file]}`
if sha1sum.strip != dict[:expire][:sha1sum].strip
  `#{FOREMAN_MAINTAIN} advanced prebuild-bash-completion`
  dict = ForemanMaintain::Utils::Bash::Completion.load_description(completion_cache_file)
end

comp_line = ENV['COMP_LINE'] || ''
comp_args = comp_line.split(' ', 2).last || ''

result = ForemanMaintain::Utils::Bash::Completion.new(dict).complete(comp_args)

puts result.join("\n")