1 | 'use strict'
|
2 |
|
3 | var nodemon
|
4 | , colors = require('colors')
|
5 | , gulp = require('gulp')
|
6 | , cp = require('child_process')
|
7 | , bus = require('nodemon/lib/utils/bus')
|
8 | , path = require('path')
|
9 |
|
10 | module.exports = function (options) {
|
11 | options = options || {};
|
12 |
|
13 |
|
14 | if (options.nodemon && typeof options.nodemon === 'function') {
|
15 | nodemon = options.nodemon
|
16 | delete options.nodemon
|
17 | } else {
|
18 | nodemon = require('nodemon')
|
19 | }
|
20 |
|
21 |
|
22 | var script = nodemon(options)
|
23 | , originalOn = script.on
|
24 | , originalListeners = bus.listeners('restart')
|
25 |
|
26 |
|
27 | if (options.tasks) {
|
28 |
|
29 | bus.removeAllListeners('restart')
|
30 |
|
31 |
|
32 | bus.on('restart', function (files){
|
33 | if (!options.quiet) nodemonLog('running tasks...')
|
34 |
|
35 | if (typeof options.tasks === 'function') run(options.tasks(files))
|
36 | else run(options.tasks)
|
37 | })
|
38 |
|
39 |
|
40 | for (var i = 0; i < originalListeners.length; i++) {
|
41 | bus.on('restart', originalListeners[i])
|
42 | }
|
43 | }
|
44 |
|
45 |
|
46 | process.once('SIGINT', function () {
|
47 | script.emit('quit')
|
48 | script.quitEmitted = true
|
49 | })
|
50 | script.on('exit', function () {
|
51 |
|
52 | if (script.quitEmitted) {
|
53 |
|
54 | if (typeof options.done === "function") {
|
55 | options.done()
|
56 | }
|
57 |
|
58 | process.exit(0)
|
59 | }
|
60 | })
|
61 |
|
62 |
|
63 | script.on('log', function (log){
|
64 | nodemonLog(log.colour)
|
65 | })
|
66 |
|
67 |
|
68 | script.on = function (event, tasks){
|
69 | var tasks = Array.prototype.slice.call(arguments)
|
70 | , event = tasks.shift()
|
71 |
|
72 | if (event === 'change') {
|
73 | script.changeTasks = tasks
|
74 | } else {
|
75 | for (var i = 0; i < tasks.length; i++) {
|
76 | void function (tasks){
|
77 | if (tasks instanceof Function) {
|
78 | originalOn(event, tasks)
|
79 | } else {
|
80 | originalOn(event, function (){
|
81 | if (Array.isArray(tasks)) {
|
82 | tasks.forEach(function (task){
|
83 | run(task)
|
84 | })
|
85 | } else run(tasks)
|
86 | })
|
87 | }
|
88 | }(tasks[i])
|
89 | }
|
90 | }
|
91 |
|
92 | return script
|
93 | }
|
94 |
|
95 | return script
|
96 |
|
97 |
|
98 | function run(tasks) {
|
99 | if (typeof tasks === 'string') tasks = [tasks]
|
100 | if (tasks.length === 0) return
|
101 | if (!(tasks instanceof Array)) throw new Error('Expected task name or array but found: ' + tasks)
|
102 | var gulpPath = path.join(process.cwd(), 'node_modules/.bin/')
|
103 | var gulpCmd = path.join(gulpPath, process.platform === 'win32' ? 'gulp.cmd' : 'gulp')
|
104 | var options = { stdio: [0, 1, 2] }
|
105 | if (process.platform === 'win32') options.shell = true
|
106 | cp.spawnSync(gulpCmd, tasks, options)
|
107 | }
|
108 | }
|
109 |
|
110 | function nodemonLog(message){
|
111 | console.log('[' + new Date().toString().split(' ')[4].gray + '] ' + message)
|
112 | }
|