Example #1
0
export default function (tag, ...msg) {
  /* make sure log tag is enabled */
  if (!config.logs || config.logs.indexOf(tag) === -1) {
    return () => {}
  }

  /* enable or disable color */
  const chalk = new Chalk.constructor({ enabled: config.logColors })

  if (msg.length) {
    const timestamp = config.logTimestamp
      ? ' ' + chalk.cyan(`${new Date().toISOString()}`)
      : ''

    const message = tag === 'error'
      ? chalk.red(...msg)
      : `${chalk.dim(config.name)}${timestamp} ${msg.join(' ')}`

    process.stdout.write(message)
  }

  return (code) => {
    if (code && tag === 'request') {
      /* if the log is a request log, this outputs the statusCode after the request complets */
      const statusCode = code >= 400 ? chalk.red(code) : chalk.green(code)
      process.stdout.write(` - ${statusCode}`)
    }

    process.stdout.write('\n')
  }
}
Example #2
0
      var formattedName = _.reduce(name.split(':'), function (memo, value, index) {
        if (index !== 0) {
          return memo + chalk.gray(':') + chalk.magenta(value)
        }

        return memo + chalk.magenta(value)
      }, '')
Example #3
0
File: log.js Project: wmhilton/log
describe('log', function () {

  const tests = [
    {
      'name': 'single string',
      'args': ['This is a test']
    }, {
      'name': 'multiple strings',
      'args': ['This is a test', 'of more features', 'and stuff']
    }, {
      'name': 'single object',
      'args': [
        {
          'key': 'value'
        }
      ]
    }
  ]

  const levels = ['log', 'debug', 'info', 'warn', 'err', 'fatal']

  const timestamps = {
    'log': chalk.gray('12:32:19 AM (log.js:56)\n'),
    'debug': chalk.gray('12:32:19 AM (log.js:56)\n'),
    'info': chalk.blue('12:32:19 AM (log.js:56)\n'),
    'warn': chalk.bold.yellow('12:32:19 AM (log.js:56)\n'),
    'err': chalk.red('12:32:19 AM (log.js:56)\n'),
    'fatal': chalk.bgRed('12:32:19 AM (log.js:56)\n'),
  }

  for (let level of levels) {
    for (let test of tests) {
      it(level + ' ' + test.name, function () {
        let stdout = new stream.Writable()
        let write_spy = sinon.stub(stdout, 'write')
        let clock = sinon.useFakeTimers(1000 * (60 * 32 + 19))
        let event_spy = sinon.spy()
        let time_stamp = timestamps[level]
        log.setup({
          quiet: false,
          timezone: 'UTC',
          colors: true,
          stdout: stdout,
        })
        try {
          log.on(level, event_spy)
          log[level].apply(log, test.args)
        } finally {
          write_spy.restore()
          clock.restore()
          log.removeListener(level, event_spy)
        }
        sinon.assert.calledOnce(event_spy)
        sinon.assert.calledWith(write_spy, time_stamp)
      })
    }
  }
})
Example #4
0
 formatError(colours) {
   const c = new chalk.constructor({enabled: Boolean(colours)});
   const quote = (s) => `"${s}"`;
   const exp = (e) => [...e].join(" or ");
   return c.cyan("Expected ") + c.white.bold(exp(this.expected))
     + c.cyan(", saw ") + c.white.bold(
       this.input.atEnd() ? "EOF"
     : quote(stringOps.nextOnLine(6, this.input.buffer, this.input.cursor))
     );
 }
Example #5
0
 suite.tests.forEach(function (test) {
     if (test.message === undefined) {
         passing += 1;
         duration += test.duration;
         result += _this.tab2(chalk.green("✓") + chalk.gray(" " + test.description + " (" + test.duration + "ms)"));
     }
     else {
         failing += 1;
         result += _this.tab2(chalk.red(failing + ") " + test.description));
     }
 });
