Module: Lemans::Config::Conversion

Included in:
Lemans::Clobber, Agent, Environment, Verifier
Defined in:
lib/lemans/config/conversion.rb

Overview

Helper methods to parse/convert config-provided values

Constant Summary collapse

DURATION =
/\A(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?\z/
DURATION_FACTORS =
{ "ms" => 0.001, "s" => 1, "m" => 60, "h" => 3600, "d" => 86_400 }.freeze
SIZE =
/\A(\d+(?:\.\d+)?)\s*(MB|GB|TB)?\z/i
SIZE_FACTORS =
{ "mb" => 1, "gb" => 1024, "tb" => 1024 * 1024 }.freeze

Instance Method Summary collapse

Instance Method Details

#absolute_path!(value) ⇒ Object

Raises:



55
56
57
58
59
# File 'lib/lemans/config/conversion.rb', line 55

def absolute_path!(value)
  raise ConfigError, "#{value.inspect} is not an absolute path" unless value.start_with?("/")

  value
end

#float!(value) ⇒ Object



21
22
23
24
25
# File 'lib/lemans/config/conversion.rb', line 21

def float!(value)
  Float(value)
rescue ArgumentError, TypeError
  raise ConfigError, "cannot read #{value.inspect} as a number"
end

#integer!(value) ⇒ Object



15
16
17
18
19
# File 'lib/lemans/config/conversion.rb', line 15

def integer!(value)
  Integer(value)
rescue ArgumentError, TypeError
  raise ConfigError, "cannot read #{value.inspect} as an integer"
end

#megabytes!(value) ⇒ Object

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lemans/config/conversion.rb', line 41

def megabytes!(value)
  if value.is_a?(Numeric)
    raise ConfigError, "size must be non-negative, got: #{value}" if value.negative?

    return value.round
  end

  match = SIZE.match(value.to_s.strip)

  raise ConfigError, "cannot read #{value.inspect} as a size (try 2GB, 512MB)" unless match

  (match[1].to_f * SIZE_FACTORS.fetch((match[2] || "mb").downcase)).round
end

#seconds!(value) ⇒ Object

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lemans/config/conversion.rb', line 27

def seconds!(value)
  if value.is_a?(Numeric)
    raise ConfigError, "duration must be non-negative, got: #{value}" if value.negative?

    return value
  end

  match = DURATION.match(value.to_s.strip)

  raise ConfigError, "cannot read #{value.inspect} as a duration (try 30m, 300s, 1h)" unless match

  match[1].to_f * DURATION_FACTORS.fetch(match[2] || "s")
end