File: converters.rb

package info (click to toggle)
ruby-tty-prompt 0.23.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,452 kB
  • sloc: ruby: 8,847; makefile: 4
file content (182 lines) | stat: -rw-r--r-- 5,093 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# frozen_string_literal: true

require_relative "const"
require_relative "converter_dsl"

module TTY
  class Prompt
    module Converters
      extend ConverterDSL

      TRUE_VALUES = /^(t(rue)?|y(es)?|on|1)$/i.freeze
      FALSE_VALUES = /^(f(alse)?|n(o)?|off|0)$/i.freeze

      SINGLE_DIGIT_MATCHER = /^(?<digit>\-?\d+(\.\d+)?)$/.freeze
      DIGIT_MATCHER = /^(?<open>-?\d+(\.\d+)?)
                       \s*(?<sep>(\.\s*){2,3}|-|,)\s*
                       (?<close>-?\d+(\.\d+)?)$
                      /x.freeze
      LETTER_MATCHER = /^(?<open>\w)
                        \s*(?<sep>(\.\s*){2,3}|-|,)\s*
                        (?<close>\w)$
                       /x.freeze

      converter(:boolean, :bool) do |input|
        case input.to_s
        when TRUE_VALUES then true
        when FALSE_VALUES then false
        else Const::Undefined
        end
      end

      converter(:string, :str) do |input|
        String(input).chomp
      end

      converter(:symbol, :sym) do |input|
        input.to_sym
      end

      converter(:char) do |input|
        String(input).chars.to_a[0]
      end

      converter(:date) do |input|
        begin
          require "date" unless defined?(::Date)
          ::Date.parse(input)
        rescue ArgumentError
          Const::Undefined
        end
      end

      converter(:datetime) do |input|
        begin
          require "date" unless defined?(::Date)
          ::DateTime.parse(input.to_s)
        rescue ArgumentError
          Const::Undefined
        end
      end

      converter(:time) do |input|
        begin
          require "time"
          ::Time.parse(input.to_s)
        rescue ArgumentError
          Const::Undefined
        end
      end

      converter(:integer, :int) do |input|
        begin
          Integer(input)
        rescue ArgumentError
          Const::Undefined
        end
      end

      converter(:float) do |input|
        begin
          Float(input)
        rescue TypeError, ArgumentError
          Const::Undefined
        end
      end

      # Convert string number to integer or float
      #
      # @return [Integer,Float,Const::Undefined]
      #
      # @api private
      def cast_to_num(num)
        ([convert(:int, num), convert(:float, num)] - [Const::Undefined]).first ||
          Const::Undefined
      end
      module_function :cast_to_num

      converter(:range) do |input|
        if input.is_a?(::Range)
          input
        elsif match = input.to_s.match(SINGLE_DIGIT_MATCHER)
          digit = cast_to_num(match[:digit])
          ::Range.new(digit, digit)
        elsif match = input.to_s.match(DIGIT_MATCHER)
          open = cast_to_num(match[:open])
          close = cast_to_num(match[:close])
          ::Range.new(open, close, match[:sep].gsub(/\s*/, "") == "...")
        elsif match = input.to_s.match(LETTER_MATCHER)
          ::Range.new(match[:open], match[:close],
                      match[:sep].gsub(/\s*/, "") == "...")
        else Const::Undefined
        end
      end

      converter(:regexp) do |input|
        Regexp.new(input)
      end

      converter(:filepath, :file) do |input|
        ::File.expand_path(input)
      end

      converter(:pathname, :path) do |input|
        require "pathname" unless defined?(::Pathname)
        ::Pathname.new(input)
      end

      converter(:uri) do |input|
        require "uri" unless defined?(::URI)
        ::URI.parse(input)
      end

      converter(:list, :array) do |val|
        (val.respond_to?(:to_a) ? val : val.split(/(?<!\\),/))
          .map { |v| v.strip.gsub(/\\,/, ",") }
          .reject(&:empty?)
      end

      converter(:hash, :map) do |val|
        values = val.respond_to?(:to_a) ? val : val.split(/[& ]/)
        values.each_with_object({}) do |pair, pairs|
          key, value = pair.split(/[=:]/, 2)
          if (current = pairs[key.to_sym])
            pairs[key.to_sym] = Array(current) << value
          else
            pairs[key.to_sym] = value
          end
          pairs
        end
      end

      converter_registry.keys.each do |type|
        next if type =~ /list|array|map|hash/

        [:"#{type}_list", :"#{type}_array", :"#{type}s"].each do |new_type|
          converter(new_type) do |val|
            converter_registry[:array].(val).map do |obj|
              converter_registry[type].(obj)
            end
          end
        end

        [:"#{type}_map", :"#{type}_hash"].each do |new_type|
          converter(new_type) do |val|
            converter_registry[:hash].(val).each_with_object({}) do |(k, v), h|
              h[k] = converter_registry[type].(v)
            end
          end
        end

        [:"string_#{type}_map", :"str_#{type}_map",
         :"string_#{type}_hash", :"str_#{type}_hash"].each do |new_type|
          converter(new_type) do |val|
            converter_registry[:hash].(val).each_with_object({}) do |(k, v), h|
              h[converter_registry[:string].(k)] = converter_registry[type].(v)
            end
          end
        end
      end
    end # Converters
  end # Prompt
end # TTY