Skip to content

Commit

Permalink
add exclusion glob patterns; closes #35, resolves #48
Browse files Browse the repository at this point in the history
  • Loading branch information
toy committed Sep 1, 2014
1 parent cdbfd7f commit e6c937a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
15 changes: 15 additions & 0 deletions bin/image_optim
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ option_parser = OptionParser.new do |op|
options[:recursive] = recursive
end

op.on("--exclude-dir='GLOB'", 'Glob for excluding directories '\
'(defaults to .*)') do |glob|
options[:exclude_dir_glob] = glob
end

op.on("--exclude-file='GLOB'", 'Glob for excluding files '\
'(defaults to .*)') do |glob|
options[:exclude_file_glob] = glob
end

op.on("--exclude='GLOB'", 'Set glob for excluding both directories and '\
'files') do |glob|
options[:exclude_file_glob] = options[:exclude_dir_glob] = glob
end

op.separator nil

op.on('--[no-]threads N', Integer, 'Number of threads or disable '\
Expand Down
34 changes: 31 additions & 3 deletions lib/image_optim/runner.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'image_optim'
require 'image_optim/hash_helpers'
require 'image_optim/runner/glob_helpers'
require 'image_optim/space'
require 'progress'
require 'optparse'
Expand Down Expand Up @@ -47,6 +48,10 @@ def initialize(args, options)
fail 'specify paths to optimize' if args.empty?
options = HashHelpers.deep_symbolise_keys(options)
@recursive = options.delete(:recursive)
@exclude_dir_globs, @exclude_file_globs = %w[dir file].map do |type|
glob = options.delete(:"exclude_#{type}_glob") || '.*'
GlobHelpers.expand_braces(glob)
end
@image_optim = ImageOptim.new(options)
@to_optimize = find_to_optimize(args)
end
Expand Down Expand Up @@ -101,13 +106,36 @@ def find_to_optimize(paths)
def find_to_optimize_recursive(dir)
to_optimize = []
Find.find(dir) do |path|
next unless File.file?(path)
next unless @image_optim.optimizable?(path)
to_optimize << path
if File.file?(path)
next if exclude_file?(dir, path)
next unless @image_optim.optimizable?(path)
to_optimize << path
elsif File.directory?(path)
Find.prune if dir != path && exclude_dir?(dir, path)
end
end
to_optimize
end

def exclude_dir?(dir, path)
exclude?(dir, path, @exclude_dir_globs)
end

def exclude_file?(dir, path)
exclude?(dir, path, @exclude_file_globs)
end

# Check if any of globs matches either part of path relative from dir or
# just basename
def exclude?(dir, path, globs)
relative_path = Pathname(path).relative_path_from(Pathname(dir)).to_s
basename = File.basename(path)
globs.any? do |glob|
File.fnmatch(glob, relative_path, File::FNM_PATHNAME) ||
File.fnmatch(glob, basename, File::FNM_PATHNAME)
end
end

def warning(message)
@warnings = true
warn message
Expand Down

0 comments on commit e6c937a

Please sign in to comment.