class RuboCop::Cop::Style::IdenticalConditionalBranches

end
do_z
do_x
else
# nothing
when 2
do_y
do_x
when 1
case foo
# good
end
do_x
else
do_x
when 2
do_x
when 1
case foo
# bad
end
do_y
else
do_x
if condition
do_z
# good
end
do_y
do_z
else
do_x
do_z
if condition
# bad
do_z
end
do_y
else
do_x
if condition
# good
end
do_z
do_y
else
do_z
do_x
if condition
# bad
@example
each branch of a conditional statement.
This cop checks for identical lines at the beginning or end of

def check_branches(branches)

def check_branches(branches)
  # return if any branch is empty. An empty branch can be an `if`
  # without an `else` or a branch that contains only comments.
  return if branches.any?(&:nil?)
  tails = branches.map { |branch| tail(branch) }
  check_expressions(tails) if tails.none?(&:nil?)
  heads = branches.map { |branch| head(branch) }
  check_expressions(heads) if tails.none?(&:nil?)
end

def check_expressions(expressions)

def check_expressions(expressions)
  return unless expressions.size > 1 && expressions.uniq.one?
  expressions.each do |expression|
    add_offense(expression)
  end
end

def expand_elses(branch)

need to recursively iterate over all `else` branches.
`elsif` branches show up in the if node as nested `else` branches. We
def expand_elses(branch)
  if branch.nil?
    [nil]
  elsif branch.if_type?
    _condition, elsif_branch, else_branch = *branch
    expand_elses(else_branch).unshift(elsif_branch)
  else
    [branch]
  end
end

def head(node)

def head(node)
  node.begin_type? ? node.children.first : node
end

def message(node)

def message(node)
  format(MSG, source: node.source)
end

def on_case(node)

def on_case(node)
  return unless node.else? && node.else_branch
  branches = node.when_branches.map(&:body).push(node.else_branch)
  check_branches(branches)
end

def on_if(node)

def on_if(node)
  return if node.elsif?
  branches = expand_elses(node.else_branch).unshift(node.if_branch)
  check_branches(branches)
end

def tail(node)

def tail(node)
  node.begin_type? ? node.children.last : node
end