File: definition.rb

package info (click to toggle)
ruby-clamp 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 364 kB
  • sloc: ruby: 2,851; makefile: 4
file content (62 lines) | stat: -rw-r--r-- 1,447 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# frozen_string_literal: true

require "clamp/attribute/definition"

module Clamp
  module Parameter

    # Represents an parameter of a Clamp::Command class.
    #
    class Definition < Attribute::Definition

      def initialize(name, description, options = {})
        @name = name
        @description = description
        super(options)
        @multivalued = (@name =~ ELLIPSIS_SUFFIX)
        @required = options.fetch(:required) do
          (@name !~ OPTIONAL)
        end
        @inheritable = options.fetch(:inheritable, true)
      end

      attr_reader :name

      def inheritable?
        @inheritable
      end

      def help_lhs
        name
      end

      def consume(arguments)
        raise ArgumentError, Clamp.message(:no_value_provided) if required? && arguments.empty?

        arguments.shift(multivalued? ? arguments.length : 1)
      end

      ELLIPSIS_SUFFIX = / \.\.\.$/.freeze
      OPTIONAL = /^\[(.*)\]/.freeze

      VALID_ATTRIBUTE_NAME = /^[a-z0-9_]+$/.freeze

      private

      def infer_attribute_name
        inferred_name = name.downcase.tr("-", "_").sub(ELLIPSIS_SUFFIX, "").sub(OPTIONAL) { Regexp.last_match(1) }

        raise "cannot infer attribute_name from #{name.inspect}" unless inferred_name.match? VALID_ATTRIBUTE_NAME

        inferred_name += "_list" if multivalued?
        inferred_name
      end

      def required_indicator
        # implied by LHS
      end

    end

  end
end