summaryrefslogtreecommitdiff
path: root/lib/rubygems/format.rb
blob: 80aae562152079638fe9ba9109059d8e637782f8 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++

require 'fileutils'

require 'rubygems/package'

##
# Gem::Format knows the guts of the RubyGem .gem file format and provides the
# capability to read gem files

class Gem::Format

  attr_accessor :spec, :file_entries, :gem_path

  extend Gem::UserInteraction

  ##
  # Constructs an instance of a Format object, representing the gem's
  # data structure.
  #
  # gem:: [String] The file name of the gem
  #
  def initialize(gem_path)
    @gem_path = gem_path
  end

  ##
  # Reads the named gem file and returns a Format object, representing
  # the data from the gem file
  #
  # file_path:: [String] Path to the gem file

  def self.from_file_by_path(file_path, security_policy = nil)
    format = nil

    unless File.exist?(file_path)
      raise Gem::Exception, "Cannot load gem at [#{file_path}] in #{Dir.pwd}"
    end

    # check for old version gem
    if File.read(file_path, 20).include?("MD5SUM =")
      require 'rubygems/old_format'

      format = Gem::OldFormat.from_file_by_path(file_path)
    else
      open file_path, Gem.binary_mode do |io|
        format = from_io io, file_path, security_policy
      end
    end

    return format
  end

  ##
  # Reads a gem from an io stream and returns a Format object, representing
  # the data from the gem file
  #
  # io:: [IO] Stream from which to read the gem

  def self.from_io(io, gem_path="(io)", security_policy = nil)
    format = new gem_path

    Gem::Package.open io, 'r', security_policy do |pkg|
      format.spec = pkg.metadata
      format.file_entries = []

      pkg.each do |entry|
        size = entry.header.size
        mode = entry.header.mode

        format.file_entries << [{
            "size" => size, "mode" => mode, "path" => entry.full_name,
          },
          entry.read
        ]
      end
    end

    format
  end

end