Example #1
0
/**
                               * Clear some text that was previously printed on an interactive stream,
                               * without trailing newline character (so we have to move back to the
                               * beginning of the line).
                               */
function clearStringBackwards(stream, str) {
  readline.moveCursor(stream, -stream.columns, 0);
  readline.clearLine(stream, 0);
  let lineCount = (str.match(/\n/g) || []).length;
  while (lineCount > 0) {
    readline.moveCursor(stream, 0, -1);
    readline.clearLine(stream, 0);
    --lineCount;
  }
}
Example #2
0
  function redraw() {
    readline.clearLine(process.stdout, 0)
    readline.cursorTo(process.stdout, 0)

    for (let i = 0; i < drawnLines; i++) {
      readline.moveCursor(process.stdout, 0, -1)
      readline.clearLine(process.stdout, 0)
    }

    draw()
  }
Example #3
0
Output.prototype.update = function (message) {
    if (!this._tty) return console.log(message)
    this._inUpdate = true
    readline.clearLine(process.stdout, 0)
    readline.cursorTo(process.stdout, 0)
    process.stdout.write(message, 'utf8')
}
function outputQueues(swtch, firstRun) {
  let total = 0;

  if (! firstRun) {
    readline.moveCursor(std, 0, -(swtch.dimension + 1));
  }

  // Print all virtual output queues of each input in one line, plus the total
  // number of packets in each input queue

  swtch.inputs.forEach(function(input) {
    const queueTotal = input.reduce((prev, cur) => prev + cur, 0);

    total += queueTotal;
    readline.clearLine(std, 0);

    std.write(input.map(function(output, i) {
      const cell = _.truncate(_.padStart(output, 3), {
        length: 3,
        omission: '…'
      });

      return argv.colored ? cell[colors[i % colors.length]] : cell;
    }).join(' '));

    std.write(`  (Σ = ${queueTotal})\n`);
  });

  readline.clearLine(std, 0);
  std.write(`Σ = ${total}\n`);
}
Example #5
0
function clearLine(stdout) {
  if (!supportsColor) {
    return;
  }

  readline.clearLine(stdout, CLEAR_WHOLE_LINE);
  readline.cursorTo(stdout, 0);
}
Example #6
0
 process.on('SIGINT', () => {
   // Remove '^C' text from stdout.
   readline.clearLine(process.stdout, -1)
   readline.moveCursor(process.stdout, -2, 0)
   // Set counter to 0 which will stop alarm.
   i = 0
   // Reset CTRL-C to default behavior.
   process.on('SIGINT', process.exit)
 })
Example #7
0
function writeOnNthLine(stdout, n, msg) {
  if (!supportsColor) {
    return;
  }

  if (n == 0) {
    readline.cursorTo(stdout, 0);
    stdout.write(msg);
    readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
    return;
  }
  readline.cursorTo(stdout, 0);
  readline.moveCursor(stdout, 0, -n);
  stdout.write(msg);
  readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR);
  readline.cursorTo(stdout, 0);
  readline.moveCursor(stdout, 0, n);
}
Example #8
0
  return (text, overwrite) => {
    if (overwrite === true) {
      readline.clearLine(process.stdout, 0);
      readline.cursorTo(process.stdout, 0);
    } else {
      process.stdout.write('\n');
    }

    process.stdout.write(text);
  };
Example #9
0
Prompt.prototype.error = function( error ) {
  readline.moveCursor( this.rl.output, -cliWidth(), 0 );
  readline.clearLine( this.rl.output, 0 );

  var errMsg = chalk.red(">> ") +
      (error || "Please enter a valid value");
  this.write( errMsg );

  return this.up();
};
 new webpack.ProgressPlugin(function handler(progress, msg){
   var perc = Math.round(progress * 100);
   var progressBar = new Array(Math.round(perc/2)).join(color.green('■'));
   progressBar += new Array( 50 - Math.round(perc/2) ).join('-');
   
   readline.clearLine(process.stdout, 0);  // clear current text
   readline.cursorTo(process.stdout, 0);  // move cursor to beginning of line
   process.stdout.write(`\nBuilding [${progressBar}] ${perc}% `);
   readline.moveCursor(process.stdout, 0, -1);
 })
