1#--
2# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
3# All rights reserved.
4# See LICENSE.txt for permissions.
5#++
6
7require 'rubygems/ext/builder'
8require 'rubygems/command'
9require 'fileutils'
10require 'tempfile'
11
12class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder
13  FileEntry = FileUtils::Entry_ # :nodoc:
14
15  def self.build(extension, directory, dest_path, results, args=[])
16    tmp_dest = Dir.mktmpdir(".gem.", ".")
17
18    t = nil
19    Tempfile.open %w"siteconf .rb", "." do |siteconf|
20      t = siteconf
21      siteconf.puts "require 'rbconfig'"
22      siteconf.puts "dest_path = #{(tmp_dest || dest_path).dump}"
23      %w[sitearchdir sitelibdir].each do |dir|
24        siteconf.puts "RbConfig::MAKEFILE_CONFIG['#{dir}'] = dest_path"
25        siteconf.puts "RbConfig::CONFIG['#{dir}'] = dest_path"
26      end
27
28      siteconf.flush
29
30      siteconf_path = File.expand_path siteconf.path
31
32      rubyopt = ENV["RUBYOPT"]
33      destdir = ENV["DESTDIR"]
34
35      begin
36        ENV["RUBYOPT"] = ["-r#{siteconf_path}", rubyopt].compact.join(' ')
37        cmd = [Gem.ruby, File.basename(extension), *args].join ' '
38
39        run cmd, results
40
41        ENV["DESTDIR"] = nil
42        ENV["RUBYOPT"] = rubyopt
43        siteconf.unlink
44
45        make dest_path, results
46
47        if tmp_dest
48          FileEntry.new(tmp_dest).traverse do |ent|
49            destent = ent.class.new(dest_path, ent.rel)
50            destent.exist? or File.rename(ent.path, destent.path)
51          end
52        end
53      ensure
54        ENV["RUBYOPT"] = rubyopt
55        ENV["DESTDIR"] = destdir
56      end
57    end
58    t.unlink if t and t.path
59
60    results
61  ensure
62    FileUtils.rm_rf tmp_dest if tmp_dest
63  end
64
65end
66
67