Example #1
0
 item: function (msg) {
   console.log(chalk.yellow('| ') + chalk.blue(msg));
 }
Example #2
0
 this.helperMethod = function () {
   this.log(chalk.blue('won\'t be called automatically'));
 }
Example #3
0
var fs = require('fs');
var es = require('event-stream')
var chalk = require('chalk')
var sys = require('sys');
var exec = require('child_process').exec;
var ip_utils = require('../util/ip_utils');
function puts(error, stdout, stderr) { sys.puts(stdout) }
  

// actually: http://archive.routeviews.org/dnszones/originas.bz2
// but domain defaults to broken ipv6 resolution.
var as_file = "http://128.223.51.20/dnszones/originas.bz2";

if (!fs.existsSync('originas.bz2') ||
    new Date() - fs.statSync('originas.bz2').mtime > (1000 * 60 * 60 * 24 * 30)) {
  console.log(chalk.blue("Refreshing OriginAS List"));
  exec("curl -O " + as_file, puts);
  exec("bunzip2 originas.bz2", puts);
}

// Take a line of the origin AS file and load it into a hash map.
// Map format is {start -> {cidr -> asn}}
var parseASLineRegex = /IN TXT\s+"(\d+)" "(\d+\.\d+\.\d+\.\d+)" "(\d+)"/;
function parseASLine(map, line) {
  var result = parseASLineRegex.exec(line),
      start;
  if (result) {
    start = new Buffer(result[2].split('.')).readInt32BE(0);
    start -= start % 256  // make sure it's class C.
    if (!map[start]) {
      map[start] = {};
Example #4
0
 server.listen(PORT, function () {
     console.log(chalk.blue('Server started on port', chalk.magenta(PORT)));
 });
gulp.task('build', function(){
  console.log(chalk.blue('-------------------------------------------------- BUILD - Development Mode'));
  runSequence('copy', 'concat', 'watch');
});
Example #6
0
File: cli.js Project: beppu/knex
 pending = initKnex(env).migrate.currentVersion().then(function(version) {
   success(chalk.green('Current Version: ') + chalk.blue(version));
 }).catch(exit);
Example #7
0
function invoke(env) {
  var filetypes = ['js', 'coffee', 'ts', 'eg', 'ls'];
  var pending = null;

  commander
    .version(
      chalk.blue('Knex CLI version: ', chalk.green(cliPkg.version)) +
        '\n' +
        chalk.blue(
          'Local Knex version: ',
          chalk.green(env.modulePackage.version)
        ) +
        '\n'
    )
    .option('--debug', 'Run with debugging.')
    .option('--knexfile [path]', 'Specify the knexfile path.')
    .option('--cwd [path]', 'Specify the working directory.')
    .option(
      '--env [name]',
      'environment, default: process.env.NODE_ENV || development'
    );

  commander
    .command('init')
    .description('        Create a fresh knexfile.')
    .option(
      `-x [${filetypes.join('|')}]`,
      'Specify the knexfile extension (default js)'
    )
    .action(function() {
      var type = (argv.x || 'js').toLowerCase();
      if (filetypes.indexOf(type) === -1) {
        exit(`Invalid filetype specified: ${type}`);
      }
      if (env.configPath) {
        exit(`Error: ${env.configPath} already exists`);
      }
      checkLocalModule(env);
      var stubPath = `./knexfile.${type}`;
      pending = fs
        .readFileAsync(
          path.dirname(env.modulePath) +
            '/lib/migrate/stub/knexfile-' +
            type +
            '.stub'
        )
        .then(function(code) {
          return fs.writeFileAsync(stubPath, code);
        })
        .then(function() {
          success(chalk.green(`Created ${stubPath}`));
        })
        .catch(exit);
    });

  commander
    .command('migrate:make <name>')
    .description('        Create a named migration file.')
    .option(
      `-x [${filetypes.join('|')}]`,
      'Specify the stub extension (default js)'
    )
    .action(function(name) {
      var instance = initKnex(env);
      var ext = (argv.x || env.configPath.split('.').pop()).toLowerCase();
      pending = instance.migrate
        .make(name, { extension: ext })
        .then(function(name) {
          success(chalk.green(`Created Migration: ${name}`));
        })
        .catch(exit);
    });

  commander
    .command('migrate:latest')
    .description('        Run all migrations that have not yet been run.')
    .action(function() {
      pending = initKnex(env)
        .migrate.latest()
        .spread(function(batchNo, log) {
          if (log.length === 0) {
            success(chalk.cyan('Already up to date'));
          }
          success(
            chalk.green(`Batch ${batchNo} run: ${log.length} migrations \n`) +
              chalk.cyan(log.join('\n'))
          );
        })
        .catch(exit);
    });

  commander
    .command('migrate:rollback')
    .description('        Rollback the last set of migrations performed.')
    .action(function() {
      pending = initKnex(env)
        .migrate.rollback()
        .spread(function(batchNo, log) {
          if (log.length === 0) {
            success(chalk.cyan('Already at the base migration'));
          }
          success(
            chalk.green(
              `Batch ${batchNo} rolled back: ${log.length} migrations \n`
            ) + chalk.cyan(log.join('\n'))
          );
        })
        .catch(exit);
    });

  commander
    .command('migrate:currentVersion')
    .description('        View the current version for the migration.')
    .action(function() {
      pending = initKnex(env)
        .migrate.currentVersion()
        .then(function(version) {
          success(chalk.green('Current Version: ') + chalk.blue(version));
        })
        .catch(exit);
    });

  commander
    .command('seed:make <name>')
    .description('        Create a named seed file.')
    .option(
      `-x [${filetypes.join('|')}]`,
      'Specify the stub extension (default js)'
    )
    .action(function(name) {
      var instance = initKnex(env);
      var ext = (argv.x || env.configPath.split('.').pop()).toLowerCase();
      pending = instance.seed
        .make(name, { extension: ext })
        .then(function(name) {
          success(chalk.green(`Created seed file: ${name}`));
        })
        .catch(exit);
    });

  commander
    .command('seed:run')
    .description('        Run seed files.')
    .action(function() {
      pending = initKnex(env)
        .seed.run()
        .spread(function(log) {
          if (log.length === 0) {
            success(chalk.cyan('No seed files exist'));
          }
          success(
            chalk.green(
              `Ran ${log.length} seed files \n${chalk.cyan(log.join('\n'))}`
            )
          );
        })
        .catch(exit);
    });

  commander.parse(process.argv);

  Promise.resolve(pending).then(function() {
    commander.outputHelp();
    exit('Unknown command-line options, exiting');
  });
}
Example #8
0
	}, function (tempDir, cb, vinylFiles) {

		// all paths passed to sass must have unix path separators
		tempDir = slash(tempDir);
		var compileDir = slash(path.join(tempDir, relativeCompileDir));

		options = options || {};
		options.update = tempDir + ':' + compileDir;
		options.loadPath = typeof options.loadPath === 'undefined' ? [] : [].concat(options.loadPath);

		// add loadPaths for each temp file
		vinylFiles.forEach(function (file) {
			var loadPath = slash(path.dirname(path.relative(procDir, file.path)));

			if (options.loadPath.indexOf(loadPath) === -1) {
				options.loadPath.push(loadPath);
			}
		});

		var args = dargs(options, ['bundleExec', 'watch', 'poll', 'sourcemapPath', 'container']);

		// temporary logging until gulp adds its own
		if (process.argv.indexOf('--verbose') !== -1) {
			gutil.log('gulp-ruby-sass:', 'Running command:', chalk.blue(command, args.join(' ')));
		}

		var command;

		if (options.bundleExec) {
			command = 'bundle';
			args.unshift('exec', 'sass');
		} else {
			command = 'sass';
		}

		var sass = spawn(command, args);

		sass.stdout.setEncoding('utf8');
		sass.stderr.setEncoding('utf8');

		sass.stdout.on('data', function (data) {
			var msg = removePaths(data, [tempDir, relativeCompileDir]).trim();

			if (sassErrMatcher.test(msg) || noBundlerMatcher.test(msg) || noGemfileMatcher.test(msg)) {
				stream.emit('error', gutilErr(msg));
			}
			else if (noBundleSassMatcher.test(msg)) {
				stream.emit('error', gutilErr(bundleErrMsg));
			}
			else {
				gutil.log('gulp-ruby-sass:', msg);
			}
		});

		sass.stderr.on('data', function (data) {
			var msg = removePaths(data, [tempDir, relativeCompileDir]).trim();

			if (noBundleSassMatcher.test(msg)) {
				stream.emit('error', gutilErr(bundleErrMsg));
			} else if (!noSassMatcher.test(msg)) {
				gutil.log('gulp-ruby-sass:, stderr', msg);
			}
		});

		sass.on('error', function (err) {
			if (noSassMatcher.test(err.message)) {
				stream.emit('error', gutilErr(noSassErrMsg));
			} else {
				stream.emit('error', gutilErr(err));
			}
		});

		sass.on('close', function (code) {
			if (options.sourcemap && options.sourcemapPath) {
				rewriteSourcemapPaths(compileDir, options.sourcemapPath, function (err) {
					if (err) {
						stream.emit('error', gutilErr(err));
					}

					cb();
				});
			} else {
				cb();
			}
		});
	});
Example #9
0
	}, function (tempDir, cb, vinylFiles) {
		// all paths passed to sass must have unix path separators
		tempDir = slash(tempDir);
		var compileDir = slash(path.join(tempDir, relativeCompileDir));

		options = options || {};
		options.update = true;
		options.loadPath = typeof options.loadPath === 'undefined' ? [] : [].concat(options.loadPath);

		// add loadPaths for each temp file
		vinylFiles.forEach(function (file) {
			var loadPath = slash(path.dirname(path.relative(procDir, file.path)));

			if (options.loadPath.indexOf(loadPath) === -1) {
				options.loadPath.push(loadPath);
			}
		});

		var command;
		var args = dargs(options, [
			'bundleExec',
			'watch',
			'poll',
			'sourcemapPath',
			'container'
		]);

        /**
         * SASS will very frequently default to Ruby's default character set
         *  for READING files (the output files all appear to be UTF-8
         *  regardless!)
         *  On Linux/Mac OS X the default is UTF-8, which is good.
         *  On Windows the default is... CP1252 - oops!
         *  Easiest way to fix this is just to force it to use UTF-8 here. All
         *  of the other options are horrendous.
         * @link http://blog.pixelastic.com/2014/09/06/compass-utf-8-encoding-on-windows/
         */
        args.push("-Eutf-8");

		args.push(tempDir + ':' + compileDir);

		if (options.bundleExec) {
			command = 'bundle';
			args.unshift('exec', 'sass');
		} else {
			command = 'sass';
		}

		// temporary logging until gulp adds its own
		if (process.argv.indexOf('--verbose') !== -1) {
			gutil.log('gulp-ruby-sass:', 'Running command:', chalk.blue(command, args.join(' ')));
		}

		var sass = spawn(command, args);

		sass.stdout.setEncoding('utf8');
		sass.stderr.setEncoding('utf8');

		sass.stdout.on('data', function (data) {
			var msg = removePaths(data, [tempDir, relativeCompileDir]).trim();

			if (sassErrMatcher.test(msg) || noBundlerMatcher.test(msg) || noGemfileMatcher.test(msg)) {
				stream.emit('error', createErr(msg, {showStack: false}));
			} else if (noBundleSassMatcher.test(msg)) {
				stream.emit('error', createErr(bundleErrMsg, {showStack: false}));
			} else {
				gutil.log('gulp-ruby-sass:', msg);
			}
		});

		sass.stderr.on('data', function (data) {
			var msg = removePaths(data, [tempDir, relativeCompileDir]).trim();

			if (noBundleSassMatcher.test(msg)) {
				stream.emit('error', createErr(bundleErrMsg, {showStack: false}));
			} else if (!noSassMatcher.test(msg)) {
				gutil.log('gulp-ruby-sass: stderr:', msg);
			}
		});

		sass.on('error', function (err) {
			if (noSassMatcher.test(err.message)) {
				stream.emit('error', createErr(noSassErrMsg, {showStack: false}));
			} else {
				stream.emit('error', createErr(err));
			}
		});

		sass.on('close', function (code) {
			if (options.sourcemap && options.sourcemapPath) {
				rewriteSourcemapPaths(compileDir, options.sourcemapPath, function (err) {
					if (err) {
						stream.emit('error', createErr(err));
					}

					cb();
				});
			} else {
				cb();
			}
		});
	});
