-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
301 lines (263 loc) · 7.62 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env node
const repl = require("repl");
const fs = require("fs");
const child_process = require("child_process");
const path = require("path");
const readline = require("readline");
const vm = require("vm");
const requireLike = require("require-like");
const { Stream, PassThrough, Readable, Writable } = require("stream");
const HISTORY_PATH = ".noshhistory";
const paths = process.env.PATH.split(":");
const NOSH = Symbol("NOSH");
global.cd = async (path = "~") => {
process.chdir(path.replace(/^~/, process.env["HOME"]));
};
global.cd[NOSH] = true;
class Process {
constructor(executablePath, args) {
// we need these streams because the actual process may not start until all the arguments are resolved
const stdin = AsymmetricalStreamPair({ allowHalfOpen: false });
const stdout = AsymmetricalStreamPair({ allowHalfOpen: false });
const stderr = AsymmetricalStreamPair({ allowHalfOpen: false });
this.stdin = stdin.writable;
this.stdout = stdout.readable;
this.stderr = stderr.readable;
let piped = false;
this.stdin.on("pipe", () => (piped = true));
this.promise = new Promise(async (resolve, reject) => {
const streams = [stdin.readable, stdout.writable, stderr.writable];
// resolve the arguments if needed
const finalArgs = await Promise.all(
args.map(arg => {
if (arg instanceof Process) {
return arg.string();
} else if (arg instanceof Stream) {
streams.push(arg);
return `/dev/fd/${streams.length - 1}`;
} else {
return arg;
}
})
);
// start the process
const proc = child_process.spawn(executablePath, finalArgs, {
stdio: streams.map(s => "pipe")
});
// pipe to/from the streams
for (const [fd, stream] of streams.entries()) {
// TODO: better way of detecting readable/writable
if (stream instanceof Readable) {
stream.pipe(proc.stdio[fd]);
}
if (stream instanceof Writable) {
proc.stdio[fd].pipe(stream);
}
}
// wait for the process to exit and resolve or reject
proc.on("close", code => {
if (code === 0) {
resolve();
} else {
reject(code);
}
});
// automatically pipe stdin/stdout/stderr if they haven't already
process.nextTick(() => {
if (!piped && !process.stdin.isTTY) {
process.stdin.pipe(this.stdin);
proc.on("close", () => {
// FIXME: sometimes doesn't exit process until next newline
process.stdin.unpipe(this.stdin);
});
}
if (this.stdout._readableState.paused) {
this.stdout.pipe(process.stdout);
proc.on("close", () => {
this.stdout.unpipe(process.stdout);
});
}
if (this.stderr._readableState.paused) {
this.stderr.pipe(process.stderr);
proc.on("close", () => {
this.stderr.unpipe(process.stderr);
});
}
});
});
// set up the bin proxy
return binProxy(this, this);
}
then(...args) {
return this.promise.then(...args);
}
catch(...args) {
return this.promise.catch(...args);
}
lines() {
return new Promise((resolve, reject) => {
const lines = [];
var lineReader = readline.createInterface({
input: this.stdout
});
lineReader.on("line", line => lines.push(line));
lineReader.on("close", () => resolve(lines));
});
}
string() {
return this.lines().then(lines => lines.join("\n"));
}
code() {
return this.promise.then(code => 0, code => code);
}
}
// TODO: backpressure?
function AsymmetricalStreamPair(options = {}) {
let readableCallback;
const readable = new Readable(options);
readable._read = function _read() {
if (!readableCallback) {
return;
}
let callback = readableCallback;
readableCallback = null;
callback();
};
const writable = new Writable(options);
writable._write = function _write(chunk, enc, callback) {
if (readableCallback) {
throw new Error();
}
if (typeof callback === "function") {
readableCallback = callback;
}
readable.push(chunk);
};
writable._final = function _final(callback) {
readable.on("end", callback);
readable.push(null);
};
return { readable, writable };
}
function findExecutableOnPath(command) {
if (command.match(/^[.\/]/)) {
if (isExecutable(command)) {
return command;
}
} else {
for (const binPath of paths) {
const fullPath = path.resolve(binPath, command);
if (isExecutable(fullPath)) {
return fullPath;
}
}
}
}
function isExecutable(path) {
try {
fs.accessSync(path, fs.constants.X_OK);
return true;
} catch (e) {
return false;
}
}
function functionForExecutable(executablePath, prevProc) {
const command = function(...args) {
const proc = new Process(executablePath, args, prevProc);
if (prevProc) {
prevProc.stdout.pipe(proc.stdin);
}
return proc;
};
command[NOSH] = true;
return command;
}
// returns a Proxy for `object` that will return functions for executables on your PATH
function binProxy(object, prevProc) {
return new Proxy(object, {
has(target, prop, receiver) {
const x = prop in target || !!findExecutableOnPath(prop);
console.log(prop, x);
return x;
},
get(target, prop, receiver) {
if (prop in target || typeof prop !== "string") {
return target[prop];
} else {
const executablePath = findExecutableOnPath(prop);
if (executablePath) {
return functionForExecutable(executablePath, prevProc);
}
}
}
});
}
function runRepl() {
const r = repl.start({ propt: "> " });
if (r.historyPath && HISTORY_PATH) {
r.historyPath(HISTORY_PATH);
}
// replace `context` with version with the "bin proxy" version
r.context = vm.createContext(binProxy(global));
r.context.require = require;
r.context.module = module;
// wrap `eval` with our own logic
const _eval = r.eval;
r.eval = function(cmd, context, filename, callback) {
_eval(cmd, context, filename, async function(err, result) {
if (err) {
callback(err);
} else {
// auto-run Nosh commands with no arguments
if (typeof result === "function" && result[NOSH]) {
result = result();
}
if (result && typeof result.then === "function") {
try {
const finalResult = await result;
if (finalResult === undefined) {
callback();
} else {
callback(null, finalResult);
}
} catch (finalError) {
callback(finalError);
}
} else {
return callback(null, result);
}
}
});
};
}
function runScript(file) {
const context = vm.createContext(binProxy(global));
context.require = requireLike(file);
context.module = module;
const code = fs.readFileSync(file, "utf-8");
vm.runInContext(code, context);
}
exports.main = function(args) {
if (args.length > 2) {
runScript(args[2]);
} else if (!process.stdin.isTTY) {
runScript("/dev/stdin");
} else {
runRepl();
}
};
if (require.main === module) {
exports.main(process.argv);
}
// process.on("beforeExit", () =>
// console.log(process._getActiveHandles().map(streamName))
// );
// function streamName(s) {
// return s === process.stdin
// ? "stdin"
// : s === process.stdout
// ? "stdout"
// : s === process.stderr
// ? "stderr"
// : s.constructor && s.constructor.name;
// }