Skip to content

Instantly share code, notes, and snippets.

@yawarsohail
Created July 18, 2017 08:45
Show Gist options
  • Save yawarsohail/b8d7762e4617a20b6f66fcffe6599920 to your computer and use it in GitHub Desktop.
Save yawarsohail/b8d7762e4617a20b6f66fcffe6599920 to your computer and use it in GitHub Desktop.
Cordova Hook to change version code before building.
#!/usr/bin/env node
// It changes version code before making build.
// You can see this link, on how I signed my apk using hooks. (https://gist.github.com/yawarsohail/1b2998d5cd860e01193cec86f6329223)
// Added below lines in script part of package.json to make build easy. (I think its prety easy, no need for description).
// "release": "TARGET=ii ionic build ios --device --release && TARGET=aa ionic build --release android",
// "release-a": "TARGET=a ionic build --release android",
// "release-i": "TARGET=i ionic build ios --device --release"
//
// Save hook under `project-root/scripts`
//
// Don't forget to install xml2js using npm if it is not already installed.
// `$ npm install xml2js`
//
// Then add below line in config.xml inside widget.
// <hook src="scripts/increment_build_number.js" type="before_build"/>
//
// Rest I'll be describing in code comments. I'll be changing my project name with imaginary name and might miss in some part.
//
// I am adding this for my self so that I can remember. And it may help others who wants to do same.
//
var fs = require('fs');
var xml2js = require('xml2js');
// Read config.xml
fs.readFile('config.xml', 'utf8', function(err, data) {
if(err) {
return console.log(err);
}
// Get XML
var xml = data;
// Parse XML to JS Obj
xml2js.parseString(xml, function (err, result) {
if(err) {
return console.log(err);
}
var target = "";
if (process.env.TARGET) {
// Log the value to the console
console.log('process.env.TARGET is set to: ' + process.env.TARGET);
target = process.env.TARGET;
// Get JS Obj
var obj = result;
// ios-CFBundleVersion doen't exist in config.xml
if(typeof obj['widget']['$']['version'] === 'undefined') {
obj['widget']['$']['version'] = "0.0.1";
}
// Increment build numbers (separately for iOS and Android)
var fullVer = obj['widget']['$']['version'];
var Arr = fullVer.split('.');
var i1 = Arr[0];
var i2 = Arr[1];
var i3 = Arr[2];
i3++;
// below conditions are to set limits that a version code part can go.
if (i3 == 21) {
i3 = '0';
i2++;
if(i2 == 10) {
i2='0';
i1++;
}
}
if(target == "aa") {
// don't inc as ios build have already incremented.
}
else {
obj['widget']['$']['version'] = i1+'.'+i2+'.'+i3;
}
var builder = new xml2js.Builder();
var xml = builder.buildObject(obj);
// Write config.xml
fs.writeFile('config.xml', xml, function(err) {
if(err) {
return console.log(err);
}
console.log('Build number successfully incremented');
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment