Merge pull request #4301 from pathawks/rubocop

Merge pull request 4301
This commit is contained in:
Parker Moore 2016-01-04 12:31:55 -08:00
commit 5580972282
52 changed files with 339 additions and 332 deletions

View File

@ -1,7 +1,7 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
STDOUT.sync = true STDOUT.sync = true
$:.unshift File.join(File.dirname(__FILE__), *%w{ .. lib }) $LOAD_PATH.unshift File.join(File.dirname(__FILE__), *%w( .. lib ))
require 'jekyll' require 'jekyll'
require 'mercenary' require 'mercenary'
@ -28,7 +28,7 @@ Mercenary.program(:jekyll) do |p|
Jekyll::Command.subclasses.each { |c| c.init_with_program(p) } Jekyll::Command.subclasses.each { |c| c.init_with_program(p) }
p.action do |args, options| p.action do |args, _|
if args.empty? if args.empty?
Jekyll.logger.error "A subcommand is required." Jekyll.logger.error "A subcommand is required."
puts p puts p

View File

@ -1,4 +1,4 @@
$:.unshift File.dirname(__FILE__) # For use/testing when no gem is installed $LOAD_PATH.unshift File.dirname(__FILE__) # For use/testing when no gem is installed
# Require all of the Ruby files in the given directory. # Require all of the Ruby files in the given directory.
# #
@ -95,7 +95,7 @@ module Jekyll
# list of option names and their defaults. # list of option names and their defaults.
# #
# Returns the final configuration Hash. # Returns the final configuration Hash.
def configuration(override = Hash.new) def configuration(override = {})
config = Configuration[Configuration::DEFAULTS] config = Configuration[Configuration::DEFAULTS]
override = Configuration[override].stringify_keys override = Configuration[override].stringify_keys
unless override.delete('skip_config_files') unless override.delete('skip_config_files')
@ -156,16 +156,15 @@ module Jekyll
clean_path = File.expand_path(questionable_path, "/") clean_path = File.expand_path(questionable_path, "/")
clean_path = clean_path.sub(/\A\w\:\//, '/') clean_path = clean_path.sub(/\A\w\:\//, '/')
unless clean_path.start_with?(base_directory.sub(/\A\w\:\//, '/')) if clean_path.start_with?(base_directory.sub(/\A\w\:\//, '/'))
File.join(base_directory, clean_path)
else
clean_path clean_path
else
File.join(base_directory, clean_path)
end end
end end
# Conditional optimizations # Conditional optimizations
Jekyll::External.require_if_present('liquid-c') Jekyll::External.require_if_present('liquid-c')
end end
end end

View File

@ -13,7 +13,7 @@ module Jekyll
# Cleans up the site's destination directory # Cleans up the site's destination directory
def cleanup! def cleanup!
FileUtils.rm_rf(obsolete_files) FileUtils.rm_rf(obsolete_files)
FileUtils.rm_rf(metadata_file) if !@site.incremental? FileUtils.rm_rf(metadata_file) unless @site.incremental?
end end
private private

View File

@ -56,7 +56,7 @@ module Jekyll
full_path = collection_dir(file_path) full_path = collection_dir(file_path)
next if File.directory?(full_path) next if File.directory?(full_path)
if Utils.has_yaml_header? full_path if Utils.has_yaml_header? full_path
doc = Jekyll::Document.new(full_path, { site: site, collection: self }) doc = Jekyll::Document.new(full_path, { :site => site, :collection => self })
doc.read doc.read
if site.publisher.publish?(doc) || !write? if site.publisher.publish?(doc) || !write?
docs << doc docs << doc
@ -76,10 +76,11 @@ module Jekyll
# Returns an Array of file paths to the documents in this collection # Returns an Array of file paths to the documents in this collection
# relative to the collection's directory # relative to the collection's directory
def entries def entries
return Array.new unless exists? return [] unless exists?
@entries ||= @entries ||=
Utils.safe_glob(collection_dir, ["**", "*.*"]).map do |entry| Utils.safe_glob(collection_dir, ["**", "*.*"]).map do |entry|
entry["#{collection_dir}/"] = ''; entry entry["#{collection_dir}/"] = ''
entry
end end
end end
@ -88,7 +89,7 @@ module Jekyll
# #
# Returns a list of filtered entry paths. # Returns a list of filtered entry paths.
def filtered_entries def filtered_entries
return Array.new unless exists? return [] unless exists?
@filtered_entries ||= @filtered_entries ||=
Dir.chdir(directory) do Dir.chdir(directory) do
entry_filter.filter(entries).reject do |f| entry_filter.filter(entries).reject do |f|
@ -195,7 +196,7 @@ module Jekyll
# Returns the metadata for this collection # Returns the metadata for this collection
def extract_metadata def extract_metadata
if site.config['collections'].is_a?(Hash) if site.config['collections'].is_a?(Hash)
site.config['collections'][label] || Hash.new site.config['collections'][label] || {}
else else
{} {}
end end

View File

@ -1,8 +1,6 @@
module Jekyll module Jekyll
class Command class Command
class << self class << self
# A list of subclasses of Jekyll::Command # A list of subclasses of Jekyll::Command
def subclasses def subclasses
@subclasses ||= [] @subclasses ||= []
@ -62,8 +60,6 @@ module Jekyll
c.option 'verbose', '-V', '--verbose', 'Print verbose output.' c.option 'verbose', '-V', '--verbose', 'Print verbose output.'
c.option 'incremental', '-I', '--incremental', 'Enable incremental rebuild.' c.option 'incremental', '-I', '--incremental', 'Enable incremental rebuild.'
end end
end
end
end end
end end

View File

@ -1,9 +1,7 @@
module Jekyll module Jekyll
module Commands module Commands
class Build < Command class Build < Command
class << self class << self
# Create the Mercenary command for the Jekyll CLI for this Command # Create the Mercenary command for the Jekyll CLI for this Command
def init_with_program(prog) def init_with_program(prog)
prog.command(:build) do |c| prog.command(:build) do |c|
@ -13,7 +11,7 @@ module Jekyll
add_build_options(c) add_build_options(c)
c.action do |args, options| c.action do |_, options|
options["serving"] = false options["serving"] = false
Jekyll::Commands::Build.process(options) Jekyll::Commands::Build.process(options)
end end
@ -67,13 +65,11 @@ module Jekyll
# options - A Hash of options passed to the command # options - A Hash of options passed to the command
# #
# Returns nothing. # Returns nothing.
def watch(site, options) def watch(_site, options)
External.require_with_graceful_fail 'jekyll-watch' External.require_with_graceful_fail 'jekyll-watch'
Jekyll::Watcher.watch(options) Jekyll::Watcher.watch(options)
end end
end # end of class << self end # end of class << self
end end
end end
end end

View File

@ -2,7 +2,6 @@ module Jekyll
module Commands module Commands
class Clean < Command class Clean < Command
class << self class << self
def init_with_program(prog) def init_with_program(prog)
prog.command(:clean) do |c| prog.command(:clean) do |c|
c.syntax 'clean [subcommand]' c.syntax 'clean [subcommand]'
@ -10,7 +9,7 @@ module Jekyll
add_build_options(c) add_build_options(c)
c.action do |args, options| c.action do |_, options|
Jekyll::Commands::Clean.process(options) Jekyll::Commands::Clean.process(options)
end end
end end
@ -37,7 +36,6 @@ module Jekyll
Jekyll.logger.info "Nothing to do for #{metadata_file}." Jekyll.logger.info "Nothing to do for #{metadata_file}."
end end
end end
end end
end end
end end

View File

@ -2,7 +2,6 @@ module Jekyll
module Commands module Commands
class Doctor < Command class Doctor < Command
class << self class << self
def init_with_program(prog) def init_with_program(prog)
prog.command(:doctor) do |c| prog.command(:doctor) do |c|
c.syntax 'doctor' c.syntax 'doctor'
@ -11,7 +10,7 @@ module Jekyll
c.option '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file' c.option '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file'
c.action do |args, options| c.action do |_, options|
Jekyll::Commands::Doctor.process(options) Jekyll::Commands::Doctor.process(options)
end end
end end
@ -39,8 +38,8 @@ module Jekyll
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, which was removed in" + " permalinks, which was removed in" \
" Jekyll v3.0.0." " Jekyll v3.0.0."
return true return true
end end
@ -52,17 +51,16 @@ module Jekyll
urls = collect_urls(urls, site.pages, site.dest) urls = collect_urls(urls, site.pages, site.dest)
urls = collect_urls(urls, site.posts.docs, site.dest) urls = collect_urls(urls, site.posts.docs, site.dest)
urls.each do |url, paths| urls.each do |url, paths|
if paths.size > 1 next unless paths.size > 1
conflicting_urls = true conflicting_urls = true
Jekyll.logger.warn "Conflict:", "The URL '#{url}' is the destination" + Jekyll.logger.warn "Conflict:", "The URL '#{url}' is the destination" \
" for the following pages: #{paths.join(", ")}" " for the following pages: #{paths.join(", ")}"
end end
end
conflicting_urls conflicting_urls
end end
def fsnotify_buggy?(site) def fsnotify_buggy?(_site)
return true if !Utils::Platforms.osx? return true unless Utils::Platforms.osx?
if Dir.pwd != `pwd`.strip if Dir.pwd != `pwd`.strip
Jekyll.logger.error " " + <<-STR.strip.gsub(/\n\s+/, "\n ") Jekyll.logger.error " " + <<-STR.strip.gsub(/\n\s+/, "\n ")
We have detected that there might be trouble using fsevent on your We have detected that there might be trouble using fsevent on your
@ -81,13 +79,12 @@ module Jekyll
urls_only_differ_by_case = false urls_only_differ_by_case = false
urls = case_insensitive_urls(site.pages + site.docs_to_write, site.dest) urls = case_insensitive_urls(site.pages + site.docs_to_write, site.dest)
urls.each do |case_insensitive_url, real_urls| urls.each do |case_insensitive_url, real_urls|
if real_urls.uniq.size > 1 next unless real_urls.uniq.size > 1
urls_only_differ_by_case = true urls_only_differ_by_case = true
Jekyll.logger.warn "Warning:", "The following URLs only differ" + Jekyll.logger.warn "Warning:", "The following URLs only differ" \
" by case. On a case-insensitive file system one of the URLs" + " by case. On a case-insensitive file system one of the URLs" \
" will be overwritten by the other: #{real_urls.join(", ")}" " will be overwritten by the other: #{real_urls.join(", ")}"
end end
end
urls_only_differ_by_case urls_only_differ_by_case
end end
@ -105,14 +102,13 @@ module Jekyll
end end
def case_insensitive_urls(things, destination) def case_insensitive_urls(things, destination)
things.inject(Hash.new) do |memo, thing| things.inject({}) do |memo, thing|
dest = thing.destination(destination) dest = thing.destination(destination)
(memo[dest.downcase] ||= []) << dest (memo[dest.downcase] ||= []) << dest
memo memo
end end
end end
end end
end end
end end
end end

View File

@ -2,7 +2,6 @@ module Jekyll
module Commands module Commands
class Help < Command class Help < Command
class << self class << self
def init_with_program(prog) def init_with_program(prog)
prog.command(:help) do |c| prog.command(:help) do |c|
c.syntax 'help [subcommand]' c.syntax 'help [subcommand]'
@ -26,7 +25,6 @@ module Jekyll
Jekyll.logger.error "Error:", "Hmm... we don't know what the '#{cmd}' command is." Jekyll.logger.error "Error:", "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
end end
end end

View File

@ -123,7 +123,14 @@ module Jekyll
private private
def launch_browser(server, opts) def launch_browser(server, opts)
command = Utils::Platforms.windows?? "start" : Utils::Platforms.osx?? "open" : "xdg-open" command =
if Utils::Platforms.windows?
"start"
elsif Utils::Platforms.osx?
"open"
else
"xdg-open"
end
system command, server_address(server, opts) system command, server_address(server, opts)
end end
@ -168,7 +175,8 @@ module Jekyll
raise RuntimeError, "--ssl-cert or --ssl-key missing." raise RuntimeError, "--ssl-cert or --ssl-key missing."
end end
require "openssl"; require "webrick/https" require "openssl"
require "webrick/https"
source_key = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_key" ]) source_key = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_key" ])
source_certificate = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_cert"]) source_certificate = Jekyll.sanitized_path(opts[:JekyllOptions]["source"], opts[:JekyllOptions]["ssl_cert"])
opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(source_certificate)) opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(File.read(source_certificate))

View File

@ -37,7 +37,7 @@ module Jekyll
# #
private private
def validate_and_ensure_charset(req, res) def validate_and_ensure_charset(_req, res)
key = res.header.keys.grep(/content-type/i).first key = res.header.keys.grep(/content-type/i).first
typ = res.header[key] typ = res.header[key]
@ -52,7 +52,7 @@ module Jekyll
def set_defaults def set_defaults
hash_ = @jekyll_opts.fetch("webrick", {}).fetch("headers", {}) hash_ = @jekyll_opts.fetch("webrick", {}).fetch("headers", {})
DEFAULTS.each_with_object(@headers = hash_) do |(key, val), hash| DEFAULTS.each_with_object(@headers = hash_) do |(key, val), hash|
hash[key] = val if !hash.key?(key) hash[key] = val unless hash.key?(key)
end end
end end
end end

View File

@ -2,7 +2,6 @@
module Jekyll module Jekyll
class Configuration < Hash class Configuration < Hash
# Default options. Overridden by values in _config.yml. # Default options. Overridden by values in _config.yml.
# Strings rather than symbols are used for compatibility with YAML. # Strings rather than symbols are used for compatibility with YAML.
DEFAULTS = Configuration[{ DEFAULTS = Configuration[{
@ -128,7 +127,7 @@ module Jekyll
# Get configuration from <source>/_config.yml or <source>/<config_file> # Get configuration from <source>/_config.yml or <source>/<config_file>
config_files = override.delete('config') config_files = override.delete('config')
if config_files.to_s.empty? if config_files.to_s.empty?
default = %w[yml yaml].find(Proc.new { 'yml' }) do |ext| default = %w(yml yaml).find(-> { 'yml' }) do |ext|
File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}")) File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}"))
end end
config_files = Jekyll.sanitized_path(source(override), "_config.#{default}") config_files = Jekyll.sanitized_path(source(override), "_config.#{default}")
@ -173,7 +172,7 @@ module Jekyll
configuration = Utils.deep_merge_hashes(configuration, new_config) configuration = Utils.deep_merge_hashes(configuration, new_config)
end end
rescue ArgumentError => err rescue ArgumentError => err
Jekyll.logger.warn "WARNING:", "Error reading configuration. " + Jekyll.logger.warn "WARNING:", "Error reading configuration. " \
"Using defaults (and options)." "Using defaults (and options)."
$stderr.puts "#{err}" $stderr.puts "#{err}"
end end
@ -198,16 +197,16 @@ module Jekyll
config = clone config = clone
# Provide backwards-compatibility # Provide backwards-compatibility
if config.key?('auto') || config.key?('watch') if config.key?('auto') || config.key?('watch')
Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" + Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" \
" be set from your configuration file(s). Use the"+ " be set from your configuration file(s). Use the"\
" --[no-]watch/-w command-line option instead." " --[no-]watch/-w command-line option instead."
config.delete('auto') config.delete('auto')
config.delete('watch') config.delete('watch')
end end
if config.key? 'server' if config.key? 'server'
Jekyll::Deprecator.deprecation_message "The 'server' configuration option" + Jekyll::Deprecator.deprecation_message "The 'server' configuration option" \
" is no longer accepted. Use the 'jekyll serve'" + " is no longer accepted. Use the 'jekyll serve'" \
" subcommand to serve your site with WEBrick." " subcommand to serve your site with WEBrick."
config.delete('server') config.delete('server')
end end
@ -218,21 +217,21 @@ module Jekyll
renamed_key 'data_source', 'data_dir', config renamed_key 'data_source', 'data_dir', config
if config.key? 'pygments' if config.key? 'pygments'
Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" + Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" \
" has been renamed to 'highlighter'. Please update your" + " has been renamed to 'highlighter'. Please update your" \
" config file accordingly. The allowed values are 'rouge', " + " config file accordingly. The allowed values are 'rouge', " \
"'pygments' or null." "'pygments' or null."
config['highlighter'] = 'pygments' if config['pygments'] config['highlighter'] = 'pygments' if config['pygments']
config.delete('pygments') config.delete('pygments')
end end
%w[include exclude].each do |option| %w(include exclude).each do |option|
config[option] ||= [] config[option] ||= []
if config[option].is_a?(String) if config[option].is_a?(String)
Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" + Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" \
" must now be specified as an array, but you specified" + " must now be specified as an array, but you specified" \
" a string. For now, we've treated the string you provided" + " a string. For now, we've treated the string you provided" \
" 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
@ -240,16 +239,16 @@ module Jekyll
end end
if (config['kramdown'] || {}).key?('use_coderay') if (config['kramdown'] || {}).key?('use_coderay')
Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" + Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" \
" to 'enable_coderay' in your configuration file." " to 'enable_coderay' in your configuration file."
config['kramdown']['use_coderay'] = config['kramdown'].delete('enable_coderay') config['kramdown']['use_coderay'] = config['kramdown'].delete('enable_coderay')
end end
if config.fetch('markdown', 'kramdown').to_s.downcase.eql?("maruku") if config.fetch('markdown', 'kramdown').to_s.downcase.eql?("maruku")
Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " + Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " \
"Markdown processor, which has been removed as of 3.0.0. " + "Markdown processor, which has been removed as of 3.0.0. " \
"We recommend you switch to Kramdown. To do this, replace " + "We recommend you switch to Kramdown. To do this, replace " \
"`markdown: maruku` with `markdown: kramdown` in your " + "`markdown: maruku` with `markdown: kramdown` in your " \
"`_config.yml` file." "`_config.yml` file."
end end
@ -260,7 +259,7 @@ module Jekyll
config = clone config = clone
if config.key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1) if config.key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1)
Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" + Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" \
" positive integer or nil. It's currently set to '#{config['paginate'].inspect}'." " positive integer or nil. It's currently set to '#{config['paginate'].inspect}'."
config['paginate'] = nil config['paginate'] = nil
end end
@ -283,10 +282,10 @@ module Jekyll
config config
end end
def renamed_key(old, new, config, allowed_values = nil) def renamed_key(old, new, config, _ = nil)
if config.key?(old) if config.key?(old)
Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" + Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" \
"option has been renamed to '#{new}'. Please update your config " + "option has been renamed to '#{new}'. Please update your config " \
"file accordingly." "file accordingly."
config[new] = config.delete(old) config[new] = config.delete(old)
end end

View File

@ -5,7 +5,7 @@ module Jekyll
priority :lowest priority :lowest
def matches(ext) def matches(_ext)
true true
end end

View File

@ -7,7 +7,7 @@ module Jekyll
def setup def setup
return if @setup return if @setup
if (!@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"]
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" if @config["safe"]
Jekyll.logger.error "", "Available processors are: #{valid_processors.join(", ")}" Jekyll.logger.error "", "Available processors are: #{valid_processors.join(", ")}"
@ -41,7 +41,7 @@ module Jekyll
def third_party_processors def third_party_processors
self.class.constants - \ self.class.constants - \
%w[KramdownParser RDiscountParser RedcarpetParser PRIORITIES].map( %w(KramdownParser RDiscountParser RedcarpetParser PRIORITIES).map(
&:to_sym &:to_sym
) )
end end
@ -56,7 +56,7 @@ module Jekyll
extname_list.include?(ext.downcase) extname_list.include?(ext.downcase)
end end
def output_ext(ext) def output_ext(_ext)
".html" ".html"
end end

View File

@ -5,7 +5,7 @@ module Jekyll
def initialize(config) def initialize(config)
Jekyll::External.require_with_graceful_fail "rdiscount" Jekyll::External.require_with_graceful_fail "rdiscount"
@config = config @config = config
@rdiscount_extensions = @config['rdiscount']['extensions'].map { |e| e.to_sym } @rdiscount_extensions = @config['rdiscount']['extensions'].map(&:to_sym)
end end
def convert(content) def convert(content)

View File

@ -2,12 +2,12 @@ module Jekyll
module Converters module Converters
class Markdown class Markdown
class RedcarpetParser class RedcarpetParser
module CommonMethods module CommonMethods
def add_code_tags(code, lang) def add_code_tags(code, lang)
code = code.to_s code = code.to_s
code = code.sub(/<pre>/, "<pre><code class=\"language-#{lang}\" data-lang=\"#{lang}\">") code = code.sub(/<pre>/, "<pre><code class=\"language-#{lang}\" data-lang=\"#{lang}\">")
code = code.sub(/<\/pre>/, "</code></pre>") code = code.sub(/<\/pre>/, "</code></pre>")
code
end end
end end
@ -48,12 +48,11 @@ module Jekyll
end end
protected protected
def rouge_formatter(lexer) def rouge_formatter(_lexer)
Rouge::Formatters::HTML.new(:wrap => false) Rouge::Formatters::HTML.new(:wrap => false)
end end
end end
def initialize(config) def initialize(config)
External.require_with_graceful_fail("redcarpet") External.require_with_graceful_fail("redcarpet")
@config = config @config = config
@ -71,10 +70,10 @@ module Jekyll
end end
when "rouge" when "rouge"
Class.new(Redcarpet::Render::HTML) do Class.new(Redcarpet::Render::HTML) do
Jekyll::External.require_with_graceful_fail(%w[ Jekyll::External.require_with_graceful_fail(%w(
rouge rouge
rouge/plugins/redcarpet rouge/plugins/redcarpet
]) ))
unless Gem::Version.new(Rouge.version) > Gem::Version.new("1.3.0") unless Gem::Version.new(Rouge.version) > Gem::Version.new("1.3.0")
abort "Please install Rouge 1.3.0 or greater and try running Jekyll again." abort "Please install Rouge 1.3.0 or greater and try running Jekyll again."

View File

@ -47,7 +47,7 @@ module Jekyll
merged_file_read_opts(opts)) merged_file_read_opts(opts))
if content =~ /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m if content =~ /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
self.content = $POSTMATCH self.content = $POSTMATCH
self.data = SafeYAML.load($1) self.data = SafeYAML.load(Regexp.last_match(1))
end end
rescue SyntaxError => e rescue SyntaxError => e
Jekyll.logger.warn "YAML Exception reading #{File.join(base, name)}: #{e.message}" Jekyll.logger.warn "YAML Exception reading #{File.join(base, name)}: #{e.message}"
@ -87,9 +87,9 @@ module Jekyll
if converters.all? { |c| c.is_a?(Jekyll::Converters::Identity) } if converters.all? { |c| c.is_a?(Jekyll::Converters::Identity) }
ext ext
else else
converters.map { |c| converters.map do |c|
c.output_ext(ext) unless c.is_a?(Jekyll::Converters::Identity) c.output_ext(ext) unless c.is_a?(Jekyll::Converters::Identity)
}.compact.last end.compact.last
end end
end end
@ -122,9 +122,9 @@ module Jekyll
# #
# Returns the Hash representation of this Convertible. # Returns the Hash representation of this Convertible.
def to_liquid(attrs = nil) def to_liquid(attrs = nil)
further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map { |attribute| further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map do |attribute|
[attribute, send(attribute)] [attribute, send(attribute)]
}] end]
defaults = site.frontmatter_defaults.all(relative_path, type) defaults = site.frontmatter_defaults.all(relative_path, type)
Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data) Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data)
@ -160,7 +160,7 @@ module Jekyll
# #
# Returns true if extname == .sass or .scss, false otherwise. # Returns true if extname == .sass or .scss, false otherwise.
def sass_file? def sass_file?
%w[.sass .scss].include?(ext) %w(.sass .scss).include?(ext)
end end
# Determine whether the document is a CoffeeScript file. # Determine whether the document is a CoffeeScript file.

View File

@ -21,7 +21,7 @@ module Jekyll
end end
def no_subcommand(args) def no_subcommand(args)
if args.size > 0 && args.first =~ /^--/ && !%w[--help --version].include?(args.first) if args.size > 0 && args.first =~ /^--/ && !%w(--help --version).include?(args.first)
deprecation_message "Jekyll now uses subcommands instead of just switches. Run `jekyll --help` to find out more." deprecation_message "Jekyll now uses subcommands instead of just switches. Run `jekyll --help` to find out more."
abort abort
end end

View File

@ -4,7 +4,8 @@ module Jekyll
class Document class Document
include Comparable include Comparable
attr_reader :path, :site, :extname, :output_ext, :content, :output, :collection attr_reader :path, :site, :extname, :output_ext, :collection
attr_accessor :content, :output
YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m
DATELESS_FILENAME_MATCHER = /^(.*)(\.[^.]+)$/ DATELESS_FILENAME_MATCHER = /^(.*)(\.[^.]+)$/
@ -32,27 +33,19 @@ module Jekyll
categories_from_path(collection.relative_directory) categories_from_path(collection.relative_directory)
end end
data.default_proc = proc do |hash, key| data.default_proc = proc do |_, key|
site.frontmatter_defaults.find(relative_path, collection.label, key) site.frontmatter_defaults.find(relative_path, collection.label, key)
end end
trigger_hooks(:post_init) trigger_hooks(:post_init)
end end
def output=(output)
@output = output
end
def content=(content)
@content = content
end
# Fetch the Document's data. # Fetch the Document's data.
# #
# Returns a Hash containing the data. An empty hash is returned if # Returns a Hash containing the data. An empty hash is returned if
# no data was read. # no data was read.
def data def data
@data ||= Hash.new @data ||= {}
end end
# Merge some data in with this document's data. # Merge some data in with this document's data.
@ -127,7 +120,7 @@ module Jekyll
# #
# Returns true if the extname is either .yml or .yaml, false otherwise. # Returns true if the extname is either .yml or .yaml, false otherwise.
def yaml_file? def yaml_file?
%w[.yaml .yml].include?(extname) %w(.yaml .yml).include?(extname)
end end
# Determine whether the document is an asset file. # Determine whether the document is an asset file.
@ -143,7 +136,7 @@ module Jekyll
# #
# Returns true if extname == .sass or .scss, false otherwise. # Returns true if extname == .sass or .scss, false otherwise.
def sass_file? def sass_file?
%w[.sass .scss].include?(extname) %w(.sass .scss).include?(extname)
end end
# Determine whether the document is a CoffeeScript file. # Determine whether the document is a CoffeeScript file.
@ -197,9 +190,9 @@ 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
@ -270,7 +263,7 @@ module Jekyll
self.content = File.read(path, merged_file_read_opts(opts)) self.content = File.read(path, merged_file_read_opts(opts))
if content =~ YAML_FRONT_MATTER_REGEXP if content =~ YAML_FRONT_MATTER_REGEXP
self.content = $POSTMATCH self.content = $POSTMATCH
data_file = SafeYAML.load($1) data_file = SafeYAML.load(Regexp.last_match(1))
merge_data!(data_file) if data_file merge_data!(data_file) if data_file
end end
@ -285,13 +278,13 @@ module Jekyll
def post_read def post_read
if DATE_FILENAME_MATCHER =~ relative_path if DATE_FILENAME_MATCHER =~ relative_path
m, cats, date, slug, ext = *relative_path.match(DATE_FILENAME_MATCHER) _, _, date, slug, ext = *relative_path.match(DATE_FILENAME_MATCHER)
merge_data!({ merge_data!({
"slug" => slug, "slug" => slug,
"ext" => ext "ext" => ext
}) })
merge_data!({ "date" => date }) if data['date'].nil? || data['date'].to_i == site.time.to_i merge_data!({ "date" => date }) if data['date'].nil? || data['date'].to_i == site.time.to_i
data['title'] ||= slug.split('-').select {|w| w.capitalize! || w }.join(' ') data['title'] ||= slug.split('-').select(&:capitalize).join(' ')
end end
populate_categories populate_categories
populate_tags populate_tags
@ -317,7 +310,7 @@ module Jekyll
merge_data!({ merge_data!({
'categories' => ( 'categories' => (
Array(data['categories']) + Utils.pluralized_array_from_hash(data, 'category', 'categories') Array(data['categories']) + Utils.pluralized_array_from_hash(data, 'category', 'categories')
).map { |c| c.to_s }.flatten.uniq ).map(&:to_s).flatten.uniq
}) })
end end

View File

@ -17,7 +17,6 @@ module Jekyll
private private
def_delegator :@obj, :metadata, :fallback_data def_delegator :@obj, :metadata, :fallback_data
end end
end end
end end

View File

@ -22,7 +22,6 @@ module Jekyll
private private
def_delegator :@obj, :data, :fallback_data def_delegator :@obj, :data, :fallback_data
end end
end end
end end

View File

@ -83,6 +83,19 @@ module Jekyll
end end
end end
# Check if key exists in Drop
#
# key - the string key whose value to fetch
#
# Returns true if the given key is present
def key?(key)
if self.class.mutable && @mutations.key?(key)
true
else
respond_to?(key) || fallback_data.key?(key)
end
end
# Generates a list of keys with user content as their values. # Generates a list of keys with user content as their values.
# This gathers up the Drop methods and keys of the mutations and # This gathers up the Drop methods and keys of the mutations and
# underlying data hashes and performs a set union to ensure a list # underlying data hashes and performs a set union to ensure a list
@ -101,7 +114,7 @@ module Jekyll
# #
# Returns a Hash with all the keys and values resolved. # Returns a Hash with all the keys and values resolved.
def to_h def to_h
keys.each_with_object({}) do |(key, val), result| keys.each_with_object({}) do |(key, _), result|
result[key] = self[key] result[key] = self[key]
end end
end end
@ -122,7 +135,6 @@ module Jekyll
def each_key(&block) def each_key(&block)
keys.each(&block) keys.each(&block)
end end
end end
end end
end end

