ManageIQ/manageiq

View on GitHub

Showing 1,314 of 1,314 total issues

Use filter_map instead.
Open

activated_vms = duplicate_vms.map do |_by, vms|
  active_vms, inactive_vms = vms.partition(&:active)

  # There should only be one of each
  active_vm   = active_vms.first
Severity: Minor
Found in tools/reconnect_vms.rb by rubocop

Use find instead of select.first.
Open

gem_dir = Pathname.new(Bundler.locked_gems.specs.select { |g| g.name == "manageiq-api" }.first.gem_dir)
Severity: Minor
Found in tools/rest_api.rb by rubocop

This cop is used to identify usages of select.first, select.last, find_all.first, and find_all.last and change them to use detect instead.

Example:

# bad
[].select { |item| true }.first
[].select { |item| true }.last
[].find_all { |item| true }.first
[].find_all { |item| true }.last

# good
[].detect { |item| true }
[].reverse.detect { |item| true }

ActiveRecord compatibility: ActiveRecord does not implement a detect method and find has its own meaning. Correcting ActiveRecord methods with this cop should be considered unsafe.

Do not mix named captures and numbered captures in a Regexp literal.
Open

  REGEX = /
(?<model_name>(?:[[:upper:]][[:alnum:]]*(?:::[[:upper:]][[:alnum:]]*)*)?)
\.?(?<associations>([a-z_]+\.)*)
(?<namespace>\bmanaged|user_tag\b)
-(?<column>[a-z]+[_:[:alnum:]]+)
Severity: Minor
Found in lib/miq_expression/tag.rb by rubocop

Do not mix named captures and numbered captures in a Regexp literal because numbered capture is ignored if they're mixed. Replace numbered captures with non-capturing groupings or named captures.

Example:

# bad
/(?<foo>FOO)(BAR)/

# good
/(?<foo>FOO)(?<bar>BAR)/

# good
/(?<foo>FOO)(?:BAR)/

# good
/(FOO)(BAR)/</foo></bar></foo></foo>

private (on line 157) does not make singleton methods private. Use private_class_method or private inside a class << self block instead.
Open

  def self.profiles_for_user(user_id, region_id)
Severity: Minor
Found in app/models/time_profile.rb by rubocop

Checks for private or protected access modifiers which are applied to a singleton method. These access modifiers do not make singleton methods private/protected. private_class_method can be used for that.

Example:

# bad

class C
  private

  def self.method
    puts 'hi'
  end
end

Example:

# good

class C
  def self.method
    puts 'hi'
  end

  private_class_method :method
end

Example:

# good

class C
  class << self
    private

    def method
      puts 'hi'
    end
  end
end

Use filter_map instead.
Open

        initial_settings[:domain] = initial_settings[:basedn].downcase.split(",").collect do |p|
          p.split('dc=')[1]
        end.compact.join('.')

Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: '-') instead.
Open

        File.write(dest_path, ERB.new(File.read(src_path), nil, '-').result(binding))

Emulates the following Ruby warnings in Ruby 2.6.

$ cat example.rb
ERB.new('hi', nil, '-', '@output_buffer')
$ ruby -rerb example.rb
example.rb:1: warning: Passing safe_level with the 2nd argument of ERB.new is
deprecated. Do not use it, and specify other arguments as keyword arguments.
example.rb:1: warning: Passing trim_mode with the 3rd argument of ERB.new is
deprecated. Use keyword argument like ERB.new(str, trim_mode:...) instead.
example.rb:1: warning: Passing eoutvar with the 4th argument of ERB.new is
deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead.

Now non-keyword arguments other than first one are softly deprecated and will be removed when Ruby 2.5 becomes EOL. ERB.new with non-keyword arguments is deprecated since ERB 2.2.0. Use :trim_mode and :eoutvar keyword arguments to ERB.new. This cop identifies places where ERB.new(str, trim_mode, eoutvar) can be replaced by ERB.new(str, :trim_mode: trim_mode, eoutvar: eoutvar).

Example:

# Target codes supports Ruby 2.6 and higher only
# bad
ERB.new(str, nil, '-', '@output_buffer')

# good
ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer')

# Target codes supports Ruby 2.5 and lower only
# good
ERB.new(str, nil, '-', '@output_buffer')

# Target codes supports Ruby 2.6, 2.5 and lower
# bad
ERB.new(str, nil, '-', '@output_buffer')