Example #6
0
 print(colours) {
   const c = new chalk.constructor({enabled: Boolean(colours)});
   const {line, row, column} = stringOps.findLine(this.input.buffer, this.input.cursor);
   const header = c.yellow(`At line ${row}, column ${column}:\n\n`);
   const arrowhead = c.cyan(`\n${stringOps.repeat(column, " ")}^\n`);
   const arrowstem = c.cyan(`${stringOps.repeat(column, " ")}|\n`);
   const msg = c.cyan.bold("ERROR: ") + this.formatError(colours);
   if (line.trim().length) {
     return header + line + arrowhead + arrowstem + msg;
   }
   return header + msg;
 }
Example #7
0
File: cli.js Project: Prosciana/dat
 function downloadCompleteMsg () {
   var outMsg = printFileProgress(stats, {
     returnMsg: true, showFilesOnly: true
   })
   outMsg += chalk.green.bold('[Done] ')
   outMsg += chalk.magenta(
     'Downloaded ' + prettyBytes(stats.progress.bytesRead) + ' '
   )
   if (stats.parentFolder) outMsg += chalk.magenta('to ') + chalk.magenta.bold(stats.parentFolder)
   outMsg += '\n'
   return outMsg
 }
Example #8
0
File: cli.js Project: Prosciana/dat
function printSwarmStatus (stats) {
  var swarm = stats.swarm
  if (!swarm) return logger.stdout('Finding data sources...\n')

  if (swarm.hasMetadata && swarm.gettingMetadata) {
    // Print final metadata output
    var scanMsg = ''
    swarm.gettingMetadata = false
    scanMsg = getScanOutput(stats, chalk.bold.green('Downloading Data'))
    logger.stdout(scanMsg)
    logger.log('')
  }

  var msg = swarm.downloading ? downloadMsg() : ''
  if (swarm.downloadComplete) msg = downloadCompleteMsg()

  var count = '0'
  var activePeers = swarm.connections.length
  var totalPeers = swarm.connecting + swarm.connections.length
  if (activePeers > 0) count = activePeers + '/' + totalPeers
  msg += chalk.bold('[Status] ') + 'Connected to ' + chalk.bold(count) + ' sources\n'

  if (!swarm.downloading) msg += chalk.bold('[Sharing] ')
  else if (swarm.downloading) msg += chalk.bold('[Downloading] ')
  msg += chalk.underline.blue('dat://' + swarm.link)

  logger.stdout(msg)

  function downloadMsg () {
    if (!stats.total.bytesTotal) return chalk.bold('Connecting...\n')
    if (swarm.gettingMetadata && !swarm.hasMetadata) {
      return getScanOutput(stats, chalk.bold.blue('Getting Metadata')) + '\n'
    }
    return printFileProgress(stats, {
      returnMsg: true, message: 'Downloading Data'
    })
  }

  function downloadCompleteMsg () {
    var outMsg = printFileProgress(stats, {
      returnMsg: true, showFilesOnly: true
    })
    outMsg += chalk.green.bold('[Done] ')
    outMsg += chalk.magenta(
      'Downloaded ' + prettyBytes(stats.progress.bytesRead) + ' '
    )
    if (stats.parentFolder) outMsg += chalk.magenta('to ') + chalk.magenta.bold(stats.parentFolder)
    outMsg += '\n'
    return outMsg
  }
}
Example #9
0
  constructor () {
    this.chalk = new chalk.constructor({ enabled: process.env.NO_ANSI === 'false' })

    /**
     * List of icons
     *
     * @type {Object}
     */
    this.iconsMain = {
      info: this.chalk.cyan('ℹ'),
      success: this.chalk.green('✔'),
      warn: this.chalk.yellow('⚠'),
      error: this.chalk.red('✖')
    }

    /**
     * The icons to be used on windows
     *
     * @type {Object}
     */
    this.iconsWin = {
      info: this.chalk.cyan('i'),
      success: this.chalk.green('√'),
      warn: this.chalk.yellow('‼'),
      error: this.chalk.red('×')
    }
  }
