deps: make node-gyp work with io.js
[platform/upstream/nodejs.git] / deps / npm / node_modules / node-gyp / lib / build.js
1
2 module.exports = exports = build
3
4 /**
5  * Module dependencies.
6  */
7
8 var fs = require('graceful-fs')
9   , rm = require('rimraf')
10   , path = require('path')
11   , glob = require('glob')
12   , log = require('npmlog')
13   , which = require('which')
14   , mkdirp = require('mkdirp')
15   , exec = require('child_process').exec
16   , win = process.platform == 'win32'
17
18 exports.usage = 'Invokes `' + (win ? 'msbuild' : 'make') + '` and builds the module'
19
20 function build (gyp, argv, callback) {
21
22   var makeCommand = gyp.opts.make || process.env.MAKE
23       || (process.platform.indexOf('bsd') != -1 && process.platform.indexOf('kfreebsd') == -1 ? 'gmake' : 'make')
24     , command = win ? 'msbuild' : makeCommand
25     , buildDir = path.resolve('build')
26     , configPath = path.resolve(buildDir, 'config.gypi')
27     , jobs = gyp.opts.jobs || process.env.JOBS
28     , buildType
29     , config
30     , arch
31     , nodeDir
32     , copyDevLib
33
34   loadConfigGypi()
35
36   /**
37    * Load the "config.gypi" file that was generated during "configure".
38    */
39
40   function loadConfigGypi () {
41     fs.readFile(configPath, 'utf8', function (err, data) {
42       if (err) {
43         if (err.code == 'ENOENT') {
44           callback(new Error('You must run `node-gyp configure` first!'))
45         } else {
46           callback(err)
47         }
48         return
49       }
50       config = JSON.parse(data.replace(/\#.+\n/, ''))
51
52       // get the 'arch', 'buildType', and 'nodeDir' vars from the config
53       buildType = config.target_defaults.default_configuration
54       arch = config.variables.target_arch
55       nodeDir = config.variables.nodedir
56       copyDevLib = config.variables.copy_dev_lib == 'true'
57
58       if ('debug' in gyp.opts) {
59         buildType = gyp.opts.debug ? 'Debug' : 'Release'
60       }
61       if (!buildType) {
62         buildType = 'Release'
63       }
64
65       log.verbose('build type', buildType)
66       log.verbose('architecture', arch)
67       log.verbose('node dev dir', nodeDir)
68
69       if (win) {
70         findSolutionFile()
71       } else {
72         doWhich()
73       }
74     })
75   }
76
77   /**
78    * On Windows, find the first build/*.sln file.
79    */
80
81   function findSolutionFile () {
82     glob('build/*.sln', function (err, files) {
83       if (err) return callback(err)
84       if (files.length === 0) {
85         return callback(new Error('Could not find *.sln file. Did you run "configure"?'))
86       }
87       guessedSolution = files[0]
88       log.verbose('found first Solution file', guessedSolution)
89       doWhich()
90     })
91   }
92
93   /**
94    * Uses node-which to locate the msbuild / make executable.
95    */
96
97   function doWhich () {
98     // First make sure we have the build command in the PATH
99     which(command, function (err, execPath) {
100       if (err) {
101         if (win && /not found/.test(err.message)) {
102           // On windows and no 'msbuild' found. Let's guess where it is
103           findMsbuild()
104         } else {
105           // Some other error or 'make' not found on Unix, report that to the user
106           callback(err)
107         }
108         return
109       }
110       log.verbose('`which` succeeded for `' + command + '`', execPath)
111       copyNodeLib()
112     })
113   }
114
115   /**
116    * Search for the location of "msbuild.exe" file on Windows.
117    */
118
119   function findMsbuild () {
120     log.verbose('could not find "msbuild.exe" in PATH - finding location in registry')
121     var notfoundErr = new Error('Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?')
122     var cmd = 'reg query "HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions" /s'
123     if (process.arch !== 'ia32')
124       cmd += ' /reg:32'
125     exec(cmd, function (err, stdout, stderr) {
126       var reVers = /ToolsVersions\\([^\\]+)$/i
127         , rePath = /\r\n[ \t]+MSBuildToolsPath[ \t]+REG_SZ[ \t]+([^\r]+)/i
128         , msbuilds = []
129         , r
130         , msbuildPath
131       if (err) {
132         return callback(notfoundErr)
133       }
134       stdout.split('\r\n\r\n').forEach(function(l) {
135         if (!l) return
136         l = l.trim()
137         if (r = reVers.exec(l.substring(0, l.indexOf('\r\n')))) {
138           var ver = parseFloat(r[1], 10)
139           if (ver >= 3.5) {
140             if (r = rePath.exec(l)) {
141               msbuilds.push({
142                 version: ver,
143                 path: r[1]
144               })
145             }
146           }
147         }
148       })
149       msbuilds.sort(function (x, y) {
150         return (x.version < y.version ? -1 : 1)
151       })
152       ;(function verifyMsbuild () {
153         if (!msbuilds.length) return callback(notfoundErr)
154         msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe')
155         fs.stat(msbuildPath, function (err, stat) {
156           if (err) {
157             if (err.code == 'ENOENT') {
158               if (msbuilds.length) {
159                 return verifyMsbuild()
160               } else {
161                 callback(notfoundErr)
162               }
163             } else {
164               callback(err)
165             }
166             return
167           }
168           command = msbuildPath
169           copyNodeLib()
170         })
171       })()
172     })
173   }
174
175   /**
176    * Copies the iojs.lib file for the current target architecture into the
177    * current proper dev dir location.
178    */
179
180   function copyNodeLib () {
181     if (!win || !copyDevLib) return doBuild()
182
183     var buildDir = path.resolve(nodeDir, buildType)
184       , archNodeLibPath = path.resolve(nodeDir, arch, 'iojs.lib')
185       , buildNodeLibPath = path.resolve(buildDir, 'iojs.lib')
186
187     mkdirp(buildDir, function (err, isNew) {
188       if (err) return callback(err)
189       log.verbose('"' + buildType + '" dir needed to be created?', isNew)
190       var rs = fs.createReadStream(archNodeLibPath)
191         , ws = fs.createWriteStream(buildNodeLibPath)
192       log.verbose('copying "iojs.lib" for ' + arch, buildNodeLibPath)
193       rs.pipe(ws)
194       rs.on('error', callback)
195       ws.on('error', callback)
196       rs.on('end', doBuild)
197     })
198   }
199
200   /**
201    * Actually spawn the process and compile the module.
202    */
203
204   function doBuild () {
205
206     // Enable Verbose build
207     var verbose = log.levels[log.level] <= log.levels.verbose
208     if (!win && verbose) {
209       argv.push('V=1')
210     }
211     if (win && !verbose) {
212       argv.push('/clp:Verbosity=minimal')
213     }
214
215     if (win) {
216       // Turn off the Microsoft logo on Windows
217       argv.push('/nologo')
218     }
219
220     // Specify the build type, Release by default
221     if (win) {
222       var p = arch === 'x64' ? 'x64' : 'Win32'
223       argv.push('/p:Configuration=' + buildType + ';Platform=' + p)
224       if (jobs) {
225         var j = parseInt(jobs, 10)
226         if (!isNaN(j) && j > 0) {
227           argv.push('/m:' + j)
228         } else if (jobs.toUpperCase() === 'MAX') {
229           argv.push('/m:' + require('os').cpus().length)
230         }
231       }
232     } else {
233       argv.push('BUILDTYPE=' + buildType)
234       // Invoke the Makefile in the 'build' dir.
235       argv.push('-C')
236       argv.push('build')
237       if (jobs) {
238         var j = parseInt(jobs, 10)
239         if (!isNaN(j) && j > 0) {
240           argv.push('--jobs')
241           argv.push(j)
242         } else if (jobs.toUpperCase() === 'MAX') {
243           argv.push('--jobs')
244           argv.push(require('os').cpus().length)
245         }
246       }
247     }
248
249     if (win) {
250       // did the user specify their own .sln file?
251       var hasSln = argv.some(function (arg) {
252         return path.extname(arg) == '.sln'
253       })
254       if (!hasSln) {
255         argv.unshift(gyp.opts.solution || guessedSolution)
256       }
257     }
258
259     var proc = gyp.spawn(command, argv)
260     proc.on('exit', onExit)
261   }
262
263   /**
264    * Invoked after the make/msbuild command exits.
265    */
266
267   function onExit (code, signal) {
268     if (code !== 0) {
269       return callback(new Error('`' + command + '` failed with exit code: ' + code))
270     }
271     if (signal) {
272       return callback(new Error('`' + command + '` got signal: ' + signal))
273     }
274     callback()
275   }
276
277 }