Example #11
0
  _write(stream, message) {
    if (this._interactive && stream.isTTY && isPreviousLogInteractive) {
      readline.moveCursor(stream, 0, -1);
      readline.clearLine(stream);
      readline.cursorTo(stream, 0);
    }

    stream.write(message + '\n');
    isPreviousLogInteractive = this._interactive;
  }
Example #12
0
Prompt.prototype.hint = function( hint ) {
  readline.moveCursor( this.rl.output, -cliWidth(), 0 );
  readline.clearLine( this.rl.output, 0 );

  if ( hint.length ) {
    var hintMsg = chalk.cyan(">> ") + hint;
    this.write( hintMsg );
  }

  return this.up();
};
 assetResponse.on("data", (chunk) => {
   downloaded += chunk.length;
   const now = Date.now();
   if (now - lastUpdate > 500) {
     const percent = Math.round(downloaded / contentLength * 10000) / 100;
     readline.clearLine(process.stdout);
     readline.cursorTo(process.stdout, 0);
     process.stdout.write("Downloading " + asset.name + "... " + percent + "%");
     lastUpdate = now;
   }
 });
Example #14
0
function writeLine (line, prevLine) {
  rl.pause()
  if (prevLine) {
    readline.moveCursor(process.stdout, 0, -1)
  }
  readline.clearLine(process.stdout, 0)
  readline.cursorTo(process.stdout, 0)
  console.log(line.toString())
  rl.prompt(true)
  rl.resume()
}
Example #15
0
tty.clean = function( extra ) {
  _.isNumber(extra) || (extra = 0);
  var len = this.height + extra;

  while ( len-- ) {
    readline.moveCursor(this.rl.output, -clc.width, 0);
    readline.clearLine(this.rl.output, 0);
    if ( len ) readline.moveCursor(this.rl.output, 0, -1);
  }
  return this;
};
            return promiseUtils.chain(download, function(err, data) {

                if(err.message === 'Resource container already exists') {
                    if(argv.verbose) {
                        readline.cursorTo(process.stdout, 0);
                        readline.clearLine(process.stdout, 0);
                        console.log('\nSkipping', data);
                    }
                } else {
                    if(argv.log) {
                        let errMessage = err.status ? err.status : err.toString();
                        fs.writeFileSync(path.join(argv.dir, 'log.txt'), errMessage + ': while downloading:\n' + JSON.stringify(data) + '\n\n', {flag: 'a'});
                    }
                    if(argv.verbose) {
                        readline.cursorTo(process.stdout, 0);
                        readline.clearLine(process.stdout, 0);
                        console.log('\n', err, 'while downloading', data);
                    }
                }
                return false;
            }, {compact: true, onProgress: function(total, completed) {
Example #17
0
function gotLogsLoop(logs){
  readline.clearLine(process.stdout);
  readline.cursorTo(process.stdout,0);
  while(logs.length > 0){
    var l = logs.pop();
    if(l.time > lastLog){
      lastLog = l.time;
      printLog(l);
    }
  }
 rl.setPrompt("(Press enter to quit)".data);
 rl.prompt(true)
}
 sessions.save(session, function (err) {
   if (err) {
     console.error('\n' + moment().format('YYYY-MM-DD HH:mm:ss') + ' - error saving session')
     console.error(err)
   }
   if (s.period) {
     engine.writeReport(true)
   } else {
     readline.clearLine(process.stdout)
     readline.cursorTo(process.stdout, 0)
     process.stdout.write('Waiting on first live trade to display reports, could be a few minutes ...')
   }
 })
Example #19
0
function clearNthLine(stdout, n) {
  if (!supportsColor) {
    return;
  }

  if (n == 0) {
    clearLine(stdout);
    return;
  }
  readline.cursorTo(stdout, 0);
  readline.moveCursor(stdout, 0, -n);
  readline.clearLine(stdout, CLEAR_WHOLE_LINE);
  readline.moveCursor(stdout, 0, n);
}
Example #20
0
				})(function (err) {
					if (err) {
						console.error('Error occurred');
						return next(err);
					}

					readline.clearLine(process.stdout, 0);
					readline.cursorTo(process.stdout, 0);
					readline.moveCursor(process.stdout, 0, -1);
					console.log('  → '.white + String('[' + [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].join('/') + '] ').gray + String(scriptExport.name).reset + '... ' + 'OK'.green);

					// Record success in schemaLog
					db.sortedSetAdd('schemaLog', Date.now(), path.basename(file, '.js'), next);
				});
Example #21
0
    function printMessage({
        from = null,
        me = null,
        to = null,
        text = "",
        timestamp = new Date()
    } = {}) {
        const message = formatter(from, me, to, text, timestamp);

        readline.clearLine(process.stdout, 0);
        readline.cursorTo(process.stdout, 0);
        process.stdout.write(message);
        rl.prompt(true);
    }
Example #22
0
File: index.js Project: Webiny/Cli
    constructor() {
        this.updateAvailable = null;
        this.version = JSON.parse(Webiny.readFile(__dirname + '/package.json')).version;

        program
            .version(this.version)
            .description([
                'Webiny CLI tool will help you manage your project from development to deployment.',
                'It supports plugins so you are welcome to develop new plugins for your project and connect to the existing plugins using hooks.',
                'Run without arguments to enter GUI mode.',
                '',
                'Visit https://www.webiny.com/ for tutorials and documentation.'
            ].join('\n  '))
            .option('--show-timestamps [format]', 'Show timestamps next to each console message');

        program
            .command('setup')
            .description('Setup Webiny project.')
            .option('--user [user]', 'Admin user email.')
            .option('--password [password]', 'Admin user password.')
            .option('--url [url]', 'Project domain.') // https://github.com/tj/commander.js/issues/370
            .option('--database [database]', 'Database name')
            .option('--cliPort [cliPort]', 'CLI port')
            .action((cmd) => {
                const config = cmd.opts();
                config.domain = config.url;

                setup(false, config).then(() => process.exit(0)).catch(e => {
                    console.log(e.message);
                    process.exit(1);
                });
            });

        program
            .command('*', null, {noHelp: true})
            .action(cmd => {
                Webiny.failure(`${chalk.magenta(cmd)} is not a valid command. Run ${chalk.magenta('webiny-cli -h')} to see all available commands.`);
                process.exit(1);
            });

        this.attachExitHandler();

        // Load plugins
        readline.cursorTo(process.stdout, 0);
        process.stdout.write('Loading plugins...');
        Webiny.getPlugins();
        readline.clearLine(process.stdout, 0);
        readline.cursorTo(process.stdout, 0, null);
    }
Example #23
0
    cursor.input.on("data", function(data) {
      log("got data " + data);
      data.toString().split("").forEach(function(c) {
        const cmd = commands[c];
        if(cmd) {
          log("command: " + cmd.name);
          cmd();
          renderAnalysis();
        }
      });

      // hide the characters
      readline.moveCursor(setup.input, -data.length, 0);
      readline.clearLine(setup.input, 1);
    });
Example #24
0
				})(function (err) {
					if (err) {
						process.stdout.write('error\n'.red);
						return next(err);
					}

					if (progress.total > 0) {
						readline.clearLine(process.stdout, 0);
						readline.cursorTo(process.stdout, 0);
						process.stdout.write('  → '.white + String('[' + [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].join('/') + '] ').gray + String(scriptExport.name).reset + '... ');
					}

					process.stdout.write('OK\n'.green);
					// Record success in schemaLog
					db.sortedSetAdd('schemaLog', Date.now(), path.basename(file, '.js'), next);
				});
