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

View File

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

View File

@ -51,26 +51,26 @@ module Jekyll
# rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/MethodLength
def add_build_options(cmd) def add_build_options(cmd)
cmd.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]", cmd.option "config", "--config CONFIG_FILE[,CONFIG_FILE2,...]",
Array, "Custom configuration file" Array, "Custom configuration file"
cmd.option "destination", "-d", "--destination DESTINATION", 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 "source", "-s", "--source SOURCE", "Custom source directory"
cmd.option "future", "--future", "Publishes posts with a future date" cmd.option "future", "--future", "Publishes posts with a future date"
cmd.option "limit_posts", "--limit_posts MAX_POSTS", Integer, 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 "watch", "-w", "--[no-]watch", "Watch for changes and rebuild"
cmd.option "baseurl", "-b", "--baseurl URL", 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 "force_polling", "--force_polling", "Force watch to use polling"
cmd.option "lsi", "--lsi", "Use LSI for improved related posts" cmd.option "lsi", "--lsi", "Use LSI for improved related posts"
cmd.option "show_drafts", "-D", "--drafts", "Render posts in the _drafts folder" cmd.option "show_drafts", "-D", "--drafts", "Render posts in the _drafts folder"
cmd.option "unpublished", "--unpublished", 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 "quiet", "-q", "--quiet", "Silence output."
cmd.option "verbose", "-V", "--verbose", "Print verbose output." cmd.option "verbose", "-V", "--verbose", "Print verbose output."
cmd.option "incremental", "-I", "--incremental", "Enable incremental rebuild." cmd.option "incremental", "-I", "--incremental", "Enable incremental rebuild."
cmd.option "strict_front_matter", "--strict_front_matter", 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 end
# rubocop:enable Metrics/MethodLength # rubocop:enable Metrics/MethodLength

View File

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

View File

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

View File

@ -25,7 +25,7 @@ module Jekyll
def invalid_command(prog, cmd) def invalid_command(prog, cmd)
Jekyll.logger.error "Error:", 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(", ") Jekyll.logger.info "Valid commands:", prog.commands.keys.join(", ")
end end
end end

View File

@ -62,38 +62,32 @@ module Jekyll
private private
def gemfile_contents def gemfile_contents
<<-RUBY <<~RUBY
source "https://rubygems.org" 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. RUBY
# 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
end end
def create_site(new_blog_path) def create_site(new_blog_path)

View File

@ -2,39 +2,41 @@
require "erb" require "erb"
class Jekyll::Commands::NewTheme < Jekyll::Command module Jekyll
class << self module Commands
def init_with_program(prog) class NewTheme < Jekyll::Command
prog.command(:"new-theme") do |c| class << self
c.syntax "new-theme NAME" def init_with_program(prog)
c.description "Creates a new Jekyll theme scaffold" prog.command(:"new-theme") do |c|
c.option "code_of_conduct", \ c.syntax "new-theme NAME"
"-c", "--code-of-conduct", \ c.description "Creates a new Jekyll theme scaffold"
"Include a Code of Conduct. (defaults to false)" c.option "code_of_conduct", \
"-c", "--code-of-conduct", \
"Include a Code of Conduct. (defaults to false)"
c.action do |args, opts| c.action do |args, opts|
Jekyll::Commands::NewTheme.process(args, opts) Jekyll::Commands::NewTheme.process(args, opts)
end
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
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
end end

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -58,13 +58,13 @@ module Jekyll
Jekyll.logger.debug "Requiring:", name.to_s Jekyll.logger.debug "Requiring:", name.to_s
require name require name
rescue LoadError => e rescue LoadError => e
Jekyll.logger.error "Dependency Error:", <<-MSG Jekyll.logger.error "Dependency Error:", <<~MSG
Yikes! It looks like you don't have #{name} or one of its dependencies installed. 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. 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 MSG
raise Jekyll::Errors::MissingDependencyException, name raise Jekyll::Errors::MissingDependencyException, name
end end

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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