Merge remote-tracking branch 'ry/v0.8' into master
[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 ? '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". guessing location')
121     var notfoundErr = new Error('Can\'t find "msbuild.exe". Do you have Microsoft Visual Studio C++ 2008+ installed?')
122     exec('reg query HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions /s /f MSBuildToolsPath /e /t REG_SZ', function (err, stdout, stderr) {
123       var reVers = /Software\\Microsoft\\MSBuild\\ToolsVersions\\([^\r]+)\r\n\s+MSBuildToolsPath\s+REG_SZ\s+([^\r]+)/gi
124         , msbuilds = []
125         , r
126         , msbuildPath
127       if (err) {
128         return callback(notfoundErr)
129       }
130       while (r = reVers.exec(stdout)) {
131         if (parseFloat(r[1], 10) >= 3.5) {
132           msbuilds.push({
133             version: parseFloat(r[1], 10),
134             path: r[2]
135           })
136         }
137       }
138       msbuilds.sort(function (x, y) {
139         return (x.version < y.version ? -1 : 1)
140       })
141       ;(function verifyMsbuild () {
142         msbuildPath = path.resolve(msbuilds.pop().path, 'msbuild.exe')
143         fs.stat(msbuildPath, function (err, stat) {
144           if (err) {
145             if (err.code == 'ENOENT') {
146               if (msbuilds.length) {
147                 return verifyMsbuild()
148               } else {
149                 callback(notfoundErr)
150               }
151             } else {
152               callback(err)
153             }
154             return
155           }
156           command = msbuildPath
157           copyNodeLib()
158         })
159       })()
160     })
161   }
162
163   /**
164    * Copies the node.lib file for the current target architecture into the
165    * current proper dev dir location.
166    */
167
168   function copyNodeLib () {
169     if (!win || !copyDevLib) return doBuild()
170
171     var buildDir = path.resolve(nodeDir, buildType)
172       , archNodeLibPath = path.resolve(nodeDir, arch, 'node.lib')
173       , buildNodeLibPath = path.resolve(buildDir, 'node.lib')
174
175     mkdirp(buildDir, function (err, isNew) {
176       if (err) return callback(err)
177       log.verbose('"' + buildType + '" dir needed to be created?', isNew)
178       var rs = fs.createReadStream(archNodeLibPath)
179         , ws = fs.createWriteStream(buildNodeLibPath)
180       log.verbose('copying "node.lib" for ' + arch, buildNodeLibPath)
181       rs.pipe(ws)
182       rs.on('error', callback)
183       ws.on('error', callback)
184       rs.on('end', doBuild)
185     })
186   }
187
188   /**
189    * Actually spawn the process and compile the module.
190    */
191
192   function doBuild () {
193
194     // Enable Verbose build
195     var verbose = log.levels[log.level] <= log.levels.verbose
196     if (!win && verbose) {
197       argv.push('V=1')
198     }
199     if (win && !verbose) {
200       argv.push('/clp:Verbosity=minimal')
201     }
202
203     if (win) {
204       // Turn off the Microsoft logo on Windows
205       argv.push('/nologo')
206     }
207
208     // Specify the build type, Release by default
209     if (win) {
210       var p = arch === 'x64' ? 'x64' : 'Win32'
211       argv.push('/p:Configuration=' + buildType + ';Platform=' + p)
212       if (jobs) {
213         if (!isNaN(parseInt(jobs, 10))) {
214           argv.push('/m:' + parseInt(jobs, 10))
215         } else if (jobs.toUpperCase() === 'MAX') {
216           argv.push('/m:' + require('os').cpus().length)
217         }
218       }
219     } else {
220       argv.push('BUILDTYPE=' + buildType)
221       // Invoke the Makefile in the 'build' dir.
222       argv.push('-C')
223       argv.push('build')
224       if (jobs) {
225         if (!isNaN(parseInt(jobs, 10))) {
226           argv.push('--jobs')
227           argv.push(parseInt(jobs, 10))
228         } else if (jobs.toUpperCase() === 'MAX') {
229           argv.push('--jobs')
230           argv.push(require('os').cpus().length)
231         }
232       }
233     }
234
235     if (win) {
236       // did the user specify their own .sln file?
237       var hasSln = argv.some(function (arg) {
238         return path.extname(arg) == '.sln'
239       })
240       if (!hasSln) {
241         argv.unshift(gyp.opts.solution || guessedSolution)
242       }
243     }
244
245     var proc = gyp.spawn(command, argv)
246     proc.on('exit', onExit)
247   }
248
249   /**
250    * Invoked after the make/msbuild command exits.
251    */
252
253   function onExit (code, signal) {
254     if (code !== 0) {
255       return callback(new Error('`' + command + '` failed with exit code: ' + code))
256     }
257     if (signal) {
258       return callback(new Error('`' + command + '` got signal: ' + signal))
259     }
260     //symlinkNodeBinding()
261     callback()
262   }
263
264   function symlinkNodeBinding () {
265     var source, target
266     var buildDir = 'build/' + buildType + '/*.node'
267     log.verbose('globbing for files', buildDir)
268     glob(buildDir, function (err, nodeFiles) {
269       if (err) return callback(err)
270       log.silly('symlink', 'linking files', nodeFiles)
271       function link () {
272         var file = nodeFiles.shift()
273         if (!file) {
274           // no more files to link... done!
275           return callback()
276         }
277         if (win) {
278           // windows requires absolute paths for junctions
279           source = path.resolve('build', path.basename(file))
280           target = path.resolve(file)
281         } else {
282           // on unix, use only relative paths since they're nice
283           source = path.join('build', path.basename(file))
284           target = path.relative('build', file)
285         }
286         log.info('symlink', 'creating %s "%s" pointing to "%s"', win ? 'junction' : 'symlink', source, target)
287         fs.symlink(target, source, 'junction', function (err) {
288           if (err) {
289             if (err.code === 'EEXIST') {
290               log.verbose('destination already exists; deleting', dest)
291               rm(dest, function (err) {
292                 if (err) return callback(err)
293                 log.verbose('delete successful; trying symlink again')
294                 nodeFiles.unshift(file)
295                 link()
296               })
297             } else {
298               callback(err)
299             }
300             return
301           }
302           // process the next file, if any
303           link()
304         })
305       }
306       // start linking
307       link()
308     })
309   }
310
311 }