This commit is contained in:
Thomas Reynolds 2016-01-14 11:21:42 -08:00
parent 5f8beba4b3
commit d82ac590db
42 changed files with 229 additions and 237 deletions

View file

@ -52,6 +52,8 @@ CaseIndentation:
IndentWhenRelativeTo: end IndentWhenRelativeTo: end
TrivialAccessors: TrivialAccessors:
ExactNameMatch: true ExactNameMatch: true
SingleLineBlockParams:
Enabled: false
Metrics/AbcSize: Metrics/AbcSize:
Enabled: false Enabled: false
Metrics/PerceivedComplexity: Metrics/PerceivedComplexity:

View file

@ -13,6 +13,8 @@ master
* Don't parse frontmatter on ignored files. * Don't parse frontmatter on ignored files.
* Fix displaying frontmatter on `/__middleman/sitemap` * Fix displaying frontmatter on `/__middleman/sitemap`
* Add `skip_build_clean` config which when set to a block, will avoid removing non-generated paths from build, like .git #1716 * Add `skip_build_clean` config which when set to a block, will avoid removing non-generated paths from build, like .git #1716
* Minor performance improvements
* DRY-up config.rb-specific commands like `ignore` or `path`.
# 4.0.0 # 4.0.0

View file

@ -3,7 +3,7 @@ require 'rake'
require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__) require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__)
ROOT = File.expand_path(File.dirname(__FILE__)) ROOT = File.expand_path(File.dirname(__FILE__))
GEM_NAME = 'middleman' GEM_NAME = 'middleman'.freeze
middleman_gems = %w(middleman-core middleman-cli middleman) middleman_gems = %w(middleman-core middleman-cli middleman)
GEM_PATHS = middleman_gems.freeze GEM_PATHS = middleman_gems.freeze
@ -36,7 +36,7 @@ end
desc 'Generate documentation for all middleman gems' desc 'Generate documentation for all middleman gems'
task :doc do task :doc do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake yard" } Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake yard" }
end end
end end
@ -45,14 +45,14 @@ task :test do
Rake::Task['rubocop'].invoke Rake::Task['rubocop'].invoke
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" } Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake test" }
end end
end end
desc 'Run specs for all middleman gems' desc 'Run specs for all middleman gems'
task :spec do task :spec do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake spec" } Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake spec" }
end end
end end

View file

@ -1,4 +1,4 @@
# coding:utf-8 # coding:utf-8
RAKE_ROOT = __FILE__ RAKE_ROOT = __FILE__.freeze
GEM_NAME = 'middleman-cli' GEM_NAME = 'middleman-cli'.freeze
require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper') require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper')

View file

@ -52,7 +52,7 @@ module Middleman::Cli
::Middleman::Logger.singleton(verbose, instrument) ::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument "builder_setup" do ::Middleman::Util.instrument 'builder_setup' do
@app = ::Middleman::Application.new do @app = ::Middleman::Application.new do
config[:mode] = :build config[:mode] = :build
config[:environment] = env config[:environment] = env
@ -67,7 +67,7 @@ module Middleman::Cli
builder.on_build_event(&method(:on_event)) builder.on_build_event(&method(:on_event))
end end
::Middleman::Util.instrument "builder_run" do ::Middleman::Util.instrument 'builder_run' do
if builder.run! if builder.run!
clean_directories! if options['clean'] clean_directories! if options['clean']
shell.say 'Project built successfully.' shell.say 'Project built successfully.'

View file

@ -1,4 +1,4 @@
# coding:utf-8 # coding:utf-8
RAKE_ROOT = __FILE__ RAKE_ROOT = __FILE__.freeze
GEM_NAME = ENV['NAME'] || 'middleman-core' GEM_NAME = ENV['NAME'] || 'middleman-core'
require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper') require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper')

View file

