Path: blob/trunk/rb/lib/selenium/webdriver/common/zipper.rb
1865 views
# frozen_string_literal: true12# Licensed to the Software Freedom Conservancy (SFC) under one3# or more contributor license agreements. See the NOTICE file4# distributed with this work for additional information5# regarding copyright ownership. The SFC licenses this file6# to you under the Apache License, Version 2.0 (the7# "License"); you may not use this file except in compliance8# with the License. You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing,13# software distributed under the License is distributed on an14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15# KIND, either express or implied. See the License for the16# specific language governing permissions and limitations17# under the License.1819require 'zip'20require 'zip/version' # Not required automatically21require 'tempfile'22require 'find'23require 'base64'2425module Selenium26module WebDriver27#28# @api private29#3031module Zipper32EXTENSIONS = %w[.zip .xpi].freeze33RUBYZIP_V3 = Zip::VERSION >= '3.0.0'3435class << self36def unzip(path)37destination = Dir.mktmpdir('webdriver-unzip')38FileReaper << destination3940Zip::File.open(path) do |zip|41zip.each do |entry|42to = File.join(destination, entry.name)43dirname = File.dirname(to)4445FileUtils.mkdir_p dirname46if RUBYZIP_V347zip.extract(entry, entry.name, destination_directory: destination)48else49zip.extract(entry, to)50end51end52end5354destination55end5657def zip(path)58with_tmp_zip do |zip|59::Find.find(path) do |file|60add_zip_entry zip, file, file.sub("#{path}/", '') unless File.directory?(file)61end6263zip.commit64File.open(zip.name, 'rb') { |io| Base64.strict_encode64 io.read }65end66end6768def zip_file(path)69with_tmp_zip do |zip|70add_zip_entry zip, path, File.basename(path)7172zip.commit73File.open(zip.name, 'rb') { |io| Base64.strict_encode64 io.read }74end75end7677private7879def with_tmp_zip(&blk)80# Don't use Tempfile since it lacks rb_file_s_rename permission on Windows.81Dir.mktmpdir do |tmp_dir|82zip_path = File.join(tmp_dir, 'webdriver-zip')83if RUBYZIP_V384Zip::File.open(zip_path, create: true, &blk)85else86Zip::File.open(zip_path, Zip::File::CREATE, &blk)87end88end89end9091def add_zip_entry(zip, file, entry_name)92entry = Zip::Entry.new(zip.name, entry_name)93entry.follow_symlinks = true9495zip.add entry, file96end97end98end # Zipper99end # WebDriver100end # Selenium101102103