Class: RuboCop::Cop::Lint::FluentdPluginConfigParamDefaultTime

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
IgnoredNode
Defined in:
lib/rubocop/cop/lint/plugin_config_param_time.rb

Overview

Examples:

FluentdPluginConfigParamDefaultTime (default)


# bad
config_param :interval, :time, :default => '1h'

# good
config_param :interval, :time, :default => 3600

See https://github.com/fluent/fluent-plugin-opensearch/pull/159

Constant Summary collapse

RESTRICT_ON_SEND =
i[config_param].freeze

Instance Method Summary collapse

Instance Method Details

#config_param_default(node) ⇒ Object



49
50
51
52
53
# File 'lib/rubocop/cop/lint/plugin_config_param_time.rb', line 49

def config_param_default(node)
  pair = node.children[4].children.first
  str = pair.children.last
  str.value
end

#config_param_default_time?(node) ⇒ Object



24
25
26
# File 'lib/rubocop/cop/lint/plugin_config_param_time.rb', line 24

def_node_matcher :config_param_default_string_time?, "(send nil? :config_param (sym _) (sym :time) (hash (pair (sym :default) (str _))))\n"

#config_param_variable(node) ⇒ Object



44
45
46
47
# File 'lib/rubocop/cop/lint/plugin_config_param_time.rb', line 44

def config_param_variable(node)
  symbol = node.children[2]
  symbol.value
end

#on_send(node) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rubocop/cop/lint/plugin_config_param_time.rb', line 28

def on_send(node)
  return unless config_param_default_string_time?(node)

  parameter = config_param_variable(node)
  default = config_param_default(node)
  message = "The value of :#{parameter} must be `integer` or `float` for default time value."

  expression = config_param_default_string_time?(node)
  add_offense(node, message: message) do |corrector|
    seconds = timestr_to_seconds(default)
    source_code = "config_param :#{parameter}, :time, :default => #{seconds}"
    corrector.replace(node, source_code)
  end
  ignore_node(node)
end

#timestr_to_seconds(literal) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rubocop/cop/lint/plugin_config_param_time.rb', line 55

def timestr_to_seconds(literal)
  value = if literal.end_with?("d")
            literal.delete("d").to_i * 60 * 60 * 24
          elsif literal.end_with?("h")
            literal.delete("h").to_i * 60 * 60
          elsif literal.end_with?("m")
            literal.delete("m").to_i * 60
          elsif literal.end_with?("s")
            literal.delete("s").to_i
          else
            literal.to_i
          end
  value
end