@ -170,7 +170,7 @@ module Middleman
ignored = false ignored = false
file[:relative_path].ascend do |f| file[:relative_path].ascend do |f|
if f.basename.to_s.match %r{^_[^_]} if f.basename.to_s =~ %r{^_[^_]}
ignored = true ignored = true
break break
end end
@ -180,8 +180,7 @@ module Middleman
end, end,
layout: proc do |file, _sitemap_app| layout: proc do |file, _sitemap_app|
file[:relative_path].to_s.start_with?('layout.') || file[:relative_path].to_s.start_with?('layout.', 'layouts/')
file[:relative_path].to_s.start_with?('layouts/')
end end
}, 'Callbacks that can exclude paths from the sitemap' }, 'Callbacks that can exclude paths from the sitemap'
@ -210,7 +209,7 @@ module Middleman
# Search the root of the project for required files # Search the root of the project for required files
$LOAD_PATH.unshift(root) unless $LOAD_PATH.include?(root) $LOAD_PATH.unshift(root) unless $LOAD_PATH.include?(root)
::Middleman::Util.instrument "application.setup" do ::Middleman::Util.instrument 'application.setup' do
@callbacks = ::Middleman::CallbackManager.new @callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [ @callbacks.install_methods!(self, [
:initialized, :initialized,
@ -431,6 +430,6 @@ module Middleman
def to_s def to_s
"#<Middleman::Application:0x#{object_id}>" "#<Middleman::Application:0x#{object_id}>"
end end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
end end
end end

View file

@ -20,7 +20,7 @@ module Middleman
def_delegator :@app, :logger def_delegator :@app, :logger
# Sort order, images, fonts, js/css and finally everything else. # Sort order, images, fonts, js/css and finally everything else.
SORT_ORDER = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .webp .ico .woff .woff2 .otf .ttf .eot .js .css) SORT_ORDER = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .webp .ico .woff .woff2 .otf .ttf .eot .js .css).freeze
# Create a new Builder instance. # Create a new Builder instance.
# @param [Middleman::Application] app The app to build. # @param [Middleman::Application] app The app to build.

View file

@ -2,7 +2,7 @@ module Middleman
module CoreExtensions module CoreExtensions
module Collections module Collections
class LazyCollectorStep < BasicObject class LazyCollectorStep < BasicObject
DELEGATE = [:hash, :eql?] DELEGATE = [:hash, :eql?].freeze
def initialize(name, args, block, parent=nil) def initialize(name, args, block, parent=nil)
@name = name @name = name

View file

@ -189,7 +189,7 @@ module Middleman
(@local_data.keys + @local_sources.keys + @callback_sources.keys).include?(key.to_s) (@local_data.keys + @local_sources.keys + @callback_sources.keys).include?(key.to_s)
end end
alias_method :has_key?, :key? alias has_key? key?
# Convert all the data into a static hash # Convert all the data into a static hash
# #

View file

@ -9,7 +9,7 @@ class Padrino::Helpers::OutputHelpers::ErbHandler
def capture_from_template(*args, &block) def capture_from_template(*args, &block)
self.output_buffer = '' self.output_buffer = ''
buf_was = output_buffer buf_was = output_buffer
raw = block.call(*args) raw = yield(*args)
captured = template.instance_variable_get(:@_out_buf) captured = template.instance_variable_get(:@_out_buf)
self.output_buffer = buf_was self.output_buffer = buf_was
engine_matches?(block) && !captured.empty? ? captured : raw engine_matches?(block) && !captured.empty? ? captured : raw
@ -55,7 +55,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
output.safe_concat ::Padrino::Helpers::TagHelpers::NEWLINE output.safe_concat ::Padrino::Helpers::TagHelpers::NEWLINE
end end
else else
output.safe_concat "#{content}" output.safe_concat content.to_s
end end
output.safe_concat "</#{name}>" output.safe_concat "</#{name}>"
@ -66,7 +66,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
result = if handler = auto_find_proper_handler(&block) result = if handler = auto_find_proper_handler(&block)
handler.capture_from_template(*args, &block) handler.capture_from_template(*args, &block)
else else
block.call(*args) yield(*args)
end end
::ActiveSupport::SafeBuffer.new.safe_concat(result) ::ActiveSupport::SafeBuffer.new.safe_concat(result)

View file

@ -21,7 +21,7 @@ module Middleman
tilde_files: /~$/, tilde_files: /~$/,
ds_store: /\.DS_Store$/, ds_store: /\.DS_Store$/,
git: /(^|\/)\.git(ignore|modules|\/)/ git: /(^|\/)\.git(ignore|modules|\/)/
} }.freeze
# Setup the extension. # Setup the extension.
def initialize(app, config={}, &block) def initialize(app, config={}, &block)