Example #25
0
  function nextHandler(){
    if (!taskCount)
    {
      var newWarnings = flow.warns.length - warningCount;
      var timeDiff = process.hrtime(time.time);
      time.time = parseInt(timeDiff[0] * 1e3 + timeDiff[1] / 1e6, 10);
      timing.push(time);
      warningCount = flow.warns.length;

      if (!options.silent && !options.verbose && !stdoutHandlerSilent && handlers.length)
      {
        var extraInfo = time.extraInfo ? time.extraInfo(flow) : '';
        if (process.stdout.isTTY)
        {
          if (process.stdout._bytesDispatched == stdoutPos)
          {
            readline.moveCursor(process.stdout, 0, -1);
            readline.clearLine(process.stdout, 0);
            process.stdout.write(
              stdoutHandlerTitle +
              (extraInfo ? chalk.gray(' [') + chalk.yellow(extraInfo) + chalk.gray(']') : '') +
              chalk.gray(' – '));
          }
          else
          {
            if (extraInfo)
              process.stdout.write('       ' + chalk.yellow(extraInfo) + '\n');
            process.stdout.write('       ');
          }

          process.stdout.write(
            chalk.green('DONE') +
            (newWarnings > 0 ? ' ' + chalk.bgRed('(' + newWarnings + (newWarnings > 1 ? ' warnings)' : ' warning)')) : '') +
            (time.time > 10 ? chalk.gray(' (' + time.time + 'ms)') : '') +
            '\n'
          );
        }
        else
        {
          if (extraInfo)
            process.stdout.write('       * ' + extraInfo + '\n');
        }
      }

      process.nextTick(runHandler);
    }
  }
