-
Notifications
You must be signed in to change notification settings - Fork 213
/
npm.js
395 lines (353 loc) · 9.5 KB
/
npm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
'use strict';
var P = require('bluebird');
var fs = require('fs');
var mkdirp = require('mkdirp');
var ncp = require('ncp');
var path = require('path');
var rimraf = require('rimraf');
var semver = require('semver');
var tar = require('tar')
var zlib = require('zlib')
var buildHelper = require('./build');
var octokit = require('./octokit');
var vermanager = require('./versions')
//make some promising APIs
P.promisifyAll(fs);
ncp = P.promisify(ncp);
rimraf = P.promisify(rimraf);
var debug = require('debug')('nodist:npm')
/**
* npmist /nopmist/
* This poorly named module manages npm versions
*/
function npmist(nodist, envVersion) {
this.nodist = nodist
this.envVersion = envVersion
//define where we store our npms
this.repoPath = path.resolve(path.join(this.nodist.nodistDir,'npmv'));
}
module.exports = npmist
var NPMIST = npmist.prototype
const versionRegex = /^v\d+\.\d+\.\d+$/;
/**
* List available NPM versions
* @return {string}
*/
NPMIST.listAvailable = function(){
return Promise.all([
octokit.paginate(octokit.rest.repos.listReleases, {
owner: 'npm',
repo: 'npm',
per_page: 100
}, function(response) {
return response.data.map(function(release) { return release.tag_name; });
}),
octokit.paginate(octokit.rest.repos.listReleases, {
owner: 'npm',
repo: 'cli',
per_page: 100
}, function(response) {
return response.data.map(function(release) { return release.tag_name; });
})
])
.then(([npm, cli]) => {
// The npm project has two kinds of releases: releases of npm,
// and releases of other utility libraries.
// Ignore the releases of libraries. They are named "library-version",
// while core npm releases are named just "version".
cli = cli.filter(release => versionRegex.test(release));
return npm.concat(cli);
});
};
/**
* List all npm versions installed in this.repoPath
* @param {function} cb A callback with (error, arrayOfVersions)
* @return {*} nothing
*/
NPMIST.listInstalled = function listInstalled(cb) {
//return from cache if we can
if(this.installedCache){
return process.nextTick(() => {
cb(null, this.installedCache);
});
}
fs.readdir(this.repoPath, (err, ls) => {
if(err){
return cb({
message: 'Reading the version directory ' +
this.repoPath + ' failed: ' + err.message
});
}
ls = ls.filter(semver.valid)
ls.sort(function(v1, v2){
if(vermanager.compareable(v1) > vermanager.compareable(v2)){
return 1;
}
else{
return -1;
}
});
//set cache for later
this.installedCache = ls;
return cb(null, ls);
});
};
function getNpmReleases(page) {
return octokit.rest.repos.listReleases({
owner: 'npm',
repo: 'cli',
per_page: 50,
page,
}).then((response) => response.data.map(release => release.tag_name)
.filter((version) => versionRegex.test(version))
.sort(semver.compare)
);
}
/**
* Get latest NPM version
* @return {string}
*/
NPMIST.latestVersion = async function(){
// use list instead of getLatestRelease because there are non npm releases in the cli repo
let releases = [];
let page = 1;
while (releases.length === 0) {
releases = await getNpmReleases(page);
page += 1;
}
return releases.pop();
};
/**
* Get latest NPM version
* @return {string}
*/
NPMIST.matchingVersion = function(){
return new Promise((done, reject) => {
this.nodist.getCurrentVersion((er, nodeVersion) => {
if (er) return reject(er)
this.nodist.getMatchingNpmVersion(nodeVersion, (er, npmVersion) => {
if (er) return reject(er)
done(npmVersion)
})
})
})
};
/**
* Get a download URL for the version
* @param {string} version
* @return {string}
*/
NPMIST.downloadUrl = function(version){
return 'https://codeload.github.com/npm/cli/tar.gz/vVERSION'
.replace('VERSION',version.replace('v',''));
};
NPMIST.resolveVersionLocally = function(spec, done) {
if (!spec) return done()
this.listInstalled((er, installed) => {
if (spec === 'latest') return done(null, installed[installed.length - 1])
if (spec === 'match') {
this.nodist.getCurrentVersion((er, nodeVersion) => {
if (er) return done(er)
this.nodist.getMatchingNpmVersion(nodeVersion, (er, npmVersion) => {
if (er) return done(er)
resolveVersion(npmVersion, installed)
})
})
return
}
resolveVersion(spec, installed)
})
function resolveVersion(spec, installed) {
//try to get a version if its explicit
var version = semver.clean(spec);
//support version ranges
if(semver.validRange(spec)){
version = semver.maxSatisfying(installed,spec);
}
done(null,version);
}
}
/**
* Resolve a version from a string
* @param {string} v
* @param {function} done
*/
NPMIST.resolveVersion = function(v,done){
if ('latest' === v || !v) {
this.latestVersion()
.then((latest) => {
done(null, latest)
})
return
}
if ('match' === v) {
this.matchingVersion()
.then((version) => {
done(null, version)
})
return
}
this.listAvailable()
.then(function(available){
//try to get a version if its explicit
var version = semver.clean(v);
//support version ranges
if(semver.validRange(v)){
version = semver.maxSatisfying(available,v);
}
if (!version) {
done(new Error('Version spec, "' + v + '", didn\'t match any version'));
return;
}
done(null,version);
})
.catch(function(err){
done(err);
});
};
/**
* Remove a version of NPM
* @param {string} v
* @param {function} done
* @return {*}
*/
NPMIST.remove = function(v, done){
var version = semver.clean(v);
if(!semver.valid(version)) return done(new Error('Invalid version'));
var archivePath = path.resolve(path.join(this.repoPath,version));
//check if this version is already not installed, if so just bail
if(!fs.existsSync(archivePath)){
return done(null,version);
}
//nuke everything for this version
P.all([rimraf(archivePath)])
.then(function(){
done(null,version);
})
.catch(function(err){
done(err);
});
};
/**
* Install NPM version
* @param {string} v
* @param {function} done
* @return {*}
*/
NPMIST.install = function(v,done){
debug('install', v)
var version = semver.clean(v);
if(!semver.valid(version)) return done(new Error('Invalid version'));
var zipFile = path.resolve(path.join(this.repoPath,version + '.zip'));
var archivePath = path.resolve(path.join(this.repoPath,version));
//check if this version is already installed, if so just bail
if(fs.existsSync(archivePath)){
debug('install', 'this version is already installed')
return done(null, version)
}
//otherwise install the new version
Promise.resolve()
.then(() => mkdirp(archivePath))
.then(() => {
var downloadLink = NPMIST.downloadUrl(version);
debug('Downloading and extracting NPM from ' + downloadLink);
return new Promise((resolve, reject) => {
buildHelper.downloadFileStream(downloadLink)
.pipe(zlib.createUnzip())
.pipe(tar.x({
cwd: archivePath
, strip: 1
}))
.on('error', reject)
.on('end', resolve)
})
})
.then(() => {
if (semver.gte(version, '8.0.0')) {
debug('Fix symlinks for npm version >= 8');
return buildHelper.resolveLinkedWorkspaces(path.join(archivePath))
.then(fixedLinks => {
debug(`Fixed ${fixedLinks} symlinks for npm node_modules`);
});
}
})
.then(() => {
done(null, version)
})
.catch((err) => {
done(err);
});
};
/**
* Sets the global npm version
* @param {string} version
* @param {function} cb accepting (err)
*/
NPMIST.setGlobal = function setGlobal(versionSpec, cb){
var globalFile = this.nodist.nodistDir+'/.npm-version-global';
fs.writeFile(globalFile, versionSpec, function(er) {
if(er){
return cb(new Error(
'Could not set npm version ' + versionSpec + ' (' + er.message + ')'
));
}
cb();
});
};
/**
* Gets the global npm version
* @param {function} cb a callback accepting (err)
*/
NPMIST.getGlobal = function getGlobal(cb){
var globalFile = this.nodist.nodistDir+'/.npm-version-global';
fs.readFile(globalFile, function(er, version){
if(er) return cb(er);
cb(null, version.toString().trim(), cb);
});
};
/**
* Sets the local npm version
* @param {string} version
* @param {function} cb function accepting (err)
*/
NPMIST.setLocal = function setLocal(versionSpec, cb) {
fs.writeFile('./.npm-version', versionSpec, function(er){
if(er){
return cb(new Error(
'Could not set npm version ' + versionSpec + ' (' + er.message + ')'
));
}
cb(null, process.cwd() + '\\.npm-version');
});
};
/**
* Gets the local npm version
* @param {function} cb callback accepting (err, version)
*/
NPMIST.getLocal = function getLocal(cb){
var dir = process.cwd();
var dirArray = dir.split('\\');
//NOTE: this function is recursive and could loop!!
function search(){
if(dirArray.length === 0) return cb();
dir = dirArray.join('\\');
var file = dir + '\\.npm-version';
fs.readFile(file, function(er, version){
if(er){
dirArray.pop();
return search();
}
cb(null, version.toString().trim(), file);
});
}
search();
};
/**
* Gets the environmental npm version
* @param {function} cb a callback accepting (err, env)
* @return {*} nothing
*/
NPMIST.getEnv = function getEnv(cb) {
if(!this.envVersion) return cb();
cb(null, this.envVersion);
};