View file

@ -127,7 +127,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
# Backwards API compat # Backwards API compat
alias_method :langs, :locales alias langs locales
Contract Symbol Contract Symbol
def locale def locale
@ -135,7 +135,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
# Backwards API compat # Backwards API compat
alias_method :lang, :locale alias lang locale
# Update the main sitemap resource list # Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource> # @return Array<Middleman::Sitemap::Resource>
@ -274,7 +274,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
File.dirname(path).split('/').each do |path_sub| File.dirname(path).split('/').each do |path_sub|
next if path_sub == '' next if path_sub == ''
partially_localized_path = "#{partially_localized_path}/#{(::I18n.t("paths.#{path_sub}", default: path_sub).to_s)}" partially_localized_path = "#{partially_localized_path}/#{::I18n.t("paths.#{path_sub}", default: path_sub)}"
end end
path = "#{partially_localized_path}/#{File.basename(path)}" path = "#{partially_localized_path}/#{File.basename(path)}"

View file

@ -6,7 +6,6 @@ require 'middleman-core/contracts'
module Middleman module Middleman
module CoreExtensions module CoreExtensions
class InlineURLRewriter < ::Middleman::Extension class InlineURLRewriter < ::Middleman::Extension
include Contracts include Contracts
@ -19,7 +18,7 @@ module Middleman
url_extensions: ArrayOf[String], url_extensions: ArrayOf[String],
source_extensions: ArrayOf[String], source_extensions: ArrayOf[String],
ignore: ArrayOf[IGNORE_DESCRIPTOR] ignore: ArrayOf[IGNORE_DESCRIPTOR]
} }.freeze
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
@ -33,19 +32,17 @@ module Middleman
end end
def after_configuration def after_configuration
app.use Rack, { app.use Rack, rewriters: @rewriters.values,
rewriters: @rewriters.values,
middleman_app: @app middleman_app: @app
}
end end
class Rack class Rack
include Contracts include Contracts
Contract RespondTo[:call], ({ Contract RespondTo[:call], {
middleman_app: IsA['Middleman::Application'], middleman_app: IsA['Middleman::Application'],
rewriters: ArrayOf[REWRITER_DESCRIPTOR] rewriters: ArrayOf[REWRITER_DESCRIPTOR]
}) => Any } => Any
def initialize(app, options={}) def initialize(app, options={})
@rack_app = app @rack_app = app
@middleman_app = options.fetch(:middleman_app) @middleman_app = options.fetch(:middleman_app)
@ -76,10 +73,8 @@ module Middleman
dirpath = ::Pathname.new(File.dirname(path)) dirpath = ::Pathname.new(File.dirname(path))
rewritten = nil rewritten = ::Middleman::Util.instrument 'inline_url_rewriter', path: path do
::Middleman::Util.rewrite_paths(body, path, all_asset_exts) do |asset_path|
# ::Middleman::Util.instrument "inline_url_rewriter", path: path do
rewritten = ::Middleman::Util.rewrite_paths(body, path, all_asset_exts) do |asset_path|
uri = ::Addressable::URI.parse(asset_path) uri = ::Addressable::URI.parse(asset_path)
relative_path = uri.host.nil? relative_path = uri.host.nil?
@ -106,7 +101,7 @@ module Middleman
next if ignore.any? { |r| should_ignore?(r, full_asset_path) } next if ignore.any? { |r| should_ignore?(r, full_asset_path) }
rewrite_ignore = Array(rewriter.fetch(:rewrite_ignore, [])) rewrite_ignore = Array(rewriter.fetch(:rewrite_ignore, []))
next if rewrite_ignore.any? { |ignore| ::Middleman::Util.path_match(ignore, path) } next if rewrite_ignore.any? { |i| ::Middleman::Util.path_match(i, path) }
proc = rewriter.fetch(:proc) proc = rewriter.fetch(:proc)
@ -115,7 +110,7 @@ module Middleman
end end
asset_path asset_path
# end end
end end
::Rack::Response.new( ::Rack::Response.new(
@ -143,6 +138,5 @@ module Middleman
end end
end end
end end
end end
end end

View file

@ -496,8 +496,8 @@ module Middleman
@descriptors[k] = [] @descriptors[k] = []
define_singleton_method(:"__original_#{v}", &method(v)) define_singleton_method(:"__original_#{v}", &method(v))
define_singleton_method(v) do |*args, &block| define_singleton_method(v) do |*args, &b|
@descriptors[k] << method(:"__original_#{v}").call(*args, &block) @descriptors[k] << method(:"__original_#{v}").call(*args, &b)
@app.sitemap.rebuild_resource_list!(:"first_run_change_#{v}") @app.sitemap.rebuild_resource_list!(:"first_run_change_#{v}")
end end
end end

View file

@ -44,7 +44,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
module LoremObject module LoremObject
class << self class << self
# Words for use in lorem text # Words for use in lorem text
WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat) WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat).freeze
# Get one placeholder word # Get one placeholder word
# @return [String] # @return [String]

