summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/build/artifacts/adapters/gzip_stream.rb
blob: 5e816c8859cc57b9a693c3eb6a4b102f64f01c5f (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
# frozen_string_literal: true

module Gitlab
  module Ci
    module Build
      module Artifacts
        module Adapters
          class GzipStream
            attr_reader :stream

            InvalidStreamError = Class.new(StandardError)

            def initialize(stream)
              raise InvalidStreamError, _("Stream is required") unless stream

              @stream = stream
            end

            def each_blob
              stream.seek(0)

              until stream.eof?
                gzip(stream) do |gz|
                  yield gz.read, gz.orig_name
                  unused = gz.unused&.length.to_i
                  # pos has already reached to EOF at the moment
                  # We rewind the pos to the top of unused files
                  # to read next gzip stream, to support multistream archives
                  # https://golang.org/src/compress/gzip/gunzip.go#L117
                  stream.seek(-unused, IO::SEEK_CUR)
                end
              end
            end

            private

            def gzip(stream, &block)
              gz = Zlib::GzipReader.new(stream)
              yield(gz)
            rescue Zlib::Error => e
              raise InvalidStreamError, e.message
            ensure
              gz&.finish
            end
          end
        end
      end
    end
  end
end