summaryrefslogtreecommitdiff
path: root/StoneIsland/plugins/cordova-plugin-app-name/src/rename-app.js
blob: 3eb4d211ebf702c2d7402262c7511006b921d9ae (plain)
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
#!/usr/bin/env node

var fs = require('fs');
var path = require("path");
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var builder = new xml2js.Builder({
    xmldec: {
        version: '1.0',
        encoding: 'UTF-8'
    }
});

module.exports = function (context) {

    if(context.opts.platforms.indexOf('android') === -1) return;

    console.log('Attempting to set app name');

    var projectRoot = context.opts.projectRoot;
    var configPath = path.join(projectRoot, 'platforms', 'android', 'res', 'xml', 'config.xml');
    var stringsPath = path.join(projectRoot, 'platforms', 'android', 'res', 'values', 'strings.xml');
    var stringsXml, name;

    // make sure the android config file exists
    try {
        fs.accessSync(configPath, fs.F_OK);
    } catch(e) {
        return;
    }

    name = getConfigParser(context, configPath).getPreference('AppName');

    if (name) {
        stringsXml = fs.readFileSync(stringsPath, 'UTF-8');
        parser.parseString(stringsXml, function (err, data) {

            data.resources.string.forEach(function (string) {

                if (string.$.name === 'app_name') {

                    console.log('Setting App Name: ', name);
                    string._ = name;
                }
            });

            fs.writeFileSync(stringsPath, builder.buildObject(data));

        });
    }
};

function getConfigParser(context, config) {
    var semver = context.requireCordovaModule('semver');

    if (semver.lt(context.opts.cordova.version, '5.4.0')) {
        ConfigParser = context.requireCordovaModule('cordova-lib/src/ConfigParser/ConfigParser');
    } else {
        ConfigParser = context.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser');
    }

    return new ConfigParser(config);
}