/
index.js
85 lines (79 loc) · 2.32 KB
/
index.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
const path = require('path')
const JSON_BUMP_FILES = require('../../defaults').bumpFiles
const updatersByType = {
json: require('./types/json'),
'plain-text': require('./types/plain-text')
}
const PLAIN_TEXT_BUMP_FILES = ['VERSION.txt', 'version.txt']
function getUpdaterByType (type) {
const updater = updatersByType[type]
if (!updater) {
throw Error(`Unable to locate updater for provided type (${type}).`)
}
return updater
}
function getUpdaterByFilename (filename) {
if (JSON_BUMP_FILES.includes(path.basename(filename))) {
return getUpdaterByType('json')
}
if (PLAIN_TEXT_BUMP_FILES.includes(filename)) {
return getUpdaterByType('plain-text')
}
throw Error(
`Unsupported file (${filename}) provided for bumping.\n Please specify the updater \`type\` or use a custom \`updater\`.`
)
}
function getCustomUpdaterFromPath (updater) {
if (typeof updater === 'string') {
return require(path.resolve(process.cwd(), updater))
}
if (
typeof updater.readVersion === 'function' &&
typeof updater.writeVersion === 'function'
) {
return updater
}
throw new Error('Updater must be a string path or an object with readVersion and writeVersion methods')
}
/**
* Simple check to determine if the object provided is a compatible updater.
*/
function isValidUpdater (obj) {
return (
typeof obj.readVersion === 'function' &&
typeof obj.writeVersion === 'function'
)
}
module.exports.resolveUpdaterObjectFromArgument = function (arg) {
/**
* If an Object was not provided, we assume it's the path/filename
* of the updater.
*/
let updater = arg
if (isValidUpdater(updater)) {
return updater
}
if (typeof updater !== 'object') {
updater = {
filename: arg
}
}
try {
if (typeof updater.updater === 'string') {
updater.updater = getCustomUpdaterFromPath(updater.updater)
} else if (updater.type) {
updater.updater = getUpdaterByType(updater.type)
} else {
updater.updater = getUpdaterByFilename(updater.filename)
}
} catch (err) {
if (err.code !== 'ENOENT') console.warn(`Unable to obtain updater for: ${JSON.stringify(arg)}\n - Error: ${err.message}\n - Skipping...`)
}
/**
* We weren't able to resolve an updater for the argument.
*/
if (!isValidUpdater(updater.updater)) {
return false
}
return updater
}