-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathdependency-version-checker.js
83 lines (72 loc) · 2.33 KB
/
dependency-version-checker.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
'use strict';
const semver = require('semver');
const getProject = require('./get-project');
const resolvePackagePath = require('resolve-package-path');
/*
* Retrieve the version field from the package.json file contents.
* NOTE: the callers have already checked that the filePath is not null/undefined.
*/
function getVersionFromJSONFile(filePath) {
try {
// Use the require cache to avoid file I/O after first call on a given path.
let pkg = require(filePath);
return pkg.version || null;
} catch (err) {
// file doesn't exist or is not a file or is not parseable.
return null;
}
}
/**
* DependencyVersionChecker
*/
class DependencyVersionChecker {
constructor(parent, name) {
this._parent = parent;
this.name = name;
}
get version() {
if (this._jsonPath === undefined) {
// get the path to the package.json file. resolvePackagePath will
// return the path or null, never undefined, so we can use that
// to only resolvePackagePath once.
let addon = this._parent._addon;
let basedir = addon.root || getProject(addon).root;
this._jsonPath = resolvePackagePath(this.name, basedir);
}
if (this._version === undefined && this._jsonPath) {
this._version = getVersionFromJSONFile(this._jsonPath);
}
if (this._version === undefined && this._fallbackJsonPath) {
this._version = getVersionFromJSONFile(this._fallbackJsonPath);
}
return this._version;
}
exists() {
return this.version !== undefined;
}
isAbove(compareVersion) {
if (!this.version) {
return false;
}
return semver.gt(this.version, compareVersion);
}
assertAbove(compareVersion, _message) {
let message = _message;
if (!this.isAbove(compareVersion)) {
if (!message) {
const parentAddon = this._parent._addon;
message = `The addon \`${parentAddon.name}\` @ \`${parentAddon.root}\` requires the npm package \`${this.name}\` to be above ${compareVersion}, but you have ${this.version}.`;
}
throw new Error(message);
}
}
}
for (let method of ['gt', 'lt', 'gte', 'lte', 'eq', 'neq', 'satisfies']) {
DependencyVersionChecker.prototype[method] = function(range) {
if (!this.version) {
return method === 'neq';
}
return semver[method](this.version, range);
};
}
module.exports = DependencyVersionChecker;