Example #10
0
 function downloadCompleteMsg () {
   var outMsg = printFileProgress(stats, {
     returnMsg: true, showFilesOnly: true
   })
   outMsg += chalk.bold.green('[Done] ')
   outMsg += chalk.bold(
     'Downloaded ' + prettyBytes(stats.progress.bytesRead) + ' '
   )
   if (stats.parentFolder) outMsg += chalk.bold('to ') + chalk.bold(stats.parentFolder)
   outMsg += '\n'
   outMsg += chalk.bold('[Sharing] ')
   outMsg += chalk.underline.blue('dat://' + swarm.link)
   return outMsg
 }
Example #11
0
module.exports = function assertEqualJSX(actual, expected, opts) {
  opts = opts || {}

  actual = renderToStaticMarkup(actual);
  expected = renderToStaticMarkup(expected);

  if (opts.sanitize) {
    actual = opts.sanitize(actual);
    expected = opts.sanitize(expected);
  }

  if (actual === expected) {
    return;
  }

  actual = beautifyHTML(actual);
  expected = beautifyHTML(expected);

  var diff = diffWords(actual, expected)
    .map(function(part) {
      if (part.added) {
        return colors.black.bgRed(part.value);
      } else if (part.removed) {
        return colors.black.bgGreen(part.value);
      } else {
        return colors.gray(part.value);
      }
    })
    .join('');

  var message = [
    '',
    '-------------------------------------------------------------------------',
    '',
    colors.gray('Diff:'),
    diff,
    '',
    colors.green('Actual:'),
    colors.green(actual),
    '',
    colors.red('Expected:'),
    colors.red(expected),
    '',
    '-------------------------------------------------------------------------',
  ].join('\n');

  fail(actual, expected, message, '==');
};
Example #12
0
File: cli.js Project: Prosciana/dat
function printFileProgress (stats, opts) {
  if (!opts) opts = {}
  var totalMsg = opts.message || 'File Progress'
  var indent = '  ' // indent for single file info
  var msg = ''

  while (true) {
    if (stats.fileQueue.length === 0) break
    var file = stats.fileQueue[0]
    msg = getSingleFileOutput(file)
    var complete = (file.stats.bytesTotal === file.stats.bytesRead)
    if (!complete && stats.fileQueue.length === 1) break
    if (stats.fileQueue.length === 1 && !queueDone) msg = getSingleFileOutput(file)
    logger.stdout(chalk.green.dim(indent + '[Done] ') + chalk.dim(file.name))
    logger.log('')
    stats.fileQueue.shift()
  }

  var queueDone = (stats.total.bytesTotal <= stats.progress.bytesRead)
  if (queueDone) msg = ''
  else msg += '\n'

  if (opts.showFilesOnly && opts.returnMsg) return msg

  msg += getTotalProgressOutput(stats, totalMsg)
  if (opts.returnMsg) return msg
  else logger.stdout(msg)
}
Example #13
0
File: cli.js Project: Prosciana/dat
function getScanOutput (stats, statusMsg) {
  if (!statusMsg) statusMsg = chalk.bold.green('Scan Progress')
  var dirCount = stats.total.directories + 1 // parent folder
  return statusMsg + ' ' + chalk.bold(
    '(' + stats.total.filesTotal + ' files, ' + dirCount + ' folders, ' +
    (stats.total.bytesTotal ? prettyBytes(stats.total.bytesTotal) + ' total' : '') + ')'
  )
}
Example #14
0
 suite.tests.forEach(function (test) {
     if (test.message !== undefined) {
         failing += 1;
         result += _this.tab1(failing + ") " + suite.description + " " + test.description + ":");
         result += "\n";
         result += _this.tab2(chalk.red(test.message));
         result += "\n";
     }
 });
Example #15
0
 .map(function(part) {
   if (part.added) {
     return colors.black.bgRed(part.value);
   } else if (part.removed) {
     return colors.black.bgGreen(part.value);
   } else {
     return colors.gray(part.value);
   }
 })
