Class: Bridgetown::Webp::WebpExec

Inherits:
Object
  • Object
show all
Defined in:
lib/bridgetown-webp/webpExec.rb

Class Method Summary collapse

Class Method Details

.exe_nameObject

Returns the correct executable name depending on the OS platform and OS architecture



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/bridgetown-webp/webpExec.rb', line 55

def self.exe_name
  if OS.mac?
    return "osx-cwebp"
  elsif OS.windows?
    if OS.x32?
      return "win-x86-cwebp.exe"
    else
      return "win-x64-cwebp.exe"
    end
  elsif OS.unix? || OS.linux?
    if OS.x32?
      return "linux-x86-cwebp"
    else
      return "linux-x64-cwebp"
    end
  else
    raise ArgumentError.new("OS platform could not be identified (gem can only be run on linux,osx or windows)")
  end
end

.run(quality, flags, input_file, output_file) ⇒ Object

Runs the WebP executable for the given input parameters the function detects the OS platform and architecture automatically



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bridgetown-webp/webpExec.rb', line 12

def self.run(quality, flags, input_file, output_file)

  # What is the path to the execs inside the gem? perhaps just bin/?
  bin_path = "bin/"

  # What is the OS and architecture specific executable name?
  exe_name = WebpExec.exe_name

  # We need to locate the Gems bin path as we're currently running inside the 
  # bridgetown site working directory
  # http://stackoverflow.com/a/10083594/779521
  gem_spec = Gem::Specification.find_by_name("bridgetown-webp")
  gem_root = gem_spec.gem_dir

  # Construct the full path to the executable
  full_path = File.join(gem_root, bin_path, exe_name)

  # Construct the full program call
  cmd = "\"#{full_path}\" -quiet -mt -q #{quality.to_s} #{flags} \"#{input_file}\" -o \"#{output_file}\""
  
  # Execute the command
  exit_code = 0
  error = ""
  output = ""
  Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
    stdin.close # we don't pass any input to the process
    output = stdout.gets
    error = stderr.gets
    exit_code = wait_thr.value
  end

  if exit_code != 0
    Bridgetown.logger.error("WebP:","Conversion for image #{input_file} failed, no webp version could be created for this image")
    Bridgetown.logger.debug("WebP:","cwebp returned #{exit_code} with error #{error}")
  end

  # Return any captured return value
  return [output, error]
end