Roman Ganchenko

Thoughts about development

Cordova Hook to Install Plugins

| Comments

Are you cordova/phonegap developer?
Have you ever used hooks in your ./hooks/ folder?
If your answer is “NO”, I encourage you to take a look at: ./hooks/README.md in your cordova project (older version has it in different location)
I came across this post and really liked the idea of preinstalling cordova plugins before building the project.
I believe that you should always need to avoid commiting any code from ./platforms or ./plugins to source repository in any cordova projects.

Here is my improved version of the code from http://devgirl.org

Cordova Hooklink
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
#!/usr/bin/env node
var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');
var sys = require('sys');
var cordova  = require('cordova');

var pluginlist = [
  "de.appplant.cordova.plugin.email-composer",
  "org.apache.cordova.globalization",
  "org.apache.cordova.contacts"
].sort(sortArray);

var pluginPath = cordova.findProjectRoot() + "/plugins";
var installedPlugins = findPlugins(pluginPath).sort(sortArray);

if(arraysIdentical(installedPlugins, pluginlist)){
  return true;
} else {
    pluginlist.forEach(function  (plug) {
        exec("cordova plugin add " + plug, puts);
    });
}

function puts(error,stdout,stderr){
    sys.puts(stdout);
};

function arraysIdentical(a, b) {
    var i = a.length;
    if (i != b.length) return false;
    while (i--) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

function findPlugins(pluginPath) {
    var plugins = [],
        stats;

    if (fs.existsSync(pluginPath)) {
        plugins = fs.readdirSync(pluginPath).filter(function (fileName) {
            stats = fs.statSync(path.join(pluginPath, fileName));
            return fileName != '.svn' && fileName != 'CVS' && stats.isDirectory();
        });
    }

    return plugins;
};

function sortArray(a, b)
{

    var va = (a === null) ? "" : "" + a,
        vb = (b === null) ? "" : "" + b;

    return va > vb ? 1 : ( va === vb ? 0 : -1 );
};