forked from pulsar-edit/pulsar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.js
196 lines (181 loc) · 6.26 KB
/
task.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const _ = require('underscore-plus');
const ChildProcess = require('child_process');
const {Emitter} = require('event-kit');
const Grim = require('grim');
// Extended: Run a node script in a separate process.
//
// Used by the fuzzy-finder and [find in project](https://github.com/pulsar-edit/pulsar/blob/master/src/scan-handler.js).
//
// For a real-world example, see the [scan-handler](https://github.com/pulsar-edit/pulsar/blob/master/src/scan-handler.js)
// and the [instantiation of the task](https://github.com/pulsar-edit/pulsar/blob/master/src/project.js).
//
// ## Examples
//
// In your package code:
//
// ```javascript
// const {Task} = require('atom');
//
// let task = Task.once('/path/to/task-file.js', parameter1, parameter2, function() {
// console.log('task has finished');
// });
//
// task.on('some-event-from-the-task', (data) => {
// console.log(data.someString); // prints 'yep this is it'
// });
// ```
//
// In `'/path/to/task-file.js'`:
//
// ```javascript
// module.exports = function(parameter1, parameter2) {
// // Indicates that this task will be async.
// // Call the `callback` to finish the task
// const callback = this.async();
// emit('some-event-from-the-task', {
// someString: 'yep this is it'
// });
// return callback();
// };
// ```
module.exports = class Task {
// Public: A helper method to easily launch and run a task once.
//
// * `taskPath` The {String} path to the CoffeeScript/JavaScript file which
// exports a single {Function} to execute.
// * `args` The arguments to pass to the exported function.
// Returns the created {Task}.
static once(taskPath, ...args) {
const task = new Task(taskPath);
task.once('task:completed', () => task.terminate());
task.start(...args);
return task;
}
// Called upon task completion.
//
// It receives the same arguments that were passed to the task.
//
// If subclassed, this is intended to be overridden. However if {::start}
// receives a completion callback, this is overridden.
callback = null;
// Public: Creates a task. You should probably use {.once}
//
// * `taskPath` The {String} path to the CoffeeScript/JavaScript file that
// exports a single {Function} to execute.
constructor(taskPath) {
this.emitter = new Emitter();
const compileCachePath = require('./compile-cache').getCacheDirectory();
taskPath = require.resolve(taskPath);
const env = Object.assign({}, process.env, {userAgent: navigator.userAgent});
this.childProcess = ChildProcess.fork(require.resolve('./task-bootstrap'), [compileCachePath, taskPath], { env, silent: true});
this.on("task:log", () => console.log(...arguments));
this.on("task:warn", () => console.warn(...arguments));
this.on("task:error", () => console.error(...arguments));
this.on("task:deprecations", (deprecations) => {
for (let i = 0; i < deprecations.length; i++) {
Grim.addSerializedDeprecation(deprecations[i]);
}
});
this.on("task:completed", (...args) => {
if (typeof this.callback === "function") {
this.callback(...args)
}
});
this.handleEvents();
}
// Routes messages from the child to the appropriate event.
handleEvents() {
this.childProcess.removeAllListeners();
this.childProcess.on('message', ({event, args}) => {
if (this.childProcess != null) {
this.emitter.emit(event, args);
}
});
// Catch the errors that happened before task-bootstrap.
if (this.childProcess.stdout != null) {
this.childProcess.stdout.removeAllListeners();
this.childProcess.stdout.on('data', (data) => console.log(data.toString()));
}
if (this.childProcess.stderr != null) {
this.childProcess.stderr.removeAllListeners();
this.childProcess.stderr.on('data', (data) => nsole.error(data.toString()));
}
}
// Public: Starts the task.
//
// Throws an error if this task has already been terminated or if sending a
// message to the child process fails.
//
// * `args` The arguments to pass to the function exported by this task's script.
// * `callback` (optional) A {Function} to call when the task completes.
start(...args) {
const [callback] = args.splice(-1);
if (this.childProcess == null) {
throw new Error('Cannot start terminated process');
}
this.handleEvents();
if (_.isFunction(callback)) {
this.callback = callback;
} else {
args.push(callback);
}
this.send({event: 'start', args});
return undefined;
}
// Public: Send message to the task.
//
// Throws an error if this task has already been terminated or if sending a
// message to the child process fails.
//
// * `message` The message to send to the task.
send(message) {
if (this.childProcess != null) {
this.childProcess.send(message);
} else {
throw new Error('Cannot send message to terminated process');
}
return undefined;
}
// Public: Call a function when an event is emitted by the child process
//
// * `eventName` The {String} name of the event to handle.
// * `callback` The {Function} to call when the event is emitted.
//
// Returns a {Disposable} that can be used to stop listening for the event.
on(eventName, callback) {
return this.emitter.on(eventName, (args) => callback(...(args || [])));
}
once(eventName, callback) {
var disposable = this.on(eventName, function(...args) {
disposable.dispose();
callback(...args);
});
}
// Public: Forcefully stop the running task.
// No more events are emitted once this method is called.
terminate() {
if (this.childProcess == null) {
return false;
}
this.childProcess.removeAllListeners();
if (this.childProcess.stdout != null) {
this.childProcess.stdout.removeAllListeners();
}
if (this.childProcess.stderr != null) {
this.childProcess.stderr.removeAllListeners();
}
this.childProcess.kill();
this.childProcess = null;
return true;
}
// Public: Cancel the running task and emit an event if it was canceled.
//
// Returns a {Boolean} indicating whether the task was terminated.
cancel() {
const didForcefullyTerminate = this.terminate();
if (didForcefullyTerminate) {
this.emitter.emit('task:cancelled');
}
return didForcefullyTerminate;
}
};