# good
# Ruby standard library style
# https://github.com/ruby/ruby/commit/3406c5d
if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+
  ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer')
else
  ERB.new(str, nil, '-', '@output_buffer')
end

# good
# Use `RUBY_VERSION` style
if RUBY_VERSION >= '2.6'
  ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer')
else
  ERB.new(str, nil, '-', '@output_buffer')
end

Use count instead of select...count.
Open

duplicate_vms = vms_index.select { |_by, vms| vms.count == 2 && vms.select(&:active).count == 1 }
Severity: Minor
Found in tools/reconnect_vms.rb by rubocop

This cop is used to identify usages of count on an Enumerable that follow calls to select or reject. Querying logic can instead be passed to the count call.

Example:

# bad
[1, 2, 3].select { |e| e > 2 }.size
[1, 2, 3].reject { |e| e > 2 }.size
[1, 2, 3].select { |e| e > 2 }.length
[1, 2, 3].reject { |e| e > 2 }.length
[1, 2, 3].select { |e| e > 2 }.count { |e| e.odd? }
[1, 2, 3].reject { |e| e > 2 }.count { |e| e.even? }
array.select(&:value).count

# good
[1, 2, 3].count { |e| e > 2 }
[1, 2, 3].count { |e| e < 2 }
[1, 2, 3].count { |e| e > 2 && e.odd? }
[1, 2, 3].count { |e| e < 2 && e.even? }
Model.select('field AS field_one').count
Model.select(:value).count

ActiveRecord compatibility: ActiveRecord will ignore the block that is passed to count. Other methods, such as select, will convert the association to an array and then run the block on the array. A simple work around to make count work with a block is to call to_a.count {...}.