Example #16
0
 this._socket.once(ioEvts.utils.disconnect, () => {
     //clean subscriptions
     if(this._subscriptions.length > 0) {
         this._subscriptions.map(subscription => { subscription.dispose(); });
         this._subscriptions = [];
     }
     this._socket = null;
     console.log(chalk.yellow(`Socket service DISCONNECTED`));
 });
Example #17
0
File: cli.js Project: Prosciana/dat
 function downloadMsg () {
   if (!stats.total.bytesTotal) return chalk.bold('Connecting...\n')
   if (swarm.gettingMetadata && !swarm.hasMetadata) {
     return getScanOutput(stats, chalk.bold.blue('Getting Metadata')) + '\n'
   }
   return printFileProgress(stats, {
     returnMsg: true, message: 'Downloading Data'
   })
 }
Example #18
0
  /**
   * Returns a multiline string to be used as the help
   * output. This method does not write anything to
   * console and consumer to should do it
   * themselves.
   *
   * @method outputHelp
   * @static
   *
   * @param  {Boolean}  colorize - Whether or not colorize the output
   *
   * @return {String}
   */
  static outputHelp (colorize = process.env.NO_ANSI === 'false') {
    const ctx = new chalk.constructor({ enabled: colorize })
    const stringifiedArgs = this._stringifyArgs()
    const maxWidth = this.biggestArg()

    /**
     * Push new lines to the strings array
     *
     * @type {Array}
     */
    const strings = []

    /**
     * Push the strings showing how to use the
     * command.
     *
     * @type {String}
     */
    strings.push(ctx.magenta.bold('Usage:'))
    const args = stringifiedArgs.length ? ` ${stringifiedArgs}` : ''
    strings.push(`  ${this.commandName}${args} [options]`)

    /**
     * Push arguments when defined
     */
    if (this.args.length) {
      strings.push(WHITE_SPACE)
      strings.push(ctx.magenta.bold('Arguments:'))
      _.each(this.args, (arg) => {
        strings.push(`  ${ctx.blue(_.padEnd(arg.name, maxWidth))} ${arg.description}`)
      })
    }

    /**
     * Push options when defined
     */
    if (this.options.length) {
      strings.push(WHITE_SPACE)
      strings.push(ctx.magenta.bold('Options:'))
      _.each(this.options, (option) => {
        strings.push(`  ${ctx.blue(_.padEnd(this._getArgOrOptionName(option), maxWidth))} ${option.description}`)
      })
    }

    /**
     * Push description when defined
     */
    if (this.description) {
      strings.push(WHITE_SPACE)
      strings.push(ctx.magenta.bold('About:'))
      strings.push(`  ${this.description}`)
    }

    strings.push(WHITE_SPACE)
    return strings.join('\n')
  }
Example #19
0
export default (async function runCommand(): Promise<ExitCode> {
  const ctx = new chalk.constructor({enabled: true});
  const out = Object.keys(process.versions)
    .map(key => [key, process.versions[key]])
    .concat([['atom', atom.getVersion()]])
    .map(([name, version]) => `${ctx.yellow(name)}=${ctx.green(version)}`)
    .sort()
    .join('\n');
  console.log(out);
  return 0;
});
Example #20
0
    function formatMessage () {
      var formattedName = _.reduce(name.split(':'), function (memo, value, index) {
        if (index !== 0) {
          return memo + chalk.gray(':') + chalk.magenta(value)
        }

        return memo + chalk.magenta(value)
      }, '')

      var parts = [
        chalk.bold[levelColors[level]](rightPad(level.toUpperCase(), 5)),
        chalk.gray('[') + formattedName + chalk.gray(']'),
        chalk.white(components.message)
      ]

      if (LOG_TIMESTAMP) {
        parts.unshift(now.toJSON())
      }

      return parts.join(' ')
    }
