summaryrefslogtreecommitdiff
path: root/lib/safe_zip/extract_params.rb
blob: 96881ad1abce6af7e43b312c8b477e8ea757753e (plain)
1
2
3
4
5
6
7
8
9
10
11
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
51
52
53
54
55
56
# frozen_string_literal: true

module SafeZip
  class ExtractParams
    include Gitlab::Utils::StrongMemoize

    attr_reader :directories, :files, :extract_path

    def initialize(to:, directories: [], files: [])
      @directories = directories
      @files = files
      @extract_path = ::File.realpath(to)
      validate!
    end

    def matching_target_directory(path)
      target_directories.find do |directory|
        path.start_with?(directory)
      end
    end

    def target_directories
      strong_memoize(:target_directories) do
        directories.map do |directory|
          ::File.join(::File.expand_path(directory, extract_path), '')
        end
      end
    end

    def directories_wildcard
      strong_memoize(:directories_wildcard) do
        directories.map do |directory|
          ::File.join(directory, '*')
        end
      end
    end

    def matching_target_file(path)
      target_files.include?(path)
    end

    private

    def target_files
      strong_memoize(:target_files) do
        files.map do |file|
          ::File.join(extract_path, file)
        end
      end
    end

    def validate!
      raise ArgumentError, 'Either directories or files are required' if directories.empty? && files.empty?
    end
  end
end