View File

@ -33,7 +33,6 @@ module Jekyll
private private
def_delegator :@obj, :config, :fallback_data def_delegator :@obj, :config, :fallback_data
end end
end end
end end

View File

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

View File

@ -19,8 +19,8 @@ module Jekyll
end end
def title def title
Utils.slugify(@obj.data['slug'], mode: "pretty", cased: true) || Utils.slugify(@obj.data['slug'], :mode => "pretty", :cased => true) ||
Utils.slugify(@obj.basename_without_ext, mode: "pretty", cased: true) Utils.slugify(@obj.basename_without_ext, :mode => "pretty", :cased => true)
end end
def slug def slug
@ -35,17 +35,49 @@ module Jekyll
category_set.to_a.join('/') category_set.to_a.join('/')
end end
def year; @obj.date.strftime("%Y"); end def year
def month; @obj.date.strftime("%m"); end @obj.date.strftime("%Y")
def day; @obj.date.strftime("%d"); end end
def hour; @obj.date.strftime("%H"); end
def minute; @obj.date.strftime("%M"); end def month
def second; @obj.date.strftime("%S"); end @obj.date.strftime("%m")
def i_day; @obj.date.strftime("%-d"); end end
def i_month; @obj.date.strftime("%-m"); end
def short_month; @obj.date.strftime("%b"); end def day
def short_year; @obj.date.strftime("%y"); end @obj.date.strftime("%d")
def y_day; @obj.date.strftime("%j"); end end
def hour
@obj.date.strftime("%H")
end
def minute
@obj.date.strftime("%M")
end
def second
@obj.date.strftime("%S")
end
def i_day
@obj.date.strftime("%-d")
end
def i_month
@obj.date.strftime("%-m")
end
def short_month
@obj.date.strftime("%b")
end
def short_year
@obj.date.strftime("%y")
end
def y_day
@obj.date.strftime("%j")
end
end end
end end
end end

View File

@ -1,16 +1,15 @@
module Jekyll module Jekyll
module External module External
class << self class << self
# #
# Gems that, if installed, should be loaded. # Gems that, if installed, should be loaded.
# Usually contain subcommands. # Usually contain subcommands.
# #
def blessed_gems def blessed_gems
%w{ %w(
jekyll-docs jekyll-docs
jekyll-import jekyll-import
} )
end end
# #
@ -54,7 +53,6 @@ If you run into trouble, you can find helpful resources at http://jekyllrb.com/h
end end
end end
end end
end end
end end
end end

View File

@ -45,7 +45,7 @@ module Jekyll
# Returns the given filename or title as a lowercase URL String. # Returns the given filename or title as a lowercase URL String.
# See Utils.slugify for more detail. # See Utils.slugify for more detail.
def slugify(input, mode=nil) def slugify(input, mode=nil)
Utils.slugify(input, mode: mode) Utils.slugify(input, :mode => mode)
end end
# Format a date in short format e.g. "27 Jan 2011". # Format a date in short format e.g. "27 Jan 2011".
@ -234,11 +234,11 @@ module Jekyll
when nils == "last" when nils == "last"
order = + 1 order = + 1
else else
raise ArgumentError.new("Invalid nils order: " + raise ArgumentError.new("Invalid nils order: " \
"'#{nils}' is not a valid nils order. It must be 'first' or 'last'.") "'#{nils}' is not a valid nils order. It must be 'first' or 'last'.")
end end
input.sort { |apple, orange| input.sort do |apple, orange|
apple_property = item_property(apple, property) apple_property = item_property(apple, property)
orange_property = item_property(orange, property) orange_property = item_property(orange, property)
@ -249,7 +249,7 @@ module Jekyll
else else
apple_property <=> orange_property apple_property <=> orange_property
end end
} end
end end
end end

View File

@ -13,7 +13,8 @@ module Jekyll
def update_deprecated_types(set) def update_deprecated_types(set)
return set unless set.key?('scope') && set['scope'].key?('type') return set unless set.key?('scope') && set['scope'].key?('type')
set['scope']['type'] = case set['scope']['type'] set['scope']['type'] =
case set['scope']['type']
when 'page' when 'page'
Deprecator.defaults_deprecate_type('page', 'pages') Deprecator.defaults_deprecate_type('page', 'pages')
'pages' 'pages'
@ -90,7 +91,7 @@ module Jekyll
end end
def applies_path?(scope, path) def applies_path?(scope, path)
return true if !scope.has_key?('path') || scope['path'].empty? return true if !scope.key?('path') || scope['path'].empty?
scope_path = Pathname.new(scope['path']) scope_path = Pathname.new(scope['path'])
Pathname.new(sanitize_path(path)).ascend do |path| Pathname.new(sanitize_path(path)).ascend do |path|
@ -150,7 +151,7 @@ module Jekyll
# Returns an array of hashes # Returns an array of hashes
def matching_sets(path, type) def matching_sets(path, type)
valid_sets.select do |set| valid_sets.select do |set|
!set.has_key?('scope') || applies?(set['scope'], path, type) !set.key?('scope') || applies?(set['scope'], path, type)
end end
end end

View File

@ -4,38 +4,38 @@ module Jekyll
# compatibility layer for octopress-hooks users # compatibility layer for octopress-hooks users
PRIORITY_MAP = { PRIORITY_MAP = {
low: 10, :low => 10,
normal: 20, :normal => 20,
high: 30, :high => 30
}.freeze }.freeze
# initial empty hooks # initial empty hooks
@registry = { @registry = {
:site => { :site => {
after_reset: [], :after_reset => [],
post_read: [], :post_read => [],
pre_render: [], :pre_render => [],
post_render: [], :post_render => [],
post_write: [], :post_write => []
}, },
:pages => { :pages => {
post_init: [], :post_init => [],
pre_render: [], :pre_render => [],
post_render: [], :post_render => [],
post_write: [], :post_write => []
}, },
:posts => { :posts => {
post_init: [], :post_init => [],
pre_render: [], :pre_render => [],
post_render: [], :post_render => [],
post_write: [], :post_write => []
}, },
:documents => { :documents => {
post_init: [], :post_init => [],
pre_render: [], :pre_render => [],
post_render: [], :post_render => [],
post_write: [], :post_write => []
}, }
} }
# map of all hooks and their priorities # map of all hooks and their priorities
@ -60,14 +60,14 @@ module Jekyll
# register a single hook to be called later, internal API # register a single hook to be called later, internal API
def self.register_one(owner, event, priority, &block) def self.register_one(owner, event, priority, &block)
@registry[owner] ||={ @registry[owner] ||={
post_init: [], :post_init => [],
pre_render: [], :pre_render => [],
post_render: [], :post_render => [],
post_write: [], :post_write => []
} }
unless @registry[owner][event] unless @registry[owner][event]
raise NotAvailable, "Invalid hook. #{owner} supports only the " << raise NotAvailable, "Invalid hook. #{owner} supports only the " \
"following hooks #{@registry[owner].keys.inspect}" "following hooks #{@registry[owner].keys.inspect}"
end end

View File

