-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (96 loc) · 2.63 KB
/
index.js
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
'use strict';
var through = require('through2')
, path = require('path')
, exec = require('child_process').exec
, findParent = require('find-parent-dir');
var activator;
function resolveCommand(file, cb) {
if (exports.cmd) return cb(null, { dir: exports.dir, cmd: exports.cmd });
findParent(file, 'package.json', function (err, dir) {
if (err) return cb(err);
if (!dir) return cb(null, null);
var packfile = path.join(dir, 'package.json');
var pack = require(packfile);
cb(null, {dir: dir, cmd: pack.commandify });
});
}
function executeCommand(cmd, dir, cb) {
exec(cmd, { cwd: dir }, function (err, stdout, stderr) {
if (stdout) console.error('commandify:', stdout);
if (stderr) console.error('commandify:', stderr);
cb(err);
});
}
exports = module.exports =
/**
* browserify transform which executes a shell command exactly once for every time the bundle is created.
*
* The command can be configured
*
* ##### inside package.json
*
* ```json
* {
* "browserify": {
* "transform": [ "commandify" ]
* },
* "commandify": "make all"
* }
* ```
*
* In this case the command is executed in the directory in which the `package.json` is defined.
*
* ##### via environment variables:
*
* ```sh
* COMMANDIFY_CMD='make all' COMMANDIFY_DIR='./compile' browserify main.js ....
* ```
*
* ##### directly on commandify when bundle step is JavaScript
*
* ```js
* commandify.cmd = 'make hello';
* commandify.dir = __dirname + '/compile';
* browserify()
* .require(require.resolve('./makeify/main.js'), { entry: true })
* .bundle()
* .pipe(....);
* ```
*
* @name commandify
* @function
* @param {string} file file whose content is to be transformed
* @return {TransformStream} through stream
*/
function (file) {
if (!activator) activator = file;
else if (activator !== file) return through();
var data = '';
return through(read, flush);
function read(d, _, cb) { data += d; cb(); }
function flush(cb) {
var self = this;
resolveCommand(file, function (err, res) {
if (err) return cb(err);
var dir = res.dir
, cmd = res.cmd;
executeCommand(cmd, dir, function (err) {
if (err) return cb(err);
self.push(data);
cb();
});
});
}
}
/**
* The command to be executed (only needed if not defined via `package.json` config).
*
* @name commandify::cmd
*/
exports.cmd = process.env.COMMANDIFY_CMD;
/**
* The directory in which the command is to be executed (only needed if not defined via `package.json` config).
*
* @name commandify::dir
*/
exports.dir = process.env.COMMANDIFY_DIR