the-shepherd
Version:
Control a herd of wild processes.
126 lines (112 loc) • 3.42 kB
JavaScript
// Generated by CoffeeScript 2.5.1
(function() {
var $, Fs, Writable, echo, expandPath, fileStream, getOutputFile, outputFile, outputStream, setOutput, toConfig, verbose;
({$, echo, verbose} = require('../common'));
Fs = require('fs');
({Writable} = require('stream'));
({outputFile, expandPath} = require('../files'));
fileStream = null;
outputStream = new Writable({
decodeStrings: false,
objectMode: false,
write: function(chunk, enc, cb) {
outputStream.emit('tail', chunk);
if (!(outputFile && fileStream)) {
return typeof cb === "function" ? cb(null) : void 0;
}
return fileStream.write(chunk, enc, cb);
},
writev: function(chunks, cb) {
var i, item, len, line;
if (!(outputFile && fileStream)) {
return typeof cb === "function" ? cb(null) : void 0;
}
if ((chunks != null ? chunks.length : void 0) > 0) {
line = '';
for (i = 0, len = chunks.length; i < len; i++) {
item = chunks[i];
line += item.chunk;
}
fileStream.write(line, chunks[0].enc, cb);
}
return null;
}
});
$.log.out = function(...args) {
var err, str;
str = args.map($.toString).join(' ');
if (str[str.length - 1] !== '\n') {
str += '\n';
}
try {
process.stdout.write(str);
} catch (error) {
err = error;
if (err) {
process.stderr.write("Failed to write to stdout: " + $.toString(err));
}
}
outputStream.write(str, 'utf8', function(err) {
if (err) {
return process.stderr.write("Failed to write to outputStream: " + $.toString(err));
}
});
return str;
};
setOutput = function(file, cb) {
var err, ref, s;
if (outputFile === file && (fileStream != null)) {
return typeof cb === "function" ? cb(null, false) : void 0;
}
if (file == null) {
outputFile = null;
return typeof cb === "function" ? cb(null, true) : void 0;
} else {
try {
echo("Starting output to", file);
s = fileStream = Fs.createWriteStream(expandPath(file), {
flags: 'a'
});
outputFile = file;
s.on('open', function() {
s.write("Opened for writing at " + String(new Date()) + "\n");
return typeof cb === "function" ? cb(null, true) : void 0;
});
s.on('close', function() {
console.log("writeStream close:", file);
return setOutput(null, cb);
});
s.on('error', function(err) {
var ref;
console.error("writeStream error:", (ref = err.stack) != null ? ref : err);
return setOutput(null, cb);
});
} catch (error) {
err = error;
console.error("setOutput error:", (ref = err.stack) != null ? ref : err);
outputFile = fileStream = null;
if (typeof cb === "function") {
cb(err, false);
}
}
}
return null;
};
toConfig = function() {
return outputFile && `log --file \"${outputFile}\"` || "";
};
getOutputFile = function() {
return outputFile && outputFile.substring(0);
};
Object.assign(module.exports, {
getOutputFile,
setOutput,
toConfig,
stream: outputStream
});
process.stdout.on('error', function(err) {
if (err.code === "EPIPE") {
return process.exit(2);
}
});
}).call(this);