@ -15,7 +15,7 @@ module Jekyll
def file(filename) def file(filename)
filename = @site.in_source_dir(filename).sub(/\A#{Regexp.escape(@site.source)}\//, '') filename = @site.in_source_dir(filename).sub(/\A#{Regexp.escape(@site.source)}\//, '')
LiquidRenderer::File.new(self, filename).tap do |file| LiquidRenderer::File.new(self, filename).tap do
@stats[filename] ||= {} @stats[filename] ||= {}
@stats[filename][:count] ||= 0 @stats[filename][:count] ||= 0
@stats[filename][:count] += 1 @stats[filename][:count] += 1

View File

@ -69,10 +69,10 @@ module Jekyll
end end
def data_for_table(n) def data_for_table(n)
sorted = @stats.sort_by{ |filename, file_stats| -file_stats[:time] } sorted = @stats.sort_by { |_, file_stats| -file_stats[:time] }
sorted = sorted.slice(0, n) sorted = sorted.slice(0, n)
table = [[ 'Filename', 'Count', 'Bytes', 'Time' ]] table = [%w(Filename Count Bytes Time)]
sorted.each do |filename, file_stats| sorted.each do |filename, file_stats|
row = [] row = []

View File

@ -8,13 +8,13 @@ module Jekyll
attr_accessor :data, :content, :output attr_accessor :data, :content, :output
# Attributes for Liquid templates # Attributes for Liquid templates
ATTRIBUTES_FOR_LIQUID = %w[ ATTRIBUTES_FOR_LIQUID = %w(
content content
dir dir
name name
path path
url url
] )
# A set of extensions that are considered HTML or HTML-like so we # A set of extensions that are considered HTML or HTML-like so we
# should not alter them, this includes .xhtml through XHTM5. # should not alter them, this includes .xhtml through XHTM5.
@ -37,11 +37,10 @@ module Jekyll
@dir = dir @dir = dir
@name = name @name = name
process(name) process(name)
read_yaml(File.join(base, dir), name) read_yaml(File.join(base, dir), name)
data.default_proc = proc do |hash, key| data.default_proc = proc do |_, key|
site.frontmatter_defaults.find(File.join(dir, name), type, key) site.frontmatter_defaults.find(File.join(dir, name), type, key)
end end

View File

@ -76,7 +76,7 @@ module Jekyll
# #
# Returns an Array of plugin search paths # Returns an Array of plugin search paths
def plugins_path def plugins_path
if (site.config['plugins_dir'] == Jekyll::Configuration::DEFAULTS['plugins_dir']) if site.config['plugins_dir'] == Jekyll::Configuration::DEFAULTS['plugins_dir']
[site.in_source_dir(site.config['plugins_dir'])] [site.in_source_dir(site.config['plugins_dir'])]
else else
Array(site.config['plugins_dir']).map { |d| File.expand_path(d) } Array(site.config['plugins_dir']).map { |d| File.expand_path(d) }
@ -86,11 +86,10 @@ module Jekyll
def deprecation_checks def deprecation_checks
pagination_included = (site.config['gems'] || []).include?('jekyll-paginate') || defined?(Jekyll::Paginate) pagination_included = (site.config['gems'] || []).include?('jekyll-paginate') || defined?(Jekyll::Paginate)
if site.config['paginate'] && !pagination_included if site.config['paginate'] && !pagination_included
Jekyll::Deprecator.deprecation_message "You appear to have pagination " + Jekyll::Deprecator.deprecation_message "You appear to have pagination " \
"turned on, but you haven't included the `jekyll-paginate` gem. " + "turned on, but you haven't included the `jekyll-paginate` gem. " \
"Ensure you have `gems: [jekyll-paginate]` in your configuration file." "Ensure you have `gems: [jekyll-paginate]` in your configuration file."
end end
end end
end end
end end

View File

@ -67,12 +67,12 @@ module Jekyll
# dot_dirs - The Array of subdirectories in the dir. # dot_dirs - The Array of subdirectories in the dir.
# #
# Returns nothing. # Returns nothing.
def retrieve_dirs(base, dir, dot_dirs) def retrieve_dirs(_base, dir, dot_dirs)
dot_dirs.map { |file| dot_dirs.map 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)
@site.reader.read_directories(rel_path) unless @site.dest.sub(/\/$/, '') == dir_path @site.reader.read_directories(rel_path) unless @site.dest.sub(/\/$/, '') == dir_path
} end
end end
# Retrieve all the pages from the current directory, # Retrieve all the pages from the current directory,

View File

@ -1,6 +1,6 @@
module Jekyll module Jekyll
class CollectionReader class CollectionReader
SPECIAL_COLLECTIONS = %w{posts data}.freeze SPECIAL_COLLECTIONS = %w(posts data).freeze
attr_reader :site, :content attr_reader :site, :content
def initialize(site) def initialize(site)
@ -16,6 +16,5 @@ module Jekyll
collection.read unless SPECIAL_COLLECTIONS.include?(collection.label) collection.read unless SPECIAL_COLLECTIONS.include?(collection.label)
end end
end end
end end
end end

View File

@ -4,7 +4,7 @@ module Jekyll
def initialize(site, dir) def initialize(site, dir)
@site = site @site = site
@dir = dir @dir = dir
@unfiltered_content = Array.new @unfiltered_content = []
end end
# Read all the files in <source>/<dir>/ for Yaml header and create a new Page # Read all the files in <source>/<dir>/ for Yaml header and create a new Page

View File

@ -53,8 +53,8 @@ module Jekyll
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

View File

@ -4,7 +4,7 @@ module Jekyll
def initialize(site, dir) def initialize(site, dir)
@site = site @site = site
@dir = dir @dir = dir
@unfiltered_content = Array.new @unfiltered_content = []
end end
# Read all the files in <source>/<dir>/ for Yaml header and create a new Page # Read all the files in <source>/<dir>/ for Yaml header and create a new Page

View File

@ -62,7 +62,6 @@ module Jekyll
clear_cache clear_cache
end end
# Clear just the cache # Clear just the cache
# #
# Returns nothing # Returns nothing
@ -70,13 +69,12 @@ module Jekyll
@cache = {} @cache = {}
end end
# Checks if the source has been modified or the # Checks if the source has been modified or the
# destination is missing # destination is missing
# #
# returns a boolean # returns a boolean
def source_modified_or_dest_missing?(source_path, dest_path) def source_modified_or_dest_missing?(source_path, dest_path)
modified?(source_path) || (dest_path and !File.exist?(dest_path)) modified?(source_path) || (dest_path && !File.exist?(dest_path))
end end
# Checks if a path's (or one of its dependencies) # Checks if a path's (or one of its dependencies)
@ -90,7 +88,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.has_key? path if cache.key? path
return cache[path] return cache[path]
end end
@ -117,9 +115,9 @@ module Jekyll
# #
# Returns nothing. # Returns nothing.
def add_dependency(path, dependency) def add_dependency(path, dependency)
return if (metadata[path].nil? || @disabled) return if metadata[path].nil? || @disabled
if !metadata[path]["deps"].include? dependency unless metadata[path]["deps"].include? dependency
metadata[path]["deps"] << dependency metadata[path]["deps"] << dependency
add(dependency) unless metadata.include?(dependency) add(dependency) unless metadata.include?(dependency)
end end
@ -157,7 +155,8 @@ module Jekyll
# #
# Returns the read metadata. # Returns the read metadata.
def read_metadata def read_metadata
@metadata = if !disabled? && File.file?(metadata_file) @metadata =
if !disabled? && File.file?(metadata_file)
content = File.binread(metadata_file) content = File.binread(metadata_file)
begin begin

View File

@ -1,6 +1,5 @@
module Jekyll module Jekyll
class RelatedPosts class RelatedPosts
class << self class << self
attr_accessor :lsi attr_accessor :lsi
end end
@ -24,7 +23,6 @@ module Jekyll
end end
end end
def build_index def build_index
self.class.lsi ||= begin self.class.lsi ||= begin
lsi = ClassifierReborn::LSI.new(:auto_rebuild => false) lsi = ClassifierReborn::LSI.new(:auto_rebuild => false)

View File

