module UltraCommandLine module Commands class OptionDefinition DEFAULT_SUMMARY = 'Option summary not provided.'.freeze attr_reader :name, :type attr_reader :short_aliases, :long_aliases attr_accessor :summary, :default, :description, :help, :dependencies, :incompatibilities, :sub_command def initialize(name, type, options = {}) @name = name @type = type @summary = options.fetch(:summary, DEFAULT_SUMMARY) @default = options.fetch(:default, nil) @description = options.fetch(:description, summary) @help = options.fetch(:help, description) @global = options.fetch(:global, false) @dependencies = options.fetch(:dependencies, []) self.dependencies = dependencies.is_a?(Array) ? dependencies : [dependencies] @incompatibilities = options.fetch(:incompatibilities, []) self.incompatibilities = incompatibilities.is_a?(Array) ? incompatibilities : [incompatibilities] short_aliases = options.fetch(:short_aliases, []) long_aliases = options.fetch(:long_aliases, []) self.short_aliases = (short_aliases.is_a?(Array) ? short_aliases : [short_aliases]).map &:to_sym self.long_aliases = (long_aliases.is_a?(Array) ? long_aliases : [long_aliases]).map &:to_sym end def short_aliases=(options) options.each do |option| raise UltraCommandLine::Error, "Invalid short option defined for slop option '#{option}' !" unless option.to_s.size == 1 end @short_aliases = options end def long_aliases=(options) if options.include? name raise UltraCommandLine::Error, "Inconsistent long options for slop option '#{name}' already defined as main option !" end @long_aliases = options # long_aliases.unshift name end def global? @global end def to_slop_options(slop_options = UltraCommandLine.new_slop_options) one_letter_options = short_aliases.map.each { |option| "-#{option}" } word_options = long_aliases.map.each { |option| "--#{option}" } # The main option as last entry before description option_def = word_options.concat(one_letter_options) << "--#{name}" << summary option_def_options = default.nil? ? {} : { default: default } slop_options.send type, *option_def, **option_def_options slop_options.banner = nil slop_options rescue NoMethodError => e raise UltraCommandLine::Error, "Invalid option type '#{e.name}' for option '#{name}' !" end def help_line(slop_options = UltraCommandLine.new_slop_options) to_slop_options(slop_options).to_s.gsub /\n/, '' end end end end