2023-12-19 23:35:16 +00:00
|
|
|
# typed: true
|
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module RuboCop
|
|
|
|
module Cop
|
|
|
|
module Cask
|
|
|
|
class ArrayAlphabetization < Base
|
|
|
|
extend AutoCorrector
|
|
|
|
|
|
|
|
def on_send(node)
|
2024-01-02 23:31:13 +00:00
|
|
|
return unless [:zap, :uninstall].include?(name = node.method_name)
|
2023-12-19 23:35:16 +00:00
|
|
|
|
|
|
|
node.each_descendant(:pair).each do |pair|
|
2024-01-14 20:55:22 +00:00
|
|
|
symbols = pair.children.select(&:sym_type?).map(&:value)
|
2024-01-02 23:31:13 +00:00
|
|
|
# For `zap`s, we only care about `trash` arrays.
|
|
|
|
next if name == :zap && !symbols.include?(:trash)
|
|
|
|
# Don't order `uninstall` arrays that contain commands.
|
2024-01-14 20:55:51 +00:00
|
|
|
next if name == :uninstall && (symbols & [:signal, :script, :early_script, :args, :input]).any?
|
2023-12-22 00:41:56 +00:00
|
|
|
|
2023-12-19 23:35:16 +00:00
|
|
|
pair.each_descendant(:array).each do |array|
|
|
|
|
if array.children.length == 1
|
2024-01-02 23:31:13 +00:00
|
|
|
add_offense(array, message: "Avoid single-element arrays by removing the []") do |corrector|
|
2023-12-19 23:35:16 +00:00
|
|
|
corrector.replace(array.source_range, array.children.first.source)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-12-22 00:22:33 +00:00
|
|
|
next if array.children.length <= 1
|
|
|
|
|
2024-01-18 12:53:23 +00:00
|
|
|
comments = find_inline_comments(array.source)
|
|
|
|
array_with_comments = array.children.dup
|
|
|
|
array.children.map(&:source).each_with_index do |child, index|
|
|
|
|
comment = comments.find { |c| c.include?(child) }
|
|
|
|
next unless comment
|
|
|
|
|
|
|
|
p comment.strip
|
|
|
|
# Add the comment to the main array.
|
|
|
|
array_with_comments[index] = comment.strip
|
|
|
|
end
|
|
|
|
|
|
|
|
sorted_array = array_with_comments.sort_by { |child| child.to_s.downcase }
|
|
|
|
next if sorted_array == array_with_comments
|
2023-12-19 23:35:16 +00:00
|
|
|
|
2024-01-02 23:31:13 +00:00
|
|
|
add_offense(array, message: "The array elements should be ordered alphabetically") do |corrector|
|
2023-12-22 00:22:33 +00:00
|
|
|
array.children.each_with_index do |child, index|
|
2024-01-18 12:53:23 +00:00
|
|
|
p sorted_array[index]
|
|
|
|
corrector.replace(child.source_range, sorted_array[index])
|
2023-12-19 23:35:16 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2024-01-18 12:53:23 +00:00
|
|
|
|
|
|
|
def find_inline_comments(source)
|
|
|
|
comments = []
|
|
|
|
source.each_line do |line|
|
|
|
|
# Comments are naively detected by looking for lines that include a `#` surrounded by spaces.
|
|
|
|
comments << line if line.include?(" # ")
|
|
|
|
end
|
|
|
|
|
|
|
|
# Remove lines that are only comments, we don't want to move those.
|
|
|
|
comments.reject { |comment| comment.strip.start_with?("# ") }
|
|
|
|
end
|
2023-12-19 23:35:16 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|