@ -2,7 +2,6 @@
module Jekyll module Jekyll
class Renderer class Renderer
attr_reader :document, :site, :payload attr_reader :document, :site, :payload
def initialize(site, document, site_payload = nil) def initialize(site, document, site_payload = nil)
@ -43,8 +42,8 @@ module Jekyll
document.trigger_hooks(:pre_render, payload) document.trigger_hooks(:pre_render, payload)
info = { info = {
filters: [Jekyll::Filters], :filters => [Jekyll::Filters],
registers: { :site => site, :page => payload.page } :registers => { :site => site, :page => payload.page }
} }
# render and transform content (this becomes the final content of the object) # render and transform content (this becomes the final content of the object)
@ -161,6 +160,5 @@ module Jekyll
output output
end end
end end
end end

View File

@ -19,8 +19,8 @@ module Jekyll
def initialize(config) def initialize(config)
@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 gems].each do |opt| show_drafts limit_posts keep_files gems).each do |opt|
self.send("#{opt}=", config[opt]) self.send("#{opt}=", config[opt])
end end
@ -165,7 +165,7 @@ module Jekyll
Jekyll::Hooks.trigger :site, :pre_render, self, payload Jekyll::Hooks.trigger :site, :pre_render, self, payload
collections.each do |label, collection| collections.each do |_, collection|
collection.docs.each do |document| collection.docs.each do |document|
if regenerator.regenerate?(document) if regenerator.regenerate?(document)
document.output = Jekyll::Renderer.new(self, document, payload).run document.output = Jekyll::Renderer.new(self, document, payload).run
@ -196,9 +196,9 @@ module Jekyll
# #
# Returns nothing. # Returns nothing.
def write def write
each_site_file { |item| each_site_file do |item|
item.write(dest) if regenerator.regenerate?(item) item.write(dest) if regenerator.regenerate?(item)
} end
regenerator.write_metadata regenerator.write_metadata
Jekyll::Hooks.trigger :site, :post_write, self Jekyll::Hooks.trigger :site, :post_write, self
end end
@ -292,10 +292,10 @@ module Jekyll
# Returns # Returns
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 http://jekyllrb.com/docs/upgrading/"+ " directory. Check http://jekyllrb.com/docs/upgrading/"\
" for more info." " for more info."
end end
end end

View File

@ -1,7 +1,7 @@
module Jekyll module Jekyll
class StaticFile class StaticFile
# The cache of last modification times [path] -> mtime. # The cache of last modification times [path] -> mtime.
@@mtimes = Hash.new @@mtimes = {}
attr_reader :relative_path, :extname attr_reader :relative_path, :extname
@ -75,7 +75,7 @@ module Jekyll
def write(dest) def write(dest)
dest_path = destination(dest) dest_path = destination(dest)
return false if File.exist?(dest_path) and !modified? return false if File.exist?(dest_path) && !modified?
@@mtimes[path] = mtime @@mtimes[path] = mtime
FileUtils.mkdir_p(File.dirname(dest_path)) FileUtils.mkdir_p(File.dirname(dest_path))
@ -90,7 +90,7 @@ module Jekyll
# #
# Returns nothing. # Returns nothing.
def self.reset_cache def self.reset_cache
@@mtimes = Hash.new @@mtimes = {}
nil nil
end end
@ -104,12 +104,12 @@ module Jekyll
def placeholders def placeholders
{ {
collection: @collection.label, :collection => @collection.label,
path: relative_path[ :path => relative_path[
@collection.relative_directory.size..relative_path.size], @collection.relative_directory.size..relative_path.size],
output_ext: '', :output_ext => '',
name: '', :name => '',
title: '', :title => ''
} }
end end
@ -121,10 +121,10 @@ module Jekyll
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.gsub /\/$/, '' end.to_s.gsub(/\/$/, '')
end end
# Returns the type of the collection if present, nil otherwise. # Returns the type of the collection if present, nil otherwise.

View File

@ -5,7 +5,7 @@ module Jekyll
@level = DEBUG @level = DEBUG
@default_formatter = Formatter.new @default_formatter = Formatter.new
@logdev = $stdout @logdev = $stdout
@formatter = proc do |severity, datetime, progname, msg| @formatter = proc do |_, _, _, msg|
"#{msg}" "#{msg}"
end end
end end
@ -14,7 +14,7 @@ module Jekyll
severity ||= UNKNOWN severity ||= UNKNOWN
@logdev = set_logdevice(severity) @logdev = set_logdevice(severity)
if @logdev.nil? or severity < @level if @logdev.nil? || severity < @level
return true return true
end end
progname ||= @progname progname ||= @progname

View File

@ -13,21 +13,21 @@ module Jekyll
def initialize(tag_name, markup, tokens) def initialize(tag_name, markup, tokens)
super super
if markup.strip =~ SYNTAX if markup.strip =~ SYNTAX
@lang = $1.downcase @lang = Regexp.last_match(1).downcase
@highlight_options = {} @highlight_options = {}
if defined?($2) && $2 != '' if defined?(Regexp.last_match(2)) && Regexp.last_match(2) != ''
# Split along 3 possible forms -- key="<quoted list>", key=value, or key # Split along 3 possible forms -- key="<quoted list>", key=value, or key
$2.scan(/(?:\w="[^"]*"|\w=\w|\w)+/) do |opt| Regexp.last_match(2).scan(/(?:\w="[^"]*"|\w=\w|\w)+/) 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 && value.include?("\"")
value.gsub!(/"/, "") value.delete!('"')
value = value.split value = value.split
end end
@highlight_options[key.to_sym] = value || true @highlight_options[key.to_sym] = value || true
end end
end end
@highlight_options[:linenos] = "inline" if @highlight_options.key?(:linenos) and @highlight_options[:linenos] == true @highlight_options[:linenos] = "inline" if @highlight_options.key?(:linenos) && @highlight_options[:linenos] == true
else else
raise SyntaxError.new <<-eos raise SyntaxError.new <<-eos
Syntax Error in tag 'highlight' while parsing the following markup: Syntax Error in tag 'highlight' while parsing the following markup:
@ -88,7 +88,7 @@ eos
puts puts
Jekyll.logger.error code Jekyll.logger.error code
puts puts
Jekyll.logger.error "While attempting to convert the above code, Pygments.rb" + Jekyll.logger.error "While attempting to convert the above code, Pygments.rb" \
" returned an unacceptable value." " returned an unacceptable value."
Jekyll.logger.error "This is usually a timeout problem solved by running `jekyll build` again." Jekyll.logger.error "This is usually a timeout problem solved by running `jekyll build` again."
raise ArgumentError.new("Pygments.rb returned an unacceptable value when attempting to highlight some code.") raise ArgumentError.new("Pygments.rb returned an unacceptable value when attempting to highlight some code.")
@ -99,7 +99,7 @@ eos
def render_rouge(code) def render_rouge(code)
Jekyll::External.require_with_graceful_fail('rouge') Jekyll::External.require_with_graceful_fail('rouge')
formatter = Rouge::Formatters::HTML.new(line_numbers: @highlight_options[:linenos], wrap: false) formatter = Rouge::Formatters::HTML.new(:line_numbers => @highlight_options[:linenos], :wrap => false)
lexer = Rouge::Lexer.find_fancy(@lang, code) || Rouge::Lexers::PlainText lexer = Rouge::Lexer.find_fancy(@lang, code) || Rouge::Lexers::PlainText
formatter.format(lexer.lex(code)) formatter.format(lexer.lex(code))
end end
@ -110,12 +110,11 @@ eos
def add_code_tag(code) def add_code_tag(code)
code_attributes = [ code_attributes = [
"class=\"language-#{@lang.to_s.gsub('+', '-')}\"", "class=\"language-#{@lang.to_s.tr('+', '-')}\"",
"data-lang=\"#{@lang.to_s}\"" "data-lang=\"#{@lang}\""
].join(" ") ].join(" ")
"<figure class=\"highlight\"><pre><code #{code_attributes}>#{code.chomp}</code></pre></figure>" "<figure class=\"highlight\"><pre><code #{code_attributes}>#{code.chomp}</code></pre></figure>"
end end
end end
end end
end end

View File

@ -12,7 +12,6 @@ module Jekyll
end end
class IncludeTag < Liquid::Tag class IncludeTag < Liquid::Tag
attr_reader :includes_dir attr_reader :includes_dir
VALID_SYNTAX = /([\w-]+)\s*=\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([\w\.-]+))/ VALID_SYNTAX = /([\w-]+)\s*=\s*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([\w\.-]+))/
@ -25,7 +24,7 @@ module Jekyll
@file = matched['variable'].strip @file = matched['variable'].strip
@params = matched['params'].strip @params = matched['params'].strip
else else
@file, @params = markup.strip.split(' ', 2); @file, @params = markup.strip.split(' ', 2)
end end
validate_params if @params validate_params if @params
@tag_name = tag_name @tag_name = tag_name
@ -115,7 +114,7 @@ eos
validate_path(path, dir, site.safe) validate_path(path, dir, site.safe)
# Add include to dependency tree # Add include to dependency tree
if context.registers[:page] and context.registers[:page].has_key? "path" if context.registers[:page] && 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
@ -138,7 +137,7 @@ eos
context.registers[:cached_partials] ||= {} context.registers[:cached_partials] ||= {}
cached_partial = context.registers[:cached_partials] cached_partial = context.registers[:cached_partials]
if cached_partial.has_key?(path) if cached_partial.key?(path)
cached_partial[path] cached_partial[path]
else else
cached_partial[path] = context.registers[:site].liquid_renderer.file(path).parse(read_file(path, context)) cached_partial[path] = context.registers[:site].liquid_renderer.file(path).parse(read_file(path, context))

