ManageIQ/manageiq

View on GitHub

Showing 1,314 of 1,314 total issues

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

      next if %w[name value].include?(cname)
Severity: Minor
Found in app/models/miq_ae_value.rb by rubocop

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

      key.data.except!(*(%w[id] + hidden_columns))

Remove redundant sort.
Open

        %w[reports compare].flat_map { |dir| Dir.glob(plugin.root.join("content", dir, "**", "*.yaml")).sort }
Severity: Minor
Found in app/models/miq_report/seeding.rb by rubocop

Sort globbed results by default in Ruby 3.0. This cop checks for redundant sort method to Dir.glob and Dir[].

Safety:

This cop is unsafe, in case of having a file and a directory with identical names, since directory will be loaded before the file, which will break exe/files.rb that rely on exe.rb file.

Example:

# bad
Dir.glob('./lib/**/*.rb').sort.each do |file|
end

Dir['./lib/**/*.rb'].sort.each do |file|
end

# good
Dir.glob('./lib/**/*.rb').each do |file|
end

Dir['./lib/**/*.rb'].each do |file|
end

Use filter_map instead.
Open

    klass_array.collect do |klass|
      cls = find_by(:id => klass.id)
      next if cls.nil?

      cls.ae_instances.sort_by(&:fqname).collect do |inst|
Severity: Minor
Found in app/models/miq_ae_class.rb by rubocop

Use filter_map instead.
Open

    verified_tags = tags.collect { |t| t if header.include?(t) }.compact
Severity: Minor
Found in app/models/miq_bulk_import.rb by rubocop

Prefer using YAML.safe_load over YAML.load.
Open

        eventData = YAML.load(row.attributes["event_data"])
Severity: Minor
Found in app/models/miq_event_definition.rb by rubocop

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)

Use filter_map instead.
Open

    dc_path = ous.keys.first.split(',').collect { |i| i.split("DC=")[1] }.compact.join(".")

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

      if col !~ /managed\./ && col !~ /virtual_custom/
Severity: Minor
Found in app/models/miq_report/generator.rb by rubocop

Remove redundant sort.
Open

      [REPORT_DIR, COMPARE_DIR].flat_map { |dir| Dir.glob(dir.join("**", "*.yaml")).sort }
Severity: Minor
Found in app/models/miq_report/seeding.rb by rubocop

Sort globbed results by default in Ruby 3.0. This cop checks for redundant sort method to Dir.glob and Dir[].

Safety:

This cop is unsafe, in case of having a file and a directory with identical names, since directory will be loaded before the file, which will break exe/files.rb that rely on exe.rb file.

Example:

# bad
Dir.glob('./lib/**/*.rb').sort.each do |file|
end

Dir['./lib/**/*.rb'].sort.each do |file|
end

# good
Dir.glob('./lib/**/*.rb').each do |file|
end

Dir['./lib/**/*.rb'].each do |file|
end

Call super to initialize state of the parent class.
Open

  def initialize(values, requester, options = {})
    initial_pass = values.blank?
    initial_pass = true if options[:initial_pass] == true
    instance_var_init(values, requester, options)

Checks for the presence of constructors and lifecycle callbacks without calls to super.

This cop does not consider method_missing (and respond_to_missing?) because in some cases it makes sense to overtake what is considered a missing method. In other cases, the theoretical ideal handling could be challenging or verbose for no actual gain.

Autocorrection is not supported because the position of super cannot be determined automatically.

Object and BasicObject are allowed by this cop because of their stateless nature. However, sometimes you might want to allow other parent classes from this cop, for example in the case of an abstract class that is not meant to be called with super. In those cases, you can use the AllowedParentClasses option to specify which classes should be allowed in addition to Object and BasicObject.

Example:

# bad
class Employee < Person
  def initialize(name, salary)
    @salary = salary
  end
end

# good
class Employee < Person
  def initialize(name, salary)
    super(name)
    @salary = salary
  end
end

# bad
Employee = Class.new(Person) do
  def initialize(name, salary)
    @salary = salary
  end
end

# good
Employee = Class.new(Person) do
  def initialize(name, salary)
    super(name)
    @salary = salary
  end
end

# bad
class Parent
  def self.inherited(base)
    do_something
  end
end

# good
class Parent
  def self.inherited(base)
    super
    do_something
  end
end

# good
class ClassWithNoParent
  def initialize
    do_something
  end
end

Example: AllowedParentClasses: [MyAbstractClass]

# good
class MyConcreteClass < MyAbstractClass
  def initialize
    do_something
  end
end

Use StandardError over Exception.
Open

      raise Exception, _("Region [%{region_id}] does not match the database's region [%{db_id}]") % {:region_id => my_region_id, :db_id => db_region_id}
Severity: Minor
Found in app/models/miq_region.rb by rubocop

Checks for raise or fail statements which are raising Exception class.

You can specify a module name that will be an implicit namespace using AllowedImplicitNamespaces option. The cop cause a false positive for namespaced Exception when a namespace is omitted. This option can prevent the false positive by specifying a namespace to be omitted for Exception. Alternatively, make Exception a fully qualified class name with an explicit namespace.

