ManageIQ/manageiq

View on GitHub

Showing 1,314 of 1,314 total issues

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

    hdr << "@page{@bottom-center{font-size: 75%;content: '" + _("Report date: %{report_date}") % {:report_date => run_date} + "'}}"
Severity: Minor
Found in app/models/miq_report_result.rb by rubocop

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

    find_all_ems_of_type(Host).collect { |h| h if host_ids.include?(h.id) }.compact
Severity: Minor
Found in app/models/miq_request_workflow.rb by rubocop

Use filter_map instead.
Open

      result = image.customization_templates.collect do |c|
        # filter customizationtemplates
        if c.pxe_image_type.provision_type.blank? || c.pxe_image_type.provision_type == prov_typ
          @values[:customization_template_script] = c.script if c.id == customization_template_id
          build_ci_hash_struct(c, [:name, :description, :updated_at])
Severity: Minor
Found in app/models/miq_request_workflow.rb by rubocop

Redundant safe navigation detected.
Open

    elsif export_attributes["filter"]&.kind_of?(MiqExpression)

Checks for redundant safe navigation calls. instance_of?, kind_of?, is_a?, eql?, respond_to?, and equal? methods are checked by default. These are customizable with AllowedMethods option.

The AllowedMethods option specifies nil-safe methods, in other words, it is a method that is allowed to skip safe navigation. Note that the AllowedMethod option is not an option that specifies methods for which to suppress (allow) this cop's check.

In the example below, the safe navigation operator (&.) is unnecessary because NilClass has methods like respond_to? and is_a?.

Safety:

This cop is unsafe, because autocorrection can change the return type of the expression. An offending expression that previously could return nil will be autocorrected to never return nil.

Example:

# bad
do_something if attrs&.respond_to?(:[])

# good
do_something if attrs.respond_to?(:[])

# bad
while node&.is_a?(BeginNode)
  node = node.parent
end

# good
while node.is_a?(BeginNode)
  node = node.parent
end

# good - without `&.` this will always return `true`
foo&.respond_to?(:to_a)

Example: AllowedMethods: [nilsafemethod]

# bad
do_something if attrs&.nil_safe_method(:[])

# good
do_something if attrs.nil_safe_method(:[])
do_something if attrs&.not_nil_safe_method(:[])

Avoid using Marshal.load.
Open

    return Marshal.load(Base64.decode64(results.split("\n").join)) unless results.nil?
Severity: Minor
Found in app/models/miq_task.rb by rubocop

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

Example:

# bad
Marshal.load("{}")
Marshal.restore("{}")

# good
Marshal.dump("{}")

# okish - deep copy hack
Marshal.load(Marshal.dump({}))

Use filter_map instead.
Open

    options.collect do |k, v|
      if skip_keys.include?(k)
        nil
      elsif v.kind_of?(Array)
        if v.length == 2

Use count instead of find_all...length.
Open

        dups = current.uniq.find_all { |u| current.find_all { |c| c == u }.length > 1 }

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 }

Wrap complex range boundaries with parentheses to avoid ambiguity.
Open

          params[attr['dialog_param_'.size..-1]] = val

Checks for ambiguous ranges.

Ranges have quite low precedence, which leads to unexpected behavior when using a range with other operators. This cop avoids that by making ranges explicit by requiring parenthesis around complex range boundaries (anything that is not a literal: numerics, strings, symbols, etc.).

This cop can be configured with RequireParenthesesForMethodChains in order to specify whether method chains (including self.foo) should be wrapped in parens by this cop.

NOTE: Regardless of this configuration, if a method receiver is a basic literal value, it will be wrapped in order to prevent the ambiguity of 1..2.to_a.

Safety:

The cop autocorrects by wrapping the entire boundary in parentheses, which makes the outcome more explicit but is possible to not be the intention of the programmer. For this reason, this cop's autocorrect is unsafe (it will not change the behavior of the code, but will not necessarily match the intent of the program).

Example:

# bad
x || 1..2
(x || 1..2)
1..2.to_a

# good, unambiguous
1..2
'a'..'z'
:bar..:baz
MyClass::MIN..MyClass::MAX
@min..@max
a..b
-a..b

# good, ambiguity removed
x || (1..2)
(x || 1)..2
(x || 1)..(y || 2)
(1..2).to_a

Example: RequireParenthesesForMethodChains: false (default)

# good
a.foo..b.bar
(a.foo)..(b.bar)

Example: RequireParenthesesForMethodChains: true

# bad
a.foo..b.bar

