ManageIQ/manageiq

View on GitHub
app/models/miq_provision_virt_workflow.rb

Summary

Maintainability
C
1 day
Test Coverage
F
57%

Method filter_by_tags has a Cognitive Complexity of 25 (exceeds 11 allowed). Consider refactoring.
Open

  def filter_by_tags(target, options)
    opt_filters = options[:tag_filters]
    return target if opt_filters.blank?

    filters = []
Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 2 hrs to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Cyclomatic complexity for ws_template_fields is too high. [17/11]
Open

  def ws_template_fields(values, fields, ws_values)
    data = parse_ws_string(fields)
    ws_values = parse_ws_string(ws_values)
    placement_cluster_name = ws_values[:cluster]
    if placement_cluster_name.present?

Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Cyclomatic complexity for filter_by_tags is too high. [15/11]
Open

  def filter_by_tags(target, options)
    opt_filters = options[:tag_filters]
    return target if opt_filters.blank?

    filters = []

Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Cyclomatic complexity for allowed_templates is too high. [15/11]
Open

  def allowed_templates(options = {})
    # Return pre-selected VM if we are called for cloning
    if [:clone_to_vm, :clone_to_template].include?(request_type)
      vm_or_template = VmOrTemplate.find_by(:id => get_value(@values[:src_vm_id]))
      return [create_hash_struct_from_vm_or_template(vm_or_template, options)].compact

Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Method initialize has a Cognitive Complexity of 22 (exceeds 11 allowed). Consider refactoring.
Open

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

Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 2 hrs to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Cyclomatic complexity for update_custom_spec is too high. [14/11]
Open

  def update_custom_spec
    vm = get_source_vm
    return if vm.nil?

    if @customize_option.nil?

Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Cyclomatic complexity for initialize is too high. [14/11]
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 that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Cyclomatic complexity for allowed_customization_specs is too high. [12/11]
Open

  def allowed_customization_specs(_options = {})
    src = get_source_and_targets
    return [] if src.blank? || src[:ems].nil?

    customization_type = get_value(@values[:sysprep_enabled])

Checks that the cyclomatic complexity of methods is not higher than the configured maximum. The cyclomatic complexity is the number of linearly independent paths through a method. The algorithm counts decision points and adds one.

An if statement (or unless or ?:) increases the complexity by one. An else branch does not, since it doesn't add a decision point. The && operator (or keyword and) can be converted to a nested if statement, and ||/or is shorthand for a sequence of ifs, so they also add one. Loops can be said to have an exit condition, so they add one. Blocks that are calls to builtin iteration methods (e.g. `ary.map{...}) also add one, others are ignored.

def each_child_node(*types)               # count begins: 1
  unless block_given?                     # unless: +1
    return to_enum(__method__, *types)

  children.each do |child|                # each{}: +1
    next unless child.is_a?(Node)         # unless: +1

    yield child if types.empty? ||        # if: +1, ||: +1
                   types.include?(child.type)
  end

  self
end                                       # total: 6

Method ws_template_fields has a Cognitive Complexity of 19 (exceeds 11 allowed). Consider refactoring.
Open

  def ws_template_fields(values, fields, ws_values)
    data = parse_ws_string(fields)
    ws_values = parse_ws_string(ws_values)
    placement_cluster_name = ws_values[:cluster]
    if placement_cluster_name.present?
Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 1 hr to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method allowed_templates has a Cognitive Complexity of 17 (exceeds 11 allowed). Consider refactoring.
Open

  def allowed_templates(options = {})
    # Return pre-selected VM if we are called for cloning
    if [:clone_to_vm, :clone_to_template].include?(request_type)
      vm_or_template = VmOrTemplate.find_by(:id => get_value(@values[:src_vm_id]))
      return [create_hash_struct_from_vm_or_template(vm_or_template, options)].compact
Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 1 hr to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method update_custom_spec has a Cognitive Complexity of 15 (exceeds 11 allowed). Consider refactoring.
Open

  def update_custom_spec
    vm = get_source_vm
    return if vm.nil?

    if @customize_option.nil?
Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 55 mins to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Avoid parameter lists longer than 5 parameters. [7/5]
Open

  def self.from_ws_ver_1_x(version, user, template_fields, vm_fields, requester, tags, options)

Checks for methods with too many parameters.

The maximum number of parameters is configurable. Keyword arguments can optionally be excluded from the total count, as they add less complexity than positional or optional parameters.

Any number of arguments for initialize method inside a block of Struct.new and Data.define like this is always allowed:

Struct.new(:one, :two, :three, :four, :five, keyword_init: true) do
  def initialize(one:, two:, three:, four:, five:)
  end
end

This is because checking the number of arguments of the initialize method does not make sense.

NOTE: Explicit block argument &block is not counted to prevent erroneous change that is avoided by making block argument implicit.

Example: Max: 3

# good
def foo(a, b, c = 1)
end

Example: Max: 2

# bad
def foo(a, b, c = 1)
end

Example: CountKeywordArgs: true (default)

# counts keyword args towards the maximum

# bad (assuming Max is 3)
def foo(a, b, c, d: 1)
end

# good (assuming Max is 3)
def foo(a, b, c: 1)
end

