UNPKG

qrepl

Version:
106 lines (94 loc) 2.75 kB
// Generated by CoffeeScript 1.12.4 (function() { var colored, colors, fs, getHomeDir, historyPath, objectAssign, path, readline, util; readline = require('readline'); fs = require('fs'); path = require('path'); util = require('util'); objectAssign = require('object-assign'); getHomeDir = function() { return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE; }; historyPath = function(name) { return path.resolve(getHomeDir(), '.' + name + '.qrepl'); }; colors = { red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36 }; colored = function(s, color) { var color_code, prefix, suffix; color_code = colors[color] || 0; prefix = '\x1b[' + color_code + 'm'; suffix = '\x1b[0m'; return prefix + s + suffix; }; module.exports = function(name, fn, options) { var loadHistory, prompt_text, rl, rl_addHistory, saveHistory; if (options == null) { options = {}; } loadHistory = function(cb) { return fs.readFile(historyPath(name), function(err, history_data) { var history_lines; if (!history_data) { return cb(null, []); } history_lines = history_data.toString().trim().split('\n'); history_lines.reverse(); return cb(null, history_lines); }); }; saveHistory = function(line) { return fs.appendFileSync(historyPath(name), line + '\n'); }; rl = readline.createInterface(objectAssign({ input: process.stdin, output: process.stdout }, options)); rl_addHistory = rl._addHistory; rl._addHistory = function() { var last, line; last = rl.history[0]; line = rl_addHistory.call(rl); if (last !== line) { saveHistory(line); } return line; }; loadHistory(function(err, saved_history) { return rl.history.push.apply(rl.history, saved_history); }); prompt_text = '> '; rl.setPrompt(colored(prompt_text, 'cyan'), prompt_text.length); rl.prompt(); return rl.on('line', function(line) { line = line.trim(); return fn(line, function(err, result) { if (err != null) { if (Array.isArray(err)) { err.map(function(err) { return console.error(colored(err.message, 'red')); }); } else { console.error(err); } } else if (result != null) { if (typeof result === 'string') { console.log(result); } else { console.log(util.inspect(result, { colors: true, depth: null })); } } return rl.prompt(); }); }); }; }).call(this);