Example: Model.where(id: [1, 2, 3].select { |m| m.method == true }.size

becomes:

Model.where(id: [1, 2, 3]).to_a.count { |m| m.method == true }

Use String#include? instead of a regex match with literal-only pattern.
Open

    raise unless /already exists/.match?(e.message)
Severity: Minor
Found in lib/container_orchestrator.rb by rubocop

Avoid more than 3 levels of block nesting.
Open

          recs = recs.first if single_rec
Severity: Minor
Found in lib/extensions/ar_to_model_hash.rb by rubocop

Checks for excessive nesting of conditional and looping constructs.

You can configure if blocks are considered using the CountBlocks option. When set to false (the default) blocks are not counted towards the nesting level. Set to true to count blocks as well.

The maximum level of nesting allowed is configurable.

Wrap expressions with varying precedence with parentheses to avoid ambiguity.
Open

          "+" + "-" * (@line_len - 2) + "+" + CRLF

Looks for expressions containing multiple binary operators where precedence is ambiguous due to lack of parentheses. For example, in 1 + 2 * 3, the multiplication will happen before the addition, but lexically it appears that the addition will happen first.

The cop does not consider unary operators (ie. !a or -b) or comparison operators (ie. a =~ b) because those are not ambiguous.

NOTE: Ranges are handled by Lint/AmbiguousRange.

Example:

# bad
a + b * c
a || b && c
a ** b + c

# good (different precedence)
a + (b * c)
a || (b && c)
(a ** b) + c

# good (same precedence)
a + b + c
a * b / c % d

Use filter_map instead.
Open

    Array.wrap(vms).collect { |f| File.dirname(f) }.compact
Severity: Minor
Found in app/models/storage.rb by rubocop

Useless assignment to variable - state. Use || instead of ||=.
Open

      state ||= obj.vim_performance_states.build(:timestamp => ts).capture_and_save
Severity: Minor
Found in app/models/vim_performance_state.rb by rubocop

Checks for every useless assignment to local variable in every scope. The basic idea for this cop was from the warning of ruby -cw:

assigned but unused variable - foo

Currently this cop has advanced logic that detects unreferenced reassignments and properly handles varied cases such as branch, loop, rescue, ensure, etc.

NOTE: Given the assignment foo = 1, bar = 2, removing unused variables can lead to a syntax error, so this case is not autocorrected.

Safety:

This cop's autocorrection is unsafe because removing assignment from operator assignment can cause NameError if this assignment has been used to declare local variable. For example, replacing a ||= 1 to a || 1 may cause "undefined local variable or method `a' for main:Object (NameError)".

Example:

# bad

def some_method
  some_var = 1
  do_something
end

Example:

# good

def some_method
  some_var = 1
  do_something(some_var)
end

Avoid more than 3 levels of block nesting.
Open

              vm.save_drift_state unless vm.nil?
Severity: Minor
Found in app/models/vm_scan.rb by rubocop

Checks for excessive nesting of conditional and looping constructs.

You can configure if blocks are considered using the CountBlocks option. When set to false (the default) blocks are not counted towards the nesting level. Set to true to count blocks as well.

The maximum level of nesting allowed is configurable.

Use filter_map instead.
Open

activated_hosts = duplicate_hosts.map do |_by, hosts|
  active_hosts, inactive_hosts = hosts.partition(&:has_active_ems?)

  # There should only be one of each
  active_host   = active_hosts.first
Severity: Minor
Found in tools/reconnect_hosts.rb by rubocop

Use String#include? instead of a regex match with literal-only pattern.
Open

    raise unless /already exists/.match?(e.message)
Severity: Minor
Found in lib/container_orchestrator.rb by rubocop

Avoid immutable Array literals in loops. It is better to extract it into a local variable or a constant.
Open

            %w[id created_on updated_on description].each { |key| dd.delete(key) }

Wrap expressions with varying precedence with parentheses to avoid ambiguity.
Open

              t = filter_val + " " * (@line_len - filter_val.length - 2)

Looks for expressions containing multiple binary operators where precedence is ambiguous due to lack of parentheses. For example, in 1 + 2 * 3, the multiplication will happen before the addition, but lexically it appears that the addition will happen first.

The cop does not consider unary operators (ie. !a or -b) or comparison operators (ie. a =~ b) because those are not ambiguous.

NOTE: Ranges are handled by Lint/AmbiguousRange.

Example:

# bad
a + b * c
a || b && c
a ** b + c

# good (different precedence)
a + (b * c)
a || (b && c)
(a ** b) + c

# good (same precedence)
a + b + c
a * b / c % d

Duplicate branch body detected.
Open

               else ""

Checks that there are no repeated bodies within if/unless, case-when, case-in and rescue constructs.

With IgnoreLiteralBranches: true, branches are not registered as offenses if they return a basic literal value (string, symbol, integer, float, rational, complex, true, false, or nil), or return an array, hash, regexp or range that only contains one of the above basic literal values.

With IgnoreConstantBranches: true, branches are not registered as offenses if they return a constant value.

Example:

# bad
if foo
  do_foo
  do_something_else
elsif bar
  do_foo
  do_something_else
end

# good
if foo || bar
  do_foo
  do_something_else
end

# bad
case x
when foo
  do_foo
when bar
  do_foo
else
  do_something_else
end

# good
case x
when foo, bar
  do_foo
else
  do_something_else
end

# bad
begin
  do_something
rescue FooError
  handle_error
rescue BarError
  handle_error
end

# good
begin
  do_something
rescue FooError, BarError
  handle_error
end

Example: IgnoreLiteralBranches: true

# good
case size
when "small" then 100
when "medium" then 250
when "large" then 1000
else 250
end

Example: IgnoreConstantBranches: true

# good
case size
when "small" then SMALL_SIZE
when "medium" then MEDIUM_SIZE
when "large" then LARGE_SIZE
else MEDIUM_SIZE
end

Use String#include? instead of a regex match with literal-only pattern.
Open

    raise unless /not found/.match?(e.message)
Severity: Minor
Found in lib/container_orchestrator.rb by rubocop

Prefer using YAML.safe_load over YAML.load.
Open

        YAML.load(data)

Checks for the use of YAML class methods which have potential security issues leading to remote code execution when loading from an untrusted source.

NOTE: Ruby 3.1+ (Psych 4) uses Psych.load as Psych.safe_load by default.

Safety:

The behavior of the code might change depending on what was in the YAML payload, since YAML.safe_load is more restrictive.

Example:

# bad
YAML.load("--- !ruby/object:Foo {}") # Psych 3 is unsafe by default

# good
YAML.safe_load("--- !ruby/object:Foo {}", [Foo])                    # Ruby 2.5  (Psych 3)
YAML.safe_load("--- !ruby/object:Foo {}", permitted_classes: [Foo]) # Ruby 3.0- (Psych 3)
YAML.load("--- !ruby/object:Foo {}", permitted_classes: [Foo])      # Ruby 3.1+ (Psych 4)
YAML.dump(foo)
Severity
Category
Status
Source
Language