Example #10
0
 npm.init().then(() => {
   console.log(chalk.blue('create package.json'));
   console.log(JSON.stringify(answers, null, '  '));
   template(answers);
 }).catch((e) => {
Example #11
0
 }).then(() => {
   console.log(chalk.blue('install packages'));
   // return npm.install();
   return;
 }).then(() => {
Example #12
0
 str.wolkenkratzer.forEach(function(entry){
    console.log(chalk.cyan('\nName:' + entry.name) + chalk.yellow('\nStadt:' + entry.stadt) + chalk.blue('\nHoehe:' + entry.hoehe + ' m') + '\n\n--------------------');
 });
Example #13
0
function stats (files, done) {
    vwl('Processing %s (%s) file(s)...', chalk.magenta(files.length), chalk.blue(extensions));
    start = moment();
    async.eachLimit(files, 10, stat, done);
}
Example #14
0
var no = function () {}
var w = function () { process.stdout.write(util.format.apply(util, arguments)); }
var wl = console.log.bind(console);
var vw = program.verbose ? w : no;
var vwl = program.verbose ? wl : no;

var directories = program.args;
if (directories.length === 0) {
    directories.push('.');
}

var extensions = program.filter.split(/[, ]+/).join(',') || '*';
var filetypes = util.format('**/*.{%s}', extensions);

vwl('Looking up files' + (extensions === '*' ? '' : ', filtered by ' + chalk.blue(extensions)) + '...');

async.waterfall([
    async.apply(async.map, directories, globber),
    join,
    stats
], finish);

function globber (directory, done) {
    var pattern = path.join(directory, filetypes);
    vwl('Globbing', pattern);
    glob(pattern, done);
}

function join (lists, done) {
    done(null, _.flatten(lists));
Example #15
0
 .then(() => {
     return console.log(chalk.blue(`Filling in images @bookiza: ${path.join('.', 'assets', 'images')}`));
 }).catch((err) => {
Example #16
0
function info(msg) {
    if(_.isUndefined(process.env['SILENT'])) {
        console.error(chalk.blue('INFO: ') + msg);
    }
}
Example #17
0
 .then(() => {
     return console.log(chalk.blue(`Original html @interim: ${path.join('.', 'interim')}`));
 }).catch(() => {
Example #18
0
    this.fs.copyTpl(this.sourceRoot() + '/bower.json', this.destinationRoot() + '/bower.json', {
      name: answers.name || "",
    });    
  },

  _logger(type) {
    var args = Array.prototype.slice.call(arguments);
    if(type === "info") {
      args[0] = chalk.green("INFO ");
      console.log.apply(console, args);
    }
  },

  _dummyCopy(filename) {
    this._logger('info', 'copy file... ' + chalk.blue(filename));
    this.fs.copy(this.sourceRoot() + '/' + filename, this.destinationRoot() + '/' + filename);
  },

  _getPrompt() {
    return [
      {
        type    : 'input',
        name    : 'name',
        message : chalk.green("What's your project name?"),
        default : chalk.bold("default " + this.appname + '\n')
      },
      {
        type    : 'input',
        name    : 'desc',
        message : chalk.green("What's your project description?"),
Example #19
0
 .then(function(version) {
   success(chalk.green('Current Version: ') + chalk.blue(version));
 })
Example #20
0
/*eslint-inv node*/
var path = require('path');
var postcss = require('postcss');
var fs = require('fs');
var chalk = require('chalk');
var cssnano = require('cssnano');

var argv = require('minimist')(process.argv.slice(2));

if (argv._.length !== 2 || argv.h || !argv.s) {
	console.log(chalk.blue('               SOFE CSS Modules Builder v' + require('./package.json').version));
	console.log('---------------------------------------------------------------');
	console.log(chalk.green('sofe-css-builder ') + chalk.yellow('-s=[serviceName] ') + chalk.yellow('[input.css] [built-output.js]'));
	process.exit(1);
}

var inputFile = path.join(process.cwd(), argv._[0]);
var outputFile = path.join(process.cwd(), argv._[1]);

var css = fs.readFileSync(inputFile, 'utf8');
var json;

console.log(chalk.blue('Building ') + inputFile);

postcss([
  require('postcss-modules')({
		scopeBehaviour: 'global',
    generateScopedName: function(name, filename, css) {
      return '_sofe_' + argv.s + '__' + name;
		},
		getJSON: function(cssFileName, _json) {
Example #21
0
 results.forEach(function(result) {
   console.log(chalk.blue("- " + result.filename));
 });
Example #22
0
const chalk = require('chalk');

console.log(chalk.blue('hello chalk'));
console.log(chalk.red('hello chalk'));
console.log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
Example #23
0
  webpack(config).run((err, stats) => {
    if (err) {
      console.error('Failed to create a production build. Reason:');
      console.error(err.message || err);
      process.exit(1);
    }

    console.log(chalk.green('Compiled successfully.'));
    console.log();

    console.log('File sizes after gzip:');
    console.log();
    printFileSizes(stats, previousSizeMap);
    console.log();

    var openCommand = process.platform === 'win32' ? 'start' : 'open';
    var homepagePath = require(paths.appPackageJson).homepage;
    var publicPath = config.output.publicPath;
    if (homepagePath && homepagePath.indexOf('.github.io/') !== -1) {
      // "homepage": "http://user.github.io/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('To publish it at ' + chalk.green(homepagePath) + ', run:');
      console.log();
      console.log('  ' + chalk.blue('git') + chalk.cyan(' commit -am ') + chalk.yellow('"Save local changes"'));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' checkout -B gh-pages'));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' add -f build'));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' commit -am ' + chalk.yellow('"Rebuild website"')));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' filter-branch -f --prune-empty --subdirectory-filter build'));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' push -f origin gh-pages'));
      console.log('  ' + chalk.blue('git') + chalk.cyan(' checkout -'));
      console.log();
    } else if (publicPath !== '/') {
      // "homepage": "http://mywebsite.com/project"
      console.log('The project was built assuming it is hosted at ' + chalk.green(publicPath) + '.');
      console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
      console.log();
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log();
    } else {
      // no homepage or "homepage": "http://mywebsite.com"
      console.log('The project was built assuming it is hosted at the server root.');
      if (homepagePath) {
        // "homepage": "http://mywebsite.com"
        console.log('You can control this with the ' + chalk.green('homepage') + ' field in your '  + chalk.cyan('package.json') + '.');
        console.log();
      } else {
        // no homepage
        console.log('To override this, specify the ' + chalk.green('homepage') + ' in your '  + chalk.cyan('package.json') + '.');
        console.log('For example, add this to build it for GitHub Pages:')
        console.log();
        console.log('  ' + chalk.green('"homepage"') + chalk.cyan(': ') + chalk.green('"http://myname.github.io/myapp"') + chalk.cyan(','));
        console.log();
      }
      console.log('The ' + chalk.cyan('build') + ' folder is ready to be deployed.');
      console.log('You may also serve it locally with a static server:')
      console.log();
      console.log('  ' + chalk.blue('npm') +  chalk.cyan(' install -g pushstate-server'));
      console.log('  ' + chalk.blue('pushstate-server') + chalk.cyan(' build'));
      console.log('  ' + chalk.blue(openCommand) + chalk.cyan(' http://localhost:9000'));
      console.log();
    }
  });
Example #24
0
var taskType, task;

var option = prompt('(p)lay, (h)ome, (s)chool or (q)uit? ');

while(option !== 'q'){
  task = prompt('What is the task? ');

  switch(option){
    case 'p':
      listPlay.push(task);
      break;
    case 'h':
      listHome.push(task);
      break;
    case 's':
      listSchool.push(task);
      break;
    default:
      console.log('Must choose p, h, or s. Try again.');
  }

  option = prompt('(p)lay, (h)ome, (s)chool or (q)uit? ');
}

console.log('\nHere\'s your to-do list:');
console.log('Play:', chalk.blue(listPlay));
console.log('Home:', chalk.green(listHome));
console.log('School:', chalk.red(listSchool));
console.log('Good Luck!\n');

gulp.task('build:prod', function(){
  console.log(chalk.blue('-------------------------------------------------- BUILD - Production Mode'));
  isProduction = true;
  runSequence('copy', 'concat', 'watch');
});
Example #26
0
 print(prefix = '') {
     console.info(`${prefix}${chalk_1.default.gray(this.fromDirname)}/${this.fromBasename}`);
     console.info(`${this.indent(prefix)} => ${chalk_1.default.blue(this.toBasename)}`);
 }
const logInfo = (text) => console.log(chalk.blue(`[INFO]: ${text}`))
Example #28
0
// More info on Webpack's Node API here: https://webpack.github.io/docs/node.js-api.html
// Allowing console calls below since this is a build file.
/*eslint-disable no-console */
import webpack from 'webpack';
import webpackConfig from '../webpack.config.prod.js';
import chalk from 'chalk';

process.env.NODE_ENV = 'production'; // this assures the Babel dev config doesn't apply.

console.log(chalk.blue('Generating minified bundle for production. This will take a moment...'));

webpack(webpackConfig).run((err, stats) => {
  if (err) { // so a fatal error occurred. Stop here.
    console.log(chalk.red(err));
    return 1;
  }

  const jsonStats = stats.toJson();

  if (jsonStats.hasErrors) {
    return jsonStats.errors.map(error => console.log(chalk.red(error)));
  }

  if (jsonStats.hasWarnings) {
    console.log(chalk.yellow('Webpack generated the following warnings: '));
    jsonStats.warnings.map(warning => console.log(chalk.yellow(warning)));
  }

  console.log(`Webpack stats: ${stats}`);

  // if we got this far, the build succeeded.
Example #29
0
    .action(function (options) {
      var
        tenant = options.tenant,
        apiKey = options.apiKey;

      // Validates inputs
      if (!options || !apiKey) {
        console.log(chalk.yellow('\n  Missing parameter. Both tenant and API key need to be specified to publish:'));
        publish.outputHelp();
        return;
      }

      var magicConstants = {
        completedMsg          : 'PUBLISH COMPLETED',
        errorMsgPrefix        : 'ERROR',
        themeStatusSuccessCode: 200,
        deploySuccessCode     : 202,
        pollingInterval       : 500
      };

      console.log('Publishing theme for %s with key %s', chalk.blue(tenant), chalk.blue(apiKey));

      // HTTP Basic Auth
      var auth = apiKey + ':' + apiKey + '@';

      // Gets the theme status log, outputting each logItem to `cb`
      // TODO: Rewrite to promises instead of callbacks, use less callbacks
      var getStatus = function (cb, doneCb) {
        request({
          uri: 'https://' + auth + 'app.referralsaasquatch.com/api/v1/' + tenant + '/theme/publish_status',
          method: 'GET'
        }, function (error, response, body) {
          if (error) {
            console.log('Unhandled error polling publish status', error);
            return;
          }

          if (response.statusCode !== magicConstants.themeStatusSuccessCode) {
            console.log('Unhandled HTTP response polling publish status', response);
            return;
          }

          var data = JSON.parse(body);

          for (var line = data.log.length; line > 0; --line) {
            var logItem = data.log[line];

            if (logItem) {
              cb(logItem);
            }
          }

          if (doneCb) {
            doneCb();
          }
        });
      };

      // Recursively watched
      var watchStatusLog = function (sinceTime) {
        var thisLoopLatest = null;
        var lastMsg = '';

        getStatus(function (logItem) {
          if (logItem.timestamp > sinceTime) {
            lastMsg        = logItem.message;
            thisLoopLatest = logItem.timestamp;

            if (logItem.message === magicConstants.completedMsg) {
              console.log(chalk.green(logItem.message));
            } else {
              console.log(logItem.message);
            }
          }
        }, function () {
          if (lastMsg === magicConstants.completedMsg) {
            return; // Quit with success
          } else if (lastMsg.indexOf(magicConstants.errorMsgPrefix) === 0) {
            return; // Quit with Error
          } else {
            var newSinceTime = thisLoopLatest ? thisLoopLatest : sinceTime;

            // NOTE -- This is recursion
            setTimeout(function () { watchStatusLog(newSinceTime); }, magicConstants.pollingInterval);
          }
        });
      };

      var previousDeployTime = 0;

      getStatus(function (logItem) {
        if (logItem.timestamp > previousDeployTime) {
          previousDeployTime = logItem.timestamp;
        }
      }, function () {
        request({
          uri: 'https://' + auth + 'app.referralsaasquatch.com/api/v1/' + tenant + '/theme/publish',
          method: 'POST',
          json: {}
        }, function (error, response) {
          if (error) {
            console.log('Unhandled error publishing theme', error);
            return;
          }

          if (response.statusCode !== magicConstants.deploySuccessCode){
            console.log('Unhandled HTTP response to publishing theme', response);
            return;
          }

          // Triggers log polling since `previousDeployTime`
          watchStatusLog(previousDeployTime + 1);
        });
      });
    });
Example #30
0
    socket.on('message', function (data) { 
        console.log(data);

        var message;
        try {
            message = JSON.parse(data);
        } catch (error) {
            console.log(chalk.red(error));
            return;
        }

        console.log(chalk.blue(message.type));
        
        switch(message.type) {
            //创建房间
            case "CREATE_ROOM":
                var room = Math.floor(Math.random()*90000) + 10000;
                rooms[room] = {
                    room: room,
                    socket: socket
                }
                var ret = {
                    type: "CREATE_ROOM",
                    data: room,
                }
                try {
                    socket.send(JSON.stringify(ret));
                } catch (error) {
                    console.log(chalk.blue(error));
                }
                break;
            //恢复房间
            case "RECONNECT_ROOM":
                //如果需要重连房间,则替换当前房间列表中的映射
                if(typeof message.data == 'Number' ){
                    rooms[message.data] = {
                        room: message.data,
                        socket: socket
                    }
                    var ret = {
                        type: "RECONNECT_ROOM",
                        data: 'success',
                    }
                    try {
                        socket.send(JSON.stringify(ret));
                    } catch (error) {
                        console.log(chalk.blue(error));
                    }
                }
                break;
            case "LEAVE_ROOM":
                // if(rooms[message.data]){
                //     delete rooms[message.data];
                // }
                break;
            default:
                console.log(chalk.blue("unknown connection"));
                socket.send("unknown");
                break;
        }
        
    });