DEV: Fix rubocop issues (#14715)

This commit is contained in:
Dan Ungureanu 2021-10-27 11:39:28 +03:00 committed by GitHub
parent 6aa6275f3f
commit 69f0f48dc0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 65 additions and 69 deletions

View File

@ -23,7 +23,7 @@ class LocaleSiteSetting < EnumSiteSetting
@lock.synchronize do @lock.synchronize do
@language_names ||= begin @language_names ||= begin
names = YAML.load(File.read(File.join(Rails.root, 'config', 'locales', 'names.yml'))) names = YAML.safe_load(File.read(File.join(Rails.root, 'config', 'locales', 'names.yml')))
DiscoursePluginRegistry.locales.each do |locale, options| DiscoursePluginRegistry.locales.each do |locale, options|
if !names.key?(locale) && options[:name] && options[:nativeName] if !names.key?(locale) && options[:name] && options[:nativeName]

View File

@ -117,8 +117,8 @@ class TopicEmbed < ActiveRecord::Base
follow_canonical: true, follow_canonical: true,
) )
url = fd.resolve uri = fd.resolve
return if url.blank? return if uri.blank?
opts = { opts = {
tags: %w[div p code pre h1 h2 h3 b em i strong a img ul li ol blockquote], tags: %w[div p code pre h1 h2 h3 b em i strong a img ul li ol blockquote],
@ -132,7 +132,7 @@ class TopicEmbed < ActiveRecord::Base
response = FetchResponse.new response = FetchResponse.new
begin begin
html = open(url, allow_redirections: :safe).read html = uri.read(allow_redirections: :safe)
rescue OpenURI::HTTPError, Net::OpenTimeout rescue OpenURI::HTTPError, Net::OpenTimeout
return return
end end
@ -256,10 +256,6 @@ class TopicEmbed < ActiveRecord::Base
body body
end end
end end
def self.open(uri, **kwargs)
URI.open(uri, **kwargs)
end
end end
# == Schema Information # == Schema Information

View File

@ -16,7 +16,7 @@ class SiteSettingsTask
counts = { updated: 0, not_found: 0, errors: 0 } counts = { updated: 0, not_found: 0, errors: 0 }
log = [] log = []
site_settings = YAML::load(yml) site_settings = YAML::safe_load(yml)
site_settings.each do |site_setting| site_settings.each do |site_setting|
key = site_setting[0] key = site_setting[0]
val = site_setting[1] val = site_setting[1]

View File

@ -86,7 +86,7 @@ class Cache
if raw if raw
begin begin
Marshal.load(raw) Marshal.load(raw) # rubocop:disable Security/MarshalLoad
rescue => e rescue => e
log_first_exception(e) log_first_exception(e)
end end
@ -113,7 +113,7 @@ class Cache
def read_entry(key) def read_entry(key)
if data = redis.get(key) if data = redis.get(key)
Marshal.load(data) Marshal.load(data) # rubocop:disable Security/MarshalLoad
end end
rescue => e rescue => e
# corrupt cache, this can happen if Marshal version # corrupt cache, this can happen if Marshal version

View File

@ -61,18 +61,34 @@ module DiscourseUpdates
Discourse.redis.get last_installed_version_key Discourse.redis.get last_installed_version_key
end end
def last_installed_version=(arg)
Discourse.redis.set(last_installed_version, arg)
end
def latest_version def latest_version
Discourse.redis.get latest_version_key Discourse.redis.get latest_version_key
end end
def latest_version=(arg)
Discourse.redis.set(latest_version, arg)
end
def missing_versions_count def missing_versions_count
Discourse.redis.get(missing_versions_count_key).try(:to_i) Discourse.redis.get(missing_versions_count_key).try(:to_i)
end end
def missing_versions_count=(arg)
Discourse.redis.set(missing_versions_count, arg)
end
def critical_updates_available? def critical_updates_available?
(Discourse.redis.get(critical_updates_available_key) || false) == 'true' (Discourse.redis.get(critical_updates_available_key) || false) == 'true'
end end
def critical_updates_available=(arg)
Discourse.redis.set(critical_updates_available, arg)
end
def updated_at def updated_at
t = Discourse.redis.get(updated_at_key) t = Discourse.redis.get(updated_at_key)
t ? Time.zone.parse(t) : nil t ? Time.zone.parse(t) : nil
@ -82,12 +98,6 @@ module DiscourseUpdates
Discourse.redis.set updated_at_key, time_with_zone.as_json Discourse.redis.set updated_at_key, time_with_zone.as_json
end end
['last_installed_version', 'latest_version', 'missing_versions_count', 'critical_updates_available'].each do |name|
eval "define_method :#{name}= do |arg|
Discourse.redis.set #{name}_key, arg
end"
end
def missing_versions=(versions) def missing_versions=(versions)
# delete previous list from redis # delete previous list from redis
prev_keys = Discourse.redis.lrange(missing_versions_list_key, 0, 4) prev_keys = Discourse.redis.lrange(missing_versions_list_key, 0, 4)

View File

@ -165,7 +165,7 @@ class LocaleFileChecker
def plural_keys def plural_keys
@plural_keys ||= begin @plural_keys ||= begin
eval(File.read("#{Rails.root}/#{PLURALS_FILE}")).map do |locale, value| eval(File.read("#{Rails.root}/#{PLURALS_FILE}")).map do |locale, value| # rubocop:disable Security/Eval
[locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)] [locale.to_s, value[:i18n][:plural][:keys].map(&:to_s)]
end.to_h end.to_h
end end

View File

@ -29,7 +29,7 @@ module Middleware
method << "|#{k}=#\{h.#{v}}" method << "|#{k}=#\{h.#{v}}"
end end
method << "\"\nend" method << "\"\nend"
eval(method) eval(method) # rubocop:disable Security/Eval
@@compiled = true @@compiled = true
end end

View File

@ -71,7 +71,7 @@ module Onebox
raw["head_commit"]["message"].lines.first raw["head_commit"]["message"].lines.first
elsif type == :pr_run elsif type == :pr_run
pr_url = "https://api.github.com/repos/#{match[:org]}/#{match[:repo]}/pulls/#{match[:pr_id]}" pr_url = "https://api.github.com/repos/#{match[:org]}/#{match[:repo]}/pulls/#{match[:pr_id]}"
::MultiJson.load(URI.open(pr_url, read_timeout: timeout))["title"] ::MultiJson.load(URI.parse(pr_url).open(read_timeout: timeout))["title"]
end end
{ {

View File

@ -6,7 +6,7 @@ module Onebox
private private
def raw def raw
@raw ||= ::MultiJson.load(URI.open(url, read_timeout: timeout)) @raw ||= ::MultiJson.load(URI.parse(url).open(read_timeout: timeout))
end end
end end
end end

View File

@ -12,7 +12,7 @@ module Onebox
def xml def xml
return @xml if defined?(@xml) return @xml if defined?(@xml)
doc = Nokogiri::XML(URI.open(URI.join(@url, "?report=xml&format=text"))) doc = Nokogiri::XML(URI.join(@url, "?report=xml&format=text").open)
pre = doc.xpath("//pre") pre = doc.xpath("//pre")
@xml = Nokogiri::XML("<root>" + pre.text + "</root>") @xml = Nokogiri::XML("<root>" + pre.text + "</root>")
end end

View File

@ -167,7 +167,7 @@ module Onebox
@model_file = @lang.dup @model_file = @lang.dup
@raw = "https://render.githubusercontent.com/view/solid?url=" + self.raw_template(m) @raw = "https://render.githubusercontent.com/view/solid?url=" + self.raw_template(m)
else else
contents = URI.open(self.raw_template(m), read_timeout: timeout).read contents = URI.parse(self.raw_template(m)).open(read_timeout: timeout).read
contents_lines = contents.lines #get contents lines contents_lines = contents.lines #get contents lines
contents_lines_size = contents_lines.size #get number of lines contents_lines_size = contents_lines.size #get number of lines

View File

@ -35,7 +35,7 @@ module Onebox
private private
def check def check
res = URI.open(@url, read_timeout: (@options.timeout || Onebox.options.timeout)) res = URI.parse(@url).open(read_timeout: (@options.timeout || Onebox.options.timeout))
@status = res.status.first.to_i @status = res.status.first.to_i
rescue OpenURI::HTTPError => e rescue OpenURI::HTTPError => e
@status = e.io.status.first.to_i @status = e.io.status.first.to_i

View File

@ -92,7 +92,7 @@ class SiteSettings::TypeSupervisor
end end
if (new_choices = opts[:choices]) if (new_choices = opts[:choices])
new_choices = eval(new_choices) if new_choices.is_a?(String) new_choices = eval(new_choices) if new_choices.is_a?(String) # rubocop:disable Security/Eval
if @choices.has_key?(name) if @choices.has_key?(name)
@choices[name].concat(new_choices) @choices[name].concat(new_choices)

View File

@ -20,7 +20,7 @@ task 'assets:prestage' => :environment do |t|
puts "pre staging: #{assets.join(' ')}" puts "pre staging: #{assets.join(' ')}"
# makes testing simpler leaving this here # makes testing simpler leaving this here
config = YAML::load(File.open("#{Rails.root}/config/cdn.yml")) config = YAML::safe_load(File.open("#{Rails.root}/config/cdn.yml"))
start = Time.now start = Time.now

View File

@ -284,7 +284,7 @@ desc "update emoji images"
task "emoji:update" do task "emoji:update" do
copy_emoji_db copy_emoji_db
json_db = open(File.join(GENERATED_PATH, "db.json")).read json_db = File.read(File.join(GENERATED_PATH, "db.json"))
db = JSON.parse(json_db) db = JSON.parse(json_db)
write_db_json(db["emojis"], db["translations"]) write_db_json(db["emojis"], db["translations"])
@ -352,7 +352,7 @@ end
def generate_emoji_groups(keywords, sections) def generate_emoji_groups(keywords, sections)
puts "Generating groups..." puts "Generating groups..."
list = open(EMOJI_ORDERING_URL).read list = URI.parse(EMOJI_ORDERING_URL).read
doc = Nokogiri::HTML5(list) doc = Nokogiri::HTML5(list)
table = doc.css("table")[0] table = doc.css("table")[0]

View File

@ -30,7 +30,7 @@ task "themes:install" => :environment do |task, args|
use_json = theme_args == '' use_json = theme_args == ''
theme_args = begin theme_args = begin
use_json ? JSON.parse(ARGV.last.gsub('--', '')) : YAML::load(theme_args) use_json ? JSON.parse(ARGV.last.gsub('--', '')) : YAML::safe_load(theme_args)
rescue rescue
puts use_json ? "Invalid JSON input. \n#{ARGV.last}" : "Invalid YML: \n#{theme_args}" puts use_json ? "Invalid JSON input. \n#{ARGV.last}" : "Invalid YML: \n#{theme_args}"
exit 1 exit 1

View File

@ -297,7 +297,7 @@ begin
run("RAILS_ENV=profile bundle exec rake assets:clean") run("RAILS_ENV=profile bundle exec rake assets:clean")
def get_mem(pid) def get_mem(pid)
YAML.load `ruby script/memstats.rb #{pid} --yaml` YAML.safe_load `ruby script/memstats.rb #{pid} --yaml`
end end
mem = get_mem(pid) mem = get_mem(pid)

View File

@ -46,7 +46,7 @@ Benchmark.ips do |x|
x.report("redis get string marshal") do |times| x.report("redis get string marshal") do |times|
while times > 0 while times > 0
Marshal.load(Discourse.redis.get("test_keym")) Marshal.load(Discourse.redis.get("test_keym")) # rubocop:disable Security/MarshalLoad
times -= 1 times -= 1
end end
end end

View File

@ -10,7 +10,7 @@ class ImportScripts::JForum < ImportScripts::Base
def initialize def initialize
super super
@settings = YAML.load(File.read(ARGV.first), symbolize_names: true) @settings = YAML.safe_load(File.read(ARGV.first), symbolize_names: true)
@database_client = Mysql2::Client.new( @database_client = Mysql2::Client.new(
host: @settings[:database][:host], host: @settings[:database][:host],

View File

@ -48,7 +48,7 @@ module ImportScripts::Mbox
if File.exist?(metadata_file) if File.exist?(metadata_file)
# workaround for YML files that contain classname in file header # workaround for YML files that contain classname in file header
yaml = File.read(metadata_file).sub(/^--- !.*$/, '---') yaml = File.read(metadata_file).sub(/^--- !.*$/, '---')
metadata = YAML.load(yaml) metadata = YAML.safe_load(yaml)
else else
metadata = {} metadata = {}
end end

View File

@ -180,7 +180,7 @@ class ImportScripts::NodeBB < ImportScripts::Base
if is_external if is_external
# download external image # download external image
begin begin
string_io = open(picture, read_timeout: 5) string_io = uri.open(read_timeout: 5)
rescue Net::ReadTimeout rescue Net::ReadTimeout
puts "timeout downloading avatar for user #{imported_user.id}" puts "timeout downloading avatar for user #{imported_user.id}"
return nil return nil
@ -246,7 +246,7 @@ class ImportScripts::NodeBB < ImportScripts::Base
if is_external if is_external
begin begin
string_io = open(picture, read_timeout: 5) string_io = uri.open(read_timeout: 5)
rescue Net::ReadTimeout rescue Net::ReadTimeout
return nil return nil
end end

View File

@ -558,7 +558,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
def read_smf_settings def read_smf_settings
settings = File.join(self.smfroot, 'Settings.php') settings = File.join(self.smfroot, 'Settings.php')
IO.readlines(settings).each do |line| File.readlines(settings).each do |line|
next unless m = /\$([a-z_]+)\s*=\s*['"](.+?)['"]\s*;\s*((#|\/\/).*)?$/.match(line) next unless m = /\$([a-z_]+)\s*=\s*['"](.+?)['"]\s*;\s*((#|\/\/).*)?$/.match(line)
case m[1] case m[1]
when 'db_server' then self.host ||= m[2] when 'db_server' then self.host ||= m[2]

View File

@ -333,7 +333,7 @@ class ImportScripts::ZendeskApi < ImportScripts::Base
attempts = 0 attempts = 0
begin begin
open("#{$1}") do |image| URI.parse(image_url).open do |image|
# IMAGE_DOWNLOAD_PATH is whatever image, it will be replaced with the downloaded image # IMAGE_DOWNLOAD_PATH is whatever image, it will be replaced with the downloaded image
File.open(IMAGE_DOWNLOAD_PATH, "wb") do |file| File.open(IMAGE_DOWNLOAD_PATH, "wb") do |file|
file.write(image.read) file.write(image.read)

View File

@ -131,7 +131,7 @@ def format_number(n)
end end
def get_commandline(pid) def get_commandline(pid)
commandline = IO.read("/proc/#{pid}/cmdline").split("\0") commandline = File.read("/proc/#{pid}/cmdline").split("\0")
if commandline.first =~ /java$/ then if commandline.first =~ /java$/ then
loop { break if commandline.shift == "-jar" } loop { break if commandline.shift == "-jar" }
return "[java] #{commandline.shift}" return "[java] #{commandline.shift}"

View File

@ -3,12 +3,16 @@
require 'rails_helper' require 'rails_helper'
describe DiscourseUpdates do describe DiscourseUpdates do
let(:latest_version_key) { DiscourseUpdates.send(:latest_version_key) }
let(:missing_versions_count_key) { DiscourseUpdates.send(:missing_versions_count_key) }
let(:critical_updates_available_key) { DiscourseUpdates.send(:critical_updates_available_key) }
let(:updated_at_key) { DiscourseUpdates.send(:updated_at_key) }
def stub_data(latest, missing, critical, updated_at) def stub_data(latest, missing, critical, updated_at)
DiscourseUpdates.stubs(:latest_version).returns(latest) Discourse.redis.set(latest_version_key, latest)
DiscourseUpdates.stubs(:missing_versions_count).returns(missing) Discourse.redis.set(missing_versions_count_key, missing)
DiscourseUpdates.stubs(:critical_updates_available?).returns(critical) Discourse.redis.set(critical_updates_available_key, critical)
DiscourseUpdates.stubs(:updated_at).returns(updated_at) Discourse.redis.set(updated_at_key, updated_at)
end end
before do before do
@ -36,7 +40,7 @@ describe DiscourseUpdates do
end end
it 'returns the timestamp of the last version check' do it 'returns the timestamp of the last version check' do
expect(subject.updated_at).to eq_time(time) expect(subject.updated_at).to be_within_one_second_of(time)
end end
end end
@ -52,7 +56,7 @@ describe DiscourseUpdates do
end end
it 'returns the timestamp of the last version check' do it 'returns the timestamp of the last version check' do
expect(subject.updated_at).to eq_time(time) expect(subject.updated_at).to be_within_one_second_of(time)
end end
end end
end end

View File

@ -191,19 +191,13 @@ describe TopicEmbed do
describe '.find_remote' do describe '.find_remote' do
fab!(:embeddable_host) { Fabricate(:embeddable_host) } fab!(:embeddable_host) { Fabricate(:embeddable_host) }
let(:file) { StringIO.new }
before do
TopicEmbed.stubs(:open).returns file
end
context ".title_scrub" do context ".title_scrub" do
let(:url) { 'http://eviltrout.com/123' } let(:url) { 'http://eviltrout.com/123' }
let(:contents) { "<title>Through the Looking Glass - Classic Books</title><body>some content here</body>" } let(:contents) { "<title>Through the Looking Glass - Classic Books</title><body>some content here</body>" }
before do before do
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
stub_request(:get, url)
end end
it "doesn't scrub the title by default" do it "doesn't scrub the title by default" do
@ -225,8 +219,7 @@ describe TopicEmbed do
before do before do
SiteSetting.allowed_embed_classnames = 'emoji, foo' SiteSetting.allowed_embed_classnames = 'emoji, foo'
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
stub_request(:get, url)
@response = TopicEmbed.find_remote(url) @response = TopicEmbed.find_remote(url)
end end
@ -257,9 +250,7 @@ describe TopicEmbed do
let(:contents) { '<html><head><meta name="author" content="eviltrout"></head><body>rich and morty</body></html>' } let(:contents) { '<html><head><meta name="author" content="eviltrout"></head><body>rich and morty</body></html>' }
before(:each) do before(:each) do
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
TopicEmbed.stubs(:open).returns file
stub_request(:get, url)
end end
it "has no author tag" do it "has no author tag" do
@ -276,8 +267,7 @@ describe TopicEmbed do
before(:each) do before(:each) do
SiteSetting.allowed_embed_classnames = '' SiteSetting.allowed_embed_classnames = ''
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
stub_request(:get, url)
@response = TopicEmbed.find_remote(url) @response = TopicEmbed.find_remote(url)
end end
@ -303,8 +293,7 @@ describe TopicEmbed do
let(:contents) { "<title>سلام</title><body>این یک پاراگراف آزمون است.</body>" } let(:contents) { "<title>سلام</title><body>این یک پاراگراف آزمون است.</body>" }
before do before do
stub_request(:get, url) stub_request(:get, url).to_return(status: 200, body: contents)
file.stubs(:read).returns contents
end end
it "doesn't throw an error" do it "doesn't throw an error" do
@ -318,8 +307,7 @@ describe TopicEmbed do
let(:contents) { "<title>Hello World!</title><body></body>" } let(:contents) { "<title>Hello World!</title><body></body>" }
before do before do
stub_request(:get, url) stub_request(:get, url).to_return(status: 200, body: contents)
file.stubs(:read).returns contents
end end
it "doesn't throw an error" do it "doesn't throw an error" do
@ -341,8 +329,7 @@ describe TopicEmbed do
let(:contents) { '<p><a href="mailto:foo%40example.com">URL encoded @ symbol</a></p><p><a href="mailto:bar@example.com">normal mailto link</a></p>' } let(:contents) { '<p><a href="mailto:foo%40example.com">URL encoded @ symbol</a></p><p><a href="mailto:bar@example.com">normal mailto link</a></p>' }
before do before do
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
stub_request(:get, url)
end end
it "handles mailto links" do it "handles mailto links" do
@ -358,8 +345,7 @@ describe TopicEmbed do
let(:contents) { '<p><a href="(http://foo.bar)">Baz</a></p>' } let(:contents) { '<p><a href="(http://foo.bar)">Baz</a></p>' }
before do before do
file.stubs(:read).returns contents stub_request(:get, url).to_return(status: 200, body: contents)
stub_request(:get, url)
end end
it "doesnt raise an exception" do it "doesnt raise an exception" do
@ -374,9 +360,9 @@ describe TopicEmbed do
let(:canonical_content) { "<title>Canonical</title><body></body>" } let(:canonical_content) { "<title>Canonical</title><body></body>" }
before do before do
file.stubs(:read).returns canonical_content stub_request(:get, url).to_return(status: 200, body: content)
stub_request(:get, url)
stub_request(:head, canonical_url) stub_request(:head, canonical_url)
stub_request(:get, canonical_url).to_return(status: 200, body: canonical_content)
end end
it 'a' do it 'a' do

View File

@ -7,7 +7,7 @@ RSpec.describe UploadSerializer do
let(:subject) { UploadSerializer.new(upload, root: false) } let(:subject) { UploadSerializer.new(upload, root: false) }
it 'should render without errors' do it 'should render without errors' do
json_data = JSON.load(subject.to_json) json_data = JSON.parse(subject.to_json)
expect(json_data['id']).to eql upload.id expect(json_data['id']).to eql upload.id
expect(json_data['width']).to eql upload.width expect(json_data['width']).to eql upload.width