|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module RuboCop |
| 4 | + module Rails |
| 5 | + # This module allows cops to detect and ignore files that have already been migrated |
| 6 | + # by leveraging the `AllCops: MigratedSchemaVersion` configuration. |
| 7 | + # |
| 8 | + # [source,yaml] |
| 9 | + # ----- |
| 10 | + # AllCops: |
| 11 | + # MigratedSchemaVersion: '20241225000000' |
| 12 | + # ----- |
| 13 | + # |
| 14 | + # When applied to cops, it dynamically overrides the `on_*` methods for all supported |
| 15 | + # node types, ensuring that cops skip processing if the file is determined to be a |
| 16 | + # migrated file based on the schema version. |
| 17 | + # |
| 18 | + # @api private |
| 19 | + module MigrationFileSkippable |
| 20 | + Parser::Meta::NODE_TYPES.each do |node_type| |
| 21 | + method_name = :"on_#{node_type}" |
| 22 | + |
| 23 | + class_eval(<<~RUBY, __FILE__, __LINE__ + 1) |
| 24 | + def #{method_name}(node, *args) # def on_if(node, *args) |
| 25 | + return if already_migrated_file? # return if already_migrated_file? |
| 26 | + # |
| 27 | + super if method(__method__).super_method # super if method(__method__).super_method |
| 28 | + rescue NameError # rescue NameError |
| 29 | + # noop # # noop |
| 30 | + end # end |
| 31 | + RUBY |
| 32 | + end |
| 33 | + |
| 34 | + def self.apply_to_cops! |
| 35 | + RuboCop::Cop::Registry.all.each { |cop| cop.prepend(MigrationFileSkippable) } |
| 36 | + end |
| 37 | + |
| 38 | + private |
| 39 | + |
| 40 | + def already_migrated_file? |
| 41 | + return false unless migrated_schema_version |
| 42 | + |
| 43 | + match_data = File.basename(processed_source.file_path).match(/(?<timestamp>\d{14})/) |
| 44 | + schema_version = match_data['timestamp'] if match_data |
| 45 | + |
| 46 | + return false unless schema_version |
| 47 | + |
| 48 | + schema_version <= migrated_schema_version.to_s # Ignore applied migration files. |
| 49 | + end |
| 50 | + |
| 51 | + def migrated_schema_version |
| 52 | + config.for_all_cops.fetch('MigratedSchemaVersion', nil) |
| 53 | + end |
| 54 | + end |
| 55 | + end |
| 56 | +end |
0 commit comments