Skip to content

Instantly share code, notes, and snippets.

@faytekin
Forked from DavidFrahm/020_build_version.js
Last active November 16, 2017 15:05
Show Gist options
  • Save faytekin/03aad5a77f0e96233fc81fe17403c0ad to your computer and use it in GitHub Desktop.
Save faytekin/03aad5a77f0e96233fc81fe17403c0ad to your computer and use it in GitHub Desktop.
Cordova build hook, to use build version from config.xml in your hybrid app
#!/usr/bin/env node
// config.xml => <hook src="hooks/020_build_version.js" type="after_prepare" />
// This plugin replaces text in a file with the app version from config.xml.
module.exports = function(ctx) {
var wwwFileToReplace = "js/index.js";
//var fs = require('fs');
var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path'),
//xml2js = ctx.requireCordovaModule('xml2js'),
deferral = ctx.requireCordovaModule('q').defer();
var xml2js = require('xml2js')
var json = "";
var fileData = fs.readFileSync("config.xml", 'ascii');
var parser = new xml2js.Parser();
parser.parseString(fileData.substring(0, fileData.length), function (err, result) {
json = result;
});
var rawJSON = json;
//var rawJSON = loadConfigXMLDoc(configXMLPath);
var version = rawJSON.widget.$.version;
console.log("Version:", version);
var rootdir = ctx.opts.projectRoot;
var wwwPath = "";
if (ctx.opts.platforms[0].indexOf('android') > -1) {
wwwPath = "platforms/android/assets/www/";
console.log("Current build platforms: Android");
}
if (ctx.opts.platforms[0].indexOf('ios') > -1) {
wwwPath = "platforms/ios/www/";
console.log("Current build platforms: iOS");
}
var fullfilename = path.join(rootdir, wwwPath + wwwFileToReplace);
if (fs.existsSync(fullfilename)) {
var data = fs.readFileSync(fullfilename, 'utf8');
var result = data.replace(new RegExp("%%VERSION%%", "g"), version);
fs.writeFileSync(fullfilename, result, 'utf8');
console.log("Replaced version in file: " + fullfilename);
}
return true;
};
angular.module('equipmentShare').controller('AppController', function ($scope, BUILD) {
$scope.appVersion = BUILD.VERSION;
});
/*
* Cordova build hook will replace this version with the actual version from config.xml.
*/
angular.module('equipmentShare').constant('BUILD', {
VERSION: "%%VERSION%%"
});
<!-- This example is from an Ionic app. Modify as needed for your framework/templating solution. -->
... other content ...
<ion-item>
Version {{appVersion}}
</ion-item>
... other content ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment