diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 357ed995450..534033db1f3 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -57,11 +57,6 @@ Style/FormatStringToken: - 'config/initializers/devise.rb' - 'lib/paperclip/color_extractor.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. -Style/GuardClause: - Enabled: false - # This cop supports unsafe autocorrection (--autocorrect-all). Style/HashTransformValues: Exclude: diff --git a/app/lib/activitypub/activity/block.rb b/app/lib/activitypub/activity/block.rb index 92a0f813fb3..52a942b7df8 100644 --- a/app/lib/activitypub/activity/block.rb +++ b/app/lib/activitypub/activity/block.rb @@ -15,9 +15,9 @@ class ActivityPub::Activity::Block < ActivityPub::Activity UnfollowService.new.call(target_account, @account) if target_account.following?(@account) RejectFollowService.new.call(target_account, @account) if target_account.requested?(@account) - unless delete_arrived_first?(@json['id']) - BlockWorker.perform_async(@account.id, target_account.id) - @account.block!(target_account, uri: @json['id']) - end + return if delete_arrived_first?(@json['id']) + + BlockWorker.perform_async(@account.id, target_account.id) + @account.block!(target_account, uri: @json['id']) end end diff --git a/app/lib/request.rb b/app/lib/request.rb index 8d4120868d4..5bfd35ac602 100644 --- a/app/lib/request.rb +++ b/app/lib/request.rb @@ -318,11 +318,9 @@ class Request end end - if outer_e - raise outer_e - else - raise SocketError, "No address for #{host}" - end + raise outer_e if outer_e + + raise SocketError, "No address for #{host}" end alias new open diff --git a/app/lib/request_pool.rb b/app/lib/request_pool.rb index 82d9a71c95e..985bc7c4272 100644 --- a/app/lib/request_pool.rb +++ b/app/lib/request_pool.rb @@ -58,13 +58,11 @@ class RequestPool close - if @fresh || retries.positive? - raise - else - @http_client = http_client - retries += 1 - retry - end + raise if @fresh || retries.positive? + + @http_client = http_client + retries += 1 + retry rescue # If this connection raises errors of any kind, it's # better if it gets reaped as soon as possible diff --git a/app/lib/webfinger.rb b/app/lib/webfinger.rb index 01a5dbc21d9..2df387f58a5 100644 --- a/app/lib/webfinger.rb +++ b/app/lib/webfinger.rb @@ -84,22 +84,18 @@ class Webfinger def body_from_host_meta host_meta_request.perform do |res| - if res.code == 200 - body_from_webfinger(url_from_template(res.body_with_limit), false) - else - raise Webfinger::Error, "Request for #{@uri} returned HTTP #{res.code}" - end + raise Webfinger::Error, "Request for #{@uri} returned HTTP #{res.code}" unless res.code == 200 + + body_from_webfinger(url_from_template(res.body_with_limit), false) end end def url_from_template(str) link = Nokogiri::XML(str).at_xpath('//xmlns:Link[@rel="lrdd"]') - if link.present? - link['template'].gsub('{uri}', @uri) - else - raise Webfinger::Error, "Request for #{@uri} returned host-meta without link to Webfinger" - end + raise Webfinger::Error, "Request for #{@uri} returned host-meta without link to Webfinger" if link.blank? + + link['template'].gsub('{uri}', @uri) rescue Nokogiri::XML::XPath::SyntaxError raise Webfinger::Error, "Invalid XML encountered in host-meta for #{@uri}" end diff --git a/app/lib/webfinger_resource.rb b/app/lib/webfinger_resource.rb index e2027e164de..95de496a6d5 100644 --- a/app/lib/webfinger_resource.rb +++ b/app/lib/webfinger_resource.rb @@ -54,11 +54,9 @@ class WebfingerResource end def username_from_acct - if domain_matches_local? - local_username - else - raise ActiveRecord::RecordNotFound - end + raise ActiveRecord::RecordNotFound unless domain_matches_local? + + local_username end def split_acct diff --git a/app/models/concerns/account/counters.rb b/app/models/concerns/account/counters.rb index 536d5ca7bcd..04291df3ff2 100644 --- a/app/models/concerns/account/counters.rb +++ b/app/models/concerns/account/counters.rb @@ -38,10 +38,10 @@ module Account::Counters result = updated_account_stat(key, value.to_i) # Reload account_stat if it was loaded, taking into account newly-created unsaved records - if association(:account_stat).loaded? - account_stat.id = result.first['id'] if account_stat.new_record? - account_stat.reload - end + return unless association(:account_stat).loaded? + + account_stat.id = result.first['id'] if account_stat.new_record? + account_stat.reload end def account_stat diff --git a/app/models/concerns/user/ldap_authenticable.rb b/app/models/concerns/user/ldap_authenticable.rb index fc1ee78d099..54479eb0b63 100644 --- a/app/models/concerns/user/ldap_authenticable.rb +++ b/app/models/concerns/user/ldap_authenticable.rb @@ -8,9 +8,9 @@ module User::LdapAuthenticable ldap = Net::LDAP.new(ldap_options) filter = format(Devise.ldap_search_filter, uid: Devise.ldap_uid, mail: Devise.ldap_mail, email: Net::LDAP::Filter.escape(params[:email])) - if (user_info = ldap.bind_as(base: Devise.ldap_base, filter: filter, password: params[:password])) - ldap_get_user(user_info.first) - end + return unless (user_info = ldap.bind_as(base: Devise.ldap_base, filter: filter, password: params[:password])) + + ldap_get_user(user_info.first) end def ldap_get_user(attributes = {}) diff --git a/app/models/tag.rb b/app/models/tag.rb index 9006e1f25d9..784589e2e29 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -178,9 +178,9 @@ class Tag < ApplicationRecord end def validate_display_name_change - unless HashtagNormalizer.new.normalize(display_name).casecmp(name.mb_chars).zero? - errors.add(:display_name, - I18n.t('tags.does_not_match_previous_name')) - end + return if HashtagNormalizer.new.normalize(display_name).casecmp(name.mb_chars).zero? + + errors.add(:display_name, + I18n.t('tags.does_not_match_previous_name')) end end diff --git a/app/models/user.rb b/app/models/user.rb index 72854569260..595ea8ff20d 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -433,16 +433,16 @@ class User < ApplicationRecord yield - if new_user - # Avoid extremely unlikely race condition when approving and confirming - # the user at the same time - reload unless approved? + return unless new_user - if approved? - prepare_new_user! - else - notify_staff_about_pending_account! - end + # Avoid extremely unlikely race condition when approving and confirming + # the user at the same time + reload unless approved? + + if approved? + prepare_new_user! + else + notify_staff_about_pending_account! end end diff --git a/app/services/fan_out_on_write_service.rb b/app/services/fan_out_on_write_service.rb index 50b414bc52b..8774358c29e 100644 --- a/app/services/fan_out_on_write_service.rb +++ b/app/services/fan_out_on_write_service.rb @@ -139,10 +139,10 @@ class FanOutOnWriteService < BaseService redis.publish('timeline:public', anonymous_payload) redis.publish(@status.local? ? 'timeline:public:local' : 'timeline:public:remote', anonymous_payload) - if @status.with_media? - redis.publish('timeline:public:media', anonymous_payload) - redis.publish(@status.local? ? 'timeline:public:local:media' : 'timeline:public:remote:media', anonymous_payload) - end + return unless @status.with_media? + + redis.publish('timeline:public:media', anonymous_payload) + redis.publish(@status.local? ? 'timeline:public:local:media' : 'timeline:public:remote:media', anonymous_payload) end def deliver_to_conversation! diff --git a/app/services/post_status_service.rb b/app/services/post_status_service.rb index 8b18ce038d8..71b23adc950 100644 --- a/app/services/post_status_service.rb +++ b/app/services/post_status_service.rb @@ -98,20 +98,18 @@ class PostStatusService < BaseService def schedule_status! status_for_validation = @account.statuses.build(status_attributes) - if status_for_validation.valid? - # Marking the status as destroyed is necessary to prevent the status from being - # persisted when the associated media attachments get updated when creating the - # scheduled status. - status_for_validation.destroy + raise ActiveRecord::RecordInvalid unless status_for_validation.valid? - # The following transaction block is needed to wrap the UPDATEs to - # the media attachments when the scheduled status is created + # Marking the status as destroyed is necessary to prevent the status from being + # persisted when the associated media attachments get updated when creating the + # scheduled status. + status_for_validation.destroy - ApplicationRecord.transaction do - @status = @account.scheduled_statuses.create!(scheduled_status_attributes) - end - else - raise ActiveRecord::RecordInvalid + # The following transaction block is needed to wrap the UPDATEs to + # the media attachments when the scheduled status is created + + ApplicationRecord.transaction do + @status = @account.scheduled_statuses.create!(scheduled_status_attributes) end end diff --git a/app/services/process_hashtags_service.rb b/app/services/process_hashtags_service.rb index 17c347b0889..9fda52f715c 100644 --- a/app/services/process_hashtags_service.rb +++ b/app/services/process_hashtags_service.rb @@ -31,10 +31,10 @@ class ProcessHashtagsService < BaseService removed_tags = @previous_tags - @current_tags - unless removed_tags.empty? - @account.featured_tags.where(tag_id: removed_tags.map(&:id)).find_each do |featured_tag| - featured_tag.decrement(@status.id) - end + return if removed_tags.empty? + + @account.featured_tags.where(tag_id: removed_tags.map(&:id)).find_each do |featured_tag| + featured_tag.decrement(@status.id) end end end diff --git a/app/workers/move_worker.rb b/app/workers/move_worker.rb index a18f38556bb..fa58e2b251c 100644 --- a/app/workers/move_worker.rb +++ b/app/workers/move_worker.rb @@ -123,11 +123,11 @@ class MoveWorker end def add_account_note_if_needed!(account, id) - unless AccountNote.exists?(account: account, target_account: @target_account) - text = I18n.with_locale(account.user&.locale.presence || I18n.default_locale) do - I18n.t(id, acct: @source_account.acct) - end - AccountNote.create!(account: account, target_account: @target_account, comment: text) + return if AccountNote.exists?(account: account, target_account: @target_account) + + text = I18n.with_locale(account.user&.locale.presence || I18n.default_locale) do + I18n.t(id, acct: @source_account.acct) end + AccountNote.create!(account: account, target_account: @target_account, comment: text) end end diff --git a/app/workers/redownload_avatar_worker.rb b/app/workers/redownload_avatar_worker.rb index df17b7718dc..da843763ef6 100644 --- a/app/workers/redownload_avatar_worker.rb +++ b/app/workers/redownload_avatar_worker.rb @@ -20,10 +20,7 @@ class RedownloadAvatarWorker rescue Mastodon::UnexpectedResponseError => e response = e.response - if response_error_unsalvageable?(response) - # Give up - else - raise e - end + raise e unless response_error_unsalvageable?(response) + # Give up end end diff --git a/app/workers/redownload_header_worker.rb b/app/workers/redownload_header_worker.rb index 3b142ec5f98..da158ac7344 100644 --- a/app/workers/redownload_header_worker.rb +++ b/app/workers/redownload_header_worker.rb @@ -20,10 +20,7 @@ class RedownloadHeaderWorker rescue Mastodon::UnexpectedResponseError => e response = e.response - if response_error_unsalvageable?(response) - # Give up - else - raise e - end + raise e unless response_error_unsalvageable?(response) + # Give up end end diff --git a/app/workers/redownload_media_worker.rb b/app/workers/redownload_media_worker.rb index 343caa32c23..202286b6651 100644 --- a/app/workers/redownload_media_worker.rb +++ b/app/workers/redownload_media_worker.rb @@ -20,10 +20,7 @@ class RedownloadMediaWorker rescue Mastodon::UnexpectedResponseError => e response = e.response - if response_error_unsalvageable?(response) - # Give up - else - raise e - end + raise e unless response_error_unsalvageable?(response) + # Give up end end diff --git a/app/workers/remote_account_refresh_worker.rb b/app/workers/remote_account_refresh_worker.rb index 9632936b547..5d9fb94fa13 100644 --- a/app/workers/remote_account_refresh_worker.rb +++ b/app/workers/remote_account_refresh_worker.rb @@ -15,10 +15,7 @@ class RemoteAccountRefreshWorker rescue Mastodon::UnexpectedResponseError => e response = e.response - if response_error_unsalvageable?(response) - # Give up - else - raise e - end + raise e unless response_error_unsalvageable?(response) + # Give up end end diff --git a/lib/devise/strategies/two_factor_ldap_authenticatable.rb b/lib/devise/strategies/two_factor_ldap_authenticatable.rb index c8258deb16d..b2384aa15a6 100644 --- a/lib/devise/strategies/two_factor_ldap_authenticatable.rb +++ b/lib/devise/strategies/two_factor_ldap_authenticatable.rb @@ -13,11 +13,9 @@ module Devise def authenticate! resource = mapping.to.authenticate_with_ldap(params[scope]) - if resource && !resource.otp_required_for_login? - success!(resource) - else - fail(:invalid) # rubocop:disable Style/SignalException -- method is from Warden::Strategies::Base - end + fail(:invalid) unless resource && !resource.otp_required_for_login? # rubocop:disable Style/SignalException -- method is from Warden::Strategies::Base + + success!(resource) end protected diff --git a/lib/devise/strategies/two_factor_pam_authenticatable.rb b/lib/devise/strategies/two_factor_pam_authenticatable.rb index a9db1b6a29f..fcaec4d3734 100644 --- a/lib/devise/strategies/two_factor_pam_authenticatable.rb +++ b/lib/devise/strategies/two_factor_pam_authenticatable.rb @@ -12,11 +12,9 @@ module Devise def authenticate! resource = mapping.to.authenticate_with_pam(params[scope]) - if resource && !resource.otp_required_for_login? - success!(resource) - else - fail(:invalid) # rubocop:disable Style/SignalException -- method is from Warden::Strategies::Base - end + fail(:invalid) unless resource && !resource.otp_required_for_login? # rubocop:disable Style/SignalException -- method is from Warden::Strategies::Base + + success!(resource) end protected diff --git a/lib/mastodon/cli/accounts.rb b/lib/mastodon/cli/accounts.rb index d3b7ebe5805..bdc21fc368d 100644 --- a/lib/mastodon/cli/accounts.rb +++ b/lib/mastodon/cli/accounts.rb @@ -320,10 +320,10 @@ module Mastodon::CLI say("Visited #{processed} accounts, removed #{culled}#{dry_run_mode_suffix}", :green) - unless skip_domains.empty? - say('The following domains were not available during the check:', :yellow) - skip_domains.each { |domain| say(" #{domain}") } - end + return if skip_domains.empty? + + say('The following domains were not available during the check:', :yellow) + skip_domains.each { |domain| say(" #{domain}") } end option :all, type: :boolean diff --git a/lib/mastodon/cli/maintenance.rb b/lib/mastodon/cli/maintenance.rb index 0b84047a1cb..d89ee612c2f 100644 --- a/lib/mastodon/cli/maintenance.rb +++ b/lib/mastodon/cli/maintenance.rb @@ -146,18 +146,18 @@ module Mastodon::CLI end end - if db_table_exists?(:severed_relationships) - SeveredRelationship.where(local_account_id: other_account.id).reorder(nil).find_each do |record| - record.update_attribute(:local_account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + return unless db_table_exists?(:severed_relationships) - SeveredRelationship.where(remote_account_id: other_account.id).reorder(nil).find_each do |record| - record.update_attribute(:remote_account_id, id) - rescue ActiveRecord::RecordNotUnique - next - end + SeveredRelationship.where(local_account_id: other_account.id).reorder(nil).find_each do |record| + record.update_attribute(:local_account_id, id) + rescue ActiveRecord::RecordNotUnique + next + end + + SeveredRelationship.where(remote_account_id: other_account.id).reorder(nil).find_each do |record| + record.update_attribute(:remote_account_id, id) + rescue ActiveRecord::RecordNotUnique + next end end end @@ -331,14 +331,14 @@ module Mastodon::CLI end def deduplicate_users_process_remember_token - if migrator_version < 2022_01_18_183010 - duplicate_record_ids_without_nulls(:users, 'remember_token').each do |row| - users = User.where(id: row['ids'].split(',')).order(updated_at: :desc).to_a.drop(1) - say "Unsetting remember token for those accounts: #{users.map { |user| user.account.acct }.join(', ')}", :yellow + return unless migrator_version < 2022_01_18_183010 - users.each do |user| - user.update!(remember_token: nil) - end + duplicate_record_ids_without_nulls(:users, 'remember_token').each do |row| + users = User.where(id: row['ids'].split(',')).order(updated_at: :desc).to_a.drop(1) + say "Unsetting remember token for those accounts: #{users.map { |user| user.account.acct }.join(', ')}", :yellow + + users.each do |user| + user.update!(remember_token: nil) end end end diff --git a/lib/mastodon/cli/media.rb b/lib/mastodon/cli/media.rb index 123973d1954..73940efda81 100644 --- a/lib/mastodon/cli/media.rb +++ b/lib/mastodon/cli/media.rb @@ -58,23 +58,23 @@ module Mastodon::CLI say("Visited #{processed} accounts and removed profile media totaling #{number_to_human_size(aggregate)}#{dry_run_mode_suffix}", :green, true) end - unless options[:prune_profiles] || options[:remove_headers] - processed, aggregate = parallelize_with_progress(MediaAttachment.cached.remote.where(created_at: ..time_ago)) do |media_attachment| - next if media_attachment.file.blank? + return if options[:prune_profiles] || options[:remove_headers] - size = (media_attachment.file_file_size || 0) + (media_attachment.thumbnail_file_size || 0) + processed, aggregate = parallelize_with_progress(MediaAttachment.cached.remote.where(created_at: ..time_ago)) do |media_attachment| + next if media_attachment.file.blank? - unless dry_run? - media_attachment.file.destroy - media_attachment.thumbnail.destroy - media_attachment.save - end + size = (media_attachment.file_file_size || 0) + (media_attachment.thumbnail_file_size || 0) - size + unless dry_run? + media_attachment.file.destroy + media_attachment.thumbnail.destroy + media_attachment.save end - say("Removed #{processed} media attachments (approx. #{number_to_human_size(aggregate)})#{dry_run_mode_suffix}", :green, true) + size end + + say("Removed #{processed} media attachments (approx. #{number_to_human_size(aggregate)})#{dry_run_mode_suffix}", :green, true) end option :start_after diff --git a/lib/tasks/repo.rake b/lib/tasks/repo.rake index 1ed1ee5c323..11f2affa71c 100644 --- a/lib/tasks/repo.rake +++ b/lib/tasks/repo.rake @@ -56,13 +56,11 @@ namespace :repo do loop do response = HTTP.headers('Authorization' => "token #{ENV['GITHUB_API_TOKEN']}").get("https://api.github.com/repos/#{REPOSITORY_NAME}/pulls/#{pull_request_number}") - if response.code == 403 - sleep_for = (response.headers['X-RateLimit-Reset'].to_i - Time.now.to_i).abs - puts "Sleeping for #{sleep_for} seconds to get over rate limit" - sleep sleep_for - else - break - end + break unless response.code == 403 + + sleep_for = (response.headers['X-RateLimit-Reset'].to_i - Time.now.to_i).abs + puts "Sleeping for #{sleep_for} seconds to get over rate limit" + sleep sleep_for end pull_request = Oj.load(response.to_s)