# good
(a.foo)..(b.bar)

Use filter_map instead.
Open

    pxe_server.pxe_images.collect do |p|
      next if p.pxe_image_type.nil? || p.default_for_windows

      # filter pxe images by provision_type to show vm/any or host/any
      build_ci_hash_struct(p, [:name, :description]) if p.pxe_image_type.provision_type.blank? || p.pxe_image_type.provision_type == prov_typ
Severity: Minor
Found in app/models/miq_request_workflow.rb by rubocop

Use filter_map instead.
Open

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

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

      error << _(". %{details}") % {:details => fld[:required_regex_fail_details]} if fld[:required_regex_fail_details]

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

Avoid more than 3 levels of block nesting.
Open

                if j.tags.any? { |t| t.to_s.starts_with?("miq_schedules_") }
                  _log.info("Removing user schedule with Tags: #{j.tags.inspect}")
                end

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.

Do not suppress exceptions.
Open

      rescue

Checks for rescue blocks with no body.

Example:

# bad
def some_method
  do_something
rescue
end

# bad
begin
  do_something
rescue
end

# good
def some_method
  do_something
rescue
  handle_exception
end

# good
begin
  do_something
rescue
  handle_exception
end

Example: AllowComments: true (default)

# good
def some_method
  do_something
rescue
  # do nothing
end

# good
begin
  do_something
rescue
  # do nothing
end

Example: AllowComments: false

# bad
def some_method
  do_something
rescue
  # do nothing
end

# bad
begin
  do_something
rescue
  # do nothing
end

Example: AllowNil: true (default)

# good
def some_method
  do_something
rescue
  nil
end

# good
begin
  do_something
rescue
  # do nothing
end

# good
do_something rescue nil

Example: AllowNil: false

# bad
def some_method
  do_something
rescue
  nil
end

# bad
begin
  do_something
rescue
  nil
end

# bad
do_something rescue nil

self used in void context.
Open

    self

Checks for operators, variables, literals, lambda, proc and nonmutating methods used in void context.

Example: CheckForMethodsWithNoSideEffects: false (default)

# bad
def some_method
  some_num * 10
  do_something
end

def some_method(some_var)
  some_var
  do_something
end

Example: CheckForMethodsWithNoSideEffects: true

# bad
def some_method(some_array)
  some_array.sort
  do_something(some_array)
end

# good
def some_method
  do_something
  some_num * 10
end

def some_method(some_var)
  do_something
  some_var
end

def some_method(some_array)
  some_array.sort!
  do_something(some_array)
end

Variable rel used in void context.
Open

    rel

Checks for operators, variables, literals, lambda, proc and nonmutating methods used in void context.

Example: CheckForMethodsWithNoSideEffects: false (default)

# bad
def some_method
  some_num * 10
  do_something
end

def some_method(some_var)
  some_var
  do_something
end

Example: CheckForMethodsWithNoSideEffects: true

# bad
def some_method(some_array)
  some_array.sort
  do_something(some_array)
end

# good
def some_method
  do_something
  some_num * 10
end

def some_method(some_var)
  do_something
  some_var
end

def some_method(some_array)
  some_array.sort!
  do_something(some_array)
end

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

    rescue Exception => err
      _log.error(err.to_s)
      _log.log_backtrace(err, :debug)
      job.signal(:abort_retry, err.to_s, "error", true)
      nil

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

Remove redundant sort.
Open

    Dir.glob(File.join(WIDGET_DIR, "*.yaml")).sort.each { |f| sync_from_file(f) }
Severity: Minor
Found in app/models/miq_widget_set.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

Duplicate branch body detected.
Open

      elsif v.kind_of?(Hash)
        nil
      else
        format_web_service_property(k, v)

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

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

  def self.calc_md5(text)

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 == if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition.
Open

    if p = parent_cluster_or_host
Severity: Minor
Found in app/models/resource_pool.rb by rubocop

Checks for assignments in the conditions of if/while/until.

AllowSafeAssignment option for safe assignment. By safe assignment we mean putting parentheses around an assignment to indicate "I know I'm using an assignment as a condition. It's not a mistake."

Safety:

This cop's autocorrection is unsafe because it assumes that the author meant to use an assignment result as a condition.

Example:

# bad
if some_var = true
  do_something
end

# good
if some_var == true
  do_something
end

Example: AllowSafeAssignment: true (default)

# good
if (some_var = true)
  do_something
end

Example: AllowSafeAssignment: false

# bad
if (some_var = true)
  do_something
end
Severity
Category
Status
Source
Language