Class: Gem::Compiler

Inherits:
Object
  • Object
show all
Includes:
UserInteraction
Defined in:
lib/rubygems/compiler.rb

Defined Under Namespace

Classes: CompilerError

Instance Method Summary collapse

Constructor Details

#initialize(gemfile, output_dir) ⇒ Compiler

Returns a new instance of Compiler.



13
14
15
16
# File 'lib/rubygems/compiler.rb', line 13

def initialize(gemfile, output_dir)
  @gemfile    = gemfile
  @output_dir = output_dir
end

Instance Method Details

#compileObject



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
88
89
90
# File 'lib/rubygems/compiler.rb', line 18

def compile
  installer = Gem::Installer.new(@gemfile, :unpack => true)

  # Hmm, gem already compiled?
  if installer.spec.platform != Gem::Platform::RUBY
    raise CompilerError,
          "The gem file seems to be compiled already."
  end

  # Hmm, no extensions?
  if installer.spec.extensions.empty?
    raise CompilerError,
          "There are no extensions to build on this gem file."
  end

  tmpdir     = Dir.mktmpdir
  basename   = File.basename(@gemfile, '.gem')
  target_dir = File.join(tmpdir, basename)

  # unpack gem sources into target_dir
  # We need the basename to keep the unpack happy
  say "Unpacking gem: '#{basename}' in temporary directory..." if Gem.configuration.verbose
  installer.unpack(target_dir)

  # build extensions
  installer.build_extensions

  # determine build artifacts from require_paths
  dlext    = RbConfig::CONFIG["DLEXT"]
  lib_dirs = installer.spec.require_paths.join(",")

  artifacts = Dir.glob("#{target_dir}/{#{lib_dirs}}/**/*.#{dlext}")

  # build a new gemspec from the original one
  gemspec = installer.spec.dup

  # add discovered artifacts
  artifacts.each do |path|
    # path needs to be relative to target_dir
    file = path.gsub("#{target_dir}/", "")

    say "Adding '#{file}' to gemspec" if Gem.configuration.really_verbose
    gemspec.files.push file
  end

  # clear out extensions from gemspec
  gemspec.extensions.clear

  # adjust platform
  gemspec.platform = Gem::Platform::CURRENT

  # build new gem
  output_gem = nil

  Dir.chdir target_dir do
    builder = Gem::Builder.new(gemspec)
    output_gem = builder.build
  end

  unless output_gem
    raise CompilerError,
          "There was a problem building the gem."
  end

  # move the built gem to the original output directory
  FileUtils.mv File.join(target_dir, output_gem), @output_dir

  # cleanup
  FileUtils.rm_rf tmpdir

  # return the path of the gem
  output_gem
end