All files / source/CaffeineMc CafRepl.js

13.02% Statements 28/215
0.99% Branches 1/101
6.06% Functions 2/33
13.02% Lines 28/215

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400  7x     7x   7x   7x   7x   7x   7x   7x   7x 7x     7x   7x   7x   7x   7x         7x                 7x                                                                                                                                                                                                                                                                                                                                                                                                               7x       7x                                   7x       7x                               7x   7x                                                                             7x                                       7x                                             7x                             7x                 7x          
// Generated by CoffeeScript 1.12.7
(function() {
  var CafRepl, CaffeineMc, Register, compactFlatten, currentSecond, defineModule, displayError, formattedInspect, fs, getCaffeineInit, highlight, historyFile, historyMaxInputSize, isArray, isArrayUniversal, isPlainObjectUniversal, log, maxOutputCharacters, maxOutputLines, merge, objectKeyCount, path, ref, ref1, repl, runInContext;
 
  ref = require('art-standard-lib'), currentSecond = ref.currentSecond, merge = ref.merge, objectKeyCount = ref.objectKeyCount, isArray = ref.isArray, isArrayUniversal = ref.isArrayUniversal, isPlainObjectUniversal = ref.isPlainObjectUniversal, formattedInspect = ref.formattedInspect, defineModule = ref.defineModule, log = ref.log, compactFlatten = ref.compactFlatten;
 
  getCaffeineInit = require('./SourceRoots').getCaffeineInit;
 
  ref1 = CaffeineMc = require('./namespace'), runInContext = ref1.runInContext, displayError = ref1.displayError;
 
  Register = require('./Register');
 
  repl = require('repl');
 
  path = require('path');
 
  fs = require('fs');
 
  Eif (process.env.HOME) {
    historyFile = path.join(process.env.HOME, '.caffeine-mc-history');
  }
 
  historyMaxInputSize = 10240;
 
  maxOutputLines = 30;
 
  maxOutputCharacters = maxOutputLines * 200;
 
  highlight = require('./Highlight').highlight;
 
  defineModule(module, CafRepl = (function() {
    var lastCompiler, logReplInfo;
 
    function CafRepl() {}
 
    logReplInfo = function(categoryName, info) {
      var out;
      out = categoryName.gray;
      if (info != null) {
        out += info.green;
      }
      return log(out);
    };
 
    CafRepl.start = function(parser) {
      return getCaffeineInit().then((function(_this) {
        return function(init) {
          var config, evaluateMode, lastOutput, showSource, toggleVerbose, verbose;
          showSource = false;
          evaluateMode = true;
          verbose = false;
          lastOutput = null;
          toggleVerbose = function() {
            return Register.verbose = verbose = !verbose;
          };
          _this.compiler = init.compiler, config = init.config;
          logReplInfo("Welcome to the CaffeineMC console.");
          logReplInfo("For help: ", ".help");
          _this._showCurrentCompiler();
          _this.cafRepl = repl.start({
            prompt: _this.getPrompt(),
            completer: function(command) {
              var __, commandToEval, error, k, key, keys, last, out, regex, result, trimmedCommand;
              trimmedCommand = command.trim();
              commandToEval = (result = trimmedCommand.match(regex = /\.([$\w\u007f-\uffff]*)$/)) ? ((__ = result[0], last = result[1], result), trimmedCommand.split(regex)[0]) : trimmedCommand.match(/^[$\w\u007f-\uffff]*$/) ? (last = trimmedCommand, "global") : trimmedCommand;
              out = (function() {
                try {
                  result = this._replEval(commandToEval);
                  keys = (function() {
                    var ref2, results;
                    results = [];
                    for (k in result) {
                      if (!last || ((ref2 = k.match(last)) != null ? ref2.index : void 0) === 0) {
                        results.push(k);
                      }
                    }
                    return results;
                  })();
                  this.cafRepl.outputStream.write("\n" + (formattedInspect({
                    "tab-completion": merge({
                      object: commandToEval,
                      prefix: last != null ? last : "(none)",
                      found: keys.length <= 3 ? keys.join(', ') : (keys.slice(0, 3).join(', ')) + "..."
                    })
                  }, {
                    color: true
                  })) + (keys.length > 3 ? ("  press tab again to show all " + keys.length + "\n").gray : ""));
                  if (last || /\.$/.test(command)) {
                    return [keys, last];
                  } else {
                    return [
                      (function() {
                        var i, len, results;
                        results = [];
                        for (i = 0, len = keys.length; i < len; i++) {
                          key = keys[i];
                          results.push("." + key);
                        }
                        return results;
                      })(), ""
                    ];
                  }
                } catch (error1) {
                  error = error1;
                  this.cafRepl.outputStream.write("\ntab-completion could not evaluate: " + commandToEval.red + "\n");
                  return [[], trimmedCommand];
                }
              }).call(_this);
              if (out[0].length === 0) {
                _this.cafRepl.displayPrompt(true);
              }
              return out;
            },
            "eval": function(command, context, filename, callback) {
              var e, midTime, result, startTime;
              try {
                startTime = currentSecond();
                if (command.trim() === '') {
                  return callback();
                }
                if (showSource || !evaluateMode) {
                  _this.cafRepl.outputStream.write("Source:\n".grey);
                  _this.cafRepl.outputStream.write(highlight(_this.compileCommand(command, filename)));
                  _this.cafRepl.outputStream.write("\n\n");
                }
                result = evaluateMode ? (showSource ? _this.cafRepl.outputStream.write("Evaluate...\n".grey) : void 0, _this.replEval(command, context, filename)) : ("evaluation off (.evaluate to turn back on)".grey, void 0);
                (_this.replEval("global", context, filename)).$last = result;
                midTime = currentSecond();
                log.resolvePromiseWrapper(result, function(toLog, label, wasResolved, wasRejected) {
                  var finalOut, finalTime, lines, obj, out;
                  finalTime = currentSecond();
                  lastOutput = out = formattedInspect(label ? (
                    obj = {},
                    obj["" + label] = toLog,
                    obj
                  ) : toLog, {
                    color: true
                  });
                  if (showSource && evaluateMode) {
                    _this.cafRepl.outputStream.write("\nOut:\n".grey);
                  }
                  finalOut = ((lines = out.split("\n")).slice(0, maxOutputLines)).join("\n");
                  if (finalOut.length > maxOutputCharacters) {
                    finalOut = finalOut.slice(0, maxOutputCharacters);
                  }
                  if (wasResolved || wasRejected) {
                    log("");
                  }
                  log(finalOut);
                  if (finalOut !== out) {
                    logReplInfo("output truncated");
                    if (isArray(toLog)) {
                      logReplInfo("  array: length: " + toLog.length);
                    } else if (isPlainObjectUniversal(toLog)) {
                      logReplInfo("  object: keys: " + (objectKeyCount(toLog)));
                    }
                    if (lines.length > maxOutputLines) {
                      logReplInfo("  showing: " + maxOutputLines + "/" + lines.length + " lines");
                    } else {
                      logReplInfo("  showing: " + finalOut.length + "/" + lastOutput.length + " characters");
                    }
                    logReplInfo("  show all:                      ", ".last");
                    logReplInfo("  result available at:           ", "$last");
                  }
                  if (wasResolved || wasRejected) {
                    logReplInfo("  promise wall-time:             ", ((finalTime - midTime) * 1000 | 0) + "ms");
                    logReplInfo("  total wall-time:               ", ((finalTime - startTime) * 1000 | 0) + "ms");
                    if (!wasRejected) {
                      logReplInfo("  resolved value available at:   ", "$lastResolved");
                      (_this.replEval("global", context, filename)).$lastResolved = toLog;
                    } else {
                      logReplInfo("  rejected value available at:   ", "$lastRejected");
                      (_this.replEval("global", context, filename)).$lastRejected = toLog;
                    }
                    (_this.replEval("global", context, filename)).$lastPromise = result;
                    logReplInfo("  promise available at:          ", "$lastPromise");
                    return _this.cafRepl.displayPrompt();
                  }
                });
                if (midTime - startTime > .1) {
                  logReplInfo("wall-time: ", ((midTime - startTime) * 1000 | 0) + "ms");
                }
                return callback();
              } catch (error1) {
                e = error1;
                return callback(e);
              }
            }
          });
          _this.setupHistory();
          _this.addCommand({
            name: 'compiler',
            help: 'CaffeineMC: Show the current compiler',
            action: function() {
              _this.cafRepl.outputStream.write(formattedInspect(_this.compiler.current));
              _this.cafRepl.outputStream.write("\n");
              return _this.cafRepl.displayPrompt();
            }
          });
          _this.addCommand({
            name: "last",
            help: "CaffeineMC: Show the last output value in its entirety. $last contains the value of the last output.",
            action: function() {
              _this.cafRepl.outputStream.write("" + lastOutput);
              _this.cafRepl.outputStream.write("\n");
              return _this.cafRepl.displayPrompt();
            }
          });
          _this.addCommand({
            name: "evaluate",
            help: "toggle evaluate command",
            action: function() {
              evaluateMode = !evaluateMode;
              _this.cafRepl.outputStream.write("Evaluate Mode is " + (evaluateMode ? 'On' : 'Off') + "\n");
              return _this.cafRepl.displayPrompt();
            }
          });
          _this.addCommand({
            name: "verbose",
            help: "toggle verbose logging",
            action: function() {
              toggleVerbose();
              _this.cafRepl.outputStream.write("Verbose logging is " + (verbose ? 'On' : 'Off') + "\n");
              return _this.cafRepl.displayPrompt();
            }
          });
          _this.addCommand({
            name: "source",
            help: "toggle show-source",
            action: function() {
              showSource = !showSource;
              _this.cafRepl.outputStream.write("Show-Source Mode is " + (showSource ? 'On' : 'Off') + "\n");
              return _this.cafRepl.displayPrompt();
            }
          });
          return runInContext("Neptune.CaffeineMc.register()", _this.cafRepl.context);
        };
      })(this))["catch"](function(error) {
        return log.error({
          replError: error
        });
      });
    };
 
    CafRepl.getPrompt = function() {
      return ("caf-mc:" + this.compiler.compilerName + "> ").gray;
    };
 
    CafRepl.compileCommand = function(command, filename) {
      var e, js;
      command = command.trim();
      js = this.compiler.compile(command, {
        bare: true,
        sourceFile: filename,
        cache: filename !== "repl"
      }).compiled.js;
      try {
        return require("prettier").format(js, {
          parser: 'babel'
        });
      } catch (error1) {
        e = error1;
        return displayError(e);
      }
    };
 
    CafRepl._showCurrentCompiler = function() {
      return logReplInfo("Your current compiler is: ", this.compiler.compilerName);
    };
 
    CafRepl._replEval = function(command, context, filename) {
      var js;
      if (context == null) {
        context = this.cafRepl.context;
      }
      if (filename == null) {
        filename = 'repl';
      }
      js = this.compileCommand(command, filename);
      if (command.match(/^\|/)) {
        return this.compiler.lastMetacompilerResult;
      } else {
        return runInContext(js, context);
      }
    };
 
    lastCompiler = null;
 
    CafRepl.replEval = function(command, context, filename) {
      var e, error, js, result;
      if (context == null) {
        context = this.cafRepl.context;
      }
      if (filename == null) {
        filename = 'repl';
      }
      result = error = null;
      try {
        js = this.compileCommand(command, filename);
        try {
          result = command.match(/^\|/) ? this.compiler.lastMetacompilerResult : runInContext(js, context);
          if (lastCompiler !== this.compiler) {
            this._showCurrentCompiler();
            lastCompiler = this.compiler;
          }
          this.cafRepl.setPrompt(this.getPrompt());
        } catch (error1) {
          e = error1;
          error = e;
        }
      } catch (error1) {
        e = error1;
        displayError(e);
        result = null;
      }
      if (error) {
        throw error;
      }
      return result;
    };
 
 
    /*
    Code BELOW was adapted FROM CoffeeScript's REPL:
      https://github.com/jashkenas/coffeescript/blob/master/src/repl.coffee
     */
 
    CafRepl.setupHistory = function(filename, maxSize) {
      if (filename == null) {
        filename = historyFile;
      }
      if (maxSize == null) {
        maxSize = historyMaxInputSize;
      }
      this.addHistoryListener(filename, maxSize);
      return this.addCommand({
        name: 'history',
        help: 'Show command history',
        action: (function(_this) {
          return function() {
            _this.cafRepl.outputStream.write((_this.cafRepl.history.slice(0).reverse().join('\n')) + "\n");
            return _this.cafRepl.displayPrompt();
          };
        })(this)
      });
    };
 
    CafRepl.loadHistory = function(filename, maxSize) {
      var buffer, lastLine, readFd, size, stat;
      lastLine = null;
      try {
        stat = fs.statSync(filename);
        size = Math.min(maxSize, stat.size);
        readFd = fs.openSync(filename, 'r');
        buffer = Buffer.alloc(size);
        fs.readSync(readFd, buffer, 0, size, stat.size - size);
        fs.closeSync(readFd);
        this.cafRepl.history = buffer.toString().split('\n').reverse();
        if (stat.size > maxSize) {
          this.cafRepl.history.pop();
        }
        if (this.cafRepl.history[0] === '') {
          this.cafRepl.history.shift();
        }
        this.cafRepl.historyIndex = -1;
        lastLine = this.cafRepl.history[0];
      } catch (error1) {}
      return lastLine;
    };
 
    CafRepl.addHistoryListener = function(filename, maxSize) {
      var fd, lastLine;
      fd = fs.openSync(filename, 'a');
      lastLine = this.loadHistory(filename, maxSize);
      this.cafRepl.addListener('line', function(code) {
        if (code && code.length && code !== '.history' && code !== '.exit' && lastLine !== code) {
          fs.writeSync(fd, code + "\n");
          return lastLine = code;
        }
      });
      return this.cafRepl.on('exit', function() {
        return fs.closeSync(fd);
      });
    };
 
    CafRepl.addCommand = function(arg) {
      var action, help, name;
      name = arg.name, help = arg.help, action = arg.action;
      return this.cafRepl.commands[name] = {
        help: help,
        action: action
      };
    };
 
    return CafRepl;
 
  })());
 
}).call(this);