# frozen_string_literal: true module Meroku # This class handles command line options. class Options def initialize @options = {} end def parse(command_line_args) define_options(command_line_args).parse!(command_line_args) @options end private def define_options(_args) OptionParser.new do |opts| opts.banner = 'Usage: meroku [options]' opts.on('--help', 'Prints this help') do puts opts end add_users_options(opts) opts.separator '' add_maintainers_options(opts) end end def add_users_options(opts) option(opts, '--login EMAIL,PASSWORD', Array) do |list| @options[:login] = true @options[:email] = list[0] @options[:password] = list[1] end option(opts, '--logout') do @options[:logout] = true end end def add_maintainers_options(opts) option(opts, '--spawn MEROKU_SECRET') do |meroku_secret| @options[:spawn] = true @options[:meroku_secret] = meroku_secret end option(opts, '--despawn MEROKU_SECRET') do |meroku_secret| @options[:despawn] = true @options[:meroku_secret] = meroku_secret end end # Sets a value in the @options hash, based on the given long option and its # value, in addition to calling the block if a block is given. def option(opts, *args) long_opt_symbol = long_opt_symbol(args) args += Array(OptionsHelp::TEXT[long_opt_symbol]) opts.on(*args) do |arg| @options[long_opt_symbol] = arg yield arg if block_given? end end # Finds the option in `args` starting with -- and converts it to a symbol, # e.g. [..., '--auto-correct', ...] to :auto_correct. def long_opt_symbol(args) long_opt = args.find { |arg| arg.start_with?('--') } long_opt[2..-1].sub(/ .*/, '').tr('-', '_').gsub(/[\[\]]/, '').to_sym end end # This module contains help texts for command line options. module OptionsHelp TEXT = { version: 'Display version.', spawn: 'Spawn infrastructure' }.freeze end end