View file

@ -36,11 +36,11 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
# Init # Init
# @param [Class] app # @param [Class] app
# @param [Hash] options # @param [Hash] options
Contract RespondTo[:call], ({ Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER], ignore: ArrayOf[PATH_MATCHER],
inline: Bool, inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]] compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
}) => Any } => Any
def initialize(app, options={}) def initialize(app, options={})
@app = app @app = app
@ignore = options.fetch(:ignore) @ignore = options.fetch(:ignore)

View file

@ -28,11 +28,11 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
# Init # Init
# @param [Class] app # @param [Class] app
# @param [Hash] options # @param [Hash] options
Contract RespondTo[:call], ({ Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER], ignore: ArrayOf[PATH_MATCHER],
inline: Bool, inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]] compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
}) => Any } => Any
def initialize(app, options={}) def initialize(app, options={})
@app = app @app = app
@ignore = options.fetch(:ignore) @ignore = options.fetch(:ignore)

View file

@ -73,11 +73,9 @@ module Middleman
# end # end
# Render using Tilt # Render using Tilt
content = nil content = ::Middleman::Util.instrument 'render.tilt', path: path do
template.render(context, locs, &block)
# ::Middleman::Util.instrument 'render.tilt', path: path do end
content = template.render(context, locs, &block)
# end
# Allow hooks to manipulate the result after render # Allow hooks to manipulate the result after render
content = @app.callbacks_for(:after_render).reduce(content) do |sum, callback| content = @app.callbacks_for(:after_render).reduce(content) do |sum, callback|

View file

@ -247,10 +247,10 @@ module Middleman
end end
end end
if is_logging http_opts[:Logger] = if is_logging
http_opts[:Logger] = FilteredWebrickLog.new FilteredWebrickLog.new
else else
http_opts[:Logger] = ::WEBrick::Log.new(nil, 0) ::WEBrick::Log.new(nil, 0)
end end
begin begin

View file

@ -10,7 +10,7 @@ module Middleman
true true
end end
alias_method :to_browser, :to_s alias to_browser to_s
end end
class ServerPlainHostname < SimpleDelegator class ServerPlainHostname < SimpleDelegator
@ -24,7 +24,7 @@ module Middleman
# rubocop:enable Style/CaseEquality # rubocop:enable Style/CaseEquality
end end
alias_method :to_browser, :to_s alias to_browser to_s
end end
def self.new(string) def self.new(string)

View file

@ -138,7 +138,7 @@ module Middleman
response[1]['Content-Encoding'] = 'gzip' if %w(.svgz .gz).include?(resource.ext) response[1]['Content-Encoding'] = 'gzip' if %w(.svgz .gz).include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise # Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500) # Rack will throw an error (500)
if !(100..199).include?(status) && ![204, 205, 304].include?(status) if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || 'application/octet-stream' response[1]['Content-Type'] = resource.content_type || 'application/octet-stream'
end end
halt response halt response

View file

@ -35,7 +35,7 @@ module Middleman
def convert_a(el, indent) def convert_a(el, indent)
content = inner(el, indent) content = inner(el, indent)
if el.attr['href'] =~ /\Amailto:/ if el.attr['href'].start_with?('mailto:')
mail_addr = el.attr['href'].sub(/\Amailto:/, '') mail_addr = el.attr['href'].sub(/\Amailto:/, '')
href = obfuscate('mailto') << ':' << obfuscate(mail_addr) href = obfuscate('mailto') << ':' << obfuscate(mail_addr)
content = obfuscate(content) if content == mail_addr content = obfuscate(content) if content == mail_addr

