UNPKG

1.88 kBJavaScriptView Raw
1var _ = require('lodash');
2var semver = require('semver');
3var config = require('./config');
4
5var ALLOWED_TAGS = ['latest', 'pre', 'beta', 'alpha'];
6
7// Returns true if a version is a tag
8function isTag(version) {
9 return _.includes(ALLOWED_TAGS, version);
10}
11
12// Return true if a version matches gitbook-cli's requirements
13function isValid(version) {
14 if (isTag(version)) return true;
15
16 var versionWithoutPre = version.replace(/\-(\S+)/g, '');
17
18 try {
19 return semver.satisfies(versionWithoutPre, config.GITBOOK_VERSION);
20 } catch(e) {
21 return false;
22 }
23}
24
25// Extract prerelease tag from a version
26function getTag(version) {
27 if (isTag(version)) return version;
28
29 var v = semver.parse(version);
30 return v.prerelease[0] || 'latest';
31}
32
33// Sort versions (tale prerelease tags in consideration)
34function sortTags(a, b) {
35 if (isTag(a) && isTag(b)) {
36 var indexA = ALLOWED_TAGS.indexOf(a);
37 var indexB = ALLOWED_TAGS.indexOf(b);
38
39 if (indexA > indexB) return -1;
40 if (indexB > indexA) return 1;
41
42 return 0;
43 }
44 if (isTag(a)) return -1;
45 if (isTag(b)) return 1;
46
47 if (semver.gt(a, b)) {
48 return -1;
49 }
50 if (semver.lt(a, b)) {
51 return 1;
52 }
53 return 0;
54}
55
56// Returns true if a version satisfies a condition
57function satisfies(version, condition, opts) {
58 opts = _.defaults(opts || {}, {
59 acceptTagCondition: true
60 });
61
62 if (isTag(version)) {
63 return (condition == '*' || version == condition);
64 }
65
66 // Condition is a tag ('beta', 'latest')
67 if (opts.acceptTagCondition) {
68 var tag = getTag(version);
69 if (tag == condition) return true;
70 }
71
72 return semver.satisfies(version, condition);
73}
74
75module.exports = {
76 isTag: isTag,
77 isValid: isValid,
78 sort: sortTags,
79 satisfies: satisfies,
80 getTag: getTag
81};