The personal finance app for everyone (by everyone)
Ruby
Keep the provider lists sorted with a custom cop (#4459)
Yong Cong Sin7919230ab02f
diff --git a/.rubocop.yml b/.rubocop.ymlindex d313b5ab51..0720c322c9 100644--- a/.rubocop.yml+++ b/.rubocop.yml@@ -1,6 +1,12 @@inherit_gem:rubocop-rails-omakase: rubocop.yml+require:+ - ./lib/rubocop/cop/sure/sorted_list++Sure/SortedList:+ Enabled: true+Layout/IndentationWidth:Enabled: truediff --git a/app/models/data_enrichment.rb b/app/models/data_enrichment.rbindex 45fbb12dbe..032729bc92 100644--- a/app/models/data_enrichment.rb+++ b/app/models/data_enrichment.rb@@ -1,28 +1,29 @@class DataEnrichment < ApplicationRecordbelongs_to :enrichable, polymorphic: true+ # sortedenum :source, {- rule: "rule",- plaid: "plaid",- simplefin: "simplefin",- lunchflow: "lunchflow",- akahu: "akahu",- up: "up",- monobank: "monobank",- synth: "synth",ai: "ai",- enable_banking: "enable_banking",- coinstats: "coinstats",- mercury: "mercury",+ akahu: "akahu",+ bayes: "bayes",brex: "brex",- indexa_capital: "indexa_capital",- sophtron: "sophtron",+ coinstats: "coinstats",+ enable_banking: "enable_banking",+ fio: "fio",ibkr: "ibkr",+ indexa_capital: "indexa_capital",+ lunchflow: "lunchflow",+ mercury: "mercury",+ monobank: "monobank",+ plaid: "plaid",questrade: "questrade",redbark: "redbark",- trade_republic: "trade_republic",- bayes: "bayes",+ rule: "rule",similar: "similar",- fio: "fio"+ simplefin: "simplefin",+ sophtron: "sophtron",+ synth: "synth",+ trade_republic: "trade_republic",+ up: "up"}enddiff --git a/app/models/family/financial_data_reset.rb b/app/models/family/financial_data_reset.rbindex da2b13b23d..837ff794f4 100644--- a/app/models/family/financial_data_reset.rb+++ b/app/models/family/financial_data_reset.rb@@ -39,28 +39,29 @@ class Family::FinancialDataResetactive_storage_attachments].freezeSTATUS_COUNT_KEYS = (COUNT_KEYS - %i[syncs]) + %i[plaid_items]+ # sortedPROVIDER_ITEM_ASSOCIATIONS = %i[- financekit_itemsbinance_itemsbrex_itemscoinbase_itemscoinstats_itemsenable_banking_items+ financekit_items+ fio_itemsibkr_itemsindexa_capital_itemskraken_items- questrade_itemslunchflow_items- redbark_itemsmercury_items+ monobank_itemsonchain_wallet_itemsplaid_items+ questrade_items+ redbark_itemssimplefin_itemssnaptrade_itemssophtron_itemsup_items- monobank_items- fio_items].freezeResult = Struct.new(:user, :family, :dry_run, :before_counts, :deleted_counts, :after_counts, keyword_init: true)diff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rbindex e5ac37e449..50d014e021 100644--- a/app/models/provider_merchant.rb+++ b/app/models/provider_merchant.rb@@ -1,5 +1,6 @@class ProviderMerchant < Merchant- enum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", monobank: "monobank", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark", fio: "fio" }+ # sorted+ enum :source, { ai: "ai", akahu: "akahu", brex: "brex", coinstats: "coinstats", enable_banking: "enable_banking", fio: "fio", indexa_capital: "indexa_capital", lunchflow: "lunchflow", mercury: "mercury", monobank: "monobank", plaid: "plaid", questrade: "questrade", redbark: "redbark", simplefin: "simplefin", sophtron: "sophtron", synth: "synth", up: "up" }# Unlike FamilyMerchant, only fill a blank logo: providers such as Plaid or# CoinStats supply their own logo_url, which must not be replaced (issue #2925).diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex e414cc9298..c0ceb7d522 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -112,7 +112,8 @@ class Transaction < ApplicationRecordINTERNAL_MOVEMENT_LABELS = [ "Transfer", "Sweep In", "Sweep Out", "Exchange" ].freeze# Providers that support pending transaction flags- PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark financekit].freeze+ # sorted+ PENDING_PROVIDERS = %w[akahu enable_banking financekit lunchflow mercury monobank plaid redbark simplefin up].freeze# Slice size for the entry touch in reassign_category! — bounds the UPDATE# statement size when a merge or category destroy hits many transactions.diff --git a/config/application.rb b/config/application.rbindex e506ecf112..fbd5fc7399 100644--- a/config/application.rb+++ b/config/application.rb@@ -18,7 +18,7 @@ module Sure# Please, add to the `ignore` list any other `lib` subdirectories that do# not contain `.rb` files, or that should not be reloaded or eager loaded.# Common ones are `templates`, `generators`, or `middleware`, for example.- config.autoload_lib(ignore: %w[assets tasks generators])+ config.autoload_lib(ignore: %w[assets tasks generators rubocop])# Configuration for the application, engines, and railties goes here.#diff --git a/lib/generators/provider/family/family_generator.rb b/lib/generators/provider/family/family_generator.rbindex bb7f88d8db..3f1ad73a50 100644--- a/lib/generators/provider/family/family_generator.rb+++ b/lib/generators/provider/family/family_generator.rb@@ -586,8 +586,9 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBaseActiveRecord::Generators::Base.next_migration_number(dirname)end- # Appends `name` as the final entry of the `enum :source, { ... }` hash in `content`.- # Returns the updated source, or nil when no such hash is present.+ # Adds `name` to the `enum :source, { ... }` hash in `content`, before the first entry+ # that sorts after it, so the alphabetical list stays sorted; after the last entry+ # when none does. Returns the updated source, or nil when no such hash is present.## Pure string transformation, extracted from the generator so the comma and# indentation handling can be tested directly. Both are easy to get wrong and fail as@@ -607,20 +608,40 @@ class Provider::FamilyGenerator < Rails::Generators::NamedBasetrailing = body[/\s*\z/] || ""core = body[0...(body.length - trailing.length)]entry = "#{name}: \"#{name}\""+ # The body with its comments blanked out, at the same offsets: text after a `#` is+ # not an entry however much it looks like one, and a comma placed there is swallowed.+ code = core.gsub(/#[^\n]*/) { |comment| " " * comment.length }++ following = code.to_enum(:scan, /(\w+):/).map { Regexp.last_match }.find { |key| key[1] > name }+ if following+ at = following.begin(0)+ # A comment on the lines above the following entry belongs to it, so insert above it.+ while (comment = core[0...at].match(/\n[ \t]*(#[^\n]*\n[ \t]*)\z/))+ at = comment.begin(1)+ end+ # Multi-line, the entry takes a line of its own at the following entry's indentation.+ line_start = core[0...at][/\n[ \t]*\z/]+ separator = line_start ? ",#{line_start}" : ", "+ new_body = "#{core[0...at]}#{entry}#{separator}#{core[at..]}#{trailing}"+ return content.sub(/(enum :source, \{)([^}]*)(\})/m) { prefix + new_body + suffix }+ end# A hash written with a trailing comma already supplies the separator, and an empty# hash needs none at all. Emitting one regardless yields `redbark: "redbark",,` or# `{, gocardless: "gocardless"}`: the same class of syntax error this method exists# to prevent.- separator = (core.empty? || core.end_with?(",")) ? "" : ","+ code_end = code.rstrip.length+ separator = (code_end.zero? || code[code_end - 1] == ",") ? "" : ","+ # The separator goes straight after the last entry, ahead of any comment that follows it.+ core = core.dup.insert(code_end, separator)new_body =if trailing.include?("\n")# Multi-line: indent to match the last entry, not the closing brace.indent = core[/\n([ \t]*)[^\n]*\z/, 1] || " "- "#{core}#{separator}\n#{indent}#{entry}#{trailing}"+ "#{core}\n#{indent}#{entry}#{trailing}"else- "#{core}#{separator} #{entry}#{trailing}"+ "#{core} #{entry}#{trailing}"end# Block form: a string replacement would interpret any backslash sequence in thediff --git a/lib/rubocop/cop/sure/sorted_list.rb b/lib/rubocop/cop/sure/sorted_list.rbnew file mode 100644index 0000000000..79ce90515a--- /dev/null+++ b/lib/rubocop/cop/sure/sorted_list.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++module RuboCop+ module Cop+ module Sure+ # Keeps a hash's keys, or an array's elements, in alphabetical order when the line+ # above the literal is the comment `# sorted`. Lists that every new provider extends+ # use it, so a new entry has a known place and two branches adding one rarely+ # conflict.+ #+ # # sorted+ # PENDING_PROVIDERS = %w[akahu plaid simplefin].freeze+ #+ # # sorted+ # enum :source, {+ # akahu: "akahu",+ # plaid: "plaid"+ # }+ class SortedList < Base+ MSG = "Keep this `# sorted` list in alphabetical order: `%<item>s` belongs before `%<previous>s`."+ MARKER = /\A#\s*sorted\s*\z/++ def on_hash(node)+ check(node, node.pairs.map(&:key))+ end++ def on_array(node)+ check(node, node.values)+ end++ private++ def check(node, items)+ return unless marked?(node)++ names = items.map { |item| entry_name(item) }+ names.each_cons(2).with_index(1) do |(previous, current), index|+ next if previous <= current++ add_offense(items[index], message: format(MSG, item: current, previous: previous))+ end+ end++ def entry_name(item)+ item.sym_type? || item.str_type? ? item.value.to_s : item.source+ end++ # The marker is the comment on the line above the list. Only the outermost list+ # starting on the line after it is meant, not one nested in it.+ def marked?(node)+ return false if node.each_ancestor(:hash, :array).any? { |outer| outer.first_line == node.first_line }++ processed_source.comments.any? { |comment| comment.loc.line == node.first_line - 1 && comment.text.match?(MARKER) }+ end+ end+ end+ end+enddiff --git a/test/lib/generators/provider/family_generator_test.rb b/test/lib/generators/provider/family_generator_test.rbindex 5d4460de2a..a17e1643e6 100644--- a/test/lib/generators/provider/family_generator_test.rb+++ b/test/lib/generators/provider/family_generator_test.rb@@ -9,8 +9,8 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCasemodule GeneratedControllersend- def append(content)- Provider::FamilyGenerator.append_source_enum_entry(content, "gocardless")+ def append(content, name = "gocardless")+ Provider::FamilyGenerator.append_source_enum_entry(content, name)enddef assert_parses(source)@@ -81,19 +81,57 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseassert_includes job, "@gocardless_account.gocardless_item&.family&.broadcast_sync_complete"end- test "appends to a single-line enum" do+ test "inserts into a single-line enum before the first source that sorts after it" doresult = append(<<~RUBY)class ProviderMerchant < Merchant- enum :source, { plaid: "plaid", redbark: "redbark" }+ enum :source, { akahu: "akahu", plaid: "plaid", redbark: "redbark" }endRUBYassert_parses result- assert_includes result, 'redbark: "redbark", gocardless: "gocardless" }'+ assert_includes result, '{ akahu: "akahu", gocardless: "gocardless", plaid: "plaid", redbark: "redbark" }'end- test "appends to a multiline enum without putting the entry after the expression ends" do+ test "inserts into a multiline enum on a line of its own, keeping the list sorted" doresult = append(<<~RUBY)+ class DataEnrichment < ApplicationRecord+ enum :source, {+ akahu: "akahu",+ plaid: "plaid",+ redbark: "redbark"+ }+ end+ RUBY++ assert_parses result+ assert_includes result, %( akahu: "akahu",\n gocardless: "gocardless",\n plaid: "plaid",\n)+ end++ test "ignores commented-out keys and keeps a comment with the entry it describes" do+ result = append(<<~RUBY)+ class DataEnrichment < ApplicationRecord+ enum :source, {+ akahu: "akahu", # zopa: "zopa"+ # plaid: imported from the Plaid API+ plaid: "plaid",+ redbark: "redbark"+ }+ end+ RUBY++ assert_parses result+ assert_includes result, %( akahu: "akahu", # zopa: "zopa"\n gocardless: "gocardless",\n # plaid: imported from the Plaid API\n plaid: "plaid",\n)+ end++ test "appends to a single-line enum a source that sorts last" do+ result = append('enum :source, { plaid: "plaid", redbark: "redbark" }', "zopa")++ assert_parses "x = #{result}"+ assert_includes result, 'redbark: "redbark", zopa: "zopa" }'+ end++ test "appends to a multiline enum a source that sorts last without putting it after the expression ends" do+ result = append(<<~RUBY, "zopa")class DataEnrichment < ApplicationRecordenum :source, {plaid: "plaid",@@ -104,18 +142,33 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseassert_parses result# The comma must attach to the previous entry, and the new entry take its indentation.- assert_includes result, %( redbark: "redbark",\n gocardless: "gocardless"\n)+ assert_includes result, %( redbark: "redbark",\n zopa: "zopa"\n)+ end++ test "appends after a last entry with a trailing comment without putting the comma in the comment" do+ result = append(<<~RUBY, "zopa")+ class DataEnrichment < ApplicationRecord+ enum :source, {+ plaid: "plaid",+ redbark: "redbark" # last one+ # zebra: "zebra"+ }+ end+ RUBY++ assert_parses result+ assert_includes result, %( redbark: "redbark", # last one\n # zebra: "zebra"\n zopa: "zopa"\n)endtest "does not double the comma on a single-line enum with a trailing comma" do- result = append('enum :source, { plaid: "plaid", redbark: "redbark", }')+ result = append('enum :source, { plaid: "plaid", redbark: "redbark", }', "zopa")assert_parses "x = #{result}"assert_not_includes result, ",,"endtest "does not double the comma on a multiline enum with a trailing comma" do- result = append(<<~RUBY)+ result = append(<<~RUBY, "zopa")class DataEnrichment < ApplicationRecordenum :source, {plaid: "plaid",@@ -126,7 +179,7 @@ class Provider::FamilyGeneratorTest < ActiveSupport::TestCaseassert_parses resultassert_not_includes result, ",,"- assert_includes result, 'gocardless: "gocardless"'+ assert_includes result, 'zopa: "zopa"'endtest "does not emit a leading comma into an empty single-line enum" dodiff --git a/test/lib/rubocop/cop/sure/sorted_list_test.rb b/test/lib/rubocop/cop/sure/sorted_list_test.rbnew file mode 100644index 0000000000..d4f1add50d--- /dev/null+++ b/test/lib/rubocop/cop/sure/sorted_list_test.rb@@ -0,0 +1,65 @@+require "test_helper"+require "rubocop"+require Rails.root.join("lib/rubocop/cop/sure/sorted_list")++class RuboCop::Cop::Sure::SortedListTest < ActiveSupport::TestCase+ test "accepts a marked list in alphabetical order" do+ assert_empty offenses(<<~RUBY)+ # sorted+ PROVIDERS = %w[akahu plaid simplefin].freeze++ # sorted+ enum :source, {+ akahu: "akahu",+ plaid: "plaid"+ }+ RUBY+ end++ test "flags the first entry out of order in a marked array or hash" do+ found = offenses(<<~RUBY)+ # sorted+ PROVIDERS = %w[plaid akahu simplefin].freeze++ # sorted+ enum :source, { plaid: "plaid", fio: "fio", up: "up" }+ RUBY++ assert_equal [ [ 2, "akahu", "plaid" ], [ 5, "fio", "plaid" ] ],+ found.map { |offense| [ offense.line, *offense.message.scan(/`(\w+)`/).flatten ] }+ end++ test "leaves unmarked lists and lists nested in a marked one alone" do+ assert_empty offenses(<<~RUBY)+ PROVIDERS = %w[plaid akahu].freeze++ # sorted+ LIMITS = { akahu: %i[z a], plaid: %i[y b] }++ # not sorted on purpose+ ORDER = %w[plaid akahu]+ RUBY+ end++ test "checks each list in the repository it marks" do+ marked = %w[app/models/data_enrichment.rb app/models/provider_merchant.rb app/models/transaction.rb+ app/models/family/financial_data_reset.rb]++ marked.each do |path|+ source = Rails.root.join(path).read+ assert_match(/^\s*# sorted$/, source, "#{path} marks its list")+ assert_empty offenses(source), path+ end+ end++ private++ def offenses(source)+ config = RuboCop::Config.new({ "Sure/SortedList" => { "Enabled" => true } }, "test.rb")+ cop = RuboCop::Cop::Sure::SortedList.new(config)+ processed = RuboCop::ProcessedSource.new(source, RUBY_VERSION.to_f, "test.rb")+ report = RuboCop::Cop::Commissioner.new([ cop ], [], raise_error: true).investigate(processed)+ assert_empty report.errors+ report.offenses+ end+end