Example #21
0
File: cli.js Project: Prosciana/dat
function getTotalProgressOutput (stats, statusText, msg) {
  if (!stats) return ''
  if (!msg) msg = ''

  var bytesProgress = stats.progress.bytesRead
  var fileProgress = stats.progress.filesRead
  var totalPer = Math.floor(100 * (bytesProgress / stats.total.bytesTotal))

  if (totalPer === 100) msg += chalk.bold.green('[Done] ')
  else if (totalPer >= 0) msg += chalk.bold.red('[' + ('  ' + totalPer).slice(-3) + '%] ')
  else msg += '        '
  msg += chalk.magenta(
    statusText + ': ' + fileProgress + ' of ' + stats.total.filesTotal +
    chalk.dim(
      ' (' + prettyBytes(bytesProgress) +
      ' of ' + prettyBytes(stats.total.bytesTotal) + ') '
    )
  )
  if (stats.downloadRate) msg += chalk.red(prettyBytes(stats.downloadRate()) + '/s ')
  msg += '\n'
  return msg
}
Example #22
0
 report.toString = function () {
     var _this = this;
     var result = "\n\n";
     var passing = 0, failing = 0;
     var duration = 0;
     suites.forEach(function (suite) {
         result += _this.tab1(suite.description);
         suite.tests.forEach(function (test) {
             if (test.message === undefined) {
                 passing += 1;
                 duration += test.duration;
                 result += _this.tab2(chalk.green("✓") + chalk.gray(" " + test.description + " (" + test.duration + "ms)"));
             }
             else {
                 failing += 1;
                 result += _this.tab2(chalk.red(failing + ") " + test.description));
             }
         });
         result += "\n";
     });
     result += "\n";
     result += this.tab1(chalk.green(passing + " passing") + chalk.gray(" (" + duration + "ms)"));
     result += this.tab1(chalk.red(failing + " failing"));
     result += "\n";
     failing = 0;
     suites.forEach(function (suite) {
         suite.tests.forEach(function (test) {
             if (test.message !== undefined) {
                 failing += 1;
                 result += _this.tab1(failing + ") " + suite.description + " " + test.description + ":");
                 result += "\n";
                 result += _this.tab2(chalk.red(test.message));
                 result += "\n";
             }
         });
     });
     return result + "\n";
 };
Example #23
0
  /**
   * End timer and log result into stderr.
   * @param {String} label
   * @param {String} format
   */
  timeEnd(label, format = '%s: %dms') {
    if (!this.verbose) {
      return;
    }

    let time = this._times[label];
    if (!time) {
      throw new Error(`No such label: ${label}`);
    }

    let duration = Date.now() - time;

    let str = fmt(`${chalk.green(checkmark)} ${format}`, label, duration);
    this._stderr.write(`${str}\n`);
  }
Example #24
0
 handleError(err, _console=console) {
   if (err.message.includes('DuplicateZipEntry')) {
     this.collector.addError(messages.DUPLICATE_XPI_ENTRY);
     this.print(_console);
   } else if (err.message.includes(
     'end of central directory record signature not found')) {
     this.collector.addError(messages.BAD_ZIPFILE);
     this.print(_console);
   } else {
     if (this.config.stack === true) {
       _console.error(err.stack);
     } else {
       _console.error(this.chalk.red(err.message || err));
     }
   }
 }
Example #25
0
function getSingleFileOutput (file) {
  var fileMsg = ''
  var filePercent = 0
  if (file.stats.bytesTotal > 0) {
    filePercent = Math.floor(
      100 * (file.stats.bytesRead / file.stats.bytesTotal)
    )
  }
  if (filePercent > 0 && filePercent < 100) {
    fileMsg = chalk.bold.blue('[' + ('   ' + filePercent).slice(-3) + '%] ')
  } else {
    fileMsg = chalk.bold.gray('       ') // # spaces = '[100%] '
  }
  fileMsg += chalk.blue(file.name)
  return fileMsg
}
Example #26
0
        this._io.on(ioEvts.utils.connect, socket => {
            console.log(chalk.green(`Socket service CONNECTED`));
            this._socket = socket;

            //handle disconnects
            this._socket.once(ioEvts.utils.disconnect, () => {
                //clean subscriptions
                if(this._subscriptions.length > 0) {
                    this._subscriptions.map(subscription => { subscription.dispose(); });
                    this._subscriptions = [];
                }
                this._socket = null;
                console.log(chalk.yellow(`Socket service DISCONNECTED`));
            });

            //handle IO
            this._setupInput();
            this._setupOutput();
        });
