function onUse(name){ var allRegistries = getAllRegistry(); if(allRegistries.hasOwnProperty(name)){ var registry = allRegistries[name]; npmconf.load(function(err, conf){ if(err){ exit(err); } conf.set('registry', registry.registry, 'user'); conf.save('user', function(err){ if(err){ exit(err); } printMsg([ '' , ' Registry has been set to: ' + registry.registry , '' ]); }); }); }else{ printMsg([ '' , ' Not find registry: ' + name , '' ]); } }
gulp.task('post-install-npm', function(cb) { // resume the default config when being installed Npmconf.load(function(_, conf) { conf.set('registry', Npmconf.defaults.registry, 'user'); conf.save('user', cb); }); });
Cli.prototype.run = function() { var _this = this, argv = null; this.generateArgs(); argv = this.yargs.argv; if (argv._.length === 0 || argv.help) { this.logger.log(this.yargs.help()); } else if (!this.commands[argv._[0]]){ this.logger.error('command ' + argv._[0] + ' not found') this.logger.log(this.yargs.help()); } else { // make the aliases actually work. argv = this.yargs.normalize().argv; npmconf.load(function (er, conf) { // update config singleton. _this.updateConfigWithNpmconf(conf); _this.updateConfigWithArgs(argv); config.updateWithOSDefaults(); try { // execute the command, passing along args. _this[argv._[0]].apply(_this, argv._.slice(1)); } catch (e) { _this.logger.error(e.message); } }); } };
.fail(function (err) { // Trying to use a local file failed, so initiate download and install // steps instead. var npmconfDeferred = kew.defer() npmconf.load(npmconfDeferred.makeNodeResolver()) return npmconfDeferred.promise })
/*//////////////// helper methods /////////////////*/ /* * get current registry */ function getCurrentRegistry (cbk) { npmconf.load(function(err, conf){ if(err){ exit(err); } cbk(conf.get('registry')); }); }
function downloadAndInstallGalen() { // Trying to use a local file failed, so initiate download and install // steps instead. const npmconfDeferred = kew.defer(); npmconf.load(npmconfDeferred.makeNodeResolver()); return npmconfDeferred.promise.then((conf) => { tmpPath = findSuitableTempDirectory(conf); const fileName = downloadUrl.split('/').pop(); const downloadedFile = path.join(tmpPath, fileName); log.info('Running at platform: ' + process.platform); // Start the install. if (!fs.existsSync(downloadedFile)) { log.info('Downloading', downloadUrl); log.info('Saving to', downloadedFile); return requestBinary(getRequestOptions(conf), downloadedFile); } else { log.info('Download already available at', downloadedFile); return { requestOptions: getRequestOptions(conf), downloadedFile: downloadedFile }; } }) .then((response) => extractDownload(response.downloadedFile, response.requestOptions, false)) .then((extractedPath) => copyIntoPlace(extractedPath, pkgPath)) .then(() => { const location = libPath; writeLocationFile(location); log.info('Done. galen binary available at ', location); // Ensure executable is executable by all users fs.chmodSync(location, '755'); fs.chmodSync(location + '/galen/galen', '755'); fs.chmodSync(location + '/galen/galen.bat', '755'); replace({ files: location + '/galen/galen.bat', replace: 'com.galenframework.GalenMain %*', with: 'com.galenframework.GalenMain %* -Djna.nosys=true' }, (error, changedFiles) => { //Catch errors if (error) { log.error('Error occurred:', error); } //List changed files log.info('Modified files:', changedFiles.join(', ')); exit(0); }); }) .fail(function (err) { log.error('Galen installation failed', err, err.stack); exit(1); }); }
gulp.task('pre-install-npm', ['setup-mirror'], function(cb) { var mirror = JSON.parse(Fs.readFileSync('local-setting.json')).mirror; Npmconf.load(function(_, conf) { var registry = Npmconf.defaults.registry; if (mirror === 'china') { registry = 'http://registry.npm.taobao.org/'; } conf.set('registry', registry, 'user'); conf.save('user', cb); }); });
function downloadDriver(_downloadUrl, _fileName, _md5, _libPath, _driverTmpDirName) { var deferred = kew.defer(); npmconf.load(function (err, conf) { if (err) { console.log('Error loading npm config') console.error(err) process.exit(1) return } var tmpPath = findSuitableTempDirectory(conf, _driverTmpDirName) //console.log("tmp path", tmpPath); var downloadedFile = path.join(tmpPath, _fileName) // Start the install. var downloadPromise = requestBinary(_downloadUrl, downloadedFile) var extractPromise = downloadPromise.then(function () { return extractDownload(downloadedFile, tmpPath) .fail(function (err) { console.error('Error extracting ' + downloadedFile, err, err.stack); }); }); var copyPromise = extractPromise.then(function () { console.log('copying ' + tmpPath + ' to ' + _libPath); return copyIntoPlace(tmpPath, _libPath) }); kew.all(downloadPromise, extractPromise, copyPromise) .then(function () { console.log('Success! IEDriverServer binary available at', _libPath + "\\IEDriverServer.exe"); deferred.resolve(true); }) .fail(function (err) { console.error('iedriver installation failed', err, err.stack); process.exit(1); }) }); return deferred.promise; }
function relock () { var packages = {}; npmconf.load(function (err, conf) { if (err) { throw err; } regHost = parse(conf.get('registry')).host; readInstalled(cwd, void 0, function (er, data) { if (er) throw er; //console.log(data); if (data.dependencies) { Object.keys(data.dependencies).forEach(function (key) { walk(data.dependencies[key], packages); }); } fs.writeFile(path.join(cwd, 'lockdown.json'), JSON.stringify(sortObj(packages), null, ' ') + '\n'); }); }); }
return new Promise(function(resolve, reject) { npmconf.load({}, function(err, conf) { if (err) { reject(err); } conf.findPrefix(cwd, function(e, pathPrefix) { if (e) { reject(e); } let nodeModulesPath = pathPrefix; if (pathPrefix) { nodeModulesPath = path.join(pathPrefix, 'node_modules'); } resolve(nodeModulesPath); }); }); });
/** Get the node_modules directory that will be used when `npm install` is run * in the current working directory (process.cwd()). This is necessary as npm walks up the * directory tree until it finds a node_modules directory when npm installing. */ function getNodeModulesDirectoryInUse(callback) { var npmconf = require('npmconf'); npmconf.load({}, function(err, conf) { if (err) { process.nextTick(function() { callback(err) }); return; } conf.findPrefix(process.cwd(), function(err, pathPrefix) { var nodeModulesPath = pathPrefix; if (pathPrefix) { nodeModulesPath = path.join(pathPrefix, "node_modules"); } process.nextTick(function() { callback(err, nodeModulesPath); }); }); }); }
fs.exists(file, function (exists) { if (!exists) { grunt.warn('Can\'t load ' + file); process.exit(0); } pkg = JSON.parse(fs.readFileSync(file)); npmconf.load(function (err, config) { config.log = { verbose: function () {}, info: function () {}, http: function () {}, silly: function () {}, error: function () {}, warn: function () {}, }; registry = new RegClient(config); checkPackage(pkg, undefined, function (result) { prettyOutput(result, done); }); }); });
function fileExists(exists) { if (!exists) { return cb(new Error('Can\'t load ' + pkgPath + '\nMake sure you have a package.json available'), null); } pkg = JSON.parse(fs.readFileSync(pkgPath)); npmconf.load(npmConfLoaded); function npmConfLoaded(err, config) { registry = new RegClient(config); checkPackage(pkg, undefined, returnResults); } function returnResults(err, results) { if (err) { return cb(err, null); } cb(null, results); } }
function getParams(done) { conf.load({}, function(err, config) { if (err) return done(err) var data = { tags: JSON.stringify(['ecosystem:stackgl'], null, 2) , user: { name: config.get('init.author.name') , site: config.get('init.author.url') , email: config.get('init.author.email') , github: config.get('init.author.github') , username: config.get('username') } } if (!data.user.username) return bail('npm login') if (!data.user.name) return bail('npm config set init.author.name "Your Name"') if (!data.user.github) return bail('npm config set init.author.github "your-github-handle"') if (!data.user.email) return bail('npm config set init.author.email "*****@*****.**"') data.user.site = data.user.site || 'http://github.com/' + data.user.github prompt([ { 'name': 'name' , 'message': 'Module name' , 'default': path.basename(target) }, { 'name': 'description' , 'message': 'Module description' }, { 'name': 'stability' , 'type': 'list' , 'message': 'Module stability:' , 'default': 'experimental' , 'choices': [ 'deprecated' , 'experimental' , 'unstable' , 'stable' , 'frozen' , 'locked' ] }, { 'name': 'shared' , 'message': 'Hosted in the stackgl GitHub organisation?' , 'default': false , 'type': 'confirm' } ], function(results) { if (err) return done(err) if (results.shared) data.user.github = 'stackgl' results.name = dequote(results.name) results.description = dequote(results.description) done(null, xtend(results, data)) }) }) }
npmconf.load(function(err, conf) { if (err) { console.log('Error loading npm config'); console.error(err); process.exit(1); return; } var tmpPath = path.join(conf.get('tmp'), 'iedriver'); var downloadedFile = path.join(tmpPath, fileName); var promise= kew.resolve(true); // Start the install. if (!fs.existsSync(downloadedFile)) { promise = promise.then(function () { rimraf(tmpPath); mkdir(downloadedFile); console.log('Downlaoading', downloadUrl); console.log('Saving to', downloadedFile); return requestBinary(getRequestOptions(conf.get('proxy')), downloadedFile); }); } else { console.log('Download already available at', downloadedFile); } promise.then(function () { return extractDownload(downloadedFile, tmpPath); }) .then(function () { return copyIntoPlace(tmpPath, libPath); }) .then(function () { return fixFilePermissions(tmpPath, libPath); }) .then(function () { console.log('Done. IEDriver binary available at', helper.path); }) .fail(function (err) { console.error('IEDriver installation failed', err.stack); process.exit(1); }); });
module.exports.start = function start(options, done) { var client; var syncURL = options.registry + config.registry.dumpURL; var cachePath = path.resolve(__dirname + '/../' + config.directory.cache); function packageInfo(name, next) { client.get(options.registry + name, config.registry, next); } function sync(next) { client.get(syncURL, config.registry, function(err, data) { if (err) { return next(err); } // remove _id and _tag // from the response data delete data._id; delete data._etag; var packages = _.values(data); packages = utils.packageCleaner(packages); store.update(packages, function update(err) { if (err) { return next(err); } }); store.count(function(err, count) { if (err) { return next(err); } }); if (typeof next === 'function') { next(null, packages); } }); } function finish(err, packages) { if (err) { return done(err); } function syncWrap() { sync(function onSync(err) { // log the error informing // that syncs are failing. if (err) { log.info(err); } }); } // start to regularly sync the packages setInterval(syncWrap, config.syncInterval); var publicAPI = { packageInfo: packageInfo }; done(null, publicAPI); } function onNpmConfLoad(err, conf) { if (err) { return finish(err); } conf.set('cache', cachePath); conf.set('always-auth', false); conf.set('strict-ssl', false); client = new Client(conf); sync(finish); } npmconf.load({}, onNpmConfLoad); };
function getParams(done) { conf.load({}, function(err, config) { if (err) return done(err) var data = { user: { name: config.get('init.author.name') , site: config.get('init.author.url')||'' , email: config.get('init.author.email') , github: config.get('init.author.github') , username: config.get('username') } } if (typeof argv.u === 'string') { data.org = { name: argv.u, github: argv.u } console.log(chalk.green('Creating module under organization '+chalk.bold(data.org.name))) } else if (argv.u) { return done('--user specified, but without an organization!') } // if (!data.user.username) return bail('npm login') if (!data.user.name) return bail('npm config set init.author.name "Your Name"') if (!data.user.email) return bail('npm config set init.author.email "*****@*****.**"') if (!data.user.github) return bail('npm config set init.author.github "your-github-handle"') //default org to user if (!data.org) { data.org = { name: data.user.name, github: data.user.github } } if (!data.user.url) { data.user.url = 'https://github.com/'+data.user.github } prompt([ { 'name': 'name' , 'message': 'Module name' , 'default': path.basename(target) }, { 'name': 'description' , 'message': 'Module description' }, { 'name': 'tags' , 'message': 'Module tags:' }, { 'name': 'stability' , 'type': 'list' , 'message': 'Module stability:' , 'default': 'experimental' , 'choices': [ 'deprecated' , 'experimental' , 'unstable' , 'stable' , 'frozen' , 'locked' ] } ], function(results) { if (err) return done(err) results.name = dequote(results.name) results.testDescription = escape(results.description).replace(/\\"+/g, '\"') results.description = dequote(results.description) results.varName = varName(results.name) results.tags = JSON.stringify(results.tags.split(' ').map(function(str) { return dequote(str).trim() }).filter(Boolean), null, 2) results.devDependencies = '{}' if (argv.t) { handleInstall(function(err, dep) { if (err) console.log(chalk.red('Error installing '+TEST_RUNNER+' '+err)) else { //prefix for --save-dev var prefix = config.get('save-prefix') if (prefix && semver.gte(dep[1], '0.1.0')) dep[1] = prefix+dep[1] console.log(chalk.green('Installed '+dep.join('@'))) var obj = {} obj[dep[0]] = dep[1] results.devDependencies = JSON.stringify(obj, null, 2) } done(null, xtend(results, data)) }) } else { done(null, xtend(results, data)) } }) }) }
}).then(function() { var uri = URL.parse(url); var d = Q.defer(); npmconf.load(function(err, conf) { // Check if NPM proxy settings are set. If so, include them in the request() call. var proxy; if (uri.protocol == 'https:') { proxy = conf.get('https-proxy'); } else if (uri.protocol == 'http:') { proxy = conf.get('proxy'); } var strictSSL = conf.get('strict-ssl'); // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv() // fails in this case with "EXDEV, cross-device link not permitted". var tmp_subidr = 'tmp_' + id + '_' + process.pid + '_' + (new Date()).valueOf(); tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr); shell.rm('-rf', tmp_dir); shell.mkdir('-p', tmp_dir); var size = 0; var request_options = {url:url}; if (proxy) { request_options.proxy = proxy; } if (typeof strictSSL == 'boolean') { request_options.strictSSL = strictSSL; } events.emit('verbose', 'Requesting ' + JSON.stringify(request_options) + '...'); events.emit('log', 'Downloading ' + id + ' library for ' + platform + '...'); var req = request.get(request_options, function(err, res, body) { if (err) { shell.rm('-rf', tmp_dir); d.reject(err); } else if (res.statusCode != 200) { shell.rm('-rf', tmp_dir); d.reject(new Error('HTTP error ' + res.statusCode + ' retrieving version ' + version + ' of ' + id + ' for ' + platform)); } else { size = body.length; } }); req.pipe(zlib.createUnzip()) .pipe(tar.Extract({path:tmp_dir})) .on('error', function(err) { shell.rm('-rf', tmp_dir); d.reject(err); }) .on('end', function() { events.emit('verbose', 'Downloaded, unzipped and extracted ' + size + ' byte response.'); events.emit('log', 'Download complete'); var entries = fs.readdirSync(tmp_dir); var entry = path.join(tmp_dir, entries[0]); shell.mkdir('-p', download_dir); shell.mv('-f', path.join(entry, '*'), download_dir); shell.rm('-rf', tmp_dir); d.resolve(hooker.fire('after_library_download', { platform:platform, url:url, id:id, version:version, path: lib_dir, size:size, symlink:false })); }); }); return d.promise.then(function () { return lib_dir; }); });
} ).fail( function(err){ var npmconfDeferred = kew.defer() npmconf.load( npmconfDeferred.makeNodeResolver() ) return npmconfDeferred.promise } ).then( function(conf){
npmconf.load({}, function (err, conf) { if (err) { log.error('init', 'Failed to load npm config.', err); process.exit(1); } var npm = { auth: { token: env.NPM_TOKEN }, loglevel: conf.get('loglevel'), registry: require('./lib/get-registry')(pkg, conf), tag: (pkg.publishConfig || {}).tag || conf.get('tag') || 'latest' }; // normalize trailing slash npm.registry = url.format(url.parse(npm.registry)); log.level = npm.loglevel; var config = { env: env, pkg: pkg, options: options, plugins: plugins, npm: npm }; var hide = {}; if (options.githubToken) hide.githubToken = '***'; log.verbose('init', 'options:', _.assign({}, options, hide)); log.verbose('init', 'Verifying config.'); var errors = require('./lib/verify')(config); errors.forEach(function (err) { return log.error('init', err.message + ' ' + err.code); }); if (errors.length) process.exit(1); if (options.argv.remain[0] === 'pre') { log.verbose('pre', 'Running pre-script.'); log.verbose('pre', 'Veriying conditions.'); plugins.verifyConditions(config, function (err) { if (err) { log[options.debug ? 'warn' : 'error']('pre', err.message); if (!options.debug) process.exit(1); } var nerfDart = require('nerf-dart')(npm.registry); var wroteNpmRc = false; if (env.NPM_TOKEN) { conf.set(nerfDart + ':_authToken', '${NPM_TOKEN}', 'project'); wroteNpmRc = true; } else if (env.NPM_OLD_TOKEN && env.NPM_EMAIL) { // Using the old auth token format is not considered part of the public API // This might go away anytime (i.e. once we have a better testing strategy) conf.set('_auth', '${NPM_OLD_TOKEN}', 'project'); conf.set('email', '${NPM_EMAIL}', 'project'); wroteNpmRc = true; } conf.save('project', function (err) { if (err) return log.error('pre', 'Failed to save npm config.', err); if (wroteNpmRc) log.verbose('pre', 'Wrote authToken to .npmrc.'); require('./pre')(config, function (err, release) { if (err) { log.error('pre', 'Failed to determine new version.'); var args = ['pre', (err.code ? err.code + ' ' : '') + err.message]; if (err.stack) args.push(err.stack); log.error.apply(log, args); process.exit(1); } var message = 'Determined version ' + release.version + ' as "' + npm.tag + '".'; log.verbose('pre', message); if (options.debug) { log.error('pre', message + ' Not publishing in debug mode.', release); process.exit(1); } try { var shrinkwrap = JSON.parse(readFileSync('./npm-shrinkwrap.json')); shrinkwrap.version = release.version; writeFileSync('./npm-shrinkwrap.json', JSON.stringify(shrinkwrap, null, 2)); log.verbose('pre', 'Wrote version ' + release.version + ' to npm-shrinkwrap.json.'); } catch (e) { log.silly('pre', 'Couldn\'t find npm-shrinkwrap.json.'); } writeFileSync('./package.json', JSON.stringify(_.assign(pkg, { version: release.version }), null, 2)); log.verbose('pre', 'Wrote version ' + release.version + ' to package.json.'); }); }); }); } else if (options.argv.remain[0] === 'post') { log.verbose('post', 'Running post-script.'); require('./post')(config, function (err, published, release) { if (err) { log.error('post', 'Failed to publish release notes.', err); process.exit(1); } log.verbose('post', (published ? 'Published' : 'Generated') + ' release notes.', release); }); } else { log.error('post', 'Command "' + options.argv.remain[0] + '" not recognized. User either "pre" or "post"'); } });
function fileExists(exists) { if (!exists) { return cb(new Error('Can\'t load ' + pkgPath + '\nMake sure you have a package.json available'), null); } try { pkg = JSON.parse(fs.readFileSync(pkgPath)); } catch (e) { return cb(e); } npmconf.load(npmConfLoaded); function npmConfLoaded(err, config) { if (err) { return cb(err); } registry = new RegClient(config); filterPackage(pkg, vulnerable, returnResults); } function getAncestry(module, list) { list = list || []; if (!module) { return list; } list.push(module); return getAncestry(module.parent, list); } function vulnerable(module, cb) { validateModule(module.name, module.version, function(err, result) { if (err) { return cb(err, null); } if (!Array.isArray(result)) { return cb(new TypeError('Unexpected API response format.'), null); } // no advisory found if (!result.length) { return cb(null, null); } var dependencyOf = getAncestry(module); dependencyOf = dependencyOf.map(function(d) { return d.name + '@' + d.version; }); var d = { module: module.name, version: module.version, advisory: result[0], dependencyOf: dependencyOf.reverse() }; cb(null, d); }); } function returnResults(err, results) { if (err) { return cb(err, null); } cb(null, results); } }
// Configure npm function configure(callback) { npmconf.load({log: npmLogger}, callback) }
npmconf.load(function(err, conf) { if (err) { console.log('Error loading npm config') console.error(err) process.exit(1) return } var tmpPath = findSuitableTempDirectory(conf) var downloadedFile = path.join(tmpPath, fileName) var promise = kew.resolve(true) // Start the install. promise = promise.then(function () { console.log('Downloading', downloadUrl) console.log('Saving to', downloadedFile) return requestBinary(downloadedFile) }) promise.then(function () { return extractDownload(downloadedFile, tmpPath) }) .then(function () { return copyIntoPlace(tmpPath, libPath) }) .then(function () { return fixFilePermissions() }) .then(function () { console.log('Done. ChromeDriver binary available at', helper.path) }) .fail(function (err) { console.error(err) console.error('ChromeDriver installation failed', err.stack) process.exit(1) }) })
npmconf.load(function(err, conf) { if (err) { console.log('Error loading npm config') console.error(err) process.exit(1) return } var tmpPath = findSuitableTempDirectory(conf), downloadedFile = path.join(tmpPath, fileName), promise = kew.resolve(true); // Start the install. promise = promise.then(function () { console.log('Downloading', downloadUrl); console.log('Saving to', downloadedFile); return requestBinary(getRequestOptions(conf.get('proxy')), downloadedFile); }) promise.then(function () { return copyIntoPlace(tmpPath, libPath); }) .then(function () { return fixFilePermissions(); }) .then(function () { console.log('Done. selenium standalone jar available at', helper.path); }) .fail(function (err) { console.error('selenium standalone jar installation failed', err.stack); process.exit(1); }) })
function publish(_confData, pkgInfo, tarballUrl, cb) { var tmp, npmLogLevels, npmLogger, log, confData; confData = _.clone(_confData); tmp = confData.tmp || os.tmpdir(); confData.cache = tmp; log = confData.log; delete confData.tmp; // wrapping the npm logger so that we can listen in on all the log data // in case we want to using the debug level npmLogger = {}; npmLogLevels = ['error', 'warn', 'info', 'verbose', 'silly', 'http', 'pause', 'resume']; npmLogLevels.forEach(function(level) { npmLogger[level] = function() { log.debug({ args : Array.prototype.slice.call(arguments), 'npm-log-level' : level }, 'npm-registry-client:publish') }; }); if (!confData._enableNpmVerbose) { npmLogger.verbose = noop; } confData.log = npmLogger; npmConf.load(confData, function(err, conf) { var req, client, auth; if (err) { return cb(err); } if (!conf.get('_auth')) { auth = conf.get('username') + ':' + conf.get('_password'); conf.set('_auth', new Buffer(auth, 'utf8').toString('base64')); } cb = once(cb); client = new RegClient(conf); req = request.get(tarballUrl); log.debug('requesting tarball ' + tarballUrl); req.on('error', cb); req.on('response', function(res) { log.debug('statusCode ' + tarballUrl + ' :: ' + res.statusCode); if (res.statusCode !== 200) { return cb(new Error('Bad status code ' + res.statusCode + ' : ' + tarballUrl)); } // pause the request until it's actually piped into something // when publishing with NPM req.pause(); var reqPipe = req.pipe; req.pipe = function() { var args = Array.prototype.slice.call(arguments); reqPipe.apply(req, args); process.nextTick(function() { // ok good to go since we actually have something to pipe into req.resume(); }); } // flag to know the package has been republicated (on the server side) pkgInfo['npmRepublicated'] = 1; log.debug('npm-registry-client :: publish ' + pkgInfo.name + '@' + pkgInfo.version); // TODO: in case there's an error you should make a request to delete // the attachment from NPM [or maybe the whole pkg version] ? client.publish(pkgInfo, req, cb); }); }); }
}).then(function() { var uri = URL.parse(url); var d = Q.defer(); npmconf.load(function(err, conf) { // Check if NPM proxy settings are set. If so, include them in the request() call. var proxy, is_https = false; if (uri.protocol == 'https:' || uri.protocol == 'git+https:') { proxy = conf.get('https-proxy'); is_https = true; } else if (uri.protocol == 'http:' || uri.protocol == 'git+http:') { proxy = conf.get('proxy'); } var strictSSL = conf.get('strict-ssl'); // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv() // fails in this case with "EXDEV, cross-device link not permitted". tmp_subidr = 'tmp_' + id + '_' + process.pid + '_' + (new Date).valueOf(); tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr); shell.rm('-rf', tmp_dir); shell.mkdir('-p', tmp_dir); var onSuccess = function(size) { events.emit('verbose', 'Downloaded, unzipped and extracted ' + size + ' byte response.'); events.emit('log', 'Download complete'); var entries = fs.readdirSync(tmp_dir); var entry = path.join(tmp_dir, entries[0]); shell.mkdir('-p', download_dir); shell.mv('-f', path.join(entry, (platform=='blackberry10'?'blackberry10':''), '*'), download_dir); shell.rm('-rf', tmp_dir); d.resolve(hooker.fire('after_library_download', { platform:platform, url:url, id:id, version:version, path: lib_dir, size:size, symlink:false })); } if (uri.protocol == 'git:' || uri.protocol.slice(0, 4) == 'git+') { events.emit('verbose', 'Cloning ' + url + ' version ' + version + ' (used as git tag)...'); events.emit('log', 'Downloading ' + id + ' library for ' + platform + ' from git repository...'); var repo_dir = path.join(tmp_dir, version), git_url = uri.protocol == 'git:' ? url : url.slice(4, url.length), cmd = 'git', // Create a shallow copy to save on disk space and download time. args = [ 'clone', '-b', version, '--depth', '0', '--recurse-submodules', git_url, repo_dir ], env = { stdio: 'inherit' }; if (proxy) { env[is_https ? 'https_proxy' : 'http_proxy'] = proxy; } if (typeof strictSSL == 'boolean' && !strictSSL) { env.GIT_SSL_NO_VERIFY = 'true'; } var execGit = superspawn.spawn(cmd, args, { env: env }) .then(onSuccess.bind(this, 0)) .fail(function() { shell.rm('-rf', tmp_dir); d.reject(new Error('Error cloning ' + url + ' version ' + version + ' (used as git tag) for ' + platform)); }); return; } var size = 0; var request_options = {uri:url}; if (proxy) { request_options.proxy = proxy; } if (typeof strictSSL == 'boolean') { request_options.strictSSL = strictSSL; } events.emit('verbose', 'Requesting ' + JSON.stringify(request_options) + '...'); events.emit('log', 'Downloading ' + id + ' library for ' + platform + '...'); var req = request.get(request_options, function(err, res, body) { if (err) { shell.rm('-rf', tmp_dir); d.reject(err); } else if (res.statusCode != 200) { shell.rm('-rf', tmp_dir); d.reject(new Error('HTTP error ' + res.statusCode + ' retrieving version ' + version + ' of ' + id + ' for ' + platform)); } else { size = body.length; } }); req.pipe(zlib.createUnzip()) .pipe(tar.Extract({path:tmp_dir})) .on('error', function(err) { shell.rm('-rf', tmp_dir); d.reject(err); }) .on('end', onSuccess.bind(this, size)); }); return d.promise.then(function () { return lib_dir; }); });
}).then(function() { var uri = URL.parse(url); var d = Q.defer(); npmconf.load(function(err, conf) { // Check if NPM proxy settings are set. If so, include them in the request() call. var proxy; if (uri.protocol == 'https:') { proxy = conf.get('https-proxy'); } else if (uri.protocol == 'http:') { proxy = conf.get('proxy'); } var strictSSL = conf.get('strict-ssl'); // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv() // fails in this case with "EXDEV, cross-device link not permitted". var tmp_subidr = 'tmp_' + id + '_' + process.pid + '_' + (new Date()).valueOf(); tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr); shell.rm('-rf', tmp_dir); shell.mkdir('-p', tmp_dir); var size = 0; var request_options = {url:url}; if (proxy) { request_options.proxy = proxy; } if (typeof strictSSL == 'boolean') { request_options.strictSSL = strictSSL; } events.emit('verbose', 'Requesting ' + JSON.stringify(request_options) + '...'); events.emit('log', 'Downloading ' + id + ' library for ' + platform + '...'); var req = request.get(request_options, function(err, res, body) { if (err) { shell.rm('-rf', tmp_dir); d.reject(err); } else if (res.statusCode != 200) { shell.rm('-rf', tmp_dir); d.reject(new Error('HTTP error ' + res.statusCode + ' retrieving version ' + version + ' of ' + id + ' for ' + platform)); } else { size = body.length; } }); req.pipe(zlib.createUnzip()) .on('error', function(err) { // Sometimes if the URL is bad (most likely unavailable version), and git-wip-us.apache.org is // particularly slow at responding, we hit an error because of bad data piped to zlib.createUnzip() // before we hit the request.get() callback above (with a 404 error). Handle that gracefully. It is // likely that we will end up calling d.reject() for an HTTP error in the request() callback above, but // in case not, reject with a useful error here. d.reject(new Error('Unable to fetch platform ' + platform + '@' + version + ': Error: version not found.')); }) .pipe(tar.Extract({path:tmp_dir})) .on('error', function(err) { shell.rm('-rf', tmp_dir); d.reject(err); }) .on('end', function() { events.emit('verbose', 'Downloaded, unzipped and extracted ' + size + ' byte response.'); events.emit('log', 'Download complete'); var entries = fs.readdirSync(tmp_dir); var entry = path.join(tmp_dir, entries[0]); shell.mkdir('-p', download_dir); shell.mv('-f', path.join(entry, '*'), download_dir); shell.rm('-rf', tmp_dir); d.resolve(HooksRunner.fire('after_library_download', { platform:platform, url:url, id:id, version:version, path: lib_dir, size:size, symlink:false })); }); }); return d.promise.then(function () { return lib_dir; }); });
.fail(function() { if (process.platform === 'linux' && process.arch === 'x64') { downloadUrl += 'linux-x86_64.tar.bz2' } else if (process.platform === 'linux') { downloadUrl += 'linux-i686.tar.bz2' } else if (process.platform === 'darwin') { downloadUrl += 'macosx.zip' } else if (process.platform === 'win32') { downloadUrl += 'windows.zip' } else { console.log('Unexpected platform or architecture:', process.platform, process.arch) process.exit(1) } var fileName = downloadUrl.split('/').pop() npmconf.load(function(err, conf) { if (err) { console.log('Error loading npm config') console.error(err) process.exit(1) return } var tmpPath = findSuitableTempDirectory(conf) var downloadedFile = path.join(tmpPath, fileName) var promise = kew.resolve(true) // Start the install. if (!fs.existsSync(downloadedFile)) { promise = promise.then(function () { console.log('Downloading', downloadUrl) console.log('Saving to', downloadedFile) return requestBinary(getRequestOptions(conf.get('proxy')), downloadedFile) }) } else { console.log('Download already available at', downloadedFile) } promise.then(function () { return extractDownload(downloadedFile, tmpPath) }) .then(function () { return copyIntoPlace(tmpPath, libPath) }) .then(function () { return fixFilePermissions() }) .then(function () { console.log('Done. Phantomjs binary available at', helper.path) }) .fail(function (err) { console.error('Phantom installation failed', err.stack) process.exit(1) }) }) })