UNPKG

2.33 kBJavaScriptView Raw
1"use strict";
2var _ = require('lodash'),
3 exec = require('child_process').exec,
4 gutil = require('gulp-util'),
5 PluginError = gutil.PluginError,
6 through = require('event-stream').through;
7
8var PLUGIN_NAME = 'gulp-nunit-runner';
9
10var assemblies = [],
11 switches = [],
12 options;
13
14var runner,
15 stream,
16 fail,
17 end;
18
19// Main entry point
20var runner = function gulpNunitRunner(opts) {
21 options = opts;
22
23 if (!opts || !opts.executable) {
24 throw new PluginError(PLUGIN_NAME, "Path to NUnit executable is required in options.executable.");
25 }
26 // trim any existing surrounding quotes and then wrap in ""
27 opts.executable = '"' + opts.executable.replace(/(^")|(^')|("$)|('$)/g, "") + '"';
28
29 if (opts.options) {
30 parseSwitches(opts.options);
31 }
32
33 // Creating and return a stream through which each file will pass
34 stream = through(transform, flush);
35 setupHandlers();
36 return stream;
37};
38
39var setupHandlers = function () {
40 fail = _.bind(function (msg) {
41 this.emit('error', new gutil.PluginError(PLUGIN_NAME, msg));
42 }, stream);
43
44 end = _.bind(function () {
45 this.emit('end');
46 }, stream);
47};
48
49runner.addAssembly = function (assembly) {
50 assemblies.push(assembly);
51}
52
53runner.getExecutionCommand = function () {
54 var execute = [];
55 execute.push(options.executable);
56 if (switches.length) {
57 execute.push(switches.join(' '));
58 }
59 execute.push('"' + assemblies.join('" "') + '"');
60 execute = execute.join(' ');
61 return execute;
62};
63
64function parseSwitches(options) {
65 _.forEach(options, function (val, key) {
66 if (typeof val === 'boolean') {
67 if (val) {
68 switches.push('/' + key);
69 }
70 return;
71 }
72 if (typeof val === 'string') {
73 switches.push('/' + key + ':"' + val + '"');
74 }
75 });
76}
77
78function transform(file, enc, callback) {
79 if (!file) {
80 return fail('File may not be null.');
81 }
82 runner.addAssembly(file.path);
83 this.push(file);
84}
85
86function flush() {
87
88 if (assemblies.length === 0) {
89 return fail('Some assemblies required.'); //<-- See what I did there ;)
90 }
91
92 var cp = exec(runner.getExecutionCommand(), function (err/*,stdout, stderr*/) {
93 if (err) {
94 gutil.log(gutil.colors.red('NUnit tests failed.'));
95 return fail('NUnit tests failed.');
96 }
97 gutil.log(gutil.colors.cyan('NUnit tests passed'));
98 return end();
99 });
100
101 cp.stdout.pipe(process.stdout);
102 cp.stderr.pipe(process.stderr);
103}
104
105module.exports = runner;