Safety:

This cop is unsafe because it will change the exception class being raised, which is a change in behavior.

Example:

# bad
raise Exception, 'Error message here'

# good
raise StandardError, 'Error message here'

Example: AllowedImplicitNamespaces: ['Gem']

# good
module Gem
  def self.foo
    raise Exception # This exception means `Gem::Exception`.
  end
end

Duplicate branch body detected.
Open

      when :max_derived_memory_reserved
        attributes = [:max_derived_memory_used, :derived_memory_used]

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 filter_map instead.
Open

    datacenters = sources.collect do |h|
      rails_logger("host_to_folder for host #{h.name}", 0)
      result = find_datacenter_for_ci(h)
      rails_logger("host_to_folder for host #{h.name}", 1)
      result
Severity: Minor
Found in app/models/miq_request_workflow.rb by rubocop

Use filter_map instead.
Open

    pxe_server.windows_images.collect do |p|
      build_ci_hash_struct(p, [:name, :description])
    end.compact
Severity: Minor
Found in app/models/miq_request_workflow.rb by rubocop

Avoid rescuing the Exception class. Perhaps you meant to rescue StandardError?
Open

    rescue Exception => err
      _log.error("#{err.message}, during reconnect!")
Severity: Minor
Found in app/models/miq_server.rb by rubocop

Checks for rescue blocks targeting the Exception class.

Example:

# bad

begin
  do_something
rescue Exception
  handle_exception
end

Example:

# good

begin
  do_something
rescue ArgumentError
  handle_exception
end

Do not shadow rescued Exceptions.
Open

    rescue StandardError, Timeout::Error => err
      _log.error("#{log_prefix} Posting of #{log_type.downcase} logs failed for #{who_am_i} due to error: [#{err.class.name}] [#{err}]")
      task.update_status("Finished", "Error", "Posting of #{log_type.downcase} logs failed for #{who_am_i} due to error: [#{err.class.name}] [#{err}]")
      logfile.update(:state => "error")
      raise

Checks for a rescued exception that get shadowed by a less specific exception being rescued before a more specific exception is rescued.

An exception is considered shadowed if it is rescued after its ancestor is, or if it and its ancestor are both rescued in the same rescue statement. In both cases, the more specific rescue is unnecessary because it is covered by rescuing the less specific exception. (ie. rescue Exception, StandardError has the same behavior whether StandardError is included or not, because all StandardErrors are rescued by rescue Exception).

Example:

# bad

begin
  something
rescue Exception
  handle_exception
rescue StandardError
  handle_standard_error
end

# bad
begin
  something
rescue Exception, StandardError
  handle_error
end

# good

begin
  something
rescue StandardError
  handle_standard_error
rescue Exception
  handle_exception
end

# good, however depending on runtime environment.
#
# This is a special case for system call errors.
# System dependent error code depends on runtime environment.
# For example, whether `Errno::EAGAIN` and `Errno::EWOULDBLOCK` are
# the same error code or different error code depends on environment.
# This good case is for `Errno::EAGAIN` and `Errno::EWOULDBLOCK` with
# the same error code.
begin
  something
rescue Errno::EAGAIN, Errno::EWOULDBLOCK
  handle_standard_error
end

Shadowing outer local variable - w.
Open

      w = workers.sort_by { |w| [w.memory_usage || -1, w.id] }.last

Checks for the use of local variable names from an outer scope in block arguments or block-local variables. This mirrors the warning given by ruby -cw prior to Ruby 2.6: "shadowing outer local variable - foo".

NOTE: Shadowing of variables in block passed to Ractor.new is allowed because Ractor should not access outer variables. eg. following style is encouraged:

```ruby
worker_id, pipe = env
Ractor.new(worker_id, pipe) do |worker_id, pipe|
end
```

Example:

# bad

def some_method
  foo = 1

  2.times do |foo| # shadowing outer `foo`
    do_something(foo)
  end
end

Example:

# good

def some_method
  foo = 1

  2.times do |bar|
    do_something(bar)
  end
end

Avoid rescuing the Exception class. Perhaps you meant to rescue StandardError?
Open

    rescue Exception => e
      safe_log("Error in releasing database connection: #{e.message}", :error)
Severity: Minor
Found in app/models/miq_worker/runner.rb by rubocop

Checks for rescue blocks targeting the Exception class.

Example:

# bad

begin
  do_something
rescue Exception
  handle_exception
end

Example:

# good

begin
  do_something
rescue ArgumentError
  handle_exception
end

Avoid rescuing the Exception class. Perhaps you meant to rescue StandardError?
Open

      rescue Exception => err
        do_exit("An error has occurred during work processing: #{err}\n#{err.backtrace.join("\n")}", 1)
Severity: Minor
Found in app/models/miq_worker/runner.rb by rubocop

Checks for rescue blocks targeting the Exception class.

Example:

# bad

begin
  do_something
rescue Exception
  handle_exception
end

Example:

# good

begin
  do_something
rescue ArgumentError
  handle_exception
end

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

    return unless options.keys.any? { |key| [:date, :warn].include?(key) }
Severity
Category
Status
Source
Language