DEV: Fix methods removed in Ruby 3.2 (#15459)

* File.exists? is deprecated and removed in Ruby 3.2 in favor of
File.exist?
* Dir.exists? is deprecated and removed in Ruby 3.2 in favor of
Dir.exist?
This commit is contained in:
Peter Zhu 2022-01-05 12:45:08 -05:00 committed by GitHub
parent 692ba188bf
commit c5fd8c42db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
75 changed files with 140 additions and 140 deletions

View File

@ -124,7 +124,7 @@ class UserAvatarsController < ApplicationController
elsif upload && optimized = get_optimized_image(upload, size) elsif upload && optimized = get_optimized_image(upload, size)
if optimized.local? if optimized.local?
optimized_path = Discourse.store.path_for(optimized) optimized_path = Discourse.store.path_for(optimized)
image = optimized_path if File.exists?(optimized_path) image = optimized_path if File.exist?(optimized_path)
else else
return proxy_avatar(Discourse.store.cdn_url(optimized.url), upload.created_at) return proxy_avatar(Discourse.store.cdn_url(optimized.url), upload.created_at)
end end

View File

@ -56,7 +56,7 @@ module Jobs
dirname = "#{UserExport.base_directory}/#{filename}" dirname = "#{UserExport.base_directory}/#{filename}"
# ensure directory exists # ensure directory exists
FileUtils.mkdir_p(dirname) unless Dir.exists?(dirname) FileUtils.mkdir_p(dirname) unless Dir.exist?(dirname)
# Generate a compressed CSV file # Generate a compressed CSV file
begin begin

View File

@ -70,7 +70,7 @@ module Jobs
dirname = "#{UserExport.base_directory}/#{filename}" dirname = "#{UserExport.base_directory}/#{filename}"
# ensure directory exists # ensure directory exists
FileUtils.mkdir_p(dirname) unless Dir.exists?(dirname) FileUtils.mkdir_p(dirname) unless Dir.exist?(dirname)
# Generate a compressed CSV file # Generate a compressed CSV file
zip_filename = nil zip_filename = nil

View File

@ -267,7 +267,7 @@ class GlobalSetting
class FileProvider < BaseProvider class FileProvider < BaseProvider
attr_reader :data attr_reader :data
def self.from(file) def self.from(file)
if File.exists?(file) if File.exist?(file)
parse(file) parse(file)
end end
end end

View File

@ -21,7 +21,7 @@ class HandleChunkUpload
def check_chunk def check_chunk
# check whether the chunk has already been uploaded # check whether the chunk has already been uploaded
has_chunk_been_uploaded = File.exists?(@chunk) && File.size(@chunk) == @params[:current_chunk_size] has_chunk_been_uploaded = File.exist?(@chunk) && File.size(@chunk) == @params[:current_chunk_size]
# 200 = exists, 404 = not uploaded yet # 200 = exists, 404 = not uploaded yet
status = has_chunk_been_uploaded ? 200 : 404 status = has_chunk_been_uploaded ? 200 : 404
end end
@ -30,7 +30,7 @@ class HandleChunkUpload
# path to chunk file # path to chunk file
dir = File.dirname(@chunk) dir = File.dirname(@chunk)
# ensure directory exists # ensure directory exists
FileUtils.mkdir_p(dir) unless Dir.exists?(dir) FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
# save chunk to the directory # save chunk to the directory
File.open(@chunk, "wb") { |f| f.write(@params[:file].tempfile.read) } File.open(@chunk, "wb") { |f| f.write(@params[:file].tempfile.read) }
end end

View File

@ -26,7 +26,7 @@ def ensure_cache_clean!
super_sha = Digest::SHA1.hexdigest(core_git_sha + plugins_combined_git_sha) super_sha = Digest::SHA1.hexdigest(core_git_sha + plugins_combined_git_sha)
hash_file = "#{RAILS_ROOT}/tmp/plugin-hash" hash_file = "#{RAILS_ROOT}/tmp/plugin-hash"
old_hash = File.exists?(hash_file) ? File.read(hash_file) : nil old_hash = File.exist?(hash_file) ? File.read(hash_file) : nil
if old_hash && old_hash != super_sha if old_hash && old_hash != super_sha
puts "WARNING: It looks like your discourse plugins or core version have recently changed." puts "WARNING: It looks like your discourse plugins or core version have recently changed."

View File

@ -10,7 +10,7 @@ require 'rubygems'
# Set up gems listed in the Gemfile. # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
if (ENV['DISABLE_BOOTSNAP'] != '1') if (ENV['DISABLE_BOOTSNAP'] != '1')
begin begin

View File

@ -14,7 +14,7 @@
Thread.new do Thread.new do
file = "#{Rails.root}/tmp/restart" file = "#{Rails.root}/tmp/restart"
old_time = File.ctime(file).to_i if File.exists? file old_time = File.ctime(file).to_i if File.exist? file
wait_seconds = 4 wait_seconds = 4
if Rails.env.development? && $PROGRAM_NAME =~ /puma/ if Rails.env.development? && $PROGRAM_NAME =~ /puma/
@ -25,7 +25,7 @@ Thread.new do
begin begin
listener = Listen.to("#{Rails.root}/tmp", only: /restart/) do listener = Listen.to("#{Rails.root}/tmp", only: /restart/) do
time = File.ctime(file).to_i if File.exists? file time = File.ctime(file).to_i if File.exist? file
if old_time != time if old_time != time
Rails.logger.info "attempting to reload #{$$} #{$PROGRAM_NAME} in #{wait_seconds} seconds" Rails.logger.info "attempting to reload #{$$} #{$PROGRAM_NAME} in #{wait_seconds} seconds"

View File

@ -71,7 +71,7 @@ before_fork do |server, worker|
if supervisor > 0 if supervisor > 0
Thread.new do Thread.new do
while true while true
unless File.exists?("/proc/#{supervisor}") unless File.exist?("/proc/#{supervisor}")
puts "Kill self supervisor is gone" puts "Kill self supervisor is gone"
Process.kill "TERM", Process.pid Process.kill "TERM", Process.pid
end end

View File

@ -13,8 +13,8 @@ class Autospec::Formatter < RSpec::Core::Formatters::BaseTextFormatter
def initialize(output) def initialize(output)
super super
FileUtils.mkdir_p("tmp") unless Dir.exists?("tmp") FileUtils.mkdir_p("tmp") unless Dir.exist?("tmp")
File.delete(RSPEC_RESULT) if File.exists?(RSPEC_RESULT) File.delete(RSPEC_RESULT) if File.exist?(RSPEC_RESULT)
@fail_file = File.open(RSPEC_RESULT, "w") @fail_file = File.open(RSPEC_RESULT, "w")
end end

View File

@ -295,7 +295,7 @@ class Autospec::Manager
if spec == file && line if spec == file && line
with_line = spec + ":" << line.to_s with_line = spec + ":" << line.to_s
end end
if File.exists?(spec) || Dir.exists?(spec) if File.exist?(spec) || Dir.exist?(spec)
if with_line != spec if with_line != spec
specs << [file, spec, runner] specs << [file, spec, runner]
end end

View File

@ -152,7 +152,7 @@ module Autospec
def try_to_find_module_name(file) def try_to_find_module_name(file)
file, _ = file.split(/:\d+$/) file, _ = file.split(/:\d+$/)
return unless File.exists?(file) return unless File.exist?(file)
File.open(file, "r").each_line do |line| File.open(file, "r").each_line do |line|
if m = /module\(['"]([^'"]+)/i.match(line) if m = /module\(['"]([^'"]+)/i.match(line)
return m[1] return m[1]

View File

@ -40,7 +40,7 @@ class Autospec::ReloadCss
paths.map! do |p| paths.map! do |p|
hash = nil hash = nil
fullpath = "#{Rails.root}/#{p}" fullpath = "#{Rails.root}/#{p}"
hash = Digest::MD5.hexdigest(File.read(fullpath)) if File.exists?(fullpath) hash = Digest::MD5.hexdigest(File.read(fullpath)) if File.exist?(fullpath)
p = p.sub(/\.sass\.erb/, "") p = p.sub(/\.sass\.erb/, "")
p = p.sub(/\.sass/, "") p = p.sub(/\.sass/, "")
p = p.sub(/\.scss/, "") p = p.sub(/\.scss/, "")

View File

@ -86,7 +86,7 @@ module BackupRestore
if @is_archive if @is_archive
# for compatibility with backups from Discourse v1.5 and below # for compatibility with backups from Discourse v1.5 and below
old_dump_path = File.join(@tmp_directory, OLD_DUMP_FILENAME) old_dump_path = File.join(@tmp_directory, OLD_DUMP_FILENAME)
File.exists?(old_dump_path) ? old_dump_path : File.join(@tmp_directory, BackupRestore::DUMP_FILE) File.exist?(old_dump_path) ? old_dump_path : File.join(@tmp_directory, BackupRestore::DUMP_FILE)
else else
File.join(@tmp_directory, @filename) File.join(@tmp_directory, @filename)
end end

View File

@ -7,7 +7,7 @@ module BackupRestore
root_directory ||= File.join(Rails.root, "public", "backups") root_directory ||= File.join(Rails.root, "public", "backups")
base_directory = File.join(root_directory, current_db) base_directory = File.join(root_directory, current_db)
FileUtils.mkdir_p(base_directory) unless Dir.exists?(base_directory) FileUtils.mkdir_p(base_directory) unless Dir.exist?(base_directory)
base_directory base_directory
end end
@ -25,13 +25,13 @@ module BackupRestore
def file(filename, include_download_source: false) def file(filename, include_download_source: false)
path = path_from_filename(filename) path = path_from_filename(filename)
create_file_from_path(path, include_download_source) if File.exists?(path) create_file_from_path(path, include_download_source) if File.exist?(path)
end end
def delete_file(filename) def delete_file(filename)
path = path_from_filename(filename) path = path_from_filename(filename)
if File.exists?(path) if File.exist?(path)
File.delete(path) File.delete(path)
reset_cache reset_cache
end end

View File

@ -42,7 +42,7 @@ module BackupRestore
def extract_metadata def extract_metadata
metadata_path = File.join(@tmp_directory, METADATA_FILE) if @tmp_directory.present? metadata_path = File.join(@tmp_directory, METADATA_FILE) if @tmp_directory.present?
if metadata_path.present? && File.exists?(metadata_path) if metadata_path.present? && File.exist?(metadata_path)
metadata = load_metadata_file(metadata_path) metadata = load_metadata_file(metadata_path)
elsif @filename =~ /-#{BackupRestore::VERSION_PREFIX}(\d{14})/ elsif @filename =~ /-#{BackupRestore::VERSION_PREFIX}(\d{14})/
metadata = { version: Regexp.last_match[1].to_i } metadata = { version: Regexp.last_match[1].to_i }

View File

@ -151,7 +151,7 @@ class Demon::Base
end end
def already_running? def already_running?
if File.exists? pid_file if File.exist? pid_file
pid = File.read(pid_file).to_i pid = File.read(pid_file).to_i
if Demon::Base.alive?(pid) if Demon::Base.alive?(pid)
return pid return pid

View File

@ -12,7 +12,7 @@ module DiscourseDev
@file_path = File.join(Rails.root, "config", "dev.yml") @file_path = File.join(Rails.root, "config", "dev.yml")
default_config = YAML.load_file(default_file_path) default_config = YAML.load_file(default_file_path)
if File.exists?(file_path) if File.exist?(file_path)
user_config = YAML.load_file(file_path) user_config = YAML.load_file(file_path)
else else
puts "I did no detect a custom `config/dev.yml` file, creating one for you where you can amend defaults." puts "I did no detect a custom `config/dev.yml` file, creating one for you where you can amend defaults."

View File

@ -72,7 +72,7 @@ module Faker
def load_image(image) def load_image(image)
cache_path = ::File.join(image_cache_dir, image[:filename]) cache_path = ::File.join(image_cache_dir, image[:filename])
if !::File.exists?(cache_path) if !::File.exist?(cache_path)
FileUtils.mkdir_p(image_cache_dir) FileUtils.mkdir_p(image_cache_dir)
temp_file = ::FileHelper.download( temp_file = ::FileHelper.download(
image[:url], image[:url],

View File

@ -173,7 +173,7 @@ module FileStore
def get_from_cache(filename) def get_from_cache(filename)
path = get_cache_path_for(filename) path = get_cache_path_for(filename)
File.open(path) if File.exists?(path) File.open(path) if File.exist?(path)
end end
def cache_file(file, filename) def cache_file(file, filename)

View File

@ -14,11 +14,11 @@ module FileStore
def remove_file(url, _) def remove_file(url, _)
return unless is_relative?(url) return unless is_relative?(url)
source = "#{public_dir}#{url}" source = "#{public_dir}#{url}"
return unless File.exists?(source) return unless File.exist?(source)
destination = "#{public_dir}#{url.sub("/uploads/", "/uploads/tombstone/")}" destination = "#{public_dir}#{url.sub("/uploads/", "/uploads/tombstone/")}"
dir = Pathname.new(destination).dirname dir = Pathname.new(destination).dirname
FileUtils.mkdir_p(dir) unless Dir.exists?(dir) FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
FileUtils.remove(destination) if File.exists?(destination) FileUtils.remove(destination) if File.exist?(destination)
FileUtils.move(source, destination, force: true) FileUtils.move(source, destination, force: true)
FileUtils.touch(destination) FileUtils.touch(destination)
end end
@ -62,7 +62,7 @@ module FileStore
end end
def purge_tombstone(grace_period) def purge_tombstone(grace_period)
if Dir.exists?(Discourse.store.tombstone_dir) if Dir.exist?(Discourse.store.tombstone_dir)
Discourse::Utils.execute_command( Discourse::Utils.execute_command(
'find', tombstone_dir, '-mtime', "+#{grace_period}", '-type', 'f', '-delete' 'find', tombstone_dir, '-mtime', "+#{grace_period}", '-type', 'f', '-delete'
) )
@ -75,7 +75,7 @@ module FileStore
def copy_file(file, path) def copy_file(file, path)
dir = Pathname.new(path).dirname dir = Pathname.new(path).dirname
FileUtils.mkdir_p(dir) unless Dir.exists?(dir) FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
# move the file to the right location # move the file to the right location
# not using mv, cause permissions are no good on move # not using mv, cause permissions are no good on move
File.open(path, "wb") { |f| f.write(file.read) } File.open(path, "wb") { |f| f.write(file.read) }

View File

@ -49,7 +49,7 @@ class LocaleFileChecker
def reference_file(path) def reference_file(path)
path = path.gsub(/\.\w{2,}\.yml$/, ".#{REFERENCE_LOCALE}.yml") path = path.gsub(/\.\w{2,}\.yml$/, ".#{REFERENCE_LOCALE}.yml")
path if File.exists?(path) path if File.exist?(path)
end end
def traverse_hash(hash, parent_keys, &block) def traverse_hash(hash, parent_keys, &block)

View File

@ -42,10 +42,10 @@ class LetterAvatar
size = FULLSIZE if size > FULLSIZE size = FULLSIZE if size > FULLSIZE
filename = cached_path(identity, size) filename = cached_path(identity, size)
return filename if cache && File.exists?(filename) return filename if cache && File.exist?(filename)
fullsize = fullsize_path(identity) fullsize = fullsize_path(identity)
generate_fullsize(identity) if !cache || !File.exists?(fullsize) generate_fullsize(identity) if !cache || !File.exist?(fullsize)
# Optimizing here is dubious, it can save up to 2x for large images (eg 359px) # Optimizing here is dubious, it can save up to 2x for large images (eg 359px)
# BUT... we are talking 2400 bytes down to 1200 bytes, both fit in one packet # BUT... we are talking 2400 bytes down to 1200 bytes, both fit in one packet

View File

@ -424,7 +424,7 @@ class Plugin::Instance
end end
def delete_extra_automatic_assets(good_paths) def delete_extra_automatic_assets(good_paths)
return unless Dir.exists? auto_generated_path return unless Dir.exist? auto_generated_path
filenames = good_paths.map { |f| File.basename(f) } filenames = good_paths.map { |f| File.basename(f) }
# nuke old files # nuke old files
@ -701,7 +701,7 @@ class Plugin::Instance
end end
public_data = File.dirname(path) + "/public" public_data = File.dirname(path) + "/public"
if Dir.exists?(public_data) if Dir.exist?(public_data)
target = Rails.root.to_s + "/public/plugins/" target = Rails.root.to_s + "/public/plugins/"
Discourse::Utils.execute_command('mkdir', '-p', target) Discourse::Utils.execute_command('mkdir', '-p', target)
@ -839,7 +839,7 @@ class Plugin::Instance
end end
def js_asset_exists? def js_asset_exists?
File.exists?(js_file_path) File.exist?(js_file_path)
end end
# Receives an array with two elements: # Receives an array with two elements:
@ -1085,7 +1085,7 @@ class Plugin::Instance
end end
def write_asset(path, contents) def write_asset(path, contents)
unless File.exists?(path) unless File.exist?(path)
ensure_directory(path) ensure_directory(path)
File.open(path, "w") { |f| f.write(contents) } File.open(path, "w") { |f| f.write(contents) }
end end

View File

@ -12,14 +12,14 @@ module PluginGem
spec_file += "-#{opts[:platform]}" if opts[:platform] spec_file += "-#{opts[:platform]}" if opts[:platform]
spec_file += ".gemspec" spec_file += ".gemspec"
unless File.exists? spec_file unless File.exist? spec_file
command = "gem install #{name} -v #{version} -i #{gems_path} --no-document --ignore-dependencies --no-user-install" command = "gem install #{name} -v #{version} -i #{gems_path} --no-document --ignore-dependencies --no-user-install"
command += " --source #{opts[:source]}" if opts[:source] command += " --source #{opts[:source]}" if opts[:source]
puts command puts command
puts `#{command}` puts `#{command}`
end end
if File.exists? spec_file if File.exist? spec_file
Gem.path << gems_path Gem.path << gems_path
Gem::Specification.load(spec_file).activate Gem::Specification.load(spec_file).activate

View File

@ -140,7 +140,7 @@ class S3Inventory
end end
def download_inventory_file_to_tmp_directory(file) def download_inventory_file_to_tmp_directory(file)
return if File.exists?(file[:filename]) return if File.exist?(file[:filename])
log "Downloading inventory file '#{file[:key]}' to tmp directory..." log "Downloading inventory file '#{file[:key]}' to tmp directory..."
failure_message = "Failed to inventory file '#{file[:key]}' to tmp directory." failure_message = "Failed to inventory file '#{file[:key]}' to tmp directory."
@ -219,8 +219,8 @@ class S3Inventory
def cleanup! def cleanup!
return if @preloaded_inventory_file return if @preloaded_inventory_file
files.each do |file| files.each do |file|
File.delete(file[:filename]) if File.exists?(file[:filename]) File.delete(file[:filename]) if File.exist?(file[:filename])
File.delete(file[:filename][0...-3]) if File.exists?(file[:filename][0...-3]) File.delete(file[:filename][0...-3]) if File.exist?(file[:filename][0...-3])
end end
end end
@ -253,7 +253,7 @@ class S3Inventory
def download_and_decompress_files def download_and_decompress_files
files.each do |file| files.each do |file|
next if File.exists?(file[:filename][0...-3]) next if File.exist?(file[:filename][0...-3])
download_inventory_file_to_tmp_directory(file) download_inventory_file_to_tmp_directory(file)
decompress_inventory_file(file) decompress_inventory_file(file)

View File

@ -107,7 +107,7 @@ class Stylesheet::Manager
def self.last_file_updated def self.last_file_updated
if Rails.env.production? if Rails.env.production?
@last_file_updated ||= if File.exists?(MANIFEST_FULL_PATH) @last_file_updated ||= if File.exist?(MANIFEST_FULL_PATH)
File.readlines(MANIFEST_FULL_PATH, 'r')[0] File.readlines(MANIFEST_FULL_PATH, 'r')[0]
else else
mtime = max_file_mtime mtime = max_file_mtime
@ -224,7 +224,7 @@ class Stylesheet::Manager
builder = Builder.new(target: target, theme: theme, manager: self) builder = Builder.new(target: target, theme: theme, manager: self)
next if builder.theme&.component && !scss_checker.has_scss(theme_id) next if builder.theme&.component && !scss_checker.has_scss(theme_id)
builder.compile unless File.exists?(builder.stylesheet_fullpath) builder.compile unless File.exist?(builder.stylesheet_fullpath)
href = builder.stylesheet_path(current_hostname) href = builder.stylesheet_path(current_hostname)
data[:new_href] = href data[:new_href] = href
@ -242,7 +242,7 @@ class Stylesheet::Manager
end end
else else
builder = Builder.new(target: target, manager: self) builder = Builder.new(target: target, manager: self)
builder.compile unless File.exists?(builder.stylesheet_fullpath) builder.compile unless File.exist?(builder.stylesheet_fullpath)
href = builder.stylesheet_path(current_hostname) href = builder.stylesheet_path(current_hostname)
data = { target: target, new_href: href } data = { target: target, new_href: href }
@ -285,7 +285,7 @@ class Stylesheet::Manager
manager: self manager: self
) )
builder.compile unless File.exists?(builder.stylesheet_fullpath) builder.compile unless File.exist?(builder.stylesheet_fullpath)
href = builder.stylesheet_path(current_hostname) href = builder.stylesheet_path(current_hostname)
stylesheet[:new_href] = href stylesheet[:new_href] = href

View File

@ -12,7 +12,7 @@ class Stylesheet::Manager::Builder
def compile(opts = {}) def compile(opts = {})
if !opts[:force] if !opts[:force]
if File.exists?(stylesheet_fullpath) if File.exist?(stylesheet_fullpath)
unless StylesheetCache.where(target: qualified_target, digest: digest).exists? unless StylesheetCache.where(target: qualified_target, digest: digest).exists?
begin begin
source_map = begin source_map = begin

View File

@ -260,7 +260,7 @@ def copy_ember_cli_assets
dest_sub = "#{dest}/#{Regexp.last_match[1]}" dest_sub = "#{dest}/#{Regexp.last_match[1]}"
end end
FileUtils.mkdir_p(dest_sub) unless Dir.exists?(dest_sub) FileUtils.mkdir_p(dest_sub) unless Dir.exist?(dest_sub)
log_file = File.basename(rel_file).sub("-#{digest}", "") log_file = File.basename(rel_file).sub("-#{digest}", "")
# It's simpler to serve the file as `application.js` # It's simpler to serve the file as `application.js`
@ -362,7 +362,7 @@ task 'assets:precompile' => 'assets:precompile:before' do
_file = (d = File.dirname(file)) == "." ? "_#{file}" : "#{d}/_#{File.basename(file)}" _file = (d = File.dirname(file)) == "." ? "_#{file}" : "#{d}/_#{File.basename(file)}"
_path = "#{assets_path}/#{_file}" _path = "#{assets_path}/#{_file}"
max_compress = max_compress?(info["logical_path"], locales) max_compress = max_compress?(info["logical_path"], locales)
if File.exists?(_path) if File.exist?(_path)
STDERR.puts "Skipping: #{file} already compressed" STDERR.puts "Skipping: #{file} already compressed"
elsif file.include? "discourse/tests" elsif file.include? "discourse/tests"
STDERR.puts "Skipping: #{file}" STDERR.puts "Skipping: #{file}"

View File

@ -511,12 +511,12 @@ class TestEmojiUpdate < MiniTest::Test
end end
def test_groups_js_es6_creation def test_groups_js_es6_creation
assert File.exists?(EMOJI_GROUPS_PATH) assert File.exist?(EMOJI_GROUPS_PATH)
assert File.size?(EMOJI_GROUPS_PATH) assert File.size?(EMOJI_GROUPS_PATH)
end end
def test_db_json_creation def test_db_json_creation
assert File.exists?(EMOJI_DB_PATH) assert File.exist?(EMOJI_DB_PATH)
assert File.size?(EMOJI_DB_PATH) assert File.size?(EMOJI_DB_PATH)
end end
@ -536,12 +536,12 @@ class TestEmojiUpdate < MiniTest::Test
def test_scales def test_scales
original_image = image_path("apple", "blonde_woman") original_image = image_path("apple", "blonde_woman")
assert File.exists?(original_image) assert File.exist?(original_image)
assert File.size?(original_image) assert File.size?(original_image)
(2..6).each do |scale| (2..6).each do |scale|
image = image_path("apple", "blonde_woman/#{scale}") image = image_path("apple", "blonde_woman/#{scale}")
assert File.exists?(image) assert File.exist?(image)
assert File.size?(image) assert File.size?(image)
end end
end end

View File

@ -307,7 +307,7 @@ task 'javascript:update' => 'clean_up' do
path = "#{public_js}/#{package_dir_name}/#{package_version}" path = "#{public_js}/#{package_dir_name}/#{package_version}"
dest = "#{path}/#{filename}" dest = "#{path}/#{filename}"
FileUtils.mkdir_p(path) unless File.exists?(path) FileUtils.mkdir_p(path) unless File.exist?(path)
end end
else else
dest = "#{vendor_js}/#{filename}" dest = "#{vendor_js}/#{filename}"
@ -336,7 +336,7 @@ task 'javascript:update' => 'clean_up' do
system("yarn run browserify #{vendor_js}/custom-uppy.js -o node_modules/custom-uppy-build.js") system("yarn run browserify #{vendor_js}/custom-uppy.js -o node_modules/custom-uppy-build.js")
end end
unless File.exists?(dest) unless File.exist?(dest)
STDERR.puts "New dependency added: #{dest}" STDERR.puts "New dependency added: #{dest}"
end end

View File

@ -37,7 +37,7 @@ task "release_note:plugins:generate", :from, :to, :plugin_glob, :org do |t, args
plugin_glob = args[:plugin_glob] || "./plugins/*" plugin_glob = args[:plugin_glob] || "./plugins/*"
git_org = args[:org] git_org = args[:org]
all_repos = Dir.glob(plugin_glob).filter { |f| File.directory?(f) && File.exists?("#{f}/.git") } all_repos = Dir.glob(plugin_glob).filter { |f| File.directory?(f) && File.exist?("#{f}/.git") }
if git_org if git_org
all_repos = all_repos.filter { |dir| `git -C #{dir} remote get-url origin`.match?(/github.com[\/:]#{git_org}\//) } all_repos = all_repos.filter { |dir| `git -C #{dir} remote get-url origin`.match?(/github.com[\/:]#{git_org}\//) }

View File

@ -38,7 +38,7 @@ def upload(path, remote_path, content_type, content_encoding = nil)
end end
end end
File.delete(path) if (File.exists?(path) && ENV["DELETE_ASSETS_AFTER_S3_UPLOAD"]) File.delete(path) if (File.exist?(path) && ENV["DELETE_ASSETS_AFTER_S3_UPLOAD"])
end end
def use_db_s3_config def use_db_s3_config

View File

@ -97,7 +97,7 @@ task 'site:export_structure', [:zip_path] => :environment do |task, args|
if args[:zip_path].blank? if args[:zip_path].blank?
STDERR.puts "ERROR: rake site:export_structure[<path to ZIP file>]" STDERR.puts "ERROR: rake site:export_structure[<path to ZIP file>]"
exit 1 exit 1
elsif File.exists?(args[:zip_path]) elsif File.exist?(args[:zip_path])
STDERR.puts "ERROR: File '#{args[:zip_path]}' already exists" STDERR.puts "ERROR: File '#{args[:zip_path]}' already exists"
exit 2 exit 2
end end
@ -328,7 +328,7 @@ task 'site:import_structure', [:zip_path] => :environment do |task, args|
if args[:zip_path].blank? if args[:zip_path].blank?
STDERR.puts "ERROR: rake site:import_structure[<path to ZIP file>]" STDERR.puts "ERROR: rake site:import_structure[<path to ZIP file>]"
exit 1 exit 1
elsif !File.exists?(args[:zip_path]) elsif !File.exist?(args[:zip_path])
STDERR.puts "ERROR: File '#{args[:zip_path]}' does not exist" STDERR.puts "ERROR: File '#{args[:zip_path]}' does not exist"
exit 2 exit 2
end end

View File

@ -31,7 +31,7 @@ task "smoke:test" do
end end
dir = ENV["SMOKE_TEST_SCREENSHOT_PATH"] || 'tmp/smoke-test-screenshots' dir = ENV["SMOKE_TEST_SCREENSHOT_PATH"] || 'tmp/smoke-test-screenshots'
FileUtils.mkdir_p(dir) unless Dir.exists?(dir) FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
wait = ENV["WAIT_FOR_URL"].to_i wait = ENV["WAIT_FOR_URL"].to_i

View File

@ -19,7 +19,7 @@ def gather_uploads_for_all_sites
end end
def file_exists?(path) def file_exists?(path)
File.exists?(path) && File.size(path) > 0 File.exist?(path) && File.size(path) > 0
rescue rescue
false false
end end
@ -188,7 +188,7 @@ def clean_up_uploads
Upload.find_each do |upload| Upload.find_each do |upload|
path = File.join(public_directory, upload.url) path = File.join(public_directory, upload.url)
if !File.exists?(path) if !File.exist?(path)
upload.destroy! upload.destroy!
putc "#" putc "#"
else else
@ -200,7 +200,7 @@ def clean_up_uploads
OptimizedImage.find_each do |optimized_image| OptimizedImage.find_each do |optimized_image|
path = File.join(public_directory, optimized_image.url) path = File.join(public_directory, optimized_image.url)
if !File.exists?(path) if !File.exist?(path)
optimized_image.destroy! optimized_image.destroy!
putc "#" putc "#"
else else
@ -326,9 +326,9 @@ def regenerate_missing_optimized
thumbnail = "#{public_directory}#{optimized_image.url}" thumbnail = "#{public_directory}#{optimized_image.url}"
original = "#{public_directory}#{upload.url}" original = "#{public_directory}#{upload.url}"
if !File.exists?(thumbnail) || File.size(thumbnail) <= 0 if !File.exist?(thumbnail) || File.size(thumbnail) <= 0
# make sure the original image exists locally # make sure the original image exists locally
if (!File.exists?(original) || File.size(original) <= 0) && upload.origin.present? if (!File.exist?(original) || File.size(original) <= 0) && upload.origin.present?
# try to fix it by redownloading it # try to fix it by redownloading it
begin begin
downloaded = FileHelper.download( downloaded = FileHelper.download(
@ -346,7 +346,7 @@ def regenerate_missing_optimized
end end
end end
if File.exists?(original) && File.size(original) > 0 if File.exist?(original) && File.size(original) > 0
FileUtils.mkdir_p(File.dirname(thumbnail)) FileUtils.mkdir_p(File.dirname(thumbnail))
OptimizedImage.resize(original, thumbnail, optimized_image.width, optimized_image.height) OptimizedImage.resize(original, thumbnail, optimized_image.width, optimized_image.height)
putc "#" putc "#"

View File

@ -24,7 +24,7 @@ class TemporaryDb
end end
if !@pg_bin_path if !@pg_bin_path
bin_path = "/Applications/Postgres.app/Contents/Versions/latest/bin" bin_path = "/Applications/Postgres.app/Contents/Versions/latest/bin"
if File.exists?("#{bin_path}/pg_ctl") if File.exist?("#{bin_path}/pg_ctl")
@pg_bin_path = bin_path @pg_bin_path = bin_path
end end
end end

View File

@ -112,7 +112,7 @@ unless $? == 0
abort "Apache Bench is not installed. Try: apt-get install apache2-utils or brew install ab" abort "Apache Bench is not installed. Try: apt-get install apache2-utils or brew install ab"
end end
unless File.exists?("config/database.yml") unless File.exist?("config/database.yml")
puts "Copying database.yml.development.sample to database.yml" puts "Copying database.yml.development.sample to database.yml"
`cp config/database.yml.development-sample config/database.yml` `cp config/database.yml.development-sample config/database.yml`
end end

View File

@ -359,7 +359,7 @@ class BulkImport::DiscourseMerger < BulkImport::Base
next if row['user_id'].nil? next if row['user_id'].nil?
end end
row['url'] = "/uploads/default/#{rel_filename}" if File.exists?(absolute_filename) row['url'] = "/uploads/default/#{rel_filename}" if File.exist?(absolute_filename)
@raw_connection.put_copy_data(row.values) @raw_connection.put_copy_data(row.values)
end end

View File

@ -203,7 +203,7 @@ class BulkImport::Vanilla < BulkImport::Base
end end
def import_avatars def import_avatars
if ATTACHMENTS_BASE_DIR && File.exists?(ATTACHMENTS_BASE_DIR) if ATTACHMENTS_BASE_DIR && File.exist?(ATTACHMENTS_BASE_DIR)
puts "", "importing user avatars" puts "", "importing user avatars"
start = Time.now start = Time.now
@ -237,7 +237,7 @@ class BulkImport::Vanilla < BulkImport::Base
next next
end end
if !File.exists?(photo_path) if !File.exist?(photo_path)
puts "Path to avatar file not found! Skipping. #{photo_path}" puts "Path to avatar file not found! Skipping. #{photo_path}"
next next
end end
@ -265,7 +265,7 @@ class BulkImport::Vanilla < BulkImport::Base
end end
def import_attachments def import_attachments
if ATTACHMENTS_BASE_DIR && File.exists?(ATTACHMENTS_BASE_DIR) if ATTACHMENTS_BASE_DIR && File.exist?(ATTACHMENTS_BASE_DIR)
puts "", "importing attachments" puts "", "importing attachments"
start = Time.now start = Time.now
@ -297,7 +297,7 @@ class BulkImport::Vanilla < BulkImport::Base
path.gsub!("s3://uploads/", "") path.gsub!("s3://uploads/", "")
file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}" file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"
if File.exists?(file_path) if File.exist?(file_path)
upload = create_upload(post.user.id, file_path, File.basename(file_path)) upload = create_upload(post.user.id, file_path, File.basename(file_path))
if upload && upload.errors.empty? if upload && upload.errors.empty?
# upload.url # upload.url
@ -318,7 +318,7 @@ class BulkImport::Vanilla < BulkImport::Base
file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}" file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"
if File.exists?(file_path) if File.exist?(file_path)
upload = create_upload(post.user.id, file_path, File.basename(file_path)) upload = create_upload(post.user.id, file_path, File.basename(file_path))
if upload && upload.errors.empty? if upload && upload.errors.empty?
upload.url upload.url
@ -348,13 +348,13 @@ class BulkImport::Vanilla < BulkImport::Base
base_guess = base_filename.dup base_guess = base_filename.dup
full_guess = File.join(path, base_guess) # often an exact match exists full_guess = File.join(path, base_guess) # often an exact match exists
return full_guess if File.exists?(full_guess) return full_guess if File.exist?(full_guess)
# Otherwise, the file exists but with a prefix: # Otherwise, the file exists but with a prefix:
# The p prefix seems to be the full file, so try to find that one first. # The p prefix seems to be the full file, so try to find that one first.
['p', 't', 'n'].each do |prefix| ['p', 't', 'n'].each do |prefix|
full_guess = File.join(path, "#{prefix}#{base_guess}") full_guess = File.join(path, "#{prefix}#{base_guess}")
return full_guess if File.exists?(full_guess) return full_guess if File.exist?(full_guess)
end end
# Didn't find it. # Didn't find it.

View File

@ -531,7 +531,7 @@ class BulkImport::VBulletin < BulkImport::Base
real_filename = db_filename real_filename = db_filename
real_filename.prepend SecureRandom.hex if real_filename[0] == '.' real_filename.prepend SecureRandom.hex if real_filename[0] == '.'
unless File.exists?(filename) unless File.exist?(filename)
puts "Attachment file #{row.inspect} doesn't exist" puts "Attachment file #{row.inspect} doesn't exist"
return nil return nil
end end
@ -601,7 +601,7 @@ class BulkImport::VBulletin < BulkImport::Base
end end
def import_avatars def import_avatars
if AVATAR_DIR && File.exists?(AVATAR_DIR) if AVATAR_DIR && File.exist?(AVATAR_DIR)
puts "", "importing user avatars" puts "", "importing user avatars"
RateLimiter.disable RateLimiter.disable
@ -620,7 +620,7 @@ class BulkImport::VBulletin < BulkImport::Base
# raise "User not found for id #{user_id}" if user.blank? # raise "User not found for id #{user_id}" if user.blank?
photo_real_filename = File.join(AVATAR_DIR, item) photo_real_filename = File.join(AVATAR_DIR, item)
puts "#{photo_real_filename} not found" unless File.exists?(photo_real_filename) puts "#{photo_real_filename} not found" unless File.exist?(photo_real_filename)
upload = create_upload(u.id, photo_real_filename, File.basename(photo_real_filename)) upload = create_upload(u.id, photo_real_filename, File.basename(photo_real_filename))
count += 1 count += 1

View File

@ -616,7 +616,7 @@ class BulkImport::VBulletin5 < BulkImport::Base
real_filename = db_filename real_filename = db_filename
real_filename.prepend SecureRandom.hex if real_filename[0] == '.' real_filename.prepend SecureRandom.hex if real_filename[0] == '.'
unless File.exists?(filename) unless File.exist?(filename)
filename = check_database_for_attachment(row) if filename.blank? filename = check_database_for_attachment(row) if filename.blank?
return nil if filename.nil? return nil if filename.nil?
end end

View File

@ -367,7 +367,7 @@ class ImportScripts::AnswerHub < ImportScripts::Base
if user if user
filename = "avatar-#{user_id}.png" filename = "avatar-#{user_id}.png"
path = File.join(AVATAR_DIR, filename) path = File.join(AVATAR_DIR, filename)
next if !File.exists?(path) next if !File.exist?(path)
# Scrape Avatars - Avatars are saved in the db, but it might be easier to just scrape them # Scrape Avatars - Avatars are saved in the db, but it might be easier to just scrape them
if SCRAPE_AVATARS == 1 if SCRAPE_AVATARS == 1
@ -403,7 +403,7 @@ class ImportScripts::AnswerHub < ImportScripts::Base
filepath = File.basename(image).split('"')[0] filepath = File.basename(image).split('"')[0]
filepath = File.join(ATTACHMENT_DIR, filepath) filepath = File.join(ATTACHMENT_DIR, filepath)
if File.exists?(filepath) if File.exist?(filepath)
filename = File.basename(filepath) filename = File.basename(filepath)
upload = create_upload(user_id, filepath, filename) upload = create_upload(user_id, filepath, filename)
image_html = html_for_upload(upload, filename) image_html = html_for_upload(upload, filename)
@ -421,7 +421,7 @@ class ImportScripts::AnswerHub < ImportScripts::Base
filepath = File.basename(file).split('"')[0] filepath = File.basename(file).split('"')[0]
filepath = File.join(ATTACHMENT_DIR, filepath) filepath = File.join(ATTACHMENT_DIR, filepath)
if File.exists?(filepath) if File.exist?(filepath)
filename = File.basename(filepath) filename = File.basename(filepath)
upload = create_upload(user_id, filepath, filename) upload = create_upload(user_id, filepath, filename)
file_html = html_for_upload(upload, filename) file_html = html_for_upload(upload, filename)

View File

@ -6,7 +6,7 @@ module ImportScripts
class GenericDatabase class GenericDatabase
def initialize(directory, batch_size:, recreate: false, numeric_keys: false) def initialize(directory, batch_size:, recreate: false, numeric_keys: false)
filename = "#{directory}/index.db" filename = "#{directory}/index.db"
File.delete(filename) if recreate && File.exists?(filename) File.delete(filename) if recreate && File.exist?(filename)
@db = SQLite3::Database.new(filename, results_as_hash: true) @db = SQLite3::Database.new(filename, results_as_hash: true)
@batch_size = batch_size @batch_size = batch_size

View File

@ -316,7 +316,7 @@ class ImportScripts::Bbpress < ImportScripts::Base
attachments.each do |a| attachments.each do |a|
print_status(count += 1, total_attachments, get_start_time("attachments_from_postmeta")) print_status(count += 1, total_attachments, get_start_time("attachments_from_postmeta"))
path = File.join(BB_PRESS_ATTACHMENTS_DIR, a["meta_value"]) path = File.join(BB_PRESS_ATTACHMENTS_DIR, a["meta_value"])
if File.exists?(path) if File.exist?(path)
if post = Post.find_by(id: post_id_from_imported_post_id(a["post_id"])) if post = Post.find_by(id: post_id_from_imported_post_id(a["post_id"]))
filename = File.basename(a["meta_value"]) filename = File.basename(a["meta_value"])
upload = create_upload(post.user.id, path, filename) upload = create_upload(post.user.id, path, filename)

View File

@ -927,7 +927,7 @@ class ImportScripts::DiscuzX < ImportScripts::Base
end end
filename = File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, row['attachment_path']) filename = File.join(DISCUZX_BASE_DIR, ATTACHMENT_DIR, row['attachment_path'])
unless File.exists?(filename) unless File.exist?(filename)
puts "Attachment file doesn't exist: #{filename}" puts "Attachment file doesn't exist: #{filename}"
return nil return nil
end end

View File

@ -428,7 +428,7 @@ class ImportScripts::Drupal < ImportScripts::Base
real_filename = CGI.unescapeHTML(uri) real_filename = CGI.unescapeHTML(uri)
file = File.join(ATTACHMENT_DIR, real_filename) file = File.join(ATTACHMENT_DIR, real_filename)
unless File.exists?(file) unless File.exist?(file)
puts "Attachment file #{attachment['filename']} doesn't exist" puts "Attachment file #{attachment['filename']} doesn't exist"
tmpfile = "attachments_failed.txt" tmpfile = "attachments_failed.txt"

View File

@ -23,7 +23,7 @@ class ImportScripts::DrupalJson < ImportScripts::Base
def load_json(arg) def load_json(arg)
filename = File.join(JSON_FILES_DIR, arg) filename = File.join(JSON_FILES_DIR, arg)
raise RuntimeError.new("File #{filename} not found!") if !File.exists?(filename) raise RuntimeError.new("File #{filename} not found!") if !File.exist?(filename)
JSON.parse(File.read(filename)).reverse JSON.parse(File.read(filename)).reverse
end end

View File

@ -178,7 +178,7 @@ class ImportScripts::FMGP < ImportScripts::Base
end end
def load_fmgp_json(filename) def load_fmgp_json(filename)
raise RuntimeError.new("File #{filename} not found") if !File.exists?(filename) raise RuntimeError.new("File #{filename} not found") if !File.exist?(filename)
JSON.parse(File.read(filename)) JSON.parse(File.read(filename))
end end

View File

@ -69,7 +69,7 @@ class ImportScripts::GetSatisfaction < ImportScripts::Base
def csv_filename(table_name, use_fixed: true) def csv_filename(table_name, use_fixed: true)
if use_fixed if use_fixed
filename = File.join(@path, "#{table_name}_fixed.csv") filename = File.join(@path, "#{table_name}_fixed.csv")
return filename if File.exists?(filename) return filename if File.exist?(filename)
end end
File.join(@path, "#{table_name}.csv") File.join(@path, "#{table_name}.csv")

View File

@ -223,7 +223,7 @@ def crawl
start_time = Time.now start_time = Time.now
status_filename = File.join(@path, "status.yml") status_filename = File.join(@path, "status.yml")
if File.exists?(status_filename) if File.exist?(status_filename)
yaml = YAML.load_file(status_filename) yaml = YAML.load_file(status_filename)
@finished = yaml[:finished] @finished = yaml[:finished]
@scraped_topic_urls = yaml[:urls] @scraped_topic_urls = yaml[:urls]

View File

@ -195,7 +195,7 @@ class ImportScripts::HigherLogic < ImportScripts::Base
original_filename = "#{a['VersionName']}.#{a['FileExtension']}" original_filename = "#{a['VersionName']}.#{a['FileExtension']}"
path = File.join(ATTACHMENT_DIR, original_filename) path = File.join(ATTACHMENT_DIR, original_filename)
if File.exists?(path) if File.exist?(path)
if post = Post.find(post_id_from_imported_post_id(a['MessageKey'])) if post = Post.find(post_id_from_imported_post_id(a['MessageKey']))
filename = File.basename(original_filename) filename = File.basename(original_filename)
upload = create_upload(post.user.id, path, filename) upload = create_upload(post.user.id, path, filename)

View File

@ -213,7 +213,7 @@ EOM
post_create_action: proc do |newuser| post_create_action: proc do |newuser|
if user['avatar_url'] && user['avatar_url'].length > 0 if user['avatar_url'] && user['avatar_url'].length > 0
photo_path = AVATARS_DIR + user['avatar_url'] photo_path = AVATARS_DIR + user['avatar_url']
if File.exists?(photo_path) if File.exist?(photo_path)
begin begin
upload = create_upload(newuser.id, photo_path, File.basename(photo_path)) upload = create_upload(newuser.id, photo_path, File.basename(photo_path))
if upload && upload.persisted? if upload && upload.persisted?

View File

@ -87,7 +87,7 @@ class ImportScripts::IPBoard3 < ImportScripts::Base
new_user.update(suspended_at: DateTime.now, suspended_till: 100.years.from_now) new_user.update(suspended_at: DateTime.now, suspended_till: 100.years.from_now)
elsif u["pp_main_photo"].present? elsif u["pp_main_photo"].present?
path = File.join(UPLOADS_DIR, u["pp_main_photo"]) path = File.join(UPLOADS_DIR, u["pp_main_photo"])
if File.exists?(path) if File.exist?(path)
begin begin
upload = create_upload(new_user.id, path, File.basename(path)) upload = create_upload(new_user.id, path, File.basename(path))
if upload.persisted? if upload.persisted?
@ -390,7 +390,7 @@ class ImportScripts::IPBoard3 < ImportScripts::Base
markdown.gsub!(/\[attachment=(\d+):.+\]/) do markdown.gsub!(/\[attachment=(\d+):.+\]/) do
if a = mysql_query("SELECT attach_file, attach_location FROM attachments WHERE attach_id = #{$1}").first if a = mysql_query("SELECT attach_file, attach_location FROM attachments WHERE attach_id = #{$1}").first
path = File.join(UPLOADS_DIR, a["attach_location"]) path = File.join(UPLOADS_DIR, a["attach_location"])
if File.exists?(path) if File.exist?(path)
begin begin
upload = create_upload(user_id, path, a["attach_file"]) upload = create_upload(user_id, path, a["attach_file"])
return html_for_upload(upload, a["attach_file"]) if upload.persisted? return html_for_upload(upload, a["attach_file"]) if upload.persisted?

View File

@ -842,7 +842,7 @@ SQL
filename = attachment_id.to_s.rjust(4, "0") filename = attachment_id.to_s.rjust(4, "0")
filename = File.join(ATTACHMENT_DIR, "000#{filename[0]}/#{filename}.dat") filename = File.join(ATTACHMENT_DIR, "000#{filename[0]}/#{filename}.dat")
unless File.exists?(filename) unless File.exist?(filename)
puts "Attachment file doesn't exist: #{filename}" puts "Attachment file doesn't exist: #{filename}"
return nil return nil
end end
@ -953,9 +953,9 @@ SQL
# check to see if we have it # check to see if we have it
if File.exist?(png) if File.exist?(png)
image = png image = png
elsif File.exists?(jpg) elsif File.exist?(jpg)
image = jpg image = jpg
elsif File.exists?(gif) elsif File.exist?(gif)
image = gif image = gif
end end

View File

@ -1,6 +1,6 @@
# frozen_string_literal: true # frozen_string_literal: true
if ARGV.length != 1 || !File.exists?(ARGV[0]) if ARGV.length != 1 || !File.exist?(ARGV[0])
STDERR.puts '', 'Usage of mbox importer:', 'bundle exec ruby mbox.rb <path/to/settings.yml>' STDERR.puts '', 'Usage of mbox importer:', 'bundle exec ruby mbox.rb <path/to/settings.yml>'
STDERR.puts '', "Use the settings file from #{File.expand_path('mbox/settings.yml', File.dirname(__FILE__))} as an example." STDERR.puts '', "Use the settings file from #{File.expand_path('mbox/settings.yml', File.dirname(__FILE__))} as an example."
exit 1 exit 1

View File

@ -261,7 +261,7 @@ FROM #{TABLE_PREFIX}discuss_users
end end
filename = File.join(ATTACHMENT_DIR, row['user_id'].to_s.split('').join('/'), "#{row['file_id']}.attach") filename = File.join(ATTACHMENT_DIR, row['user_id'].to_s.split('').join('/'), "#{row['file_id']}.attach")
unless File.exists?(filename) unless File.exist?(filename)
puts "Attachment file doesn't exist: #{filename}" puts "Attachment file doesn't exist: #{filename}"
return return
end end

View File

@ -55,7 +55,7 @@ class ImportScripts::Ning < ImportScripts::Base
def load_ning_json(arg) def load_ning_json(arg)
filename = File.join(JSON_FILES_DIR, arg) filename = File.join(JSON_FILES_DIR, arg)
raise RuntimeError.new("File #{filename} not found!") if !File.exists?(filename) raise RuntimeError.new("File #{filename} not found!") if !File.exist?(filename)
JSON.parse(repair_json(File.read(filename))).reverse JSON.parse(repair_json(File.read(filename))).reverse
end end
@ -112,7 +112,7 @@ class ImportScripts::Ning < ImportScripts::Base
if u["profilePhoto"] && newuser.user_avatar.try(:custom_upload_id).nil? if u["profilePhoto"] && newuser.user_avatar.try(:custom_upload_id).nil?
photo_path = file_full_path(u["profilePhoto"]) photo_path = file_full_path(u["profilePhoto"])
if File.exists?(photo_path) if File.exist?(photo_path)
begin begin
upload = create_upload(newuser.id, photo_path, File.basename(photo_path)) upload = create_upload(newuser.id, photo_path, File.basename(photo_path))
if upload.persisted? if upload.persisted?
@ -315,7 +315,7 @@ class ImportScripts::Ning < ImportScripts::Base
ning_filename = matches[1] ning_filename = matches[1]
filename = File.join(JSON_FILES_DIR, ning_filename.split("?").first) filename = File.join(JSON_FILES_DIR, ning_filename.split("?").first)
if !File.exists?(filename) if !File.exist?(filename)
puts "Attachment file doesn't exist: #{filename}" puts "Attachment file doesn't exist: #{filename}"
next s next s
end end
@ -339,7 +339,7 @@ class ImportScripts::Ning < ImportScripts::Base
file_names.each do |f| file_names.each do |f|
filename = File.join(JSON_FILES_DIR, f.split("?").first) filename = File.join(JSON_FILES_DIR, f.split("?").first)
if !File.exists?(filename) if !File.exist?(filename)
puts "Attachment file doesn't exist: #{filename}" puts "Attachment file doesn't exist: #{filename}"
next next
end end
@ -363,7 +363,7 @@ class ImportScripts::Ning < ImportScripts::Base
# filename = File.join(JSON_FILES_DIR, file_name) # filename = File.join(JSON_FILES_DIR, file_name)
filename = file_full_path(file_name) filename = file_full_path(file_name)
if File.exists?(filename) if File.exist?(filename)
upload = create_upload(@system_user.id, filename, File.basename(filename)) upload = create_upload(@system_user.id, filename, File.basename(filename))
if upload.nil? || !upload.valid? if upload.nil? || !upload.valid?

View File

@ -216,7 +216,7 @@ class ImportScripts::NodeBB < ImportScripts::Base
filepath = File.join(ATTACHMENT_DIR, picture) filepath = File.join(ATTACHMENT_DIR, picture)
filename = File.basename(picture) filename = File.basename(picture)
unless File.exists?(filepath) unless File.exist?(filepath)
puts "Avatar file doesn't exist: #{filepath}" puts "Avatar file doesn't exist: #{filepath}"
return nil return nil
end end
@ -276,7 +276,7 @@ class ImportScripts::NodeBB < ImportScripts::Base
filepath = File.join(ATTACHMENT_DIR, picture) filepath = File.join(ATTACHMENT_DIR, picture)
filename = File.basename(picture) filename = File.basename(picture)
unless File.exists?(filepath) unless File.exist?(filepath)
puts "Background file doesn't exist: #{filepath}" puts "Background file doesn't exist: #{filepath}"
return nil return nil
end end
@ -481,7 +481,7 @@ class ImportScripts::NodeBB < ImportScripts::Base
# if file exists # if file exists
# upload attachment and return html for it # upload attachment and return html for it
if File.exists?(filepath) if File.exist?(filepath)
filename = File.basename(filepath) filename = File.basename(filepath)
upload = create_upload(post.user_id, filepath, filename) upload = create_upload(post.user_id, filepath, filename)

View File

@ -3,7 +3,7 @@
# Importer for phpBB 3.0 and 3.1 # Importer for phpBB 3.0 and 3.1
# Documentation: https://meta.discourse.org/t/importing-from-phpbb3/30810 # Documentation: https://meta.discourse.org/t/importing-from-phpbb3/30810
if ARGV.length != 1 || !File.exists?(ARGV[0]) if ARGV.length != 1 || !File.exist?(ARGV[0])
STDERR.puts '', 'Usage of phpBB3 importer:', 'bundle exec ruby phpbb3.rb <path/to/settings.yml>' STDERR.puts '', 'Usage of phpBB3 importer:', 'bundle exec ruby phpbb3.rb <path/to/settings.yml>'
STDERR.puts '', "Use the settings file from #{File.expand_path('phpbb3/settings.yml', File.dirname(__FILE__))} as an example." STDERR.puts '', "Use the settings file from #{File.expand_path('phpbb3/settings.yml', File.dirname(__FILE__))} as an example."
STDERR.puts '', 'Still having problems? Take a look at https://meta.discourse.org/t/importing-from-phpbb3/30810' STDERR.puts '', 'Still having problems? Take a look at https://meta.discourse.org/t/importing-from-phpbb3/30810'

View File

@ -411,7 +411,7 @@ class ImportScripts::Smf1 < ImportScripts::Base
next unless post = PostCustomField.joins(:post).find_by(name: "import_id", value: u["id_msg"].to_s)&.post next unless post = PostCustomField.joins(:post).find_by(name: "import_id", value: u["id_msg"].to_s)&.post
path = File.join(UPLOADS_DIR, "#{u["id_attach"]}_#{u["file_hash"]}") path = File.join(UPLOADS_DIR, "#{u["id_attach"]}_#{u["file_hash"]}")
next unless File.exists?(path) && File.size(path) > 0 next unless File.exist?(path) && File.size(path) > 0
if upload = create_upload(post.user_id, path, u["filename"]) if upload = create_upload(post.user_id, path, u["filename"])
html = html_for_upload(upload, u["filename"]) html = html_for_upload(upload, u["filename"])

View File

@ -303,7 +303,7 @@ class ImportScripts::Smf2 < ImportScripts::Base
[ filename, "#{attachment_id}_#{file_hash}", legacy_name ] [ filename, "#{attachment_id}_#{file_hash}", legacy_name ]
.map { |name| File.join(options.smfroot, 'attachments', name) } .map { |name| File.join(options.smfroot, 'attachments', name) }
.detect { |file| File.exists?(file) } .detect { |file| File.exist?(file) }
end end
def decode_entities(*args) def decode_entities(*args)

View File

@ -156,7 +156,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
end end
def import_avatars def import_avatars
if ATTACHMENTS_BASE_DIR && File.exists?(ATTACHMENTS_BASE_DIR) if ATTACHMENTS_BASE_DIR && File.exist?(ATTACHMENTS_BASE_DIR)
puts "", "importing user avatars" puts "", "importing user avatars"
User.find_each do |u| User.find_each do |u|
@ -183,7 +183,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
next next
end end
if !File.exists?(photo_path) if !File.exist?(photo_path)
puts "Path to avatar file not found! Skipping. #{photo_path}" puts "Path to avatar file not found! Skipping. #{photo_path}"
next next
end end
@ -214,13 +214,13 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
base_guess = base_filename.dup base_guess = base_filename.dup
full_guess = File.join(path, base_guess) # often an exact match exists full_guess = File.join(path, base_guess) # often an exact match exists
return full_guess if File.exists?(full_guess) return full_guess if File.exist?(full_guess)
# Otherwise, the file exists but with a prefix: # Otherwise, the file exists but with a prefix:
# The p prefix seems to be the full file, so try to find that one first. # The p prefix seems to be the full file, so try to find that one first.
['p', 't', 'n'].each do |prefix| ['p', 't', 'n'].each do |prefix|
full_guess = File.join(path, "#{prefix}#{base_guess}") full_guess = File.join(path, "#{prefix}#{base_guess}")
return full_guess if File.exists?(full_guess) return full_guess if File.exist?(full_guess)
end end
# Didn't find it. # Didn't find it.
@ -554,7 +554,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
end end
def import_attachments def import_attachments
if ATTACHMENTS_BASE_DIR && File.exists?(ATTACHMENTS_BASE_DIR) if ATTACHMENTS_BASE_DIR && File.exist?(ATTACHMENTS_BASE_DIR)
puts "", "importing attachments" puts "", "importing attachments"
start = Time.now start = Time.now
@ -586,7 +586,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
path.gsub!("s3://uploads/", "") path.gsub!("s3://uploads/", "")
file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}" file_path = "#{ATTACHMENTS_BASE_DIR}/#{path}"
if File.exists?(file_path) if File.exist?(file_path)
upload = create_upload(post.user.id, file_path, File.basename(file_path)) upload = create_upload(post.user.id, file_path, File.basename(file_path))
if upload && upload.errors.empty? if upload && upload.errors.empty?
# upload.url # upload.url
@ -607,7 +607,7 @@ class ImportScripts::VanillaSQL < ImportScripts::Base
file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}" file_path = "#{ATTACHMENTS_BASE_DIR}/#{attachment_id}"
if File.exists?(file_path) if File.exist?(file_path)
upload = create_upload(post.user.id, file_path, File.basename(file_path)) upload = create_upload(post.user.id, file_path, File.basename(file_path))
if upload && upload.errors.empty? if upload && upload.errors.empty?
upload.url upload.url

View File

@ -426,7 +426,7 @@ EOM
real_filename = row['filename'] real_filename = row['filename']
real_filename.prepend SecureRandom.hex if real_filename[0] == '.' real_filename.prepend SecureRandom.hex if real_filename[0] == '.'
unless File.exists?(filename) unless File.exist?(filename)
if row['dbsize'].to_i == 0 if row['dbsize'].to_i == 0
puts "Attachment file #{row['filedataid']} doesn't exist" puts "Attachment file #{row['filedataid']} doesn't exist"
return nil return nil

View File

@ -138,7 +138,7 @@ class ImportScripts::VBulletin < ImportScripts::Base
upload = UploadCreator.new(file, picture["filename"]).create_for(imported_user.id) upload = UploadCreator.new(file, picture["filename"]).create_for(imported_user.id)
else else
filename = File.join(AVATAR_DIR, picture['filename']) filename = File.join(AVATAR_DIR, picture['filename'])
unless File.exists?(filename) unless File.exist?(filename)
puts "Avatar file doesn't exist: #{filename}" puts "Avatar file doesn't exist: #{filename}"
return nil return nil
end end
@ -366,7 +366,7 @@ class ImportScripts::VBulletin < ImportScripts::Base
real_filename = upload['filename'] real_filename = upload['filename']
real_filename.prepend SecureRandom.hex if real_filename[0] == '.' real_filename.prepend SecureRandom.hex if real_filename[0] == '.'
unless File.exists?(filename) unless File.exist?(filename)
# attachments can be on filesystem or in database # attachments can be on filesystem or in database
# try to retrieve from database if the file did not exist on filesystem # try to retrieve from database if the file did not exist on filesystem
if upload['dbsize'].to_i == 0 if upload['dbsize'].to_i == 0

View File

@ -5,7 +5,7 @@ require "rails_helper"
describe CommonPasswords do describe CommonPasswords do
it "the passwords file should exist" do it "the passwords file should exist" do
expect(File.exists?(described_class::PASSWORD_FILE)).to eq(true) expect(File.exist?(described_class::PASSWORD_FILE)).to eq(true)
end end
describe "#common_password?" do describe "#common_password?" do

View File

@ -5,7 +5,7 @@ require 'rails_helper'
describe Oneboxer do describe Oneboxer do
def response(file) def response(file)
file = File.join("spec", "fixtures", "onebox", "#{file}.response") file = File.join("spec", "fixtures", "onebox", "#{file}.response")
File.exists?(file) ? File.read(file) : "" File.exist?(file) ? File.read(file) : ""
end end
it "returns blank string for an invalid onebox" do it "returns blank string for an invalid onebox" do

View File

@ -230,11 +230,11 @@ describe Plugin::Instance do
# calls ensure_assets! make sure they are there # calls ensure_assets! make sure they are there
expect(plugin.assets.count).to eq(1) expect(plugin.assets.count).to eq(1)
plugin.assets.each do |a, opts| plugin.assets.each do |a, opts|
expect(File.exists?(a)).to eq(true) expect(File.exist?(a)).to eq(true)
end end
# ensure it cleans up all crap in autogenerated directory # ensure it cleans up all crap in autogenerated directory
expect(File.exists?(junk_file)).to eq(false) expect(File.exist?(junk_file)).to eq(false)
end end
it "registers auth providers correctly" do it "registers auth providers correctly" do

View File

@ -36,16 +36,16 @@ describe BackupRestore::LocalBackupStore do
end end
def remove_backups def remove_backups
@paths.each { |path| File.delete(path) if File.exists?(path) } @paths.each { |path| File.delete(path) if File.exist?(path) }
@paths.clear @paths.clear
end end
def create_file(db_name:, filename:, last_modified:, size_in_bytes:) def create_file(db_name:, filename:, last_modified:, size_in_bytes:)
path = File.join(@root_directory, db_name) path = File.join(@root_directory, db_name)
Dir.mkdir(path) unless Dir.exists?(path) Dir.mkdir(path) unless Dir.exist?(path)
path = File.join(path, filename) path = File.join(path, filename)
return if File.exists?(path) return if File.exist?(path)
@paths << path @paths << path
FileUtils.touch(path) FileUtils.touch(path)

View File

@ -174,7 +174,7 @@ shared_examples "backup store" do
destination_path = File.join(path, File.basename(filename)) destination_path = File.join(path, File.basename(filename))
store.download_file(filename, destination_path) store.download_file(filename, destination_path)
expect(File.exists?(destination_path)).to eq(true) expect(File.exist?(destination_path)).to eq(true)
expect(File.size(destination_path)).to eq(backup1.size) expect(File.size(destination_path)).to eq(backup1.size)
end end
end end

View File

@ -41,7 +41,7 @@ RSpec.describe UploadRecovery do
[ [
public_path, public_path,
public_path.sub("uploads", "uploads/tombstone") public_path.sub("uploads", "uploads/tombstone")
].each { |path| File.delete(path) if File.exists?(path) } ].each { |path| File.delete(path) if File.exist?(path) }
end end
end end

View File

@ -28,7 +28,7 @@ describe OptimizedImage do
expect(cropped_size).to be > 50 expect(cropped_size).to be > 50
ensure ensure
File.delete(tmp_path) if File.exists?(tmp_path) File.delete(tmp_path) if File.exist?(tmp_path)
end end
end end
@ -73,7 +73,7 @@ describe OptimizedImage do
expect(new_size).not_to eq(0) expect(new_size).not_to eq(0)
ensure ensure
File.delete(original_path) if File.exists?(original_path) File.delete(original_path) if File.exist?(original_path)
end end
end end
@ -124,7 +124,7 @@ describe OptimizedImage do
) )
end.to raise_error(RuntimeError, /improper image header/) end.to raise_error(RuntimeError, /improper image header/)
ensure ensure
File.delete(tmp_path) if File.exists?(tmp_path) File.delete(tmp_path) if File.exist?(tmp_path)
end end
end end
end end
@ -146,7 +146,7 @@ describe OptimizedImage do
expect(File.size(tmp_path)).to be < 2300 expect(File.size(tmp_path)).to be < 2300
ensure ensure
File.delete(tmp_path) if File.exists?(tmp_path) File.delete(tmp_path) if File.exist?(tmp_path)
end end
end end
end end

View File

@ -425,7 +425,7 @@ end
def file_from_fixtures(filename, directory = "images") def file_from_fixtures(filename, directory = "images")
SpecSecureRandom.value ||= SecureRandom.hex SpecSecureRandom.value ||= SecureRandom.hex
FileUtils.mkdir_p(file_from_fixtures_tmp_folder) unless Dir.exists?(file_from_fixtures_tmp_folder) FileUtils.mkdir_p(file_from_fixtures_tmp_folder) unless Dir.exist?(file_from_fixtures_tmp_folder)
tmp_file_path = File.join(file_from_fixtures_tmp_folder, SecureRandom.hex << filename) tmp_file_path = File.join(file_from_fixtures_tmp_folder, SecureRandom.hex << filename)
FileUtils.cp("#{Rails.root}/spec/fixtures/#{directory}/#{filename}", tmp_file_path) FileUtils.cp("#{Rails.root}/spec/fixtures/#{directory}/#{filename}", tmp_file_path)
File.new(tmp_file_path) File.new(tmp_file_path)

View File

@ -37,7 +37,7 @@ RSpec.describe Admin::BackupsController do
after do after do
Discourse.redis.flushdb Discourse.redis.flushdb
@paths&.each { |path| File.delete(path) if File.exists?(path) } @paths&.each { |path| File.delete(path) if File.exist?(path) }
@paths = nil @paths = nil
end end
@ -133,14 +133,14 @@ RSpec.describe Admin::BackupsController do
begin begin
path = backup_path(backup_filename) path = backup_path(backup_filename)
create_backup_files(backup_filename) create_backup_files(backup_filename)
expect(File.exists?(path)).to eq(true) expect(File.exist?(path)).to eq(true)
expect do expect do
delete "/admin/backups/#{backup_filename}.json" delete "/admin/backups/#{backup_filename}.json"
end.to change { UserHistory.where(action: UserHistory.actions[:backup_destroy]).count }.by(1) end.to change { UserHistory.where(action: UserHistory.actions[:backup_destroy]).count }.by(1)
expect(response.status).to eq(200) expect(response.status).to eq(200)
expect(File.exists?(path)).to eq(false) expect(File.exist?(path)).to eq(false)
end end
end end

View File

@ -29,7 +29,7 @@ describe 'backups' do
after do after do
Discourse.redis.flushdb Discourse.redis.flushdb
@paths&.each { |path| File.delete(path) if File.exists?(path) } @paths&.each { |path| File.delete(path) if File.exist?(path) }
@paths = nil @paths = nil
end end