View file

@ -26,7 +26,7 @@ module Middleman
if ::Less.const_defined? :Engine if ::Less.const_defined? :Engine
@engine = ::Less::Engine.new(data) @engine = ::Less::Engine.new(data)
else else
parser = ::Less::Parser.new(options.merge filename: eval_file, line: line, paths: ['.', File.dirname(eval_file)]) parser = ::Less::Parser.new(options.merge(filename: eval_file, line: line, paths: ['.', File.dirname(eval_file)]))
@engine = parser.parse(data) @engine = parser.parse(data)
end end
end end

View file

@ -8,7 +8,7 @@ module Middleman
# in the wrong direction # in the wrong direction
ALIASES = { ALIASES = {
escape_html: :filter_html escape_html: :filter_html
} }.freeze
def initialize(*args, &block) def initialize(*args, &block)
super super

View file

@ -1,11 +1,9 @@
require 'sass' require 'sass'
module Middleman module Middleman
module Renderers module Renderers
# Sass renderer # Sass renderer
class Sass < ::Middleman::Extension class Sass < ::Middleman::Extension
opts = { output_style: :nested } opts = { output_style: :nested }
opts[:line_comments] = false if ENV['TEST'] opts[:line_comments] = false if ENV['TEST']
define_setting :sass, opts, 'Sass engine options' define_setting :sass, opts, 'Sass engine options'

View file

@ -23,9 +23,9 @@ module Middleman
# Ignore based on the source path (without template extensions) # Ignore based on the source path (without template extensions)
if ignored?(r.path) if ignored?(r.path)
r.ignore! r.ignore!
else elsif !r.is_a?(ProxyResource) && r.file_descriptor && ignored?(r.file_descriptor[:relative_path].to_s)
# This allows files to be ignored by their source file name (with template extensions) # This allows files to be ignored by their source file name (with template extensions)
r.ignore! if !r.is_a?(ProxyResource) && r.file_descriptor && ignored?(r.file_descriptor[:relative_path].to_s) r.ignore!
end end
r r

View file

@ -113,7 +113,7 @@ module Middleman
def to_s def to_s
"#<#{self.class} path=#{@path} target=#{@target}>" "#<#{self.class} path=#{@path} target=#{@target}>"
end end
alias_method :inspect, :to_s alias inspect to_s
end end
end end
end end

View file

@ -28,7 +28,7 @@ module Middleman
# Setup a redirect from a path to a target # Setup a redirect from a path to a target
# @param [String] path # @param [String] path
# @param [Hash] opts The :to value gives a target path # @param [Hash] opts The :to value gives a target path
Contract String, ({ to: Or[String, ::Middleman::Sitemap::Resource] }), Maybe[Proc] => RedirectDescriptor Contract String, { to: Or[String, ::Middleman::Sitemap::Resource] }, Maybe[Proc] => RedirectDescriptor
def redirect(path, opts={}, &block) def redirect(path, opts={}, &block)
RedirectDescriptor.new(path, opts[:to], block_given? ? block : nil) RedirectDescriptor.new(path, opts[:to], block_given? ? block : nil)
end end

View file

