|
| 1 | +#!/usr/bin/env ruby |
| 2 | + |
| 3 | +# Checks the given file for repeated "config.xyz = " lines |
| 4 | +# |
| 5 | +# @param [String] file |
| 6 | +# |
| 7 | +# @return [Array<String>] |
| 8 | +def check_file_for_repeated_config_properties(file) |
| 9 | + # @type [Array<String>] |
| 10 | + seen = [] |
| 11 | + # @type [Array<String>] |
| 12 | + duplicates = [] |
| 13 | + in_condition = false |
| 14 | + |
| 15 | + File.readlines(file).each do |line| |
| 16 | + in_condition = true if line.strip.start_with?("if") |
| 17 | + in_condition = false if line.strip == "end" |
| 18 | + |
| 19 | + # ignore conditions for now |
| 20 | + next if in_condition |
| 21 | + |
| 22 | + line.match(/(config\.[a-zA-Z_]+) = /) do |match| |
| 23 | + duplicates << match[1] if seen.include?(match[1]) |
| 24 | + |
| 25 | + seen << match[1] |
| 26 | + end |
| 27 | + end |
| 28 | + |
| 29 | + duplicates |
| 30 | +end |
| 31 | + |
| 32 | +# Checks each environment config file for duplicate config properties, |
| 33 | +# as we should be reusing lines where possible to avoid confusion |
| 34 | +# and reduce the diff when doing Rails upgrades on applications |
| 35 | +def ensure_no_duplicate_config_lines_in_environment_files |
| 36 | + # @type [Hash<String, Array<String>>] |
| 37 | + results = {} |
| 38 | + |
| 39 | + Dir.glob("**/config/environments/*.rb").each do |file| |
| 40 | + results[file] = check_file_for_repeated_config_properties(file) |
| 41 | + end |
| 42 | + |
| 43 | + results.reject! { |_, duplicates| duplicates.empty? } |
| 44 | + |
| 45 | + results.each do |file, duplicates| |
| 46 | + puts "#{file} has duplicate config properties:" |
| 47 | + duplicates.each { |line| puts " - #{line}" } |
| 48 | + end |
| 49 | + |
| 50 | + raise "one or more environment files had duplicate configs" unless results.empty? |
| 51 | +end |
| 52 | + |
| 53 | +if __FILE__ == $PROGRAM_NAME |
| 54 | + Dir.chdir(ARGV[0]) do |
| 55 | + ensure_no_duplicate_config_lines_in_environment_files |
| 56 | + end |
| 57 | +end |
0 commit comments