Example #27
0
  /**
   * Returns a multiline string to be used for showing
   * the help screen.
   *
   * @method outputHelp
   *
   * @param  {Object}   options
   *
   * @return {Array}
   */
  outputHelp (options, colorize = process.env.NO_ANSI === 'false') {
    const strings = []
    const ctx = new chalk.constructor({ enabled: colorize })
    const commandsGroup = this._groupCommands()
    const groupNames = _.keys(commandsGroup).sort()
    const maxWidth = this._largestCommandLength(_.map(options, (option) => option.long)) + 2

    /**
     * Usage lines
     */
    strings.push(ctx.magenta.bold('Usage:'))
    strings.push('  command [arguments] [options]')

    /**
     * Only print global options when they exists.
     */
    if (_.size(options)) {
      strings.push(WHITE_SPACE)
      strings.push(ctx.magenta.bold('Global Options:'))
      _.each(options, (option) => {
        strings.push(`  ${ctx.blue(_.padEnd(option.long, maxWidth))} ${option.description}`)
      })
    }

    /**
     * Only print commands when they are available
     */
    if (_.size(groupNames)) {
      strings.push(WHITE_SPACE)
      strings.push(ctx.magenta.bold('Available Commands:'))
      _.each(groupNames, (groupName) => {
        this._pushGroups(groupName, commandsGroup[groupName], maxWidth, ctx, strings)
      })
    }

    strings.push(WHITE_SPACE)
    return strings.join('\n')
  }
Example #28
0
var util   = require('util')
  , core   = require('./core')
  , Chalk  = require('chalk').constructor
  , chalk  = new Chalk({ enabled :  true })
  , levels = {
        error : { text: chalk.red('error'),          pad: '  ' }
      , debug : { text: chalk.gray.inverse('debug'), pad: '  ' }
      , info  : { text: chalk.blue('info'),          pad: '   ' }
      , warn  : { text: chalk.yellow('warn'),        pad: '   ' }
      , help  : { text: chalk.cyan('help'),          pad: '   ' }
      , step  : { text: chalk.magenta('step'),       pad: '   ' }
      , data  : { text: chalk.gray('data'),          pad: '   ' }
    };

function enabled (name) {
    var env = process.env.NODE_ENV;
    return name !== 'debug' || (env === 'debug' || env === 'development');
}

function Logger (options) {
    var self = this;

    self.options = options || {};

    Object.keys(levels).forEach(function(name) {
        self[name] = function(obj) {
            if (enabled(name)) {
                self.write(levels[name], obj);
            }
        };
    });
Example #29
0
 .map(([name, version]) => `${ctx.yellow(name)}=${ctx.green(version)}`)
var program = require('commander');
var backend = require("./backend/commands.js");
var chalk_lib = require('chalk');
var chalk = new chalk_lib.constructor({enabled: true});
var hostname_val = /^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$/
var ipv6_val = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/

program
  .parse(process.argv);

var args = program.args;

console.log();

if (args.length < 3) {
  console.error(chalk.bold.red('Please set all required Arguments'));
  process.exit(1);
}
if (args.length === 3) {
  var ip = args[1]
  var key = args[2]
  var switchPosition = args[3]
  if (switchPosition === "on") {
    if (ipv6_val.test(ip) || hostname_val.test(ip)) {
      backend.activateMOW(ip, key)
      console.log(chalk.green("Mesh on Wan activated successfully!"));
    }else {
      console.error(chalk.bold.red('Please set correct IPv6 or Hostname'));
      process.exit(1);
    }
  }else if (switchPosition === "off") {