@ -44,14 +44,14 @@ module Middleman
def children def children
return [] unless directory_index? return [] unless directory_index?
if eponymous_directory? base_path = if eponymous_directory?
base_path = eponymous_directory_path eponymous_directory_path
prefix = %r{^#{base_path.sub("/", "\\/")}}
else else
base_path = path.sub("#{@app.config[:index_file]}", '') path.sub(@app.config[:index_file].to_s, '')
prefix = %r{^#{base_path.sub("/", "\\/")}}
end end
prefix = %r{^#{base_path.sub("/", "\\/")}}
@store.resources.select do |sub_resource| @store.resources.select do |sub_resource|
if sub_resource.path == path || sub_resource.path !~ prefix if sub_resource.path == path || sub_resource.path !~ prefix
false false

View file

@ -29,9 +29,9 @@ module Middleman
# The path to use when requesting this resource. Normally it's # The path to use when requesting this resource. Normally it's
# the same as {#destination_path} but it can be overridden in subclasses. # the same as {#destination_path} but it can be overridden in subclasses.
# @return [String] # @return [String]
alias_method :request_path, :destination_path alias request_path destination_path
METADATA_HASH = ({ options: Maybe[Hash], locals: Maybe[Hash], page: Maybe[Hash] }) METADATA_HASH = { options: Maybe[Hash], locals: Maybe[Hash], page: Maybe[Hash] }.freeze
# The metadata for this resource # The metadata for this resource
# @return [Hash] # @return [Hash]
@ -53,10 +53,10 @@ module Middleman
source = Pathname(source) if source && source.is_a?(String) source = Pathname(source) if source && source.is_a?(String)
if source && source.is_a?(Pathname) @file_descriptor = if source && source.is_a?(Pathname)
@file_descriptor = ::Middleman::SourceFile.new(source.relative_path_from(@app.source_dir), source, @app.source_dir, Set.new([:source])) ::Middleman::SourceFile.new(source.relative_path_from(@app.source_dir), source, @app.source_dir, Set.new([:source]))
else else
@file_descriptor = source source
end end
@destination_path = @path @destination_path = @path
@ -189,7 +189,7 @@ module Middleman
def to_s def to_s
"#<#{self.class} path=#{@path}>" "#<#{self.class} path=#{@path}>"
end end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
end end
class StringResource < Resource class StringResource < Resource

View file

@ -201,7 +201,7 @@ module Middleman
@lock.synchronize do @lock.synchronize do
return unless @needs_sitemap_rebuild return unless @needs_sitemap_rebuild
::Middleman::Util.instrument "sitemap.update", reasons: @rebuild_reasons.uniq do ::Middleman::Util.instrument 'sitemap.update', reasons: @rebuild_reasons.uniq do
@needs_sitemap_rebuild = false @needs_sitemap_rebuild = false
@app.logger.debug '== Rebuilding resource list' @app.logger.debug '== Rebuilding resource list'
@ -209,7 +209,7 @@ module Middleman
@resources = [] @resources = []
@resource_list_manipulators.each do |m| @resource_list_manipulators.each do |m|
::Middleman::Util.instrument "sitemap.manipulator", name: m[:name] do ::Middleman::Util.instrument 'sitemap.manipulator', name: m[:name] do
@app.logger.debug "== Running manipulator: #{m[:name]}" @app.logger.debug "== Running manipulator: #{m[:name]}"
@resources = m[:manipulator].send(m[:custom_name] || :manipulate_resource_list, @resources) @resources = m[:manipulator].send(m[:custom_name] || :manipulate_resource_list, @resources)

View file

@ -15,10 +15,10 @@ module Middleman
include Contracts include Contracts
# Types which could cause output to change. # Types which could cause output to change.
OUTPUT_TYPES = [:source, :locales, :data] OUTPUT_TYPES = [:source, :locales, :data].freeze
# Types which require a reload to eval ruby # Types which require a reload to eval ruby
CODE_TYPES = [:reload] CODE_TYPES = [:reload].freeze
Matcher = Or[Regexp, RespondTo[:call]] Matcher = Or[Regexp, RespondTo[:call]]
@ -257,11 +257,11 @@ module Middleman
# #
# @param [nil,Regexp] matcher A Regexp to match the change path against # @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any Contract Maybe[Matcher] => Any
def changed(matcher=nil, &block) def changed(matcher=nil, &_block)
on_change OUTPUT_TYPES do |updated, _removed| on_change OUTPUT_TYPES do |updated, _removed|
updated updated
.select { |f| matcher.nil? ? true : matches?(matcher, f) } .select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| block.call(f[:relative_path]) } .each { |f| yield f[:relative_path] }
end end
end end
@ -269,11 +269,11 @@ module Middleman
# #
# @param [nil,Regexp] matcher A Regexp to match the change path against # @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any Contract Maybe[Matcher] => Any
def deleted(matcher=nil, &block) def deleted(matcher=nil, &_block)
on_change OUTPUT_TYPES do |_updated, removed| on_change OUTPUT_TYPES do |_updated, removed|
removed removed
.select { |f| matcher.nil? ? true : matches?(matcher, f) } .select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| block.call(f[:relative_path]) } .each { |f| yield f[:relative_path] }
end end
end end

View file

@ -202,7 +202,7 @@ module Middleman
def to_s def to_s
"#<Middleman::SourceWatcher:0x#{object_id} type=#{@type.inspect} directory=#{@directory.inspect}>" "#<Middleman::SourceWatcher:0x#{object_id} type=#{@type.inspect} directory=#{@directory.inspect}>"
end end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
protected protected

View file

@ -162,7 +162,7 @@ module Middleman
return nil unless current_path return nil unless current_path
sitemap.find_resource_by_destination_path(current_path) sitemap.find_resource_by_destination_path(current_path)
end end
alias_method :current_page, :current_resource alias current_page current_resource
protected protected

View file

@ -28,6 +28,75 @@ module Middleman
@_cache ||= Cache.new @_cache ||= Cache.new
end end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
# @param [Symbol] preferred_engine
# @return [String]
Contract IsA['Middleman::Application'], Or[String, Symbol], Symbol => Maybe[IsA['Middleman::SourceFile']]
def self.locate_layout(app, name, preferred_engine=nil)
resolve_opts = {}
resolve_opts[:preferred_engine] = preferred_engine unless preferred_engine.nil?
# Check layouts folder
layout_file = resolve_template(app, File.join(app.config[:layouts_dir], name.to_s), resolve_opts)
# If we didn't find it, check root
layout_file = resolve_template(app, name, resolve_opts) unless layout_file
# Return the path
layout_file
end
# Find a template on disk given a output path
# @param [String] request_path
# @option options [Boolean] :preferred_engine If set, try this engine first, then fall back to any engine.
# @return [String, Boolean] Either the path to the template, or false
Contract IsA['Middleman::Application'], Or[Symbol, String], Maybe[Hash] => Maybe[IsA['Middleman::SourceFile']]
def self.resolve_template(app, request_path, options={})
# Find the path by searching
relative_path = Util.strip_leading_slash(request_path.to_s)
# By default, any engine will do
preferred_engines = []
# If we're specifically looking for a preferred engine
if options.key?(:preferred_engine)
extension_class = ::Tilt[options[:preferred_engine]]
# Get a list of extensions for a preferred engine
preferred_engines += ::Tilt.mappings.select do |_, engines|
engines.include? extension_class
end.keys
end
preferred_engines << '*'
preferred_engines << nil if options[:try_static]
found_template = nil
preferred_engines.each do |preferred_engine|
path_with_ext = relative_path.dup
path_with_ext << ('.' + preferred_engine) unless preferred_engine.nil?
globbing = preferred_engine == '*'
# Cache lookups in build mode only
file = if app.build?
cache.fetch(path_with_ext, preferred_engine) do
app.files.find(:source, path_with_ext, globbing)
end
else
app.files.find(:source, path_with_ext, globbing)
end
found_template = file if file && (preferred_engine.nil? || ::Tilt[file[:full_path]])
break if found_template
end
# If we found one, return it
found_template
end
# Custom error class for handling # Custom error class for handling
class TemplateNotFound < RuntimeError; end class TemplateNotFound < RuntimeError; end
@ -132,16 +201,15 @@ module Middleman
# Look for :layout of any extension # Look for :layout of any extension
# If found, use it. If not, continue # If found, use it. If not, continue
locate_layout(:layout, layout_engine) locate_layout(:layout, layout_engine)
else elsif layout_file = locate_layout(local_layout, layout_engine)
# Look for specific layout # Look for specific layout
# If found, use it. If not, error. # If found, use it. If not, error.
if layout_file = locate_layout(local_layout, layout_engine)
layout_file layout_file
else else
raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate layout: #{local_layout}" raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate layout: #{local_layout}"
end end
end end
end
# Find a layout on-disk, optionally using a specific engine # Find a layout on-disk, optionally using a specific engine
# @param [String] name # @param [String] name
@ -152,25 +220,6 @@ module Middleman
self.class.locate_layout(@app, name, preferred_engine) self.class.locate_layout(@app, name, preferred_engine)
end end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
# @param [Symbol] preferred_engine
# @return [String]
Contract IsA['Middleman::Application'], Or[String, Symbol], Symbol => Maybe[IsA['Middleman::SourceFile']]
def self.locate_layout(app, name, preferred_engine=nil)
resolve_opts = {}
resolve_opts[:preferred_engine] = preferred_engine unless preferred_engine.nil?
# Check layouts folder
layout_file = resolve_template(app, File.join(app.config[:layouts_dir], name.to_s), resolve_opts)
# If we didn't find it, check root
layout_file = resolve_template(app, name, resolve_opts) unless layout_file
# Return the path
layout_file
end
# Find a template on disk given a output path # Find a template on disk given a output path
# @param [String] request_path # @param [String] request_path
# @param [Hash] options # @param [Hash] options
@ -179,55 +228,5 @@ module Middleman
def resolve_template(request_path, options={}) def resolve_template(request_path, options={})
self.class.resolve_template(@app, request_path, options) self.class.resolve_template(@app, request_path, options)
end end
# Find a template on disk given a output path
# @param [String] request_path
# @option options [Boolean] :preferred_engine If set, try this engine first, then fall back to any engine.
# @return [String, Boolean] Either the path to the template, or false
Contract IsA['Middleman::Application'], Or[Symbol, String], Maybe[Hash] => Maybe[IsA['Middleman::SourceFile']]
def self.resolve_template(app, request_path, options={})
# Find the path by searching
relative_path = Util.strip_leading_slash(request_path.to_s)
# By default, any engine will do
preferred_engines = []
# If we're specifically looking for a preferred engine
if options.key?(:preferred_engine)
extension_class = ::Tilt[options[:preferred_engine]]
# Get a list of extensions for a preferred engine
preferred_engines += ::Tilt.mappings.select do |_, engines|
engines.include? extension_class
end.keys
end
preferred_engines << '*'
preferred_engines << nil if options[:try_static]
found_template = nil
preferred_engines.each do |preferred_engine|
path_with_ext = relative_path.dup
path_with_ext << ('.' + preferred_engine) unless preferred_engine.nil?
globbing = preferred_engine == '*'
# Cache lookups in build mode only
file = if app.build?
cache.fetch(path_with_ext, preferred_engine) do
app.files.find(:source, path_with_ext, globbing)
end
else
app.files.find(:source, path_with_ext, globbing)
end
found_template = file if file && (preferred_engine.nil? || ::Tilt[file[:full_path]])
break if found_template
end
# If we found one, return it
found_template
end
end end
end end

View file

@ -153,7 +153,7 @@ module Middleman
all_files_under(child, &ignore) all_files_under(child, &ignore)
end.compact end.compact
elsif path.file? elsif path.file?
if block_given? && ignore.call(path) if block_given? && yield(path)
[] []
else else
[path] [path]
@ -332,7 +332,7 @@ module Middleman
end end
Contract String, String, ArrayOf[String], Proc => String Contract String, String, ArrayOf[String], Proc => String
def rewrite_paths(body, _path, exts, &block) def rewrite_paths(body, _path, exts, &_block)
matcher = /([=\'\"\(,]\s*)([^\s\'\"\)>]+(#{Regexp.union(exts)}))/ matcher = /([=\'\"\(,]\s*)([^\s\'\"\)>]+(#{Regexp.union(exts)}))/
url_fn_prefix = 'url(' url_fn_prefix = 'url('
@ -349,7 +349,7 @@ module Middleman
begin begin
uri = ::Addressable::URI.parse(asset_path) uri = ::Addressable::URI.parse(asset_path)
if uri.relative? && uri.host.nil? && (result = block.call(asset_path)) if uri.relative? && uri.host.nil? && (result = yield asset_path)
"#{opening_character}#{result}" "#{opening_character}#{result}"
else else
match match

View file

@ -1,5 +1,5 @@
module Middleman module Middleman
# Current Version # Current Version
# @return [String] # @return [String]
VERSION = '4.1.0.rc.1' unless const_defined?(:VERSION) VERSION = '4.1.0.rc.1'.freeze unless const_defined?(:VERSION)
end end

View file

@ -1,4 +1,4 @@
# coding:utf-8 # coding:utf-8
RAKE_ROOT = __FILE__ RAKE_ROOT = __FILE__.freeze
GEM_NAME = 'middleman' GEM_NAME = 'middleman'.freeze
require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper') require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper')