DEV: Apply syntax_tree formatting to lib/*

This commit is contained in:
David Taylor
2023-01-09 12:10:19 +00:00
parent b0fda61a8e
commit 6417173082
507 changed files with 16550 additions and 12627 deletions

View File

@@ -3,9 +3,8 @@
module Ember
module Handlebars
class Template
# Wrap in an IIFE in development mode to get the correct filename
def compile_ember_handlebars(string, ember_template = 'Handlebars', options = nil)
def compile_ember_handlebars(string, ember_template = "Handlebars", options = nil)
if ::Rails.env.development?
"(function() { try { return Ember.#{ember_template}.compile(#{indent(string).inspect}); } catch(err) { throw err; } })()"
else

View File

@@ -1,7 +1,7 @@
# frozen_string_literal: true
require 'cose'
require 'openssl/signature_algorithm/rsapkcs1'
require "cose"
require "openssl/signature_algorithm/rsapkcs1"
# 'cose' gem does not implement all algorithms from the Web Authentication
# (WebAuthn) standard specification. This patch implements one of the missing
@@ -38,11 +38,11 @@ module COSE
when OpenSSL::PKey::RSA
key
else
raise(COSE::Error, 'Incompatible key for algorithm')
raise(COSE::Error, "Incompatible key for algorithm")
end
end
end
register(RSAPKCS1.new(-257, 'RS256', hash_function: 'SHA256'))
register(RSAPKCS1.new(-257, "RS256", hash_function: "SHA256"))
end
end

View File

@@ -5,7 +5,6 @@
#
#
class ActiveRecord::Relation
# Note: In discourse, the following code is included in lib/sql_builder.rb
#
# class RailsDateTimeDecoder < PG::SimpleDecoder
@@ -43,7 +42,8 @@ class ActiveRecord::Relation
end
def pluck(*column_names)
if loaded? && (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
if loaded? &&
(column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
return records.pluck(*column_names)
end
@@ -55,10 +55,12 @@ class ActiveRecord::Relation
relation.select_values = column_names
klass.connection.select_raw(relation.arel) do |result, _|
result.type_map = DB.type_map
result.nfields == 1 ? result.column_values(0) : result.values
end
klass
.connection
.select_raw(relation.arel) do |result, _|
result.type_map = DB.type_map
result.nfields == 1 ? result.column_values(0) : result.values
end
end
end
end

View File

@@ -6,7 +6,6 @@
module ActiveSupport
module Inflector
LRU_CACHE_SIZE = 200
LRU_CACHES = []
@@ -22,26 +21,30 @@ module ActiveSupport
uncached = "#{method_name}_without_cache"
alias_method uncached, method_name
m = define_method(method_name) do |*arguments|
# this avoids recursive locks
found = true
data = cache.fetch(arguments) { found = false }
unless found
cache[arguments] = data = public_send(uncached, *arguments)
m =
define_method(method_name) do |*arguments|
# this avoids recursive locks
found = true
data = cache.fetch(arguments) { found = false }
cache[arguments] = data = public_send(uncached, *arguments) unless found
# so cache is never corrupted
data.dup
end
# so cache is never corrupted
data.dup
end
# https://bugs.ruby-lang.org/issues/16897
if Module.respond_to?(:ruby2_keywords, true)
ruby2_keywords(m)
end
ruby2_keywords(m) if Module.respond_to?(:ruby2_keywords, true)
end
end
memoize :pluralize, :singularize, :camelize, :underscore, :humanize,
:titleize, :tableize, :classify, :foreign_key
memoize :pluralize,
:singularize,
:camelize,
:underscore,
:humanize,
:titleize,
:tableize,
:classify,
:foreign_key
end
end

View File

@@ -1,29 +1,28 @@
# frozen_string_literal: true
class IPAddr
def self.handle_wildcards(val)
return if val.blank?
num_wildcards = val.count('*')
num_wildcards = val.count("*")
return val if num_wildcards == 0
# strip ranges like "/16" from the end if present
v = val.gsub(/\/.*/, '')
v = val.gsub(%r{/.*}, "")
return if v[v.index('*')..-1] =~ /[^\.\*]/
return if v[v.index("*")..-1] =~ /[^\.\*]/
parts = v.split('.')
(4 - parts.size).times { parts << '*' } # support strings like 192.*
v = parts.join('.')
parts = v.split(".")
(4 - parts.size).times { parts << "*" } # support strings like 192.*
v = parts.join(".")
"#{v.tr('*', '0')}/#{32 - (v.count('*') * 8)}"
"#{v.tr("*", "0")}/#{32 - (v.count("*") * 8)}"
end
def to_cidr_s
if @addr
mask = @mask_addr.to_s(2).count('1')
mask = @mask_addr.to_s(2).count("1")
if mask == 32
to_s
else
@@ -33,5 +32,4 @@ class IPAddr
nil
end
end
end

View File

@@ -11,9 +11,7 @@ module FreedomPatches
def build_smtp_session
super.tap do |smtp|
unless settings[:enable_starttls_auto]
if smtp.respond_to?(:disable_starttls)
smtp.disable_starttls
end
smtp.disable_starttls if smtp.respond_to?(:disable_starttls)
end
end
end

View File

@@ -5,11 +5,13 @@
# Backporting a fix to rails itself may get too complex
module FreedomPatches
module Rails4
def self.distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
options = {
scope: :'datetime.distance_in_words',
}.merge!(options)
def self.distance_of_time_in_words(
from_time,
to_time = 0,
include_seconds = false,
options = {}
)
options = { scope: :"datetime.distance_in_words" }.merge!(options)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
@@ -20,49 +22,68 @@ module FreedomPatches
I18n.with_options locale: options[:locale], scope: options[:scope] do |locale|
case distance_in_minutes
when 0..1
return distance_in_minutes == 0 ?
locale.t(:less_than_x_minutes, count: 1) :
locale.t(:x_minutes, count: distance_in_minutes) unless include_seconds
unless include_seconds
return(
(
if distance_in_minutes == 0
locale.t(:less_than_x_minutes, count: 1)
else
locale.t(:x_minutes, count: distance_in_minutes)
end
)
)
end
case distance_in_seconds
when 0..4 then locale.t :less_than_x_seconds, count: 5
when 5..9 then locale.t :less_than_x_seconds, count: 10
when 10..19 then locale.t :less_than_x_seconds, count: 20
when 20..39 then locale.t :half_a_minute
when 40..59 then locale.t :less_than_x_minutes, count: 1
else locale.t :x_minutes, count: 1
end
when 2..44 then locale.t :x_minutes, count: distance_in_minutes
when 45..89 then locale.t :about_x_hours, count: 1
when 90..1439 then locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round
when 1440..2519 then locale.t :x_days, count: 1
case distance_in_seconds
when 0..4
locale.t :less_than_x_seconds, count: 5
when 5..9
locale.t :less_than_x_seconds, count: 10
when 10..19
locale.t :less_than_x_seconds, count: 20
when 20..39
locale.t :half_a_minute
when 40..59
locale.t :less_than_x_minutes, count: 1
else
locale.t :x_minutes, count: 1
end
when 2..44
locale.t :x_minutes, count: distance_in_minutes
when 45..89
locale.t :about_x_hours, count: 1
when 90..1439
locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round
when 1440..2519
locale.t :x_days, count: 1
# this is were we diverge from Rails
when 2520..129599 then locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round
when 129600..525599 then locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round
else
when 2520..129_599
locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round
when 129_600..525_599
locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round
else
fyear = from_time.year
fyear += 1 if from_time.month >= 3
tyear = to_time.year
tyear -= 1 if to_time.month < 3
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count { |x| Date.leap?(x) }
minute_offset_for_leap_year = leap_years * 1440
# Discount the leap year days when calculating year distance.
# e.g. if there are 20 leap year days between 2 dates having the same day
# and month then the based on 365 days calculation
# the distance in years will come out to over 80 years when in written
# english it would read better as about 80 years.
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
remainder = (minutes_with_offset % 525600)
distance_in_years = (minutes_with_offset / 525600)
if remainder < 131400
locale.t(:about_x_years, count: distance_in_years)
elsif remainder < 394200
locale.t(:over_x_years, count: distance_in_years)
else
locale.t(:almost_x_years, count: distance_in_years + 1)
end
fyear += 1 if from_time.month >= 3
tyear = to_time.year
tyear -= 1 if to_time.month < 3
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count { |x| Date.leap?(x) }
minute_offset_for_leap_year = leap_years * 1440
# Discount the leap year days when calculating year distance.
# e.g. if there are 20 leap year days between 2 dates having the same day
# and month then the based on 365 days calculation
# the distance in years will come out to over 80 years when in written
# english it would read better as about 80 years.
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
remainder = (minutes_with_offset % 525_600)
distance_in_years = (minutes_with_offset / 525_600)
if remainder < 131_400
locale.t(:about_x_years, count: distance_in_years)
elsif remainder < 394_200
locale.t(:over_x_years, count: distance_in_years)
else
locale.t(:almost_x_years, count: distance_in_years + 1)
end
end
end
end