Example: CountKeywordArgs: false

# don't count keyword args towards the maximum

# good (assuming Max is 3)
def foo(a, b, c, d: 1)
end

This cop also checks for the maximum number of optional parameters. This can be configured using the MaxOptionalParameters config option.

Example: MaxOptionalParameters: 3 (default)

# good
def foo(a = 1, b = 2, c = 3)
end

Example: MaxOptionalParameters: 2

# bad
def foo(a = 1, b = 2, c = 3)
end

Avoid parameter lists longer than 5 parameters. [7/5]
Open

  def self.from_ws_ver_1_0(version, user, src_name, target_name, auto_approve, tags, additional_values)

Checks for methods with too many parameters.

The maximum number of parameters is configurable. Keyword arguments can optionally be excluded from the total count, as they add less complexity than positional or optional parameters.

Any number of arguments for initialize method inside a block of Struct.new and Data.define like this is always allowed:

Struct.new(:one, :two, :three, :four, :five, keyword_init: true) do
  def initialize(one:, two:, three:, four:, five:)
  end
end

This is because checking the number of arguments of the initialize method does not make sense.

NOTE: Explicit block argument &block is not counted to prevent erroneous change that is avoided by making block argument implicit.

Example: Max: 3

# good
def foo(a, b, c = 1)
end

Example: Max: 2

# bad
def foo(a, b, c = 1)
end

Example: CountKeywordArgs: true (default)

# counts keyword args towards the maximum

# bad (assuming Max is 3)
def foo(a, b, c, d: 1)
end

# good (assuming Max is 3)
def foo(a, b, c: 1)
end

Example: CountKeywordArgs: false

# don't count keyword args towards the maximum

# good (assuming Max is 3)
def foo(a, b, c, d: 1)
end

This cop also checks for the maximum number of optional parameters. This can be configured using the MaxOptionalParameters config option.

Example: MaxOptionalParameters: 3 (default)

# good
def foo(a = 1, b = 2, c = 3)
end

Example: MaxOptionalParameters: 2

# bad
def foo(a = 1, b = 2, c = 3)
end

Method set_on_vm_id_changed has a Cognitive Complexity of 12 (exceeds 11 allowed). Consider refactoring.
Open

  def set_on_vm_id_changed
    src = get_source_and_targets
    vm, ems = load_ar_obj(src[:vm]), src[:ems]

    clear_field_values(fields_to_clear)
Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 25 mins to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Method parse_ws_hardware_fields has a Cognitive Complexity of 12 (exceeds 11 allowed). Consider refactoring.
Open

  def parse_ws_hardware_fields(hw_key, regex_filter, values, data)
    data.keys.each do |k|
      key_name = k.to_s.split('.').first
      next unless key_name =~ regex_filter

Severity: Minor
Found in app/models/miq_provision_virt_workflow.rb - About 25 mins to fix

Cognitive Complexity

Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

A method's cognitive complexity is based on a few simple rules:

  • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
  • Code is considered more complex for each "break in the linear flow of the code"
  • Code is considered more complex when "flow breaking structures are nested"

Further reading

Use filter_map instead.
Open

      spec_hash[:wins_servers] = [adapter['primaryWINS'], adapter['secondaryWINS']].collect { |s| s.presence }.compact.join(', ')

Use filter_map instead.
Open

      @values[:src_vm_lans] = vm.lans.collect(&:name).compact

Use result["fields"] = "Specification"; result["file"] = "Sysprep Answer File" instead of result.merge!("fields" => "Specification", "file" => "Sysprep Answer File").
Open

    when 'windows' then result.merge!("fields" => "Specification", "file" => "Sysprep Answer File")

This cop identifies places where Hash#merge! can be replaced by Hash#[]=.

Example:

hash.merge!(a: 1)
hash.merge!({'key' => 'value'})
hash.merge!(a: 1, b: 2)

Use filter_map instead.
Open

      @values[:src_vm_nics] = vm.hardware && vm.hardware.nics.collect(&:device_name).compact

Use filter_map instead.
Open

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

Similar blocks of code found in 2 locations. Consider refactoring.
Open

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

Severity: Major
Found in app/models/miq_provision_virt_workflow.rb and 1 other location - About 3 hrs to fix
app/models/miq_provision_orch_workflow.rb on lines 2..38

Duplicated Code

Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

Tuning

This issue has a mass of 119.

We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

Refactorings

Further Reading

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

Avoid (in)equality comparisons of floats as they are unreliable.
Open

    return from_ws_ver_1_0(*args) if version == 1.0

Checks for the presence of precise comparison of floating point numbers.

Floating point values are inherently inaccurate, and comparing them for exact equality is almost never the desired semantics. Comparison via the ==/!= operators checks floating-point value representation to be exactly the same, which is very unlikely if you perform any arithmetic operations involving precision loss.

Example:

# bad
x == 0.1
x != 0.1

# good - using BigDecimal
x.to_d == 0.1.to_d

# good
(x - 0.1).abs < Float::EPSILON

# good
tolerance = 0.0001
(x - 0.1).abs < tolerance

# Or some other epsilon based type of comparison:
# https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/

There are no issues that match your filters.

Category
Status