Example #26
0
  function nextHandler(){
    var lastHandler = !handlers.length;

    if (!taskCount && !lastHandler)
    {
      time.time = new Date - time.time;
      timing.push(time);

      if (!options.verbose)
      {
        var extraInfo = time.extraInfo ? time.extraInfo(flow) : '';
        if (process.stdout.isTTY)
        {

          if (process.stdout._bytesDispatched == stdoutPos)
          {
            readline.moveCursor(process.stdout, 0, -1);
            readline.clearLine(process.stdout, 0);
            process.stdout.write(
              stdoutHandlerTitle +
              (extraInfo ? chalk.gray(' [') + chalk.yellow(extraInfo) + chalk.gray(']') : '') +
              chalk.gray(' – '));
          }
          else
          {
            if (extraInfo)
              process.stdout.write('       ' + chalk.yellow(extraInfo) + '\n');
            process.stdout.write('       ');
          }

          process.stdout.write(
            chalk.green('DONE') +
            (time.time > 10 ? chalk.gray(' (' + time.time + 'ms)') : '') +
            '\n'
          );
        }
        else
        {
          if (extraInfo)
            process.stdout.write('       * ' + extraInfo + '\n');
        }
      }

      process.nextTick(runHandler);
    }
  }
  swtch.inputs.forEach(function(input) {
    const queueTotal = input.reduce((prev, cur) => prev + cur, 0);

    total += queueTotal;
    readline.clearLine(std, 0);

    std.write(input.map(function(output, i) {
      const cell = _.truncate(_.padStart(output, 3), {
        length: 3,
        omission: '…'
      });

      return argv.colored ? cell[colors[i % colors.length]] : cell;
    }).join(' '));

    std.write(`  (Σ = ${queueTotal})\n`);
  });