View File

@@ -19,12 +19,10 @@ module RailsMultisite
handler
end
ActiveRecord::Base.connected_to(role: reading_role) do
yield(db) if block_given?
end
ActiveRecord::Base.connected_to(role: reading_role) { yield(db) if block_given? }
rescue => e
STDERR.puts "URGENT: Failed to initialize site #{db}: "\
"#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"
STDERR.puts "URGENT: Failed to initialize site #{db}: " \
"#{e.class} #{e.message}\n#{e.backtrace.join("\n")}"
# the show must go on, don't stop startup if multisite fails
end
@@ -34,11 +32,7 @@ module RailsMultisite
class DiscoursePatches
def self.config
{
db_lookup: lambda do |env|
env["PATH_INFO"] == "/srv/status" ? "default" : nil
end
}
{ db_lookup: lambda { |env| env["PATH_INFO"] == "/srv/status" ? "default" : nil } }
end
end
end

View File

@@ -12,7 +12,8 @@ module FreedomPatches
rescue Encoding::CompatibilityError
raise if raise_encoding_err
encoding_diags = +"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
encoding_diags =
+"internal encoding #{Encoding.default_internal}, external encoding #{Encoding.default_external}"
if encoding != Encoding::UTF_8
encoding_diags << " my encoding is #{encoding} "
force_encoding("UTF-8")
@@ -20,12 +21,16 @@ module FreedomPatches
encode!("utf-16", "utf-8", invalid: :replace)
encode!("utf-8", "utf-16")
end
Rails.logger.warn("Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}")
Rails.logger.warn(
"Encountered a non UTF-8 string in SafeBuffer - #{self} - #{encoding_diags}",
)
end
if value.encoding != Encoding::UTF_8
encoding_diags << " attempted to append encoding #{value.encoding} "
value = value.dup.force_encoding("UTF-8").scrub
Rails.logger.warn("Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}")
Rails.logger.warn(
"Attempted to concat a non UTF-8 string in SafeBuffer - #{value} - #{encoding_diags}",
)
end
concat(value, _raise = true)
end

View File

@@ -5,7 +5,7 @@
# which rake:multisite_migrate uses
#
# The protection is only needed in Dev and Test
if ENV['RAILS_ENV'] != "production"
require_dependency 'migration/safe_migrate'
if ENV["RAILS_ENV"] != "production"
require_dependency "migration/safe_migrate"
Migration::SafeMigrate.patch_active_record!
end

View File

