Skip to content

Instantly share code, notes, and snippets.

@MikelArnaiz
Last active June 26, 2017 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikelArnaiz/e3dc0f4b114c7aef84921153109f5811 to your computer and use it in GitHub Desktop.
Save MikelArnaiz/e3dc0f4b114c7aef84921153109f5811 to your computer and use it in GitHub Desktop.
Cordova hook for incrementing build numbers. Increases only the platform you build
#!/usr/bin/env node
// Fork of:
// https://gist.github.com/ohh2ahh/f35ff6e0d9f8b4268cdb
// Save hook under `project-root/hooks/before_build/`
//
// Don't forget to install xml2js using npm
// `$ npm install xml2js`
var fs = require('fs');
var xml2js = require('xml2js');
function getPlatform() {
if (process.argv[2]) {
// go through each of the platform directories that have been prepared
var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);
for(var x=0; x<platforms.length; x++) {
// open up the index.html file at the www root
try {
var platform = platforms[x].trim().toLowerCase();
return platform;
} catch(e) {
process.stdout.write(e);
}
}
}
}
function incrementAndroidBuildNumber(obj) {
// android-versionCode doen't exist in config.xml
if(typeof obj['widget']['$']['android-versionCode'] === 'undefined') {
obj['widget']['$']['android-versionCode'] = 0;
}
// Increment build number
obj['widget']['$']['android-versionCode']++;
return obj;
}
function incrementiOSBuildNumber(obj) {
// ios-CFBundleVersion doen't exist in config.xml
if(typeof obj['widget']['$']['ios-CFBundleVersion'] === 'undefined') {
obj['widget']['$']['ios-CFBundleVersion'] = 0;
}
// Increment build number
obj['widget']['$']['ios-CFBundleVersion']++;
return obj;
}
// 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);
}
// Get JS Obj
var obj = result;
var platform = getPlatform();
var buildNumber;
if (platform == 'android') {
obj = incrementAndroidBuildNumber(obj);
buildNumber = obj['widget']['$']['android-versionCode'];
} else if (platform == 'ios') {
obj = incrementiOSBuildNumber(obj);
buildNumber = obj['widget']['$']['ios-CFBundleVersion'];
}
// Build XML from JS Obj
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 for ' + platform + ' successfully incremented to build ' + buildNumber);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment