Update Rubocop's config (#7050)

Merge pull request 7050
This commit is contained in:
Frank Taillandier 2018-06-02 12:50:32 +02:00 committed by jekyllbot
parent 6805f1c342
commit 6c771608e5
57 changed files with 492 additions and 591 deletions

View File

@ -18,30 +18,14 @@ AllCops:
- script/**/*
- vendor/**/*
- tmp/**/*
Layout/AlignArray:
Enabled: false
Layout/AlignHash:
EnforcedHashRocketStyle: table
Layout/AlignParameters:
Enabled: false
Layout/EmptyLinesAroundAccessModifier:
Enabled: false
Layout/EmptyLinesAroundModuleBody:
Enabled: false
Layout/EndOfLine:
EnforcedStyle: native
Layout/ExtraSpacing:
AllowForAlignment: true
Layout/FirstParameterIndentation:
EnforcedStyle: consistent
Layout/IndentationWidth:
Severity: error
Layout/IndentArray:
EnforcedStyle: consistent
Layout/IndentHash:
EnforcedStyle: consistent
Layout/IndentHeredoc:
Enabled: false
Layout/MultilineMethodCallIndentation:
EnforcedStyle: indented
Layout/MultilineOperationIndentation:
@ -53,12 +37,11 @@ Layout/EmptyComment:
Enabled: false
Layout/EndAlignment:
Severity: error
Lint/UnneededRequireStatement:
Enabled: false
Lint/UnreachableCode:
Severity: error
Lint/Void:
Enabled: false
Exclude:
- lib/jekyll/site.rb
Metrics/AbcSize:
Max: 21
Metrics/BlockLength:
@ -66,22 +49,26 @@ Metrics/BlockLength:
- test/**/*.rb
- lib/jekyll/configuration.rb
- rake/*.rake
- jekyll.gemspec
Metrics/ClassLength:
Exclude:
- !ruby/regexp /features\/.*.rb$/
- !ruby/regexp /test\/.*.rb$/
Max: 300
- lib/jekyll/document.rb
- lib/jekyll/site.rb
- lib/jekyll/commands/serve.rb
- lib/jekyll/configuration.rb
Max: 240
Metrics/CyclomaticComplexity:
Max: 9
Exclude:
- lib/jekyll/utils.rb
- lib/jekyll/commands/serve.rb
Metrics/LineLength:
Exclude:
- !ruby/regexp /features\/.*.rb/
- Rakefile
- rake/*.rake
- Gemfile
- jekyll.gemspec
Max: 90
Max: 100
Severity: warning
Metrics/MethodLength:
CountComments: false
@ -95,8 +82,6 @@ Metrics/PerceivedComplexity:
Max: 8
Naming/FileName:
Enabled: false
Naming/HeredocDelimiterNaming:
Enabled: false
Naming/MemoizedInstanceVariableName:
Exclude:
- lib/jekyll/page_without_a_file.rb
@ -105,8 +90,6 @@ Naming/MemoizedInstanceVariableName:
Naming/UncommunicativeMethodParamName:
AllowedNames:
- _
Performance/UnfreezeString:
Enabled: false
Security/MarshalLoad:
Exclude:
- !ruby/regexp /test\/.*.rb$/
@ -116,19 +99,13 @@ Security/YAMLLoad:
- !ruby/regexp /features\/.*.rb/
- !ruby/regexp /test\/.*.rb$/
Style/Alias:
Enabled: false
EnforcedStyle: prefer_alias_method
Style/AndOr:
Severity: error
Style/BracesAroundHashParameters:
Enabled: false
Style/ClassAndModuleChildren:
Enabled: false
Style/FrozenStringLiteralComment:
EnforcedStyle: always
Style/Documentation:
Enabled: false
Exclude:
- !ruby/regexp /features\/.*.rb$/
Style/DoubleNegation:
Enabled: false
Style/FormatStringToken:
@ -139,10 +116,6 @@ Style/GuardClause:
Style/HashSyntax:
EnforcedStyle: hash_rockets
Severity: error
Style/IfUnlessModifier:
Enabled: false
Style/InverseMethods:
Enabled: false
Style/MixinUsage:
Exclude:
- test/helper.rb
@ -150,8 +123,6 @@ Style/ModuleFunction:
Enabled: false
Style/MultilineTernaryOperator:
Severity: error
Style/NumericPredicate:
Enabled: false
Style/PercentLiteralDelimiters:
PreferredDelimiters:
"%q": "{}"
@ -161,28 +132,21 @@ Style/PercentLiteralDelimiters:
"%w": "()"
"%W": "()"
"%x": "()"
Style/RedundantFreeze:
Enabled: false
Style/RedundantReturn:
Enabled: false
Style/RedundantSelf:
Enabled: false
Style/RegexpLiteral:
EnforcedStyle: percent_r
Style/RescueModifier:
Enabled: false
Style/SafeNavigation:
Enabled: false
Exclude:
- lib/jekyll/document.rb
Style/SignalException:
EnforcedStyle: only_raise
Style/SingleLineMethods:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
Style/StringLiteralsInInterpolation:
EnforcedStyle: double_quotes
Style/SymbolArray:
Enabled: false
EnforcedStyle: brackets
Style/TrailingCommaInArrayLiteral:
EnforcedStyleForMultiline: consistent_comma
Style/TrailingCommaInHashLiteral:

View File

@ -35,7 +35,7 @@ module Jekyll
def method_missing(method, *args, &blck)
if docs.respond_to?(method.to_sym)
Jekyll.logger.warn "Deprecation:",
"#{label}.#{method} should be changed to #{label}.docs.#{method}."
"#{label}.#{method} should be changed to #{label}.docs.#{method}."
Jekyll.logger.warn "", "Called by #{caller(0..0)}."
docs.public_send(method.to_sym, *args, &blck)
else
@ -210,9 +210,7 @@ module Jekyll
def read_document(full_path)
doc = Document.new(full_path, :site => site, :collection => self)
doc.read
if site.unpublished || doc.published?
docs << doc
end
docs << doc if site.unpublished || doc.published?
end
def read_static_file(file_path, full_path)

View File

@ -51,26 +51,26 @@ module Jekyll
# rubocop:disable Metrics/MethodLength
def add_build_options(cmd)
cmd.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]",
Array, "Custom configuration file"
Array, "Custom configuration file"
cmd.option "destination", "-d", "--destination DESTINATION",
"The current folder will be generated into DESTINATION"
"The current folder will be generated into DESTINATION"
cmd.option "source", "-s", "--source SOURCE", "Custom source directory"
cmd.option "future", "--future", "Publishes posts with a future date"
cmd.option "limit_posts", "--limit_posts MAX_POSTS", Integer,
"Limits the number of posts to parse and publish"
"Limits the number of posts to parse and publish"
cmd.option "watch", "-w", "--[no-]watch", "Watch for changes and rebuild"
cmd.option "baseurl", "-b", "--baseurl URL",
"Serve the website from the given base URL"
"Serve the website from the given base URL"
cmd.option "force_polling", "--force_polling", "Force watch to use polling"
cmd.option "lsi", "--lsi", "Use LSI for improved related posts"
cmd.option "show_drafts", "-D", "--drafts", "Render posts in the _drafts folder"
cmd.option "unpublished", "--unpublished",
"Render posts that were marked as unpublished"
"Render posts that were marked as unpublished"
cmd.option "quiet", "-q", "--quiet", "Silence output."
cmd.option "verbose", "-V", "--verbose", "Print verbose output."
cmd.option "incremental", "-I", "--incremental", "Enable incremental rebuild."
cmd.option "strict_front_matter", "--strict_front_matter",
"Fail if errors are present in front matter"
"Fail if errors are present in front matter"
end
# rubocop:enable Metrics/MethodLength

View File

@ -31,14 +31,14 @@ module Jekyll
if options.fetch("skip_initial_build", false)
Jekyll.logger.warn "Build Warning:", "Skipping the initial build." \
" This may result in an out-of-date site."
" This may result in an out-of-date site."
else
build(site, options)
end
if options.fetch("detach", false)
Jekyll.logger.info "Auto-regeneration:",
"disabled when running server detached."
"disabled when running server detached."
elsif options.fetch("watch", false)
watch(site, options)
else
@ -60,7 +60,7 @@ module Jekyll
Jekyll.logger.info "Source:", source
Jekyll.logger.info "Destination:", destination
Jekyll.logger.info "Incremental build:",
(incremental ? "enabled" : "disabled. Enable with --incremental")
(incremental ? "enabled" : "disabled. Enable with --incremental")
Jekyll.logger.info "Generating..."
process_site(site)
Jekyll.logger.info "", "done in #{(Time.now - t).round(3)} seconds."
@ -76,12 +76,12 @@ module Jekyll
# Warn Windows users that they might need to upgrade.
if Utils::Platforms.bash_on_windows?
Jekyll.logger.warn "",
"Auto-regeneration may not work on some Windows versions."
"Auto-regeneration may not work on some Windows versions."
Jekyll.logger.warn "",
"Please see: https://github.com/Microsoft/BashOnWindows/issues/216"
"Please see: https://github.com/Microsoft/BashOnWindows/issues/216"
Jekyll.logger.warn "",
"If it does not work, please upgrade Bash on Windows or "\
"run Jekyll with --no-watch."
"If it does not work, please upgrade Bash on Windows or "\
"run Jekyll with --no-watch."
end
External.require_with_graceful_fail "jekyll-watch"

View File

@ -11,7 +11,7 @@ module Jekyll
c.alias(:hyde)
c.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]", Array,
"Custom configuration file"
"Custom configuration file"
c.action do |_, options|
Jekyll::Commands::Doctor.process(options)
@ -48,19 +48,18 @@ module Jekyll
posts_at_root = site.in_source_dir("_posts")
return true unless File.directory?(posts_at_root)
Jekyll.logger.warn "Warning:",
"Detected '_posts' directory outside custom `collections_dir`!"
"Detected '_posts' directory outside custom `collections_dir`!"
Jekyll.logger.warn "",
"Please move '#{posts_at_root}' into the custom directory at " \
"Please move '#{posts_at_root}' into the custom directory at " \
"'#{site.in_source_dir(site.config["collections_dir"])}'"
false
end
def deprecated_relative_permalinks(site)
if site.config["relative_permalinks"]
Jekyll::Deprecator.deprecation_message "Your site still uses relative" \
" permalinks, which was removed in" \
" Jekyll v3.0.0."
return true
Jekyll::Deprecator.deprecation_message "Your site still uses relative permalinks," \
" which was removed in Jekyll v3.0.0."
true
end
end
@ -117,6 +116,7 @@ module Jekyll
end
private
def collect_urls(urls, things, destination)
things.each do |thing|
dest = thing.destination(destination)

View File

@ -25,7 +25,7 @@ module Jekyll
def invalid_command(prog, cmd)
Jekyll.logger.error "Error:",
"Hmm... we don't know what the '#{cmd}' command is."
"Hmm... we don't know what the '#{cmd}' command is."
Jekyll.logger.info "Valid commands:", prog.commands.keys.join(", ")
end
end

View File

@ -62,38 +62,32 @@ module Jekyll
private
def gemfile_contents
<<-RUBY
source "https://rubygems.org"
<<~RUBY
source "https://rubygems.org"
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
gem "jekyll", "~> #{Jekyll::VERSION}"
# This is the default theme for new Jekyll sites. You may change this to anything you like.
gem "minima", "~> 2.0"
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
# gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
group :jekyll_plugins do
gem "jekyll-feed", "~> 0.6"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.0" if Gem.win_platform?
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
gem "jekyll", "~> #{Jekyll::VERSION}"
# This is the default theme for new Jekyll sites. You may change this to anything you like.
gem "minima", "~> 2.0"
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
# gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
group :jekyll_plugins do
gem "jekyll-feed", "~> 0.6"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.0" if Gem.win_platform?
RUBY
RUBY
end
def create_site(new_blog_path)

View File

@ -2,39 +2,41 @@
require "erb"
class Jekyll::Commands::NewTheme < Jekyll::Command
class << self
def init_with_program(prog)
prog.command(:"new-theme") do |c|
c.syntax "new-theme NAME"
c.description "Creates a new Jekyll theme scaffold"
c.option "code_of_conduct", \
"-c", "--code-of-conduct", \
"Include a Code of Conduct. (defaults to false)"
module Jekyll
module Commands
class NewTheme < Jekyll::Command
class << self
def init_with_program(prog)
prog.command(:"new-theme") do |c|
c.syntax "new-theme NAME"
c.description "Creates a new Jekyll theme scaffold"
c.option "code_of_conduct", \
"-c", "--code-of-conduct", \
"Include a Code of Conduct. (defaults to false)"
c.action do |args, opts|
Jekyll::Commands::NewTheme.process(args, opts)
c.action do |args, opts|
Jekyll::Commands::NewTheme.process(args, opts)
end
end
end
# rubocop:disable Metrics/AbcSize
def process(args, opts)
if !args || args.empty?
raise Jekyll::Errors::InvalidThemeName, "You must specify a theme name."
end
new_theme_name = args.join("_")
theme = Jekyll::ThemeBuilder.new(new_theme_name, opts)
Jekyll.logger.abort_with "Conflict:", "#{theme.path} already exists." if theme.path.exist?
theme.create!
Jekyll.logger.info "Your new Jekyll theme, #{theme.name.cyan}," \
" is ready for you in #{theme.path.to_s.cyan}!"
Jekyll.logger.info "For help getting started, read #{theme.path}/README.md."
end
# rubocop:enable Metrics/AbcSize
end
end
# rubocop:disable Metrics/AbcSize
def process(args, opts)
if !args || args.empty?
raise Jekyll::Errors::InvalidThemeName, "You must specify a theme name."
end
new_theme_name = args.join("_")
theme = Jekyll::ThemeBuilder.new(new_theme_name, opts)
if theme.path.exist?
Jekyll.logger.abort_with "Conflict:", "#{theme.path} already exists."
end
theme.create!
Jekyll.logger.info "Your new Jekyll theme, #{theme.name.cyan}," \
" is ready for you in #{theme.path.to_s.cyan}!"
Jekyll.logger.info "For help getting started, read #{theme.path}/README.md."
end
# rubocop:enable Metrics/AbcSize
end
end

View File

@ -1,7 +1,5 @@
# frozen_string_literal: true
require "thread"
module Jekyll
module Commands
class Serve < Command
@ -19,25 +17,28 @@ module Jekyll
"host" => ["host", "-H", "--host [HOST]", "Host to bind to"],
"open_url" => ["-o", "--open-url", "Launch your site in a browser"],
"detach" => ["-B", "--detach",
"Run the server in the background",],
"Run the server in the background",],
"ssl_key" => ["--ssl-key [KEY]", "X.509 (SSL) Private Key."],
"port" => ["-P", "--port [PORT]", "Port to listen on"],
"show_dir_listing" => ["--show-dir-listing",
"Show a directory listing instead of loading your index file.",],
"Show a directory listing instead of loading" \
" your index file.",],
"skip_initial_build" => ["skip_initial_build", "--skip-initial-build",
"Skips the initial site build which occurs before the server is started.",],
"Skips the initial site build which occurs before" \
" the server is started.",],
"livereload" => ["-l", "--livereload",
"Use LiveReload to automatically refresh browsers",],
"Use LiveReload to automatically refresh browsers",],
"livereload_ignore" => ["--livereload-ignore ignore GLOB1[,GLOB2[,...]]",
Array,
"Files for LiveReload to ignore. Remember to quote the values so your shell "\
"won't expand them",],
Array,
"Files for LiveReload to ignore. " \
"Remember to quote the values so your shell " \
"won't expand them",],
"livereload_min_delay" => ["--livereload-min-delay [SECONDS]",
"Minimum reload delay",],
"Minimum reload delay",],
"livereload_max_delay" => ["--livereload-max-delay [SECONDS]",
"Maximum reload delay",],
"Maximum reload delay",],
"livereload_port" => ["--livereload-port [PORT]", Integer,
"Port for LiveReload to listen on",],
"Port for LiveReload to listen on",],
}.freeze
DIRECTORY_INDEX = %w(
@ -107,8 +108,8 @@ module Jekyll
def validate_options(opts)
if opts["livereload"]
if opts["detach"]
Jekyll.logger.warn "Warning:",
"--detach and --livereload are mutually exclusive. Choosing --livereload"
Jekyll.logger.warn "Warning:", "--detach and --livereload are mutually exclusive." \
" Choosing --livereload"
opts["detach"] = false
end
if opts["ssl_cert"] || opts["ssl_key"]
@ -123,9 +124,9 @@ module Jekyll
opts["watch"] = true
end
elsif %w(livereload_min_delay
livereload_max_delay
livereload_ignore
livereload_port).any? { |o| opts[o] }
livereload_max_delay
livereload_ignore
livereload_port).any? { |o| opts[o] }
Jekyll.logger.abort_with "--livereload-min-delay, "\
"--livereload-max-delay, --livereload-ignore, and "\
"--livereload-port require the --livereload option."
@ -204,9 +205,7 @@ module Jekyll
end
def start_up_webrick(opts, destination)
if opts["livereload"]
@reload_reactor.start(opts)
end
@reload_reactor.start(opts) if opts["livereload"]
@server = WEBrick::HTTPServer.new(webrick_opts(opts)).tap { |o| o.unmount("") }
@server.mount(opts["baseurl"].to_s, Servlet, destination, file_handler_opts)
@ -218,12 +217,12 @@ module Jekyll
# Recreate NondisclosureName under utf-8 circumstance
def file_handler_opts
WEBrick::Config::FileHandler.merge({
WEBrick::Config::FileHandler.merge(
:FancyIndexing => true,
:NondisclosureName => [
".ht*", "~*",
],
})
]
)
end
def server_address(server, options = {})
@ -236,12 +235,11 @@ module Jekyll
end
def format_url(ssl_enabled, address, port, baseurl = nil)
format("%<prefix>s://%<address>s:%<port>i%<baseurl>s", {
:prefix => ssl_enabled ? "https" : "http",
:address => address,
:port => port,
:baseurl => baseurl ? "#{baseurl}/" : "",
})
format("%<prefix>s://%<address>s:%<port>i%<baseurl>s",
:prefix => ssl_enabled ? "https" : "http",
:address => address,
:port => port,
:baseurl => baseurl ? "#{baseurl}/" : "")
end
def default_url(opts)
@ -273,7 +271,8 @@ module Jekyll
Process.detach(pid)
Jekyll.logger.info "Server detached with pid '#{pid}'.", \
"Run `pkill -f jekyll' or `kill -9 #{pid}' to stop the server."
"Run `pkill -f jekyll' or `kill -9 #{pid}'" \
" to stop the server."
else
t = Thread.new { server.start }
trap("INT") { server.shutdown }
@ -311,7 +310,7 @@ module Jekyll
proc do
mutex.synchronize do
# Block until EventMachine reactor starts
@reload_reactor.started_event.wait unless @reload_reactor.nil?
@reload_reactor&.started_event&.wait
@running = true
Jekyll.logger.info("Server running...", "press ctrl-c to stop.")
@run_cond.broadcast

View File

@ -58,7 +58,7 @@ module Jekyll
EM.add_shutdown_hook { @stopped_event.set }
Jekyll.logger.info "LiveReload address:",
"http://#{opts["host"]}:#{opts["livereload_port"]}"
"http://#{opts["host"]}:#{opts["livereload_port"]}"
end
end
@thread.abort_on_exception = true
@ -68,11 +68,11 @@ module Jekyll
# http://feedback.livereload.com/knowledgebase/articles/86174-livereload-protocol
def reload(pages)
pages.each do |p|
json_message = JSON.dump({
json_message = JSON.dump(
:command => "reload",
:path => p.url,
:liveCSS => true,
})
:liveCSS => true
)
Jekyll.logger.debug "LiveReload:", "Reloading #{p.url}"
Jekyll.logger.debug "", json_message
@ -108,9 +108,7 @@ module Jekyll
msg = JSON.parse(json_message)
# Not sure what the 'url' command even does in LiveReload. The spec is silent
# on its purpose.
if msg["command"] == "url"
Jekyll.logger.info "LiveReload:", "Browser URL: #{msg["url"]}"
end
Jekyll.logger.info "LiveReload:", "Browser URL: #{msg["url"]}" if msg["command"] == "url"
end
def log_error(error)

View File

@ -121,9 +121,7 @@ module Jekyll
if @options["livereload_max_delay"]
src += "&amp;maxdelay=#{@options["livereload_max_delay"]}"
end
if @options["livereload_port"]
src += "&amp;port=#{@options["livereload_port"]}"
end
src += "&amp;port=#{@options["livereload_port"]}" if @options["livereload_port"]
src
end
end

View File

@ -346,7 +346,7 @@ module Jekyll
" as a list of comma-separated values."
config[option] = csv_to_array(config[option])
end
config[option].map!(&:to_s) if config[option]
config[option]&.map!(&:to_s)
end
end
@ -381,8 +381,8 @@ module Jekyll
" use an array instead. If you wanted to set the directory of your" \
" plugins, use the config key `plugins_dir` instead."
raise Jekyll::Errors::InvalidConfigurationError,
"'plugins' should not be a string, but was: " \
"#{config["plugins"].inspect}. Use 'plugins_dir' instead."
"'plugins' should not be a string, but was: " \
"#{config["plugins"].inspect}. Use 'plugins_dir' instead."
end
end
end

View File

@ -11,9 +11,7 @@ module Jekyll
return if @setup ||= false
unless (@parser = get_processor)
Jekyll.logger.error "Invalid Markdown processor given:", @config["markdown"]
if @config["safe"]
Jekyll.logger.info "", "Custom processors are not loaded in safe mode"
end
Jekyll.logger.info "", "Custom processors are not loaded in safe mode" if @config["safe"]
Jekyll.logger.error(
"",
"Available processors are: #{valid_processors.join(", ")}"
@ -30,7 +28,7 @@ module Jekyll
# rubocop:disable Naming/AccessorMethodName
def get_processor
case @config["markdown"].downcase
when "kramdown" then return KramdownParser.new(@config)
when "kramdown" then KramdownParser.new(@config)
else
custom_processor
end
@ -79,9 +77,7 @@ module Jekyll
def custom_processor
converter_name = @config["markdown"]
if custom_class_allowed?(converter_name)
self.class.const_get(converter_name).new(@config)
end
self.class.const_get(converter_name).new(@config) if custom_class_allowed?(converter_name)
end
# Private: Determine whether a class name is an allowed custom

View File

@ -1,16 +1,20 @@
# frozen_string_literal: true
class Kramdown::Parser::SmartyPants < Kramdown::Parser::Kramdown
def initialize(source, options)
super
@block_parsers = [:block_html, :content]
@span_parsers = [:smart_quotes, :html_entity, :typographic_syms, :span_html]
end
module Kramdown
module Parser
class SmartyPants < Kramdown::Parser::Kramdown
def initialize(source, options)
super
@block_parsers = [:block_html, :content]
@span_parsers = [:smart_quotes, :html_entity, :typographic_syms, :span_html]
end
def parse_content
add_text @src.scan(%r!\A.*\n!)
def parse_content
add_text @src.scan(%r!\A.*\n!)
end
define_parser(:content, %r!\A!)
end
end
define_parser(:content, %r!\A!)
end
module Jekyll
@ -20,9 +24,7 @@ module Jekyll
priority :low
def initialize(config)
unless defined?(Kramdown)
Jekyll::External.require_with_graceful_fail "kramdown"
end
Jekyll::External.require_with_graceful_fail "kramdown" unless defined?(Kramdown)
@config = config["kramdown"].dup || {}
@config[:input] = :SmartyPants
end

View File

@ -46,10 +46,10 @@ module Jekyll
end
rescue Psych::SyntaxError => e
Jekyll.logger.warn "YAML Exception reading #{filename}: #{e.message}"
raise e if self.site.config["strict_front_matter"]
raise e if site.config["strict_front_matter"]
rescue StandardError => e
Jekyll.logger.warn "Error reading file #{filename}: #{e.message}"
raise e if self.site.config["strict_front_matter"]
raise e if site.config["strict_front_matter"]
end
self.data ||= {}
@ -64,12 +64,12 @@ module Jekyll
def validate_data!(filename)
unless self.data.is_a?(Hash)
raise Errors::InvalidYAMLFrontMatterError,
"Invalid YAML front matter in #{filename}"
"Invalid YAML front matter in #{filename}"
end
end
def validate_permalink!(filename)
if self.data["permalink"] && self.data["permalink"].to_s.empty?
if self.data["permalink"]&.to_s&.empty?
raise Errors::InvalidPermalinkError, "Invalid permalink in #{filename}"
end
end
@ -125,16 +125,12 @@ module Jekyll
#
# Returns the type of self.
def type
if is_a?(Page)
:pages
end
:pages if is_a?(Page)
end
# returns the owner symbol for hook triggering
def hook_owner
if is_a?(Page)
:pages
end
:pages if is_a?(Page)
end
# Determine whether the document is an asset file.
@ -181,7 +177,7 @@ module Jekyll
#
# Returns true if the layout is invalid, false if otherwise
def invalid_layout?(layout)
!data["layout"].nil? && layout.nil? && !(self.is_a? Jekyll::Excerpt)
!data["layout"].nil? && layout.nil? && !(is_a? Jekyll::Excerpt)
end
# Recursively render layouts
@ -210,7 +206,7 @@ module Jekyll
renderer.payload = payload
end.run
Jekyll.logger.debug "Post-Render Hooks:", self.relative_path
Jekyll.logger.debug "Post-Render Hooks:", relative_path
Jekyll::Hooks.trigger hook_owner, :post_render, self
ensure
@_renderer = nil # this will allow the modifications above to disappear

View File

@ -34,9 +34,7 @@ module Jekyll
end
def arg_is_present?(args, deprecated_argument, message)
if args.include?(deprecated_argument)
deprecation_message(message)
end
deprecation_message(message) if args.include?(deprecated_argument)
end
def deprecation_message(message)

View File

@ -204,11 +204,11 @@ module Jekyll
#
# Returns the computed URL for the document.
def url
@url ||= URL.new({
@url ||= URL.new(
:template => url_template,
:placeholders => url_placeholders,
:permalink => permalink,
}).to_s
:permalink => permalink
).to_s
end
def [](key)
@ -315,7 +315,7 @@ module Jekyll
# method returns true, and if the site's Publisher will publish the document.
# False otherwise.
def write?
collection && collection.write? && site.publisher.publish?(self)
collection&.write? && site.publisher.publish?(self)
end
# The Document excerpt_separator, from the YAML Front-Matter or site
@ -335,16 +335,12 @@ module Jekyll
def next_doc
pos = collection.docs.index { |post| post.equal?(self) }
if pos && pos < collection.docs.length - 1
collection.docs[pos + 1]
end
collection.docs[pos + 1] if pos && pos < collection.docs.length - 1
end
def previous_doc
pos = collection.docs.index { |post| post.equal?(self) }
if pos && pos > 0
collection.docs[pos - 1]
end
collection.docs[pos - 1] if pos && pos.positive?
end
def trigger_hooks(hook_name, *args)
@ -400,28 +396,26 @@ module Jekyll
end
def populate_categories
merge_data!({
merge_data!(
"categories" => (
Array(data["categories"]) + Utils.pluralized_array_from_hash(
data, "category", "categories"
)
).map(&:to_s).flatten.uniq,
})
).map(&:to_s).flatten.uniq
)
end
def populate_tags
merge_data!({
"tags" => Utils.pluralized_array_from_hash(data, "tag", "tags").flatten,
})
merge_data!(
"tags" => Utils.pluralized_array_from_hash(data, "tag", "tags").flatten
)
end
private
def merge_categories!(other)
if other.key?("categories") && !other["categories"].nil?
if other["categories"].is_a?(String)
other["categories"] = other["categories"].split
end
other["categories"] = other["categories"].split if other["categories"].is_a?(String)
other["categories"] = (data["categories"] || []) | other["categories"]
end
end
@ -493,9 +487,7 @@ module Jekyll
end
def generate_excerpt
if generate_excerpt?
data["excerpt"] ||= Jekyll::Excerpt.new(self)
end
data["excerpt"] ||= Jekyll::Excerpt.new(self) if generate_excerpt?
end
end
end

View File

@ -7,9 +7,8 @@ module Jekyll
mutable false
def_delegator :@obj, :write?, :output
def_delegators :@obj, :label, :docs, :files, :directory,
:relative_directory
def_delegator :@obj, :write?, :output
def_delegators :@obj, :label, :docs, :files, :directory, :relative_directory
private def_delegator :@obj, :metadata, :fallback_data

View File

@ -173,7 +173,7 @@ module Jekyll
end
def merge(other, &block)
self.dup.tap do |me|
dup.tap do |me|
if block.nil?
me.merge!(other)
else

View File

@ -8,8 +8,7 @@ module Jekyll
mutable false
def_delegator :@obj, :site_data, :data
def_delegators :@obj, :time, :pages, :static_files, :documents,
:tags, :categories
def_delegators :@obj, :time, :pages, :static_files, :documents, :tags, :categories
private def_delegator :@obj, :config, :fallback_data

View File

@ -17,6 +17,7 @@ module Jekyll
end
private
def fallback_data
@fallback_data ||= {}
end

View File

@ -80,6 +80,7 @@ module Jekyll
end
private
def fallback_data
{}
end

View File

@ -31,9 +31,7 @@ module Jekyll
def filter(entries)
entries.reject do |e|
unless included?(e)
special?(e) || backup?(e) || excluded?(e) || symlink?(e)
end
special?(e) || backup?(e) || excluded?(e) || symlink?(e) unless included?(e)
end
end

View File

@ -8,10 +8,11 @@ module Jekyll
attr_accessor :content, :ext
attr_writer :output
def_delegators :@doc, :site, :name, :ext, :extname,
:collection, :related_posts,
:coffeescript_file?, :yaml_file?,
:url, :next_doc, :previous_doc
def_delegators :@doc,
:site, :name, :ext, :extname,
:collection, :related_posts,
:coffeescript_file?, :yaml_file?,
:url, :next_doc, :previous_doc
private :coffeescript_file?, :yaml_file?
@ -55,7 +56,7 @@ module Jekyll
#
# Returns true if the string passed in
def include?(something)
(output && output.include?(something)) || content.include?(something)
(output&.include?(something)) || content.include?(something)
end
# The UID for this doc (useful in feeds).
@ -76,7 +77,7 @@ module Jekyll
# Returns the shorthand String identifier of this doc.
def inspect
"<Excerpt: #{self.id}>"
"<Excerpt: #{id}>"
end
def output
@ -160,19 +161,18 @@ module Jekyll
Liquid::Template.tags[tag_name].superclass == Liquid::Block
rescue NoMethodError
Jekyll.logger.error "Error:",
"A Liquid tag in the excerpt of #{doc.relative_path} couldn't be " \
"parsed."
"A Liquid tag in the excerpt of #{doc.relative_path} couldn't be parsed."
raise
end
def print_build_warning
Jekyll.logger.warn "Warning:", "Excerpt modified in #{doc.relative_path}!"
Jekyll.logger.warn "",
"Found a Liquid block containing separator '#{doc.excerpt_separator}' and has " \
"been modified with the appropriate closing tag."
"Found a Liquid block containing separator '#{doc.excerpt_separator}'" \
" and has been modified with the appropriate closing tag."
Jekyll.logger.warn "",
"Feel free to define a custom excerpt or excerpt_separator in the document's " \
"Front Matter if the generated excerpt is unsatisfactory."
"Feel free to define a custom excerpt or excerpt_separator in the" \
" document's Front Matter if the generated excerpt is unsatisfactory."
end
end
end

View File

@ -58,13 +58,13 @@ module Jekyll
Jekyll.logger.debug "Requiring:", name.to_s
require name
rescue LoadError => e
Jekyll.logger.error "Dependency Error:", <<-MSG
Yikes! It looks like you don't have #{name} or one of its dependencies installed.
In order to use Jekyll as currently configured, you'll need to install this gem.
Jekyll.logger.error "Dependency Error:", <<~MSG
Yikes! It looks like you don't have #{name} or one of its dependencies installed.
In order to use Jekyll as currently configured, you'll need to install this gem.
The full error message from Ruby is: '#{e.message}'
The full error message from Ruby is: '#{e.message}'
If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/!
If you run into trouble, you can find helpful resources at https://jekyllrb.com/help/!
MSG
raise Jekyll::Errors::MissingDependencyException, name
end

View File

@ -225,9 +225,7 @@ module Jekyll
#
# Returns the filtered array of objects
def sort(input, property = nil, nils = "first")
if input.nil?
raise ArgumentError, "Cannot sort a null object."
end
raise ArgumentError, "Cannot sort a null object." if input.nil?
if property.nil?
input.sort
else
@ -367,7 +365,6 @@ module Jekyll
condition
end
end
end

View File

@ -64,6 +64,7 @@ module Jekyll
end
private
# month_type: Notations that evaluate to 'Month' via `Time#strftime` ("%b", "%B")
# type: nil (default) or "ordinal"
# style: nil (default) or "US"
@ -96,7 +97,7 @@ module Jekyll
date = Liquid::Utils.to_date(input)
unless date.respond_to?(:to_time)
raise Errors::InvalidDateError,
"Invalid Date: '#{input.inspect}' is not a valid datetime."
"Invalid Date: '#{input.inspect}' is not a valid datetime."
end
date.to_time.dup.localtime
end

View File

@ -57,7 +57,6 @@ module Jekyll
return input if input.nil? || input.empty? || input.start_with?("/")
"/#{input}"
end
end
end
end

View File

@ -122,9 +122,7 @@ module Jekyll
def path_is_subpath?(path, parent_path)
path.ascend do |ascended_path|
if ascended_path.to_s == parent_path.to_s
return true
end
return true if ascended_path.to_s == parent_path.to_s
end
false

View File

@ -77,9 +77,7 @@ module Jekyll
"following hooks #{@registry[owner].keys.inspect}"
end
unless block.respond_to? :call
raise Uncallable, "Hooks must respond to :call"
end
raise Uncallable, "Hooks must respond to :call" unless block.respond_to? :call
insert_hook owner, event, priority, &block
end

View File

@ -2,7 +2,6 @@
module Jekyll
module LiquidExtensions
# Lookup a Liquid variable in the given context.
#
# context - the Liquid context in question.
@ -19,6 +18,5 @@ module Jekyll
lookup || variable
end
end
end

View File

@ -1,96 +1,98 @@
# frozen_string_literal: true
module Jekyll
class LiquidRenderer::Table
def initialize(stats)
@stats = stats
end
def to_s(num_of_rows = 50)
data = data_for_table(num_of_rows)
widths = table_widths(data)
generate_table(data, widths)
end
private
def generate_table(data, widths)
str = String.new("\n")
table_head = data.shift
str << generate_row(table_head, widths)
str << generate_table_head_border(table_head, widths)
data.each do |row_data|
str << generate_row(row_data, widths)
class LiquidRenderer
class Table
def initialize(stats)
@stats = stats
end
str << "\n"
str
end
def generate_table_head_border(row_data, widths)
str = String.new("")
row_data.each_index do |cell_index|
str << "-" * widths[cell_index]
str << "-+-" unless cell_index == row_data.length - 1
def to_s(num_of_rows = 50)
data = data_for_table(num_of_rows)
widths = table_widths(data)
generate_table(data, widths)
end
str << "\n"
str
end
private
def generate_row(row_data, widths)
str = String.new("")
def generate_table(data, widths)
str = +"\n"
row_data.each_with_index do |cell_data, cell_index|
str << if cell_index.zero?
cell_data.ljust(widths[cell_index], " ")
else
cell_data.rjust(widths[cell_index], " ")
end
table_head = data.shift
str << generate_row(table_head, widths)
str << generate_table_head_border(table_head, widths)
str << " | " unless cell_index == row_data.length - 1
end
str << "\n"
str
end
def table_widths(data)
widths = []
data.each do |row|
row.each_with_index do |cell, index|
widths[index] = [cell.length, widths[index]].compact.max
data.each do |row_data|
str << generate_row(row_data, widths)
end
str << "\n"
str
end
widths
end
def generate_table_head_border(row_data, widths)
str = +""
def data_for_table(num_of_rows)
sorted = @stats.sort_by { |_, file_stats| -file_stats[:time] }
sorted = sorted.slice(0, num_of_rows)
row_data.each_index do |cell_index|
str << "-" * widths[cell_index]
str << "-+-" unless cell_index == row_data.length - 1
end
table = [%w(Filename Count Bytes Time)]
sorted.each do |filename, file_stats|
row = []
row << filename
row << file_stats[:count].to_s
row << format_bytes(file_stats[:bytes])
row << format("%.3f", file_stats[:time])
table << row
str << "\n"
str
end
table
end
def generate_row(row_data, widths)
str = +""
def format_bytes(bytes)
bytes /= 1024.0
format("%.2fK", bytes)
row_data.each_with_index do |cell_data, cell_index|
str << if cell_index.zero?
cell_data.ljust(widths[cell_index], " ")
else
cell_data.rjust(widths[cell_index], " ")
end
str << " | " unless cell_index == row_data.length - 1
end
str << "\n"
str
end
def table_widths(data)
widths = []
data.each do |row|
row.each_with_index do |cell, index|
widths[index] = [cell.length, widths[index]].compact.max
end
end
widths
end
def data_for_table(num_of_rows)
sorted = @stats.sort_by { |_, file_stats| -file_stats[:time] }
sorted = sorted.slice(0, num_of_rows)
table = [%w(Filename Count Bytes Time)]
sorted.each do |filename, file_stats|
row = []
row << filename
row << file_stats[:count].to_s
row << format_bytes(file_stats[:bytes])
row << format("%.3f", file_stats[:time])
table << row
end
table
end
def format_bytes(bytes)
bytes /= 1024.0
format("%.2fK", bytes)
end
end
end
end

View File

@ -95,11 +95,11 @@ module Jekyll
#
# Returns the String url.
def url
@url ||= URL.new({
@url ||= URL.new(
:template => template,
:placeholders => url_placeholders,
:permalink => permalink,
}).to_s
:permalink => permalink
).to_s
end
# Returns a hash of URL placeholder names (as symbols) mapping to the

View File

@ -13,7 +13,7 @@ module Jekyll
#
def self.inherited(const)
return catch_inheritance(const) do |const_|
catch_inheritance(const) do |const_|
catch_inheritance(const_)
end
end
@ -23,9 +23,7 @@ module Jekyll
def self.catch_inheritance(const)
const.define_singleton_method :inherited do |const_|
(@children ||= Set.new).add const_
if block_given?
yield const_
end
yield const_ if block_given?
end
end
@ -48,9 +46,7 @@ module Jekyll
# Returns the Symbol priority.
def self.priority(priority = nil)
@priority ||= nil
if priority && PRIORITIES.key?(priority)
@priority = priority
end
@priority = priority if priority && PRIORITIES.key?(priority)
@priority || :normal
end
@ -62,9 +58,7 @@ module Jekyll
#
# Returns the safety Boolean.
def self.safe(safe = nil)
unless defined?(@safe) && safe.nil?
@safe = safe
end
@safe = safe unless defined?(@safe) && safe.nil?
@safe || false
end
@ -74,7 +68,7 @@ module Jekyll
#
# Returns -1, 0, 1.
def self.<=>(other)
PRIORITIES[other.priority] <=> PRIORITIES[self.priority]
PRIORITIES[other.priority] <=> PRIORITIES[priority]
end
# Spaceship is priority [higher -> lower]

View File

@ -76,9 +76,7 @@ module Jekyll
dot_dirs.each do |file|
dir_path = site.in_source_dir(dir, file)
rel_path = File.join(dir, file)
unless @site.dest.chomp("/") == dir_path
@site.reader.read_directories(rel_path)
end
@site.reader.read_directories(rel_path) unless @site.dest.chomp("/") == dir_path
end
end

View File

@ -54,16 +54,14 @@ module Jekyll
def read_data_file(path)
case File.extname(path).downcase
when ".csv"
CSV.read(path, {
:headers => true,
:encoding => site.config["encoding"],
}).map(&:to_hash)
CSV.read(path,
:headers => true,
:encoding => site.config["encoding"]).map(&:to_hash)
when ".tsv"
CSV.read(path, {
:col_sep => "\t",
:headers => true,
:encoding => site.config["encoding"],
}).map(&:to_hash)
CSV.read(path,
:col_sep => "\t",
:headers => true,
:encoding => site.config["encoding"]).map(&:to_hash)
else
SafeYAML.load_file(path)
end

View File

@ -63,9 +63,7 @@ module Jekyll
def layout_directory_in_cwd
dir = Jekyll.sanitized_path(Dir.pwd, site.config["layouts_dir"])
if File.directory?(dir) && !site.safe
dir
end
dir if File.directory?(dir) && !site.safe
end
end
end

View File

@ -62,10 +62,9 @@ module Jekyll
@site.reader.get_entries(dir, magic_dir).map do |entry|
next unless entry =~ matcher
path = @site.in_source_dir(File.join(dir, magic_dir, entry))
Document.new(path, {
:site => @site,
:collection => @site.posts,
})
Document.new(path,
:site => @site,
:collection => @site.posts)
end.reject(&:nil?)
end
end

View File

@ -8,7 +8,7 @@ module Jekyll
end
def read
return unless site.theme && site.theme.assets_path
return unless site.theme&.assets_path
Find.find(site.theme.assets_path) do |path|
next if File.directory?(path)
@ -21,6 +21,7 @@ module Jekyll
end
private
def read_theme_asset(path)
base = site.theme.root
dir = File.dirname(path.sub("#{site.theme.root}/", ""))
@ -28,18 +29,18 @@ module Jekyll
if Utils.has_yaml_header?(path)
append_unless_exists site.pages,
Jekyll::Page.new(site, base, dir, name)
Jekyll::Page.new(site, base, dir, name)
else
append_unless_exists site.static_files,
Jekyll::StaticFile.new(site, base, "/#{dir}", name)
Jekyll::StaticFile.new(site, base, "/#{dir}", name)
end
end
def append_unless_exists(haystack, new_item)
if haystack.any? { |file| file.relative_path == new_item.relative_path }
Jekyll.logger.debug "Theme:",
"Ignoring #{new_item.relative_path} in theme due to existing file " \
"with that path in site."
"Ignoring #{new_item.relative_path} in theme due to existing file " \
"with that path in site."
return
end

View File

@ -28,9 +28,7 @@ module Jekyll
regenerate_document?(document)
else
source_path = document.respond_to?(:path) ? document.path : nil
dest_path = if document.respond_to?(:destination)
document.destination(@site.dest)
end
dest_path = document.destination(@site.dest) if document.respond_to?(:destination)
source_modified_or_dest_missing?(source_path, dest_path)
end
end
@ -89,9 +87,7 @@ module Jekyll
return true if path.nil?
# Check for path in cache
if cache.key? path
return cache[path]
end
return cache[path] if cache.key? path
if metadata[path]
# If we have seen this file before,
@ -183,9 +179,7 @@ module Jekyll
# If one of this file dependencies have been modified,
# set the regeneration bit for both the dependency and the file to true
metadata[path]["deps"].each do |dependency|
if modified?(dependency)
return cache[dependency] = cache[path] = true
end
return cache[dependency] = cache[path] = true if modified?(dependency)
end
if File.exist?(path) && metadata[path]["mtime"].eql?(File.mtime(path))

View File

@ -101,8 +101,8 @@ module Jekyll
converter.convert output
rescue StandardError => e
Jekyll.logger.error "Conversion error:",
"#{converter.class} encountered an error while "\
"converting '#{document.relative_path}':"
"#{converter.class} encountered an error while "\
"converting '#{document.relative_path}':"
Jekyll.logger.error("", e.to_s)
raise e
end
@ -121,13 +121,13 @@ module Jekyll
template = site.liquid_renderer.file(path).parse(content)
template.warnings.each do |e|
Jekyll.logger.warn "Liquid Warning:",
LiquidRenderer.format_error(e, path || document.relative_path)
LiquidRenderer.format_error(e, path || document.relative_path)
end
template.render!(payload, info)
# rubocop: disable RescueException
rescue Exception => e
Jekyll.logger.error "Liquid Exception:",
LiquidRenderer.format_error(e, path || document.relative_path)
LiquidRenderer.format_error(e, path || document.relative_path)
raise e
end
# rubocop: enable RescueException
@ -213,9 +213,7 @@ module Jekyll
# Returns nothing
def assign_pages!
payload["page"] = document.to_liquid
payload["paginator"] = if document.respond_to?(:pager)
document.pager.to_liquid
end
payload["paginator"] = (document.pager.to_liquid if document.respond_to?(:pager))
end
# Set related posts to payload if document is a post.
@ -235,9 +233,7 @@ module Jekyll
def assign_layout_data!
layout = layouts[document.data["layout"]]
if layout
payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {})
end
payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) if layout
end
def permalink_ext

View File

@ -44,8 +44,8 @@ module Jekyll
@config = config.clone
%w(safe lsi highlighter baseurl exclude include future unpublished
show_drafts limit_posts keep_files).each do |opt|
self.send("#{opt}=", config[opt])
show_drafts limit_posts keep_files).each do |opt|
send("#{opt}=", config[opt])
end
# keep using `gems` to avoid breaking change
@ -98,9 +98,7 @@ module Jekyll
@liquid_renderer.reset
@site_cleaner = nil
if limit_posts < 0
raise ArgumentError, "limit_posts must be a non-negative number"
end
raise ArgumentError, "limit_posts must be a non-negative number" if limit_posts.negative?
Jekyll::Hooks.trigger :site, :after_reset, self
end
@ -124,7 +122,7 @@ module Jekyll
Pathname.new(source).ascend do |path|
if path == dest_pathname
raise Errors::FatalException,
"Destination directory cannot be or contain the Source directory."
"Destination directory cannot be or contain the Source directory."
end
end
end
@ -174,7 +172,7 @@ module Jekyll
start = Time.now
generator.generate(self)
Jekyll.logger.debug "Generating:",
"#{generator.class} finished in #{Time.now - start} seconds."
"#{generator.class} finished in #{Time.now - start} seconds."
end
end
@ -234,7 +232,7 @@ module Jekyll
# array of posts ) then sort each array in reverse order.
hash = Hash.new { |h, key| h[key] = [] }
posts.docs.each do |p|
p.data[post_attr].each { |t| hash[t] << p } if p.data[post_attr]
p.data[post_attr]&.each { |t| hash[t] << p }
end
hash.each_value { |posts| posts.sort!.reverse! }
hash
@ -303,10 +301,10 @@ module Jekyll
def relative_permalinks_are_deprecated
if config["relative_permalinks"]
Jekyll.logger.abort_with "Since v3.0, permalinks for pages" \
" in subfolders must be relative to the" \
" site source directory, not the parent" \
" directory. Check https://jekyllrb.com/docs/upgrading/"\
" for more info."
" in subfolders must be relative to the" \
" site source directory, not the parent" \
" directory. Check https://jekyllrb.com/docs/upgrading/"\
" for more info."
end
end
@ -409,9 +407,9 @@ module Jekyll
#
# Returns nothing
def limit_posts!
if limit_posts > 0
if limit_posts.positive?
limit = posts.docs.length < limit_posts ? posts.docs.length : limit_posts
self.posts.docs = posts.docs[-limit, limit]
posts.docs = posts.docs[-limit, limit]
end
end
@ -444,12 +442,12 @@ module Jekyll
def configure_include_paths
@includes_load_paths = Array(in_source_dir(config["includes_dir"].to_s))
@includes_load_paths << theme.includes_path if theme && theme.includes_path
@includes_load_paths << theme.includes_path if theme&.includes_path
end
def configure_file_read_opts
self.file_read_opts = {}
self.file_read_opts[:encoding] = config["encoding"] if config["encoding"]
file_read_opts[:encoding] = config["encoding"] if config["encoding"]
self.file_read_opts = Jekyll::Utils.merged_file_read_opts(self, {})
end

View File

@ -133,10 +133,10 @@ module Jekyll
@url ||= if @collection.nil?
relative_path
else
::Jekyll::URL.new({
::Jekyll::URL.new(
:template => @collection.url_template,
:placeholders => placeholders,
})
:placeholders => placeholders
)
end.to_s.chomp("/")
end
@ -152,6 +152,7 @@ module Jekyll
end
private
def copy_file(dest_path)
if @site.safe || Jekyll.env == "production"
FileUtils.cp(path, dest_path)

View File

@ -16,9 +16,7 @@ module Jekyll
severity ||= UNKNOWN
@logdev = logdevice(severity)
if @logdev.nil? || severity < @level
return true
end
return true if @logdev.nil? || severity < @level
progname ||= @progname
if message.nil?
if block_given?

View File

@ -18,13 +18,13 @@ module Jekyll
@lang = Regexp.last_match(1).downcase
@highlight_options = parse_options(Regexp.last_match(2))
else
raise SyntaxError, <<-MSG
Syntax Error in tag 'highlight' while parsing the following markup:
raise SyntaxError, <<~MSG
Syntax Error in tag 'highlight' while parsing the following markup:
#{markup}
#{markup}
Valid syntax: highlight <lang> [linenos]
MSG
Valid syntax: highlight <lang> [linenos]
MSG
end
end
@ -75,7 +75,7 @@ MSG
input.scan(OPTIONS_REGEX) do |opt|
key, value = opt.split("=")
# If a quoted list, convert to array
if value && value.include?('"')
if value&.include?('"')
value.delete!('"')
value = value.split
end
@ -96,14 +96,14 @@ MSG
)
if highlighted_code.nil?
Jekyll.logger.error <<-MSG
There was an error highlighting your code:
Jekyll.logger.error <<~MSG
There was an error highlighting your code:
#{code}
#{code}
While attempting to convert the above code, Pygments.rb returned an unacceptable value.
This is usually a timeout problem solved by running `jekyll build` again.
MSG
While attempting to convert the above code, Pygments.rb returned an unacceptable value.
This is usually a timeout problem solved by running `jekyll build` again.
MSG
raise ArgumentError, "Pygments.rb returned an unacceptable value "\
"when attempting to highlight some code."
end

View File

@ -55,31 +55,31 @@ module Jekyll
def validate_file_name(file)
if file =~ INVALID_SEQUENCES || file !~ VALID_FILENAME_CHARS
raise ArgumentError, <<-MSG
Invalid syntax for include tag. File contains invalid characters or sequences:
raise ArgumentError, <<~MSG
Invalid syntax for include tag. File contains invalid characters or sequences:
#{file}
#{file}
Valid syntax:
Valid syntax:
#{syntax_example}
#{syntax_example}
MSG
MSG
end
end
def validate_params
unless @params =~ FULL_VALID_SYNTAX
raise ArgumentError, <<-MSG
Invalid syntax for include tag:
raise ArgumentError, <<~MSG
Invalid syntax for include tag:
#{@params}
#{@params}
Valid syntax:
Valid syntax:
#{syntax_example}
#{syntax_example}
MSG
MSG
end
end
@ -138,7 +138,7 @@ MSG
end
def add_include_to_dependency(site, path, context)
if context.registers[:page] && context.registers[:page].key?("path")
if context.registers[:page]&.key?("path")
site.regenerator.add_dependency(
site.in_source_dir(context.registers[:page]["path"]),
path

View File

@ -5,7 +5,7 @@ module Jekyll
class Link < Liquid::Tag
class << self
def tag_name
self.name.split("::").last.downcase
name.split("::").last.downcase
end
end
@ -27,11 +27,11 @@ module Jekyll
return item.url if item.relative_path == "/#{relative_path}"
end
raise ArgumentError, <<-MSG
Could not find document '#{relative_path}' in tag '#{self.class.tag_name}'.
raise ArgumentError, <<~MSG
Could not find document '#{relative_path}' in tag '#{self.class.tag_name}'.
Make sure the document exists and the path is correct.
MSG
Make sure the document exists and the path is correct.
MSG
end
end
end

View File

@ -13,7 +13,7 @@ module Jekyll
all, @path, @date, @slug = *name.sub(%r!^/!, "").match(MATCHER)
unless all
raise Jekyll::Errors::InvalidPostNameError,
"'#{name}' does not contain valid date and/or title."
"'#{name}' does not contain valid date and/or title."
end
escaped_slug = Regexp.escape(slug)
@ -22,8 +22,10 @@ module Jekyll
end
def post_date
@post_date ||= Utils.parse_date(date,
"\"#{date}\" does not contain valid date and/or title.")
@post_date ||= Utils.parse_date(
date,
"'#{date}' does not contain valid date and/or title."
)
end
def ==(other)
@ -38,6 +40,7 @@ module Jekyll
end
private
# Construct the directory-aware post slug for a Jekyll::Post
#
# other - the Jekyll::Post
@ -60,13 +63,11 @@ module Jekyll
begin
@post = PostComparer.new(@orig_post)
rescue StandardError => e
raise Jekyll::Errors::PostURLError, <<-MSG
Could not parse name of post "#{@orig_post}" in tag 'post_url'.
Make sure the post exists and the name is correct.
#{e.class}: #{e.message}
MSG
raise Jekyll::Errors::PostURLError, <<~MSG
Could not parse name of post "#{@orig_post}" in tag 'post_url'.
Make sure the post exists and the name is correct.
#{e.class}: #{e.message}
MSG
end
end
@ -90,11 +91,10 @@ MSG
return p.url
end
raise Jekyll::Errors::PostURLError, <<-MSG
Could not find post "#{@orig_post}" in tag 'post_url'.
Make sure the post exists and the name is correct.
MSG
raise Jekyll::Errors::PostURLError, <<~MSG
Could not find post "#{@orig_post}" in tag 'post_url'.
Make sure the post exists and the name is correct.
MSG
end
end
end

View File

@ -3,7 +3,7 @@
module Jekyll
class Theme
extend Forwardable
attr_reader :name
attr_reader :name
def_delegator :gemspec, :version, :version
def initialize(name)
@ -23,19 +23,19 @@ module Jekyll
end
def includes_path
@includes_path ||= path_for "_includes".freeze
@includes_path ||= path_for "_includes"
end
def layouts_path
@layouts_path ||= path_for "_layouts".freeze
@layouts_path ||= path_for "_layouts"
end
def sass_path
@sass_path ||= path_for "_sass".freeze
@sass_path ||= path_for "_sass"
end
def assets_path
@assets_path ||= path_for "assets".freeze
@assets_path ||= path_for "assets"
end
def configure_sass
@ -66,7 +66,7 @@ module Jekyll
@gemspec ||= Gem::Specification.find_by_name(name)
rescue Gem::LoadError
raise Jekyll::Errors::MissingDependencyException,
"The #{name} theme could not be found."
"The #{name} theme could not be found."
end
end
end

View File

@ -1,119 +1,121 @@
# frozen_string_literal: true
class Jekyll::ThemeBuilder
SCAFFOLD_DIRECTORIES = %w(
assets _layouts _includes _sass
).freeze
module Jekyll
class ThemeBuilder
SCAFFOLD_DIRECTORIES = %w(
assets _layouts _includes _sass
).freeze
attr_reader :name, :path, :code_of_conduct
attr_reader :name, :path, :code_of_conduct
def initialize(theme_name, opts)
@name = theme_name.to_s.tr(" ", "_").squeeze("_")
@path = Pathname.new(File.expand_path(name, Dir.pwd))
@code_of_conduct = !!opts["code_of_conduct"]
end
def initialize(theme_name, opts)
@name = theme_name.to_s.tr(" ", "_").squeeze("_")
@path = Pathname.new(File.expand_path(name, Dir.pwd))
@code_of_conduct = !!opts["code_of_conduct"]
end
def create!
create_directories
create_starter_files
create_gemspec
create_accessories
initialize_git_repo
end
def create!
create_directories
create_starter_files
create_gemspec
create_accessories
initialize_git_repo
end
def user_name
@user_name ||= `git config user.name`.chomp
end
def user_name
@user_name ||= `git config user.name`.chomp
end
def user_email
@user_email ||= `git config user.email`.chomp
end
def user_email
@user_email ||= `git config user.email`.chomp
end
private
private
def root
@root ||= Pathname.new(File.expand_path("../", __dir__))
end
def root
@root ||= Pathname.new(File.expand_path("../", __dir__))
end
def template_file(filename)
[
root.join("theme_template", "#{filename}.erb"),
root.join("theme_template", filename.to_s),
].find(&:exist?)
end
def template_file(filename)
[
root.join("theme_template", "#{filename}.erb"),
root.join("theme_template", filename.to_s),
].find(&:exist?)
end
def template(filename)
erb.render(template_file(filename).read)
end
def template(filename)
erb.render(template_file(filename).read)
end
def erb
@erb ||= ERBRenderer.new(self)
end
def erb
@erb ||= ERBRenderer.new(self)
end
def mkdir_p(directories)
Array(directories).each do |directory|
full_path = path.join(directory)
def mkdir_p(directories)
Array(directories).each do |directory|
full_path = path.join(directory)
Jekyll.logger.info "create", full_path.to_s
FileUtils.mkdir_p(full_path)
end
end
def write_file(filename, contents)
full_path = path.join(filename)
Jekyll.logger.info "create", full_path.to_s
FileUtils.mkdir_p(full_path)
end
end
def write_file(filename, contents)
full_path = path.join(filename)
Jekyll.logger.info "create", full_path.to_s
File.write(full_path, contents)
end
def create_directories
mkdir_p(SCAFFOLD_DIRECTORIES)
end
def create_starter_files
%w(page post default).each do |layout|
write_file("_layouts/#{layout}.html", template("_layouts/#{layout}.html"))
end
end
def create_gemspec
write_file("Gemfile", template("Gemfile"))
write_file("#{name}.gemspec", template("theme.gemspec"))
end
def create_accessories
accessories = %w(README.md LICENSE.txt)
accessories << "CODE_OF_CONDUCT.md" if code_of_conduct
accessories.each do |filename|
write_file(filename, template(filename))
end
end
def initialize_git_repo
Jekyll.logger.info "initialize", path.join(".git").to_s
Dir.chdir(path.to_s) { `git init` }
write_file(".gitignore", template("gitignore"))
end
class ERBRenderer
extend Forwardable
def_delegator :@theme_builder, :name, :theme_name
def_delegator :@theme_builder, :user_name, :user_name
def_delegator :@theme_builder, :user_email, :user_email
def initialize(theme_builder)
@theme_builder = theme_builder
File.write(full_path, contents)
end
def jekyll_version_with_minor
Jekyll::VERSION.split(".").take(2).join(".")
def create_directories
mkdir_p(SCAFFOLD_DIRECTORIES)
end
def theme_directories
SCAFFOLD_DIRECTORIES
def create_starter_files
%w(page post default).each do |layout|
write_file("_layouts/#{layout}.html", template("_layouts/#{layout}.html"))
end
end
def render(contents)
ERB.new(contents).result binding
def create_gemspec
write_file("Gemfile", template("Gemfile"))
write_file("#{name}.gemspec", template("theme.gemspec"))
end
def create_accessories
accessories = %w(README.md LICENSE.txt)
accessories << "CODE_OF_CONDUCT.md" if code_of_conduct
accessories.each do |filename|
write_file(filename, template(filename))
end
end
def initialize_git_repo
Jekyll.logger.info "initialize", path.join(".git").to_s
Dir.chdir(path.to_s) { `git init` }
write_file(".gitignore", template("gitignore"))
end
class ERBRenderer
extend Forwardable
def_delegator :@theme_builder, :name, :theme_name
def_delegator :@theme_builder, :user_name, :user_name
def_delegator :@theme_builder, :user_email, :user_email
def initialize(theme_builder)
@theme_builder = theme_builder
end
def jekyll_version_with_minor
Jekyll::VERSION.split(".").take(2).join(".")
end
def theme_directories
SCAFFOLD_DIRECTORIES
end
def render(contents)
ERB.new(contents).result binding
end
end
end
end

View File

@ -98,8 +98,8 @@ module Jekyll
winner = pool.find { |key| @placeholders.key?(key) }
if winner.nil?
raise NoMethodError,
"The URL template doesn't have #{pool.join(" or ")} keys. "\
"Check your permalink template!"
"The URL template doesn't have #{pool.join(" or ")} keys. "\
"Check your permalink template!"
end
value = @placeholders[winner]

View File

@ -21,7 +21,6 @@ module Jekyll
[stdin, stdout, stderr].each(&:close)
[process.value, out + err]
end
end
end
end

View File

@ -3,7 +3,6 @@
module Jekyll
module Utils
module Internet
# Public: Determine whether the present device has a connection to
# the Internet. This allows plugin writers which require the outside
# world to have a neat fallback mechanism for offline building.
@ -18,7 +17,9 @@ module Jekyll
# end
#
# Returns true if a DNS call can successfully be made, or false if not.
module_function
def connected?
!dns("example.com").nil?
end
@ -31,7 +32,6 @@ module Jekyll
rescue Resolv::ResolvError, Resolv::ResolvTimeout
nil
end
end
end
end

View File

@ -31,7 +31,7 @@ module Jekyll
# --
alias_method :really_windows?, \
:vanilla_windows?
:vanilla_windows?
#
@ -68,6 +68,7 @@ module Jekyll
#
private
def proc_version
@proc_version ||= begin
Pathutil.new(

View File

@ -1,7 +1,5 @@
# frozen_string_literal: true
require "thread"
module Jekyll
module Utils
# Based on the pattern and code from
@ -25,9 +23,7 @@ module Jekyll
def wait
@lock.synchronize do
unless @flag
@cond.wait(@lock)
end
@cond.wait(@lock) unless @flag
end
end
end

View File

@ -21,7 +21,7 @@ module Jekyll
# is denoted as:
# EST+5 (or) EST+05:00
# Reference: http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
sign = difference < 0 ? "-" : "+"
sign = difference.negative? ? "-" : "+"
offset = sign == "-" ? "+" : "-" unless difference.zero?
#
# convert the difference (in seconds) to hours, as a rational number, and perform

View File

@ -1,5 +1,5 @@
# frozen_string_literal: true
module Jekyll
VERSION = "3.8.2".freeze
VERSION = "3.8.2"
end