View File

@ -60,23 +60,20 @@ eos
site = context.registers[:site] site = context.registers[:site]
site.posts.docs.each do |p| site.posts.docs.each do |p|
if @post == p return p.url if @post == p
return p.url
end
end end
# New matching method did not match, fall back to old method # New matching method did not match, fall back to old method
# with deprecation warning if this matches # with deprecation warning if this matches
site.posts.docs.each do |p| site.posts.docs.each do |p|
if @post.deprecated_equality p next unless @post.deprecated_equality p
Jekyll::Deprecator.deprecation_message "A call to '{{ post_url #{@post.name} }}' did not match " + Jekyll::Deprecator.deprecation_message "A call to '{{ post_url #{@post.name} }}' did not match " \
"a post using the new matching method of checking name " + "a post using the new matching method of checking name " \
"(path-date-slug) equality. Please make sure that you " + "(path-date-slug) equality. Please make sure that you " \
"change this tag to match the post's name exactly." "change this tag to match the post's name exactly."
return p.url return p.url
end end
end
raise ArgumentError.new <<-eos raise ArgumentError.new <<-eos
Could not find post "#{@orig_post}" in tag 'post_url'. Could not find post "#{@orig_post}" in tag 'post_url'.

View File

@ -11,7 +11,6 @@ require 'uri'
# #
module Jekyll module Jekyll
class URL class URL
# options - One of :permalink or :template must be supplied. # options - One of :permalink or :template must be supplied.
# :template - The String used as template for URL generation, # :template - The String used as template for URL generation,
# for example "/:path/:basename:output_ext", where # for example "/:path/:basename:output_ext", where
@ -93,7 +92,7 @@ module Jekyll
# as well as the beginning "/" so we can enforce and ensure it. # as well as the beginning "/" so we can enforce and ensure it.
def sanitize_url(str) def sanitize_url(str)
"/" + str.gsub(/\/{2,}/, "/").gsub(%r!\.+\/|\A/+!, "") "/" + str.gsub(/\/{2,}/, "/").gsub(/\.+\/|\A\/+/, "")
end end
# Escapes a path to be a valid URL path segment # Escapes a path to be a valid URL path segment

View File

@ -4,7 +4,7 @@ module Jekyll
autoload :Ansi, "jekyll/utils/ansi" autoload :Ansi, "jekyll/utils/ansi"
# Constants for use in #slugify # Constants for use in #slugify
SLUGIFY_MODES = %w{raw default pretty} SLUGIFY_MODES = %w(raw default pretty)
SLUGIFY_RAW_REGEXP = Regexp.new('\\s+').freeze SLUGIFY_RAW_REGEXP = Regexp.new('\\s+').freeze
SLUGIFY_DEFAULT_REGEXP = Regexp.new('[^[:alnum:]]+').freeze SLUGIFY_DEFAULT_REGEXP = Regexp.new('[^[:alnum:]]+').freeze
SLUGIFY_PRETTY_REGEXP = Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze SLUGIFY_PRETTY_REGEXP = Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze
@ -31,8 +31,8 @@ module Jekyll
# Thanks to whoever made it. # Thanks to whoever made it.
def deep_merge_hashes!(target, overwrite) def deep_merge_hashes!(target, overwrite)
overwrite.each_key do |key| overwrite.each_key do |key|
if (overwrite[key].is_a?(Hash) or overwrite[key].is_a?(Drops::Drop)) and if (overwrite[key].is_a?(Hash) || overwrite[key].is_a?(Drops::Drop)) &&
(target[key].is_a?(Hash) or target[key].is_a?(Drops::Drop)) (target[key].is_a?(Hash) || target[key].is_a?(Drops::Drop))
target[key] = Utils.deep_merge_hashes(target[key], overwrite[key]) target[key] = Utils.deep_merge_hashes(target[key], overwrite[key])
next next
end end
@ -62,7 +62,7 @@ module Jekyll
end end
def value_from_singular_key(hash, key) def value_from_singular_key(hash, key)
hash[key] if (hash.key?(key) || (hash.default_proc && hash[key])) hash[key] if hash.key?(key) || (hash.default_proc && hash[key])
end end
def value_from_plural_key(hash, key) def value_from_plural_key(hash, key)
@ -164,7 +164,8 @@ module Jekyll
end end
# Replace each character sequence with a hyphen # Replace each character sequence with a hyphen
re = case mode re =
case mode
when 'raw' when 'raw'
SLUGIFY_RAW_REGEXP SLUGIFY_RAW_REGEXP
when 'default' when 'default'
@ -225,7 +226,6 @@ module Jekyll
template template
end end
# Work the same way as Dir.glob but seperating the input into two parts # Work the same way as Dir.glob but seperating the input into two parts
# ('dir' + '/' + 'pattern') to make sure the first part('dir') does not act # ('dir' + '/' + 'pattern') to make sure the first part('dir') does not act
# as a pattern. # as a pattern.

View File

@ -19,7 +19,6 @@ module Jekyll
{ :windows? => /mswin|mingw|cygwin/, :linux? => /linux/, \ { :windows? => /mswin|mingw|cygwin/, :linux? => /linux/, \
:osx? => /darwin|mac os/, :unix? => /solaris|bsd/ }.each do |k, v| :osx? => /darwin|mac os/, :unix? => /solaris|bsd/ }.each do |k, v|
define_method k do define_method k do
!!( !!(
RbConfig::CONFIG["host_os"] =~ v RbConfig::CONFIG["host_os"] =~ v