require 'zip' require 'securerandom' module GoldenRose class FileResource attr_reader :path, :file_name, :folder_path, :source_type, :resource_type TEST_SUMMARIES_FILE_NAME = 'action_TestSummaries.plist' INFO_FILE_NAME = 'Info.plist' ALLOWED_RESOURCE_TYPES = [ :test_summaries_plist, :info_plist, :build_log, :screenshoot ] def initialize(type, source_type, folder_path, file_name = nil, destination = nil) @resource_type = validate_resource_type(type) @source_type = source_type @folder_path = folder_path @destination = destination initialize_filename(file_name) open_source rescue Zip::Error, Errno::ENOENT raise GeneratingError, "Could not open the folder #{folder_path}." end def extension @file_name.split('.').last end def delete_extracted_file return unless @path File.delete(@path) if source_type == :zip end private def initialize_filename(file_name) @file_name = case @resource_type when :test_summaries_plist then TEST_SUMMARIES_FILE_NAME when :info_plist then INFO_FILE_NAME else file_name end end def validate_resource_type(type) return type if ALLOWED_RESOURCE_TYPES.include? type fail ArgumentError, "FileResource of #{type} type is disallowed!" end def open_source case @source_type when :zip then open_zip when :dir then open_directory(@file_name) end end def compare_file_path(expected_path, file_path) path_array = file_path.split('/').reverse expected_path.split('/').reverse.map.with_index do |val, idx| path_array[idx] == val end.all? end def open_zip Zip::File.open(folder_path) do |zip_file| entry = zip_file.find do |entry| compare_file_path(@file_name, entry.name) end if entry uuid = ::SecureRandom.uuid @path = if @destination File.join(GoldenRose.root, "/#{@destination}") else File.join(GoldenRose.root, "/source_#{uuid}.#{extension}") end entry.extract(path) end end end def open_directory(file_name) unless @destination @path = Dir.glob("#{folder_path}/**/#{file_name}").first return end source_path = Dir.glob("#{folder_path}/**/#{file_name}").first cp_file(source_path, @destination) dest_arr = @destination.split('/') @path = dest_arr[1..dest_arr.length].join('/') end def cp_file(source, destination) FileUtils.cp(source, destination) end end end