Example #28
0
race.on("update", function() {
    process.stderr.write('\x1B[?25l'); // this hides our cursor
    let colNum = process.stdout.columns;
    let lengthPerCol = this.length / colNum;    
    let trackEdge = new Array(colNum).fill("◎").join("");
    readline.clearLine(process.stdout, 0);
    console.log(trackEdge);
    this.cars.forEach(function(car) {
        let numOfSpaces = Math.floor(car.position / lengthPerCol);
        if(numOfSpaces  > colNum - 1) {
            numOfSpaces = colNum - 1;
        }
        let spaces = numOfSpaces > 0 ? new Array(numOfSpaces).fill(" ").join("") : "";
        let carChar = chalk[car.color]("►");
        console.log(`${spaces}${carChar}`);
    });
    console.log(trackEdge);
    readline.moveCursor(process.stdout, 0, 0 - (this.cars.length + 2));        
});
Example #29
0
			async.eachSeries(files, function (file, next) {
				var scriptExport = require(file);
				var date = new Date(scriptExport.timestamp);
				var version = path.dirname(file).split('/').pop();
				var progress = {
					current: 0,
					total: 0,
					incr: Upgrade.incrementProgress,
					script: scriptExport,
					date: date,
				};

				console.log('  → '.white + String('[' + [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].join('/') + '] ').gray + String(scriptExport.name).reset + '...');

				// For backwards compatibility, cross-reference with schemaDate (if found). If a script's date is older, skip it
				if ((!results.schemaDate && !results.schemaLogCount) || (scriptExport.timestamp <= results.schemaDate && semver.lt(version, '1.5.0'))) {
					readline.clearLine(process.stdout, 0);
					readline.cursorTo(process.stdout, 0);
					readline.moveCursor(process.stdout, 0, -1);
					console.log('  → '.white + String('[' + [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].join('/') + '] ').gray + String(scriptExport.name).reset + '... ' + 'skipped'.grey);
					db.sortedSetAdd('schemaLog', Date.now(), path.basename(file, '.js'), next);
					return;
				}

				// Do the upgrade...
				scriptExport.method.bind({
					progress: progress,
				})(function (err) {
					if (err) {
						console.error('Error occurred');
						return next(err);
					}

					readline.clearLine(process.stdout, 0);
					readline.cursorTo(process.stdout, 0);
					readline.moveCursor(process.stdout, 0, -1);
					console.log('  → '.white + String('[' + [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].join('/') + '] ').gray + String(scriptExport.name).reset + '... ' + 'OK'.green);

					// Record success in schemaLog
					db.sortedSetAdd('schemaLog', Date.now(), path.basename(file, '.js'), next);
				});
			}, next);
Example #30
0
function handleError(context, filename, error) {
  if (error instanceof errors.UndefinedParserError) {
    if (context.argv["write"] && process.stdout.isTTY) {
      readline.clearLine(process.stdout, 0);
      readline.cursorTo(process.stdout, 0, null);
    }
    if (!context.argv["list-different"]) {
      process.exitCode = 2;
    }
    context.logger.error(error.message);
    return;
  }

  if (context.argv["write"]) {
    // Add newline to split errors from filename line.
    process.stdout.write("\n");
  }

  const isParseError = Boolean(error && error.loc);
  const isValidationError = /Validation Error/.test(error && error.message);

  // For parse errors and validation errors, we only want to show the error
  // message formatted in a nice way. `String(error)` takes care of that. Other
  // (unexpected) errors are passed as-is as a separate argument to
  // `console.error`. That includes the stack trace (if any), and shows a nice
  // `util.inspect` of throws things that aren't `Error` objects. (The Flow
  // parser has mistakenly thrown arrays sometimes.)
  if (isParseError) {
    context.logger.error(`${filename}: ${String(error)}`);
  } else if (isValidationError || error instanceof errors.ConfigError) {
    context.logger.error(String(error));
    // If validation fails for one file, it will fail for all of them.
    process.exit(1);
  } else if (error instanceof errors.DebugError) {
    context.logger.error(`${filename}: ${error.message}`);
  } else {
    context.logger.error(filename + ": " + (error.stack || error));
  }

  // Don't exit the process if one file failed
  process.exitCode = 2;
}