@@ -5,9 +5,7 @@ module FreedomPatches
def exec_migration(conn, direction)
rval = nil
time = Benchmark.measure do
rval = super
end
time = Benchmark.measure { rval = super }
sql = <<SQL
INSERT INTO schema_migration_details(
@@ -32,16 +30,23 @@ module FreedomPatches
SQL
hostname = Discourse.os_hostname
sql = ActiveRecord::Base.public_send(:sanitize_sql_array, [sql, {
version: version || "",
duration: (time.real * 1000).to_i,
hostname: hostname,
name: name,
git_version: Discourse.git_version,
created_at: Time.zone.now,
direction: direction.to_s,
rails_version: Rails.version
}])
sql =
ActiveRecord::Base.public_send(
:sanitize_sql_array,
[
sql,
{
version: version || "",
duration: (time.real * 1000).to_i,
hostname: hostname,
name: name,
git_version: Discourse.git_version,
created_at: Time.zone.now,
direction: direction.to_s,
rails_version: Rails.version,
},
],
)
conn.execute(sql)

View File

@@ -20,7 +20,10 @@ module FreedomPatches
end
if Rails.env.development? || Rails.env.test?
Sprockets.register_bundle_metadata_reducer 'application/javascript', :data, proc { +"" }, method(:concat_javascript_sources)
Sprockets.register_bundle_metadata_reducer "application/javascript",
:data,
proc { +"" },
method(:concat_javascript_sources)
end
end
end

View File

@@ -11,7 +11,6 @@
# This patch depends on the convention that locale yml files must be named [locale_name].yml
module I18n
# this accelerates translation a tiny bit (halves the time it takes)
class << self
alias_method :translate_no_cache, :translate
@@ -45,10 +44,7 @@ module I18n
# load plural rules from plugins
DiscoursePluginRegistry.locales.each do |plugin_locale, options|
if options[:plural]
I18n.backend.store_translations(
plugin_locale,
i18n: { plural: options[:plural] }
)
I18n.backend.store_translations(plugin_locale, i18n: { plural: options[:plural] })
end
end
end
@@ -57,8 +53,12 @@ module I18n
I18n.backend.load_translations(I18n.load_path.grep(/\.#{Regexp.escape locale}\.yml$/))
if Discourse.allow_dev_populate?
I18n.backend.load_translations(I18n.load_path.grep(/.*faker.*\/#{Regexp.escape locale}\.yml$/))
I18n.backend.load_translations(I18n.load_path.grep(/.*faker.*\/#{Regexp.escape locale}\/.*\.yml$/))
I18n.backend.load_translations(
I18n.load_path.grep(%r{.*faker.*/#{Regexp.escape locale}\.yml$}),
)
I18n.backend.load_translations(
I18n.load_path.grep(%r{.*faker.*/#{Regexp.escape locale}/.*\.yml$}),
)
end
@loaded_locales << locale
@@ -93,11 +93,7 @@ module I18n
end
def add_if_matches(translations, results, regexp)
translations.each do |key, value|
if key =~ regexp || value =~ regexp
results[key] = value
end
end
translations.each { |key, value| results[key] = value if key =~ regexp || value =~ regexp }
end
def ensure_loaded!(locale)
@@ -115,7 +111,8 @@ module I18n
@overrides_enabled = true
end
class MissingTranslation; end
class MissingTranslation
end
def translate_no_override(key, options)
# note we skip cache for :format and :count
@@ -129,9 +126,7 @@ module I18n
locale = dup_options.delete(:locale)
end
if dup_options.present?
return translate_no_cache(key, **options)
end
return translate_no_cache(key, **options) if dup_options.present?
locale ||= config.locale
locale = locale.to_sym
@@ -139,13 +134,14 @@ module I18n
@cache ||= LruRedux::ThreadSafeCache.new(LRU_CACHE_SIZE)
k = "#{key}#{locale}#{config.backend.object_id}"
val = @cache.getset(k) do
begin
translate_no_cache(key, locale: locale, raise: true).freeze
rescue I18n::MissingTranslationData
MissingTranslation
val =
@cache.getset(k) do
begin
translate_no_cache(key, locale: locale, raise: true).freeze
rescue I18n::MissingTranslationData
MissingTranslation
end
end
end
if val != MissingTranslation
val
@@ -170,7 +166,8 @@ module I18n
if !by_site.has_key?(locale)
# Load overrides
translations_overrides = TranslationOverride.where(locale: locale).pluck(:translation_key, :value)
translations_overrides =
TranslationOverride.where(locale: locale).pluck(:translation_key, :value)
if translations_overrides.empty?
by_site[locale] = {}
@@ -196,9 +193,9 @@ module I18n
def translate(*args)
execute_reload if @requires_reload
options = args.last.is_a?(Hash) ? args.pop.dup : {}
key = args.shift
locale = (options[:locale] || config.locale).to_sym
options = args.last.is_a?(Hash) ? args.pop.dup : {}
key = args.shift
locale = (options[:locale] || config.locale).to_sym
load_locale(locale) unless @loaded_locales.include?(locale)
@@ -222,9 +219,7 @@ module I18n
options[:overrides] = overrides
# I18n likes to use throw...
catch(:exception) do
return backend.translate(locale, key, options)
end
catch(:exception) { return backend.translate(locale, key, options) }
end
end