1 | 'use strict';
|
2 |
|
3 | var Runner = require('./runner')
|
4 | , glob = require('glob')
|
5 | , path = require('path');
|
6 |
|
7 | function FileRunner(paths) {
|
8 | Runner.call(this);
|
9 |
|
10 | this._fileQueue = [];
|
11 | this.paths = Array.isArray(paths) ? paths : [paths];
|
12 | }
|
13 |
|
14 | FileRunner.prototype = Object.create(Runner.prototype);
|
15 | FileRunner.prototype.constructor = FileRunner;
|
16 |
|
17 | FileRunner.prototype.run = function () {
|
18 | if (Runner.current) throw new Error('Another runner is already running.');
|
19 |
|
20 | var self = Runner.current = this;
|
21 |
|
22 | var done = 0;
|
23 | this.paths.forEach(function (globPath) {
|
24 | glob(globPath, runFileCallback(self))
|
25 | .on('end', function () {
|
26 | if (++done === self.paths.length) {
|
27 | self._globDone = true;
|
28 | }
|
29 | });
|
30 | });
|
31 | };
|
32 |
|
33 | FileRunner.prototype._done = function () {
|
34 | if (this._globDone && this._fileQueue.length === 0)
|
35 | Runner.prototype._done.call(this);
|
36 | else if (this._fileQueue.length > 0) {
|
37 | this._queue = this._fileQueue.shift();
|
38 | this.emit('file', this._queue.path);
|
39 | Runner.prototype.run.call(this);
|
40 | }
|
41 | };
|
42 |
|
43 | FileRunner.prototype.enqueue = function () {
|
44 | console.error('enqueue improperly called');
|
45 | };
|
46 |
|
47 | function runFileCallback(runner) {
|
48 | return function (err, filePaths) {
|
49 | if (err) console.error(err);
|
50 | else if (filePaths.length === 0) runner.emit('done');
|
51 | else filePaths
|
52 | .map(path.resolve)
|
53 | .forEach(function (filePath) {
|
54 | var fileQueue = [];
|
55 | fileQueue.path = filePath;
|
56 | runner._fileQueue.push(fileQueue);
|
57 | runner.enqueue = fileQueue.push.bind(fileQueue);
|
58 |
|
59 | try {
|
60 | require(filePath);
|
61 | Runner.prototype.run.call(runner);
|
62 | } catch (err) {
|
63 | runner.emit('error', err);
|
64 | } finally {
|
65 | delete runner.enqueue;
|
66 | }
|
67 | });
|
68 | };
|
69 | }
|
70 |
|
71 | module.exports = FileRunner; |
\ | No newline at end of file |