Sha256: 4b8d1afeb72c5a73b6c5f1ef2194a35ce2050b740b3d02c6c7d9c3eefff2a37a

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

require "thor/group"
require "s3imageoptim"
require "image_optim"
require "open3"

class S3imageoptim::Command < Thor::Group
  argument :bucket, desc: "S3 Bucket to compress"
  desc "Get all files from BUCKET and put them back compressed"
  def get
    s3cmd("get --exclude '*' --rinclude '\.(#{extensions("|")})$' --recursive #{bucket} #{tmpdir}") do |error|
      abort("An error ocurred while getting the files: #{error}")
    end

    if local_files.empty?
      abort("No images were found in the bucket")
    end
  end

  def compress
    ImageOptim.new(pngout: false, svgo: false).optimize_images!(local_files)
  end

  def put
    s3cmd("sync #{tmpdir}/ #{bucket}") do |error|
      abort("An error ocurred while putting the files: #{error}")
    end
  end

  def remove
    FileUtils.remove_entry(tmpdir)
  end

  private
  def local_files
    Dir.glob(File.join(tmpdir, "**", "*.{#{extensions(",")}}"))
  end

  def extensions(separator)
    %w{jpg jpeg png}.join(separator)
  end

  def tmpdir
    @tmpdir ||= Dir.mktmpdir
  end

  def s3cmd(args, &failure_block)
    Open3.popen3("s3cmd #{args}") do |stdin, stdout, stderr, thread|
      thread.value.success? ? stdout.read : failure_block.call(stderr.read)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
s3imageoptim-0.1.0 lib/s3imageoptim/command.rb