return Object.keys(deps).reduce((accum, depName) => {
   if (deps[depName] !== currDeps[depName] && currDeps.hasOwnProperty(depName)) {
     accum[depName] = isPkg ? !semver.satisfies(currDeps[depName], deps[depName]) : true
   }
   return accum
 }, {})
Example #2
0
var util = require('util');
var stream = require('stream');
var semver = require('semver');

var pool = require('./trireme-jdbc-pool');

var jdbc;

try {
  jdbc = process.binding('trireme-jdbc-wrap');
} catch (e) {
  throw new Error('trireme-jdbc does not appear to be running on Trireme.');
}

if (!semver.satisfies(jdbc.interfaceVersion, '>=1.0.0 < 2.0.0')) {
  throw new Error('Trireme does not support a compatible version of the interface');
}

var DEFAULT_POOL_MIN = 1;
var DEFAULT_POOL_MAX = 10;
var DEFAULT_IDLE_TIMEOUT = 60;

var debug;
var debugEnabled;
if (process.env.NODE_DEBUG && /jdbc/.test(process.env.NODE_DEBUG)) {
  debug = function(a) { console.error('JDBC:', a); };
  debugEnabled = true;
} else {
  debug = function() { };
  debugEnabled = false;
Example #3
0
File: index.js Project: dgeb/data
    let checker = new VersionChecker(this);
    // prevent errors when ember-cli-shims is no longer required
    let shims = bowerDeps['ember-cli-shims'] && checker.for('ember-cli-shims', 'bower');

    let version = require('./package').version;

    if (process.env.EMBER_DATA_SKIP_VERSION_CHECKING_DO_NOT_USE_THIS_ENV_VARIABLE) {
      // Skip for node tests as we can't currently override the version of ember-cli-shims
      // before the test helpers run.
      return;
    }

    let hasShims = !!shims;
    let shimsHasEmberDataShims = hasShims && shims.satisfies('< 0.1.0');
    let emberDataNPMWithShimsIncluded = semver.satisfies(version, '^2.3.0-beta.3');

    if (bowerDeps['ember-data']) {
      this._warn('Please remove `ember-data` from `bower.json`. As of Ember Data 2.3.0, only the NPM package is needed. If you need an ' +
                'earlier version of ember-data (< 2.3.0), you can leave this unchanged for now, but we strongly suggest you upgrade your version of Ember Data ' +
                'as soon as possible.');
      this._forceBowerUsage = true;

      let emberDataBower = checker.for('ember-data', 'bower');
      let emberDataBowerWithShimsIncluded = emberDataBower.satisfies('>= 2.3.0-beta.3');

      if (hasShims && !shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
        throw new SilentError('Using a version of ember-cli-shims greater than or equal to 0.1.0 will cause errors while loading Ember Data < 2.3.0-beta.3 Please update ember-cli-shims from ' + shims.version + ' to 0.0.6');
      }

      if (hasShims && shimsHasEmberDataShims && !emberDataBowerWithShimsIncluded) {
 yoCheckPromise = runCmd('yo --version').then(function(stdout) {
   if(!semver.satisfies(semver.clean(stdout), '>= 1.7.1')) {
     throw new Error('ERROR: You need to update yo to at least 1.7.1 (npm i -g yo)');
   }
 });
Example #5
0
	/**
	 * called to load the metabase (and generate if needed)
	 */
	function loadMetabase(options, arch, sdks, settings, callback, generate) {
		// semver requires 0.0.0 versioning
		var version = settings.version;

		if (version.split('.').length===2) {
			version+='.0';
		}

		// we require a minimum of iOS 7 to build
		if (!options.ticurrent && !semver.satisfies(version,'>=7.0.0')) {
			return callback("iOS SDK must be >= "+"7.0".green+", you are currently using: "+settings.version.red+" and your active Xcode is set to "+settings.xcodePath.green);
		}

		// set the minVersion for iOS compile if not set
		if (!options.minVersion) {
			options.minVersion = options.ticurrent ? '6.0' : version;
		}

		var opts = _.clone(options);
		opts.arch = arch;
		opts.isysroot = sdks[arch].path;

		options.F = Array.isArray(options.F) ? options.F : (options.F ? [options.F] : []);
		options.thirdPartyFrameworks = options.thirdPartyFrameworks || [];
		async.eachSeries(options.F, 
			function(dir, done) {
				// framework directory could be relative path or full path
				var otherFrameworkDir = dir.match(/^\//) ? dir : path.resolve(process.cwd(), dir);
				xcode.frameworksFromDir(otherFrameworkDir, function(err, thirdPartyFrameworks) {
					if (err) log.fatal(err);
				    opts.thirdPartyFrameworks = options.thirdPartyFrameworks = options.thirdPartyFrameworks.concat(thirdPartyFrameworks);
					done();
				});
			}, function (err) { processSystemFrameworks(err); } );

		function processSystemFrameworks(err) {
			if (err) log.fatal(err);
			xcode.systemFrameworks(function(err,frameworks) {
				frameworks = frameworks.concat(options.thirdPartyFrameworks);
				var dir = options.dest,
					astFile = path.join(dir, 'metabase-'+arch+'.json.gz'),
					headerfile = path.join(dir, 'libraries.h'),
					header = generate && (options.header||'') + frameworks.map(function(e){return '#include "'+path.resolve(e.header)+'"'}).join('\n');

				if (generate) {
					log.debug('writing header file to',headerfile);
					fs.writeFileSync(headerfile, header, 'utf8');
				}

				opts.cacheFile = astFile;
				opts.skipSystemFrameworks = true;
				opts.productDir = dir;

				// if not a force re-compile and we already have generated it, use it
				if (!opts.force && 
					fs.existsSync(astFile)) {
					var zlib = require('zlib'),
						ast = fs.readFileSync(astFile);
					log.debug('attempting to load previously generated metabase from',astFile.cyan);
					return zlib.gunzip(ast, function(err,ast) {
						ast = !err && JSON.parse(ast.toString());
						callback(err, ast, astFile);
					});
				}

				metabase.loadMetabase(headerfile, opts, function(err, ast){
					callback(null, ast, astFile);
				});
			});
		}
	}
Example #6
0
module.exports.isMountainLion = function() {
  return os.type() === 'Darwin' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '>=12.0.0');
};
Example #7
0
 installMany(deps.filter(function (d) {
   // prefer to not install things that are satisfied by
   // something in the "previously" list.
   return !semver.satisfies(previously[d], target.dependencies[d])
 }).map(function (d) {
  return function receiveIncomingSailsIOMsg(options) {
    app.log.verbose('Receiving incoming message from Socket.io: ', options.incomingSailsIOMsg);

    // If invalid callback function specified, freak out
    // (it's ok to NOT include a callback, but if it exists, it should be a function)
    if (options.socketIOClientCallback && !_.isFunction(options.socketIOClientCallback)) {
      delete options.socketIOClientCallback;
      return respondWithParseError('Could not parse request- callback may be omitted... but if provided, it must be a function.');
    }

    // Check that URL is specified
    if (!options.incomingSailsIOMsg.url) {
      return respondWithParseError(util.format('No url provided in request: %s',options.incomingSailsIOMsg));
    }

    // Check that URL is valid
    if (!_.isString(options.incomingSailsIOMsg.url)) {
      return respondWithParseError(util.format('Invalid url provided: %s',options.incomingSailsIOMsg.url));
    }

    // Grab the metadata for the SDK
    var sdk = parseSdkMetadata(options.socket.handshake);

    // No more backwards-compatibility for clients < v0.11.0
    if (!semver.satisfies(sdk.version, '>=0.11.0')) {
      return respondWithParseError(util.format('Sails v0.11.x is not compatible with the socket.io/sails.io.js client SDK version you are using (%s). Please see the v0.11 migration guide on http://sailsjs.org for more information.',sdk.version));
    }


    // Use heuristic to guess forwarded ip:port (using `x-forwarded-for` header if IIS)
    var ip;
    var port;
    try {
      var forwardedFor = options.socket.handshake.headers['x-forwarded-for'];
      forwardedFor = forwardedFor && forwardedFor.split(':') || [];
      ip = forwardedFor[0] || (options.socket.handshake.address && options.socket.handshake.address.address);
      port = forwardedFor[1] || (options.socket.handshake.address && options.socket.handshake.address.port);
    }
    catch (e) {
      app.log.silly('Unable to parse IP / port using x-forwarded-for header');
    }


    // Start building up the request context which we'll pass into the interpreter in Sails core:
    var requestContext = {

      transport: 'socket.io', // TODO: consider if this is really helpful or just a waste of LoC

      protocol: 'ws', // TODO: consider if this is really helpful or just a waste of LoC

      isSocket: true,

      ip      : ip,

      port    : port,

      // Access to underlying SIO socket
      socket  : options.socket,

      url     : options.incomingSailsIOMsg.url,

      method  : options.eventName,

      // Attached data becomes simulated HTTP body (`req.body`)
      // (allow `params` or `data` to be specified for backwards/sideways-compatibility)
      body    : _.isArray(options.incomingSailsIOMsg.data) ? options.incomingSailsIOMsg.data : _.extend({}, options.incomingSailsIOMsg.params || {}, options.incomingSailsIOMsg.data || {}),

      // Allow optional headers
      headers: _.defaults({

        host: app.config.host,

        // Default the "cookie" request header to what was provided in the handshake.
        cookie: (function (){
          var _cookie;
          try {
            _cookie = options.socket.handshake.headers.cookie;
          }
          catch (e) {}
          // console.log('REQUEST to "%s %s" IS USING COOKIE:', options.eventName, options.incomingSailsIOMsg.url, _cookie);
          return _cookie;
        })(),

        nosession: options.socket.handshake.headers.nosession ? true : undefined,

      }, options.incomingSailsIOMsg.headers || {})

    };

    // app.log.verbose('Interpreting socket.io message as virtual request to "%s %s"...', requestContext.method, requestContext.url);
    // app.log.verbose('(cookie: %s)', requestContext.headers.cookie);

    // Set the `origin` header to what was provided in the handshake
    // (the origin header CANNOT BE OVERRIDDEN by sockets at virtual request-time-- only
    //  upon first connection.)
    if (requestContext.headers.origin){
      // TODO:
      // Document security reasons why `origin` may not be passed manually at virtual request-time.
      // Has to do w/ xdomain security concerns.
      app.log.verbose('Igoring provided `origin` header in virtual request from socket.io: It would not be safe to change `origin` for this socket now!');
    }
    requestContext.headers.origin = (function (){
      var _origin;
      try {
        _origin = options.socket.handshake.headers.origin;
      }
      catch (e){}
      return _origin;
    })();


    // console.log('handshake:',options.socket.handshake);
    app.log.verbose('Interpreting socket.io message as virtual request to "%s %s"...', requestContext.method, requestContext.url);



    // Start building up the response context which we'll pass into the interpreter in Sails core:
    var responseContext = {

      /**
       * This `_clientCallback` function we provide here will be used by Sails core as a final step
       * when trying to run methods like `res.send()`.
       *
       * Since Socket.io v1.x does not support streaming socket messages out of the box,
       * currently we'll just use this callback vs passing in a stream (so the client response
       * stream will just be buffered to build up clientRes.body)
       *
       * IMPORTANT:
       * The `clientRes` provided here is a Readable client response stream, not the same `res`
       * that is available in userland code.
       */

      _clientCallback: function _clientCallback(clientRes) {

        // If no cookie was sent initially on the handshake, and a 'set-cookie' exists in response
        // headers, then save the cookie on the handshake (no need to send extra data over the wire
        // since we're maintaining a persistent connection on this side, plus this prevents client-side
        // js from accessing the cookie)
        //
        // This allows for anything relying on cookies (e.g. default `req.session` support)
        // to last as long as the socket connection (i.e. until the browser tab is closed)
        //
        // Note that we **STILL GENERATE A COOKIE** using socket.io middleware when the socket
        // initially connects.  This is so that by the time we run the `onConnect` lifecycle event,
        // it has access to the real session.  So in general, this should never fire.
        //
        // In the future, we may want to always reset the handshake's cookie based on the `set-cookie`
        // response header to allow for custom HTTP cookies to work completely via sockets, but that
        // should be evaluated carefully to avoid unexpected race conditions.
        try {
          if (!options.socket.handshake.headers.cookie && clientRes.headers['set-cookie']){
              options.socket.handshake.headers.cookie = clientRes.headers['set-cookie'][0];
          }
        }
        catch (e) {
          app.log.warn('Could not persist res.headers["set-cookie"] into the socket handshake:',e);
        }

        // If socket.io callback does not exist as a valid function, don't bother responding.
        if (!_.isFunction(options.socketIOClientCallback)) {
          return;
        }

        // Modern behavior
        // (builds a complete simulation of an HTTP response.)
        var jwr = {
          body: clientRes.body
        };

        // Allow headers and status code to be disabled to allow for squeezing
        // out a little more performance when relevant (and reducing bandwidth usage).
        // To achieve this, set `sails.config.sockets.sendResponseHeaders=false` and/or
        // `sails.config.sockets.sendStatusCode=false`.
        if (app.config.sockets.sendResponseHeaders) {
          jwr.headers = clientRes.headers;
        }
        if (app.config.sockets.sendStatusCode) {
          jwr.statusCode = clientRes.statusCode;
        }

        // Remove 'set-cookie' header
        // (to prevent cookie from reaching client-side js)
        delete jwr.headers['set-cookie'];

        // TODO:
        // Try out http://socket.io/blog/introducing-socket-io-1-0/#socket.io-stream
        // to explore how we could make it work with Sails.
        // (the old way in 0.9 was streams1 style, just emitting `data` and `end` messages)

        // Send down response.
        options.socketIOClientCallback(jwr);
        return;
      }

    };


    // Finally, lob a virtual request at the interpreter
    app.router.route(requestContext, responseContext);










    /**
     * Send a parse error back over the socket.
     * If a callback was provided by the socket.io client, it will be used,
     * but otherwise a low-level event will be emitted (since otherwise there's
     * no way to communicate with the client)
     *
     * Relies on closure scope for `options` and `app`.
     */

    function respondWithParseError (detailedErrorMsg) {

      var error = ERRORPACK.PARSE_VIRTUAL_REQ('Failed to parse incoming socket.io request.');
      error.details = detailedErrorMsg;

      // Log parse error
      app.log.error(error);

      // If callback is invalid or non-existent:
      if ( !_.isFunction(options.socketIOClientCallback) ) {
        // Emit parse error
        options.socket.emit('sails:parseError', error);
        return;
      }

      // Otherwise just send the error directly to the callback...
      return options.socketIOClientCallback(error);
    }

  };
Example #9
0
DebuggerAgent.nodeVersionHasSetVariableValue = function(version) {
  return semver.satisfies(version, '~0.10.12 || ~0.11.2 || >=0.12');
};
Example #10
0
 var matchingProjects = this.projects.filter(function (project) {
     return (!target || target === project.target) &&
         (!versions || semver.satisfies(project.getSemVersion(), versions, /* loose */ true));
 });
Example #11
0
 versions.some(v => v === '*' || satisfies(version, v))
Example #12
0
 var cb = function() {
   var version = this._debuggerClient.target.nodeVersion;
   if (semver.satisfies(version, '~0.12'))
     // Relative to https://github.com/joyent/node/issues/25266
     this._onAfterCompile(event);
 }.bind(this);
ProfilerAgent.nodeVersionIsCompatible = function(version) {
  return semver.satisfies(version, '>=0.11.13');
};
Example #14
0
 satisfies: test => semver.satisfies(process.versions.node, test),
Example #15
0
 versions = versions.filter(function (version) {
   return semver.satisfies(version, this.tag);
 }.bind(this));
Example #16
0
  return defs.filter((def: LibDef) => {
    let filterMatch = false;
    switch (filter.type) {
      case 'exact':
        filterMatch = (
          packageNameMatch(def.pkgName, filter.pkgName)
          && libdefMatchesPackageVersion(filter.pkgVersionStr, def.pkgVersionStr)
        );
        break;

      case 'exact-name':
        filterMatch = (
          packageNameMatch(def.pkgName, filter.term)
        );
        break;

      case 'fuzzy':
        filterMatch = (
          def.pkgName.toLowerCase().indexOf(filter.term.toLowerCase()) !== -1
        );
        break;

      default:
        throw new Error(
          `'${filter.type}' is an unexpected filter type! This should never ` +
          `happen!`
        );
    }

    if (!filterMatch) {
      return false;
    }

    const filterFlowVerStr = filter.flowVersionStr;
    if (filterFlowVerStr) {
      const {flowVersion} = def;
      switch (flowVersion.kind) {
        case 'all':
          return semver.satisfies(
            filterFlowVerStr,
            def.flowVersionStr
          );
        case 'specific':
          return semver.satisfies(
            filterFlowVerStr,
            def.flowVersionStr
          );
        case 'ranged':
          const {upper} = flowVersion;
          if (upper) {
            const lowerSpecific = {
              kind: 'ranged',
              upper: null,
              lower: flowVersion.lower,
            };
            const lowerSpecificSemver = flowVerToSemver(lowerSpecific);
            const upperSpecificSemver = flowVerToSemver({
              kind: 'specific',
              ver: upper,
            });
            return (
              semver.satisfies(filterFlowVerStr, lowerSpecificSemver)
              && semver.satisfies(filterFlowVerStr, upperSpecificSemver)
            );
          } else {
            return semver.satisfies(
              filterFlowVerStr,
              def.flowVersionStr,
            );
          }

        default: (flowVersion: empty); throw new Error('Unexpected FlowVersion kind!');
      }
    }

    return true;
  }).sort((a, b) => {
Example #17
0
function upgrade(args, config) {
  args = args || process.argv;
  const env = yeoman.createEnv();
  const pak = JSON.parse(fs.readFileSync('package.json', 'utf8'));
  const version = pak.dependencies['react-native'];

  if (version) {
    if (version === 'latest' || version === '*') {
      console.warn(
        chalk.yellow(
          'Major releases are most likely to introduce breaking changes.\n' +
          'Use a proper version number in your \'package.json\' file to avoid breakage.\n' +
          'e.g. - ^0.18.0'
        )
      );
    } else {
      const installed = JSON.parse(fs.readFileSync('node_modules/react-native/package.json', 'utf8'));

      if (semver.satisfies(installed.version, version)) {
        const v = version.replace(/^(~|\^|=)/, '').replace(/x/i, '0');

        if (semver.valid(v)) {
          console.log(
            'Upgrading project to react-native v' + installed.version + '\n' +
            'Be sure to read the release notes and breaking changes:\n' +
            chalk.blue(
              'https://github.com/facebook/react-native/releases/tag/v' + semver.major(v) + '.' + semver.minor(v) + '.0'
            )
          );

          // >= v0.21.0, we require react to be a peer dependency
          if (semver.gte(v, '0.21.0') && !pak.dependencies.react) {
            console.log(
              chalk.yellow(
                '\nYour \'package.json\' file doesn\'t seem to have \'react\' as a dependency.\n' +
                '\'react\' was changed from a dependency to a peer dependency in react-native v0.21.0.\n' +
                'Therefore, it\'s necessary to include \'react\' in your project\'s dependencies.\n' +
                'Just run \'npm install --save react\', then re-run \'react-native upgrade\'.\n'
              )
            );
            return;
          }

          if (semver.satisfies(v, '~0.26.0')) {
            console.log(
              chalk.yellow(
                'React Native 0.26 introduced some breaking changes to the native files on iOS. You can\n' +
                'perform them manually by checking the release notes or use \'rnpm\' to do it automatically.\n' +
                'Just run:\n' +
                '\'npm install -g rnpm && npm install rnpm-plugin-upgrade@0.26 --save-dev\', then run \'rnpm upgrade\''
              )
            );
          }
        } else {
          console.log(
            chalk.yellow(
              'A valid version number for \'react-native\' is not specified in your \'package.json\' file.'
            )
          );
        }
      } else {
        console.warn(
          chalk.yellow(
            'react-native version in \'package.json\' doesn\'t match the installed version in \'node_modules\'.\n' +
            'Try running \'npm install\' to fix the issue.'
          )
        );
      }
    }
  } else {
    console.warn(
      chalk.yellow(
        'Your \'package.json\' file doesn\'t seem to have \'react-native\' as a dependency.'
      )
    );
  }

  const generatorPath = path.join(__dirname, '..', 'generator');
  env.register(generatorPath, 'react:app');
  const generatorArgs = ['react:app', pak.name].concat(args);
  return new Promise((resolve) => env.run(generatorArgs, {upgrade: true}, resolve));
}
Example #18
0
 tPkgs.forEach(function(p) {
   if (config.loader.baseMap[p])
     if (config.loader.baseMap[p].version !== tPackages[p].split('@').pop() && !nodeSemver.satisfies(config.loader.baseMap[p].version, tPackages[p].split('@').pop()))
       ui.log('warn', '`' + p + '@' + config.loader.baseMap[p].version + '` is unsupported for this version of jspm. Use %jspm dl-loader --latest% to update.');
 });
Example #19
0
module.exports.isLessThanWin8 = function() {
  return os.type() === 'Windows_NT' &&
    semver.satisfies(garanteeSemverFormat(os.release()), '<6.2.9200');
};
Example #20
0
 .filter(function(v) {
   return nodeSemver.satisfies(v, version);
 })[0];
Example #21
0
/**
 * @param {string} version
 * @returns {boolean}
 */
function isLegacyVersion(version){
    return semver.satisfies(version, '<0.12.3');
}
Example #22
0
 Object.keys(data.versions).filter(function (v) {
   return semver.satisfies(v, ver)
 }).forEach(function (v) {
Example #23
0
    }

    if (!fs.existsSync(path.resolve(path.join(cfgDir, opts.projFile)))) {
        console.log("ERROR: Cannot find project file: " + opts.projFile);
        process.exit(1);
    }

    // Check version
    var curNpmCfg = path.join(cfgDir, "package.json");
    if (fs.existsSync(curNpmCfg)) {
        curNpmCfg = JSON.parse(fs.readFileSync(curNpmCfg).toString());
        if (curNpmCfg.engines && (curNpmCfg.engines.fable || curNpmCfg.engines["fable-compiler"])) {
            var semver = require("semver");
            var fableRequiredVersion = curNpmCfg.engines.fable || curNpmCfg.engines["fable-compiler"];
            var fableVersion = require("./package.json").version;
            if (!semver.satisfies(fableVersion, fableRequiredVersion)) {
                console.log("Fable version: " + fableVersion);
                console.log("Required: " + fableRequiredVersion);
                console.log("Please upgrade fable-compiler package");
                process.exit(1);
            }
        }
    }
    
    if (opts.verbose) {
        console.log("Fable F# to JS compiler version " + require("./package.json").version);
    }

    if (opts.scripts && opts.scripts.prebuild) {
        runCommand(opts.scripts.prebuild, function (exitCode) {
            if (exitCode == 0)
Example #24
0
Common.sink.resolveInterpreter = function(app) {
  var noInterpreter     = (!app.exec_interpreter || 'none' == app.exec_interpreter),
      extName           = path.extname(app.pm_exec_path),
      betterInterpreter = extItps[extName];

  var thereIsNVMInstalled = false;

  // No interpreter defined and correspondance in schema hashmap
  if (noInterpreter && betterInterpreter)
    app.exec_interpreter = betterInterpreter;
  // Else if no Interpreter detect if process is binary
  else if (noInterpreter)
    app.exec_interpreter = isBinary(app.pm_exec_path) ? 'none' : 'node';
  else if (app.exec_interpreter.indexOf('node@') > -1 ||
           app.node_version && thereIsNVMInstalled) {

    if (!process.env.NVM_DIR) {
      Common.printError(cst.PREFIX_MSG_ERR + chalk.red('NVM is not available in PATH'));
      Common.printError(cst.PREFIX_MSG_ERR + chalk.red('Fallback to node in PATH'));
      Common.printOut(cst.PREFIX_MSG_ERR + chalk.bold('Install NVM:\n$ curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash'));
    }
    else {
      var node_version  = app.exec_interpreter.split('@')[1];
      var nvm_node_path;

      if (semver.satisfies(node_version, '>= 0.12.0'))
        nvm_node_path = path.join(process.env.NVM_DIR, '/versions/node/v' + node_version + '/bin/node');
      else
        nvm_node_path = path.join(process.env.NVM_DIR, '/v' + node_version + '/bin/node');

      try {
        fs.accessSync(nvm_node_path);
      } catch(e) {
        Common.printOut(cst.PREFIX_MSG + 'Installing Node v%s', node_version);
        var nvm_bin = path.join(process.env.NVM_DIR, 'nvm.sh');
        var nvm_cmd = '. ' + nvm_bin + ' ; nvm install ' + node_version;

        Common.printOut(cst.PREFIX_MSG + 'Executing: %s', nvm_cmd);
        shelljs.exec(nvm_cmd);
      }

      Common.printOut(cst.PREFIX_MSG + chalk.green.bold('Setting Node to v%s (path=%s)'),
                      node_version,
                      nvm_node_path);

      app.exec_interpreter = nvm_node_path;
    }
  }

  /**
   * Specific installed JS transpilers
   */
  if (app.exec_interpreter == 'ts-node') {
    app.exec_interpreter = path.join(__dirname, '../node_modules/.bin/ts-node');
  }

  if (app.exec_interpreter == 'lsc') {
    app.exec_interpreter = path.join(__dirname, '../node_modules/.bin/lsc');
  }

  if (app.exec_interpreter == 'coffee') {
    app.exec_interpreter = path.join(__dirname, '../node_modules/.bin/coffee');
  }

  if (app.exec_interpreter != 'none' && shelljs.which(app.exec_interpreter) == null) {
    Common.printError(cst.PREFIX_MSG_ERR + 'Interpreter ' + app.exec_interpreter + ' does not seems to be available');
  }
  return app;
};
 let matchedVersions = mockComponents[this.params.componentName].versions.filter(version => {
     return semver.satisfies(version, versionRange);
 });
Example #26
0
}, function (env) {
    var cwd = argv.cwd || process.cwd();

    var htmllintPath = 'htmllint';

    if (env.modulePath) {
        var cliPackage = require('../package.json'),
            semver = require('semver');

        var acceptedRange = cliPackage.dependencies.htmllint,
            localVersion = env.modulePackage.version;

        if (semver.satisfies(localVersion, acceptedRange)) {
            htmllintPath = env.modulePath;
        } else {
            console.log(
                chalk.red('local htmllint version is not supported:'),
                chalk.magenta(localVersion, '!=', acceptedRange)
            );
            console.log('using builtin version of htmllint');
        }
    }

    var htmllint = require(htmllintPath);
    var formatters = require('../lib/formatters');

    if (args[0] === 'init') {
        // copy .htmllintrc file
        var srcPath = path.join(__dirname, '../lib/default_cfg.json'),
            outputPath = path.join(env.cwd, '.htmllintrc');

        var opts = htmllint.Linter.getOptions('default'),
            config = JSON.stringify(opts, null, 4);
        config = '{\n    "plugins": [],  // npm modules to load\n'
               + config.slice(1);

        fs.writeFile(outputPath, config, function (err) {
            if (err) {
                console.error('error writing config file: ', err);
            }
        });
        return;
    }

    if (!env.configPath) {
        console.log(
            chalk.red('local .htmllintrc file not found'),
            '(you can create one using "htmllint init")'
        );
        process.exit(1);
    }

    var cfg = cjson.load(env.configPath);

    htmllint.use(cfg.plugins || []);
    delete cfg.plugins;

    if (argv.stdin) {
        args.unshift(STDIN_FILENO);
    }
    if (!args.length) {
        args = ['**/*.html'];
    }

    function lintFile(filename) {
        var p;
        if (filename === STDIN_FILENO) {
            filename = argv.stdin === true ? 'stdin' : argv.stdin;
            p = new Promise(function (resolve, reject) {
                process.stdin.resume();
                process.stdin.setEncoding('utf8');

                var content = '';
                process.stdin.on('data', function (chunk) {
                    content += chunk;
                });
                process.stdin.on('end', function () {
                    resolve(content);
                });
                process.stdin.on('error', function (err) {
                    reject(err);
                });
            });
        } else {
            var filepath = path.resolve(cwd, filename);
            p = readFilePromise(filepath, 'utf8');
        }

        return p.then(function (src) {
                return htmllint(src, cfg);
            })
            .then(function (issues) {
                formatters.formatMessage.call(htmllint, argv.format, filename, issues);
                return { errorCount: issues.length };
            })
            .catch(function (err) {
                // MC: muahahahahah :D
                throw ('[htmllint error in ' + filename + ' ] ' + err);
            });
    }

    Promise.all(
        args.map(function (pattern) {
            if (pattern === STDIN_FILENO) {
                return STDIN_FILENO;
            }
            return globPromise(pattern, { cwd: cwd });
        })
    ).then(function (filesArr) {
        var files = Array.prototype.concat.apply([], filesArr);

        return Promise.settle(
            files.map(lintFile)
        );
    }, function (err) {
        console.error(chalk.red.bold('error during glob expansion:'), err);
    }).done(function (results) {
        var errorCount = 0;

        results.forEach(function (result) {
            if (result.isFulfilled()) {
                var resultValue = result.value();

                errorCount += resultValue.errorCount;
            } else {
                console.error(chalk.bold.red(result.reason()));
            }
        });

        formatters.done.call(htmllint, argv.format, errorCount, results.length);

        if (errorCount > 0) {
            process.exit(1);
        }
    });
});
Example #27
0
'use babel'

import environmentHelpers from './environment-helpers'
import semver from 'semver'

export default {
  activate () {
    if (semver.satisfies(this.version(), '<1.7.0')) {
      environmentHelpers.normalize()
    }
  },

  deactivate () {
  },

  provide () {
    return Object.assign({}, process.env)
  },

  version () {
    return semver.major(atom.appVersion) + '.' + semver.minor(atom.appVersion) + '.' + semver.patch(atom.appVersion)
  }
}
Example #28
0
Context.prototype.load = function load(logger, config, cli, callback) {
	if (this.loaded) {
		callback(null, this);
	} else if (!this.path) {
		logger.error(__('Unable to load "%s" command because command file path unknown', this.name) + '\n');
		process.exit(1);
	} else if (!fs.existsSync(this.path)) {
		logger.error(__('Unable to load "%s" command because command file path does not exist', this.name));
		logger.error(__('Command file: %s', this.path) + '\n');
		process.exit(1);
	} else {
		// load the command module
		try {
			vm.runInThisContext('(function (exports, require, module, __filename, __dirname) { ' + fs.readFileSync(this.path).toString() + '\n});', this.path, 0, false);
			this.module = require(this.path);
			this.conf = {};
			this.loaded = true;
		} catch (ex) {
			// if the command fails to load, then we simply ignore it exists
			callback(new AppcException(ex.toString().trim(), '   at ' + this.path), this);
			return;
		}

		// check if this command is compatible with this version of the CLI
		if (this.module.cliVersion && !semver.satisfies(appc.version.format(cli.version, 0, 3, true), this.module.cliVersion)) {
			logger.banner();
			logger.error(__('Command "%s" incompatible with this version of the CLI', this.name));
			logger.error(__('Requires version %s, currently %s', this.module.cliVersion, cli.version) + '\n');
			process.exit(1);
		}

		// load the commands configuration
		var conf = (typeof this.module.config == 'function' && this.module.config(logger, config, cli)),
			processConf = function processConf(conf) {
				this.conf = conf = conf || {};
				this.module.title && (this.title = this.module.title);
				this.module.desc && (this.desc = this.module.desc);
				this.module.extendedDesc && (this.extendedDesc = this.module.extendedDesc);
				this.loaded = true;

				// old SDKs have their own --sdk option, but now it's global
				if (this.parent && conf.options) {
					delete conf.options.sdk;
				}

				// set the flags and options
				conf.flags && this.flag(conf.flags);
				conf.options && this.option(conf.options);
				conf.args && (this.args = conf.args);
				conf.subcommands && this.subcommand(conf.subcommands);

				// needed for backwards compatibility for Titanium SDKs 3.0.x and 3.1.x
				cli.sdk && Object.defineProperty(this, cli.sdk.name, {
					enumerable: false,
					value: {
						__global__: this
					}
				});

				if (!cli.argv) {
					return callback(null, this);
				}

				// parse the args to get the --platform
				var argv = this.parse(cli.argv.$_, Object.keys(this.commands).length ? Object.keys(this.commands) : [this.name]),
					isHelpCommand = cli.argv.$command == 'help';

				var options = this.options,
					finish = function () {
						// apply missing option defaults
						Object.keys(options).forEach(function (name) {
							if (!argv.hasOwnProperty(name) && options[name].default) {
								argv[name] = options[name].default;
							}
						});

						// mix our new argv into the existing argv
						mix(cli.argv, argv);

						// complete the load() call
						callback(null, this);
					}.bind(this);

				if (options.platform) {
					var loadPlatform = function loadPlatform() {
						if (conf.platforms && conf.platforms.hasOwnProperty(argv.platform) && cli.sdk && cli.sdk.path) {
							var platformConf = conf.platforms[argv.platform],
								platformContext = new Context({
									title: platformConf.title || argv.platform,
									name: argv.platform,
									path: path.join(cli.sdk.path, argv.platform) || '',
									conf: platformConf,
									parent: this
								});

							this.platform = platformContext;

							// set the platforms for 3.0 and 3.1 builds
							this.platforms[this.platform.name] = this.platform;

							options = platformContext.options;
							mix(argv, platformContext.parse(cli.argv.$_, [this.name]));
							argv.platform = platformContext.name;
							argv.$platform = argv.platform;

							// find all platform hooks
							cli.scanHooks(path.join(cli.sdk.path, platformContext.name, 'cli', 'hooks'));

							// TODO: add support for platform level subcommands (hasn't been needed yet)
						}
					}.bind(this);

					if (!isHelpCommand && argv.platform) {
						// --platform was set, the load only that platform
						loadPlatform();

					} else if (!isHelpCommand && options.platform.required) {
						if (argv.prompt) {
							// no --platform, but it's required, so prompt for it
							logger.banner();

							fields.select({
								title: __('Target platform to build for:'),
								complete: true,
								completeIgnoreCase: true,
								suggest: true,
								suggestThreshold: 2,
								numbered: true,
								margin: '',
								promptLabel: __('Enter # or platform name'),
								relistOnError: true,
								options: options.platform.values,
								validate: options.platform.prompt.validate || function (value) {
									// first run the sdk's platform validator
									if (options.platform.prompt.validator) {
										try {
											options.platform.prompt.validator(value);
										} catch (ex) {
											if (ex.type == 'AppcException') {
												ex.dump(logger);
											} else {
												logger.log();
												logger.error(ex.message || ex);
												logger.log();
											}
											return false;
										}
									} else if (!value.length || (options.platform.prompt.pattern && !options.platform.prompt.pattern.test(value))) {
										logger.error(options.platform.prompt.error);
										return false;
									}
									return true;
								}
							}).prompt(function (err, platform) {
								logger.log();
								if (err) {
									logger.log();
									process.exit(1);
								}

								// the option should probably have a callback, so fire it
								if (options.platform.callback) {
									platform = options.platform.callback(platform);
								}

								// set the platform we just prompted for
								argv.platform = platform;

								if (!conf.platforms || !conf.platforms.hasOwnProperty(platform)) {
									logger.error(__('Unable to find platform configuration for "%s"', platform));
									logger.log();
									process.exit(1);
								}

								loadPlatform();
								finish();
							});
						} else {
							logger.banner();
							logger.error(__('Missing required option "--platform"') + '\n');
							logger.log(__('Available Platforms:'));
							options.platform.values.forEach(function (v) {
								logger.log('   ' + v.cyan);
							});
							logger.log();
							process.exit(1);
						}
						return;

					} else if (conf.platforms && (isHelpCommand || (cli.sdk && cli.sdk.path))) {
						// no platform specified, load all platforms and set their options and flags
						Object.keys(conf.platforms).forEach(function (platform) {
							this.platforms[platform] = new Context({
								title: conf.platforms[platform].title || platform,
								name: platform,
								path: path.join(cli.sdk.path, platform) || '',
								conf: conf.platforms[platform],
								parent: this
							});
						}, this);
					}

				} else {
					// no platform option

					// check if this command has any subcommands, if so, parse the args again
					if (Object.keys(this.subcommands).length) {
						var subcmd = argv._.length && argv._[0] || conf.defaultSubcommand,
							subcommandContext = this.subcommands[subcmd];
						if (subcommandContext) {
							// parse the args again to get any subcommand flags/options
							argv = subcommandContext.parse(cli.argv.$_, Object.keys(this.subcommands).concat(this.name));
							argv.$subcommand = subcmd;
							options = subcommandContext.options;
						}
					}
				}

				finish();
			}.bind(this),
			done = 0;

		if (typeof conf == 'function') {
			conf(function (realConf) {
				if (done++) return; // if callback is fired more than once, just ignore
				processConf(realConf);
			}.bind(this));
		} else {
			processConf(conf);
		}
	}
};
Example #29
0
 Object.keys(controllersFor).forEach(function (dependency) {
   if (!semver.satisfies(release, dependency)) return;
   controllersInRelease = controllersInRelease.concat(controllersFor[dependency]);
 });
Example #30
0
  var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) {
    let errCount = 0;
    function reportError(msg) {
      for (var _len = arguments.length, vars = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        vars[_key - 1] = arguments[_key];
      }

      reporter.error(reporter.lang(msg, ...vars));
      errCount++;
    }
    // check all dependencies recursively without relying on internal resolver
    const registryName = 'yarn';
    const registry = config.registries[registryName];
    const rootManifest = yield config.readManifest(registry.cwd, registryName);

    const dependenciesToCheckVersion = [];
    if (rootManifest.dependencies) {
      for (const name in rootManifest.dependencies) {
        dependenciesToCheckVersion.push({
          name,
          originalKey: name,
          parentCwd: registry.cwd,
          version: rootManifest.dependencies[name]
        });
      }
    }
    if (rootManifest.devDependencies && !config.production) {
      for (const name in rootManifest.devDependencies) {
        dependenciesToCheckVersion.push({
          name,
          originalKey: name,
          parentCwd: registry.cwd,
          version: rootManifest.devDependencies[name]
        });
      }
    }

    const locationsVisited = new Set();
    while (dependenciesToCheckVersion.length) {
      const dep = dependenciesToCheckVersion.shift();
      const manifestLoc = path.join(dep.parentCwd, registry.folder, dep.name);
      if (locationsVisited.has(manifestLoc + `@${dep.version}`)) {
        continue;
      }
      locationsVisited.add(manifestLoc + `@${dep.version}`);
      if (!(yield (_fs || _load_fs()).exists(manifestLoc))) {
        reportError('packageNotInstalled', `${dep.originalKey}`);
        continue;
      }
      const pkg = yield config.readManifest(manifestLoc, registryName);
      if (semver.validRange(dep.version, config.looseSemver) && !semver.satisfies(pkg.version, dep.version, config.looseSemver)) {
        reportError('packageWrongVersion', dep.originalKey, dep.version, pkg.version);
        continue;
      }
      const dependencies = pkg.dependencies;
      if (dependencies) {
        for (const subdep in dependencies) {
          const subDepPath = path.join(manifestLoc, registry.folder, subdep);
          let found = false;
          const relative = path.relative(registry.cwd, subDepPath);
          const locations = path.normalize(relative).split(registry.folder + path.sep).filter(function (dir) {
            return !!dir;
          });
          locations.pop();
          while (locations.length >= 0) {
            let possiblePath;
            if (locations.length > 0) {
              possiblePath = path.join(registry.cwd, registry.folder, locations.join(path.sep + registry.folder + path.sep));
            } else {
              possiblePath = registry.cwd;
            }
            if (yield (_fs || _load_fs()).exists(path.join(possiblePath, registry.folder, subdep))) {
              dependenciesToCheckVersion.push({
                name: subdep,
                originalKey: `${dep.originalKey}#${subdep}`,
                parentCwd: possiblePath,
                version: dependencies[subdep]
              });
              found = true;
              break;
            }
            if (!locations.length) {
              break;
            }
            locations.pop();
          }
          if (!found) {
            reportError('packageNotInstalled', `${dep.originalKey}#${subdep}`);
          }
        }
      }
    }

    if (errCount > 0) {
      throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount));
    } else {
      reporter.success(reporter.lang('folderInSync'));
    }
  });