Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/rubocop/cop/layout/module_description_indentation.rb
Views: 11784
module RuboCop1module Cop2module Layout3class ModuleDescriptionIndentation < Base4extend AutoCorrector5include Alignment67MSG = "Module descriptions should be properly aligned to the 'Description' key, and within %q{ ... }"89def_node_matcher :find_update_info_node, <<~PATTERN10(def :initialize _args (begin (super $(send nil? {:update_info :merge_info} (lvar :info) (hash ...))) ...))11PATTERN1213def_node_matcher :find_nested_update_info_node, <<~PATTERN14(def :initialize _args (super $(send nil? {:update_info :merge_info} (lvar :info) (hash ...)) ...))15PATTERN1617def on_def(node)18update_info_node = find_update_info_node(node) || find_nested_update_info_node(node)19return if update_info_node.nil?2021hash = update_info_node.arguments.find { |argument| hash_arg?(argument) }22hash.each_pair do |key, value|23if key.value == "Description"24if requires_correction?(key, value)25add_offense(value.location.end, &autocorrector(value))26end27end28end29end3031private3233def autocorrector(description_value)34lambda do |corrector|35description_key = description_value.parent.key36new_content = indent_description_value_correctly(description_key, description_value)3738corrector.replace(description_value.source_range, new_content)39end40end4142def requires_correction?(description_key, description_value)43return false if description_value.single_line?4445current_content = description_value.source46expected_content = indent_description_value_correctly(description_key, description_value)47expected_content != current_content48end4950def indent_description_value_correctly(description_key, description_value)51content_whitespace = indentation(description_key)52final_line_whitespace = offset(description_key)5354description_lines = node_content(description_value).strip.lines55indented_description = description_lines.map do |line|56cleaned_content = line.strip57if cleaned_content.empty?58"\n"59else60"#{content_whitespace}#{cleaned_content}\n"61end62end.join6364new_literal = "%q{\n"65new_literal <<= indented_description66new_literal <<= final_line_whitespace67new_literal <<= '}'6869new_literal70end7172def node_content(node)73if node.str_type?74node.value75elsif node.dstr_type?76node.children.map(&:value).join77else78raise "Module description should be a string, instead found '#{node.type}'"79end80end8182def hash_arg?(node)83node.type == :hash84end85end86end87end88end899091