forked from gligoran/cordova-set-version
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (65 loc) · 2.2 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
86
import fs from 'node:fs';
import xml2js, { Builder } from 'xml2js';
const xmlBuilder = new Builder({
renderOpts: {
pretty: true,
indent: ' ',
},
});
function checkTypeErrors(configPath, version, buildNumber) {
if (typeof configPath !== 'string') {
throw new TypeError('"configPath" argument must be a string');
}
if (version && typeof version !== 'string') {
throw new TypeError('"version" argument must be a string');
}
if (buildNumber && typeof buildNumber !== 'number') {
throw new TypeError('"buildNumber" argument must be an integer');
}
}
async function getXml(configPath) {
const configFile = fs.readFileSync(configPath, 'utf8');
return xml2js.parseStringPromise(configFile);
}
function getVersionFromPackage() {
const packageFile = fs.readFileSync('./package.json');
const pkg = JSON.parse(packageFile);
const { version } = pkg;
return version;
}
function setAttributes(xml, version, buildNumber) {
const newXml = xml;
const element = newXml.plugin ? 'plugin' : 'widget';
if (version) {
newXml[element].$.version = version;
}
if (element === 'widget' && buildNumber) {
newXml.widget.$['android-versionCode'] = buildNumber;
newXml.widget.$['ios-CFBundleVersion'] = buildNumber;
newXml.widget.$['osx-CFBundleVersion'] = buildNumber;
}
return newXml;
}
function getCurrentUnixTimeInSeconds() {
return Math.floor(Date.now() / 1000);
}
/**
* set Version and/or Build Number of Cordova config.xml.
* @param {string} [configPath]
* @param {string} [version]
* @param {number} [buildNumber]
*/
async function cordovaSetVersion({ configPath, version, buildNumber } = {}) {
const cPath = configPath || './config.xml';
const bNumber =
buildNumber === 'date'
? getCurrentUnixTimeInSeconds()
: Number.parseInt(buildNumber, 10) || buildNumber;
checkTypeErrors(cPath, version, bNumber);
const currentConfig = await getXml(cPath);
const v = !version && !bNumber ? getVersionFromPackage(version) : version;
const newConfig = setAttributes(currentConfig, v, bNumber);
const newData = xmlBuilder.buildObject(newConfig);
return fs.writeFileSync(cPath, newData, { encoding: 'utf8' });
}
export default cordovaSetVersion;