Skip to content

Commit

Permalink
checking bin versions, closes #33
Browse files Browse the repository at this point in the history
  • Loading branch information
toy committed Mar 2, 2014
1 parent 922cf52 commit e66d8fc
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
51 changes: 49 additions & 2 deletions lib/image_optim/bin_resolver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,20 @@

class ImageOptim
class BinNotFoundError < StandardError; end
class BadBinVersion < StandardError; end

class BinResolver
class Bin
attr_reader :name, :version
def initialize(name, version)
@name, @version = name, version
end

def to_s
"#{@name} #{@version || '-'}"
end
end

attr_reader :dir
def initialize
@bins = {}
Expand All @@ -12,10 +25,16 @@ def initialize

def resolve!(name)
name = name.to_sym

resolving(name) do
@bins[name] = resolve?(name)
@bins[name] = resolve?(name) && Bin.new(name, version(name))
end

if @bins[name]
check!(@bins[name])
else
raise BinNotFoundError, "`#{name}` not found"
end
@bins[name] or raise BinNotFoundError, "`#{name}` not found"
end

VENDOR_PATH = File.expand_path('../../../vendor', __FILE__)
Expand Down Expand Up @@ -52,6 +71,34 @@ def accessible?(name)
capture_output("which #{name.to_s.shellescape}") != ''
end

def version(name)
case name.to_sym
when :advpng, :gifsicle, :jpegoptim, :optipng
capture_output("#{name} --version")[/\d+(\.\d+){1,}/]
when :svgo
capture_output("#{name} --version 2>&1")[/\d+(\.\d+){1,}/]
when :jhead
capture_output("#{name} -V")[/\d+(\.\d+){1,}/]
when :jpegtran
capture_output("#{name} -v - 2>&1")[/version (\d+\S*)/, 1]
when :pngcrush
capture_output("#{name} -version 2>&1")[/\d+(\.\d+){1,}/]
when :pngout
date_str = capture_output("#{name} 2>&1")[/[A-Z][a-z]{2} (?: |\d)\d \d{4}/]
Date.parse(date_str).strftime('%Y%m%d')
end
end

def check!(bin)
case bin.name
when :pngcrush
case bin.version
when '1.7.60'..'1.7.65'
raise BadBinVersion, "`#{bin}` is known to produce broken pngs"
end
end
end

def capture_output(command)
`env PATH=#{env_path.shellescape} #{command}`
end
Expand Down
16 changes: 16 additions & 0 deletions spec/image_optim/bin_resolver_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,20 @@ def with_env(key, value)
end.each(&:join)
end
end

it "should raise on detection of problematic version" do
with_env 'PNGCRUSH_BIN', nil do
resolver = ImageOptim::BinResolver.new
resolver.should_receive(:accessible?).with(:pngcrush).once.and_return(true)
resolver.should_receive(:version).with(:pngcrush).once.and_return('1.7.60')
FSPath.should_not_receive(:temp_dir)

5.times do
expect do
resolver.resolve!(:pngcrush)
end.to raise_error ImageOptim::BadBinVersion
end
resolver.env_path.should == "#{ENV['PATH']}:#{ImageOptim::BinResolver::VENDOR_PATH}"
end
end
end

0 comments on commit e66d8fc

Please sign in to comment.