Example #1
0
#!/usr/bin/env node

'use strict';

var fs = require('fs');
var semver = require('semver');

var npmData = require(__dirname + '/../package.json');
var currentVersion = npmData.version;
var versionArg = process.argv[process.argv.length - 1];
var newVersion = semver.valid(versionArg);
if (!newVersion) {
  newVersion = semver.inc(currentVersion, versionArg);
}
if (!newVersion) {
  console.error('Version not changed');
  process.exit(1);
}

npmData.version = newVersion;
fs.writeFileSync('package.json', JSON.stringify(npmData, null, 2) + '\n'), {
  encoding: 'utf8'
};

var bowerData = require(__dirname + '/../bower.json');
bowerData.version = newVersion;
fs.writeFileSync('bower.json', JSON.stringify(bowerData, null, 2) + '\n', {
  encoding: 'utf8'
});

console.log('Version ' + newVersion);
Example #2
0
						validate: function (value) {
							var valid = semver.valid(value);
							return valid || 'Must be a valid semver, such as 1.2.3-rc1. See http://semver.org/ for more details.';
						}
Example #3
0
/* eslint no-console:0 max-len:0 */
import fs from 'fs';
import path from 'path';

import mversion from 'mversion';

import semver from 'semver';
import currentVersion from '../src/version.js';

if (!process.env.VERSION) {
  throw new Error('bump: Usage is VERSION=MAJOR.MINOR.PATCH scripts/bump-package-version.js');
}
let newVersion = process.env.VERSION;

if (!semver.valid(newVersion)) {
  throw new Error('bump: Provided new version (' + newVersion + ') is not a valid version per semver');
}

if (semver.gte(currentVersion, newVersion)) {
  throw new Error('bump: Provided new version is not higher than current version (' + newVersion + ' <= ' + currentVersion + ')');
}

console.log('Bumping ' + newVersion);

console.log('..Updating src/version.js');

let versionFile = path.join(__dirname, '../src/version.js');
let newContent = "export default '" + newVersion + "';\n";
fs.writeFileSync(versionFile, newContent);

console.log('..Updating package.json');
Example #4
0
 return semver.maxSatisfying(servers.map(function (server) {
   return semver.valid(server.version) && server.version
 }), version)
Example #5
0
function validateSemver (data, k, val) {
  if (!semver.valid(val)) return false
  data[k] = semver.valid(val)
}
Example #6
0
updates.package = function (doc, req) {
  require("monkeypatch").patch(Object, Date, Array, String)

  var semver = require("semver")
  var valid = require("valid")
  function error (reason) {
    return [{_id: "error: forbidden", forbidden:reason}, JSON.stringify({forbidden:reason})]
  }

  function ok (doc, message) {
    delete doc.mtime
    delete doc.ctime
    var time = doc.time = doc.time || {}
    time.modified = (new Date()).toISOString()
    time.created = time.created || time.modified
    for (var v in doc.versions) {
      var ver = doc.versions[v]
      delete ver.ctime
      delete ver.mtime
      time[v] = time[v] || (new Date()).toISOString()
    }
    return [doc, JSON.stringify({ok:message})]
  }

  if (doc) {
    if (req.query.version) {
      var parsed = semver.valid(req.query.version)
      if (!parsed) {
        // it's a tag.
        var tag = req.query.version
          , ver = JSON.parse(req.body)
        if (!semver.valid(ver)) {
          return error("setting tag "+tag+" to invalid version: "+req.body)
        }
        doc["dist-tags"][tag] = semver.clean(ver)
        return ok(doc, "updated tag")
      }
      // adding a new version.
      var ver = req.query.version
      if (!semver.valid(ver)) {
        return error("invalid version: "+ver)
      }

      if ((ver in doc.versions) || (semver.clean(ver) in doc.versions)) {
        // attempting to overwrite an existing version.
        // not supported at this time.
        if (!req.query.rev || req.query.rev !== doc._rev) {
          return error("cannot modify existing version")
        }
      }

      var body = JSON.parse(req.body)
      if (!valid.name(body.name)) {
        return error( "Invalid name: "+JSON.stringify(body.name))
      }
      body.version = semver.clean(body.version)
      ver = semver.clean(ver)
      if (body.version !== ver) {
        return error( "version in doc doesn't match version in request: "
                    + JSON.stringify(body.version)
                    + " !== " + JSON.stringify(ver) )
      }
      body._id = body.name + "@" + body.version
      if (body.description) doc.description = body.description
      if (body.author) doc.author = body.author
      if (body.repository) doc.repository = body.repository
      body.maintainers = doc.maintainers

      if (body.publishConfig && typeof body.publishConfig === 'object') {
        Object.keys(body.publishConfig).filter(function (k) {
          return k.match(/^_/)
        }).forEach(function (k) {
          delete body.publishConfig[k]
        })
      }

      var tag = req.query.tag
              || (body.publishConfig && body.publishConfig.tag)
              || body.tag
              || "latest"

      if (!req.query.pre)
        doc["dist-tags"][tag] = body.version
      if (!doc["dist-tags"].latest)
        doc["dist-tags"].latest = body.version
      doc.versions[ver] = body
      doc.time = doc.time || {}
      doc.time[ver] = (new Date()).toISOString()
      return ok(doc, "added version")
    }

    // update the package info
    var newdoc = JSON.parse(req.body)
      , changed = false
    if (doc._rev && doc._rev !== newdoc._rev) {
      return error( "must supply latest _rev to update existing package" )
    }
    for (var i in newdoc) if (typeof newdoc[i] === "string" || i === "maintainers") {
      doc[i] = newdoc[i]
    }
    if (newdoc.versions) {
      doc.versions = newdoc.versions
    }
    if (newdoc["dist-tags"]) {
      doc["dist-tags"] = newdoc["dist-tags"]
    }
    if (newdoc.users) {
      if (!doc.users) doc.users = {}
      doc.users[req.userCtx.name] = newdoc.users[req.userCtx.name]
    }
    return ok(doc, "updated package metadata")
  } else {
    // Create new package doc
    doc = JSON.parse(req.body)
    if (!doc._id) doc._id = doc.name
    if (!doc.versions) doc.versions = {}
    var latest
    for (var v in doc.versions) {
      if (!semver.valid(v)) return error("Invalid version: "+JSON.stringify(v))
      var p = doc.versions[v]
      if (p.version !== v) return error("Version mismatch: "+JSON.stringify(v)
                                       +" !== "+JSON.stringify(p.version))
      if (!valid.name(p.name)) return error("Invalid name: "+JSON.stringify(p.name))
      latest = semver.clean(v)
    }
    if (!doc['dist-tags']) doc['dist-tags'] = {}
    if (latest) doc["dist-tags"].latest = latest
    return ok(doc, "created new entry")
  }
}
Example #7
0
'use strict';
var fs = require('fs'),
    path = require('path'),
    version = require('../package').version,
    semver = require('semver'),
    script = process.argv[1];

if (process.argv[2] && semver.valid(process.argv[2]) === process.argv[2]) {
  main(process.argv[2]);
} else if (process.argv[2] === 'commit') {
  fs.readFile(path.join(__dirname, 'pre-version'), 'utf8', function (err, v) {
    if (err) {
      // nothing to do
      process.exit(1);
    }
    fs.unlink(path.join(__dirname, 'pre-version'));
    main(v.trim());
  });
} else {
  console.log('Either test with `' + script + ' <prev-version>`\nor `' + script + ' commit` to run in live mode');
}

function main(oldVersion) {
  console.log('[jsbin post-update] Testing if there is any migration from ' + oldVersion + ' -> ' + version);

  return getVersions(oldVersion, version);
}

function getVersionUpdate(file) {
  return new Promise(function (resolve) {
    var dir = path.join(__dirname, 'upgrade', file);
Example #8
0
function valid(x) {
  return semver.valid(x, true);
}
Example #9
0
function processObject (opts, cb) { return function (er, json) {

  // slashes would be a security risk.
  // anything else will just fail harmlessly.
  if (!json.name) {
    var e = new Error("No 'name' field found in package.json")
    if (cb) return cb(e)
    throw e
  }
  json.name = json.name.trim()
  if (json.name.charAt(0) === "." || json.name.match(/[\/@\s\+%:]/)) {
    var msg = "Invalid name: "
            + JSON.stringify(json.name)
            + " may not start with '.' or contain %/@+: or whitespace"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  if (json.name.toLowerCase() === "node_modules") {
    var msg = "Invalid package name: node_modules"
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }
  if (json.name.toLowerCase() === "favicon.ico") {
    var msg = "Sorry, favicon.ico is a picture, not a package."
      , e = new Error(msg)
    if (cb) return cb(e)
    throw e
  }

  if (json.repostories) {
    var msg = "'repositories' (plural) No longer supported.\n"
            + "Please pick one, and put it in the 'repository' field."
      , e = new Error(msg)
    // uncomment once this is no longer an issue.
    // if (cb) return cb(e)
    // throw e
    log.error(msg, "incorrect json")
    json.repostory = json.repositories[0]
    delete json.repositories
  }

  if (json.repository) {
    if (typeof json.repository === "string") {
      json.repository = { type : "git"
                        , url : json.repository }
    }
    var repo = json.repository.url || ""
    repo = repo.replace(/^(https?|git):\/\/[^\@]+\@github.com/
                       ,'$1://github.com')
    if (json.repository.type === "git"
        && ( repo.match(/^https?:\/\/github.com/)
          || repo.match(/github.com\/[^\/]+\/[^\/]+\/?$/)
             && !repo.match(/\.git$/)
        )) {
      repo = repo.replace(/^https?:\/\/github.com/, 'git://github.com')
      if (!repo.match(/\.git$/)) {
        repo = repo.replace(/\/?$/, '.git')
      }
    }
    if (repo.match(/github\.com\/[^\/]+\/[^\/]+\/?$/)
        && repo.match(/\.git\.git$/)) {
      log.warn(repo, "Probably broken git url")
    }
    json.repository.url = repo
  }

  var kw = json.keywords
  if (typeof kw === "string") {
    kw = kw.split(/,\s+/)
    json.keywords = kw
  }

  var tag = opts.tag
  if (tag) json.version = tag//+"-"+json.version

  if (json.modules) {
    if (typeof json.modules !== "object") {
      var e = new Error("Invalid modules object")
      if (cb) return cb(e)
      throw e
    }
    Object.keys(json.modules).forEach(function (mod) {
      if (typeof json.modules[mod] !== "string") {
        var e = new Error("Invalid module "+mod+", not a string: "
                         +JSON.stringify(json.modules[mod]))
        if (cb) return cb(e)
        throw e
      }
    })
  }

  if (opts.wscript) {
    var scripts = json.scripts = json.scripts || {}
    if (!scripts.install && !scripts.preinstall) {
      // don't fail if it was unexpected, just try.
      scripts.preinstall = "node-waf clean || true; node-waf configure build"
    }
  }

  if (!(semver.valid(json.version))) {
    var e = new Error("Invalid version: "+json.version+"\n"
                     +"Must be X.Y.Z, with an optional trailing tag.\n"
                     +"See the section on 'version' in `npm help json`")
    if (cb) return cb(e)
    throw e
  }
  json.version = semver.clean(json.version)

  if (json.bin && typeof json.bin === "string") {
    var b = {}
    b[ json.name ] = json.bin
    json.bin = b
  }

  if (json["dev-dependencies"] && !json.devDependencies) {
    json.devDependencies = json["dev-dependencies"]
    delete json["dev-dependencies"]
  }
  ;["dependencies", "devDependencies"].forEach(function (d) {
    if (!json[d]) return
    json[d] = depObjectify(json[d])
  })
  if (npm.config.get("dev") || npm.config.get("npat")) {
    Object.keys(json.devDependencies || {}).forEach(function (d) {
      json.dependencies[d] = json.devDependencies[d]
    })
  }


  json._id = json.name+"@"+json.version
  json = testEngine(json)
  json = parsePeople(unParsePeople(json))
  if ( json.bugs ) json.bugs = parsePerson(unParsePerson(json.bugs))
  json._npmVersion = npm.version
  json._nodeVersion = process.version
  if (opts.file) {
    log.verbose(opts.file, "caching")
    cache[opts.file] = json
    // arbitrary
    var keys = Object.keys(cache)
      , l = keys.length
    if (l > 10000) for (var i = 0; i < l - 5000; i ++) {
      delete cache[keys[i]]
    }
  }
  if (cb) cb(null,json)
  return json
}}
Example #10
0
  grunt.registerTask('bumpnexus', 'Task to bump nexus deployment files', function(release) {


    var options = this.options({
      backup : true
    });

    if(!options.project){

      grunt.fail.fatal('No project found to update!');

    }

    if(!options.version_identifier){

      grunt.fail.fatal('No version identifier found to bump!');

    }

    var src = grunt.file.expand(options.files).filter(function(filepath){

      // Warn on and remove invalid source files (if nonull was set).
      if (!grunt.file.exists(filepath)) {

        grunt.log.warn('Source file "' + filepath + '" not found.');

        return false;

      } else {

        return true;

      }

    });

    if (src.length === 0) {

      grunt.log.warn('Could not bump nexus deployment file because src files were empty.');

      return;

    }

    if(options.backup){

      var _backup_dest = '';

      src.forEach(function(filepath){

        if(options.backup_dest){

          _backup_dest = path.normalize(options.backup_dest);

        } else {

          _backup_dest = path.dirname(filepath) + path.sep;

        }

        try{

        // Copy file from filepath to dest, append .bak
        fs.writeFileSync( _backup_dest + Date.now() + '_' + path.basename(filepath) + '.bak', fs.readFileSync(filepath));

        grunt.verbose.ok("Copyied file successfully to : '" + _backup_dest + Date.now() + '_' + path.basename(filepath) + '.bak' + "'")

        } catch(ex){

          grunt.fail.warn(ex);
        }

      });

    }

    release     = release || 'patch';

    if(
      release === 'major' ||
      release === 'minor' ||
      release === 'patch' ||
      release === 'prerelease' ||
      semver.valid(release)
    ){

      src.forEach(function(filepath){

        var config          = ini.parse(fs.readFileSync(filepath, 'utf-8'));
        var _config_version = config[ options.project ][ options.version_identifier ];

        if( semver.valid( _config_version ) ){

          grunt.verbose.ok("Version in '" + filepath + "': '" + _config_version + "' is valid, continuing..");

          config[ options.project ][ options.version_identifier ] = semver.inc( _config_version, release );

          try{

            fs.writeFileSync( filepath, ini.stringify( config ) );

            grunt.verbose.write("Wrote file: '"+ filepath +"' with updated version: '" + config[ options.project ][ options.version_identifier ] + "'" );

          } catch(e){

            grunt.fail.fatal("Could not write '" + filepath + "'!");
          }

        } else {

          grunt.fail.fatal("Version in '" + filepath + "': '" + _config_version + "' is NOT valid!");

        }


      });





    } else {

      grunt.fail.fatal('Could not update nexus configuration file for release: ' + release + ". Allowed releases are: 'major', 'minor', 'patch', 'prerelase' or a given valid semver version.");

    }

  });
Example #11
0
		}).filter(function (i) {
			// exclude falsy values and filenames that without a valid semver
			return i && semver.valid(i.split('-')[0]);
		}).sort(function (a, b) {
Example #12
0
 versions = versions.filter(function (ver) {
   return semver.valid(ver);
 });
Example #13
0
updates.package = function (doc, req) {
  require("monkeypatch").patch(Object, Date, Array, String)

  var semver = require("semver")
  var valid = require("valid")
  function error (reason) {
    return [{_id: "_error_", forbidden:reason}, JSON.stringify({forbidden:reason})]
  }

  function ok (doc, message) {
    delete doc.mtime
    delete doc.ctime
    var time = doc.time = doc.time || {}
    time.modified = (new Date()).toISOString()
    time.created = time.created || time.modified
    for (var v in doc.versions) {
      var ver = doc.versions[v]
      delete ver.ctime
      delete ver.mtime
      time[v] = time[v] || (new Date()).toISOString()
    }
    readmeTrim(doc)
    return [doc, JSON.stringify({ok:message})]
  }

  var README_MAXLEN = 64 * 1024

  function readmeTrim(doc) {
    var changed = false
    var readme = doc.readme || ''
    var readmeFilename = doc.readmeFilename || ''
    if (doc['dist-tags'] && doc['dist-tags'].latest) {
      var latest = doc.versions[doc['dist-tags'].latest]
      if (latest && latest.readme) {
        readme = latest.readme
        readmeFilename = latest.readmeFilename || ''
      }
    }

    for (var v in doc.versions) {
      // If we still don't have one, just take the first one.
      if (doc.versions[v].readme && !readme)
        readme = doc.versions[v].readme
      if (doc.versions[v].readmeFilename && !readmeFilename)
        readmeFilename = doc.versions[v].readmeFilename

      if (doc.versions[v].readme)
        changed = true

      delete doc.versions[v].readme
      delete doc.versions[v].readmeFilename
    }

    if (readme && readme.length > README_MAXLEN) {
      changed = true
      readme = readme.slice(0, README_MAXLEN)
    }
    doc.readme = readme
    doc.readmeFilename = readmeFilename

    return changed
  }

  if (doc) {
    if (req.query.version) {
      var parsed = semver.valid(req.query.version, true)
      if (!parsed) {
        // it's a tag.
        var tag = req.query.version
          , ver = JSON.parse(req.body)
        if (!semver.valid(ver)) {
          return error("setting tag "+tag+" to invalid version: "+req.body)
        }
        doc["dist-tags"][tag] = semver.clean(ver, true)
        return ok(doc, "updated tag")
      }
      // adding a new version.
      var ver = req.query.version
      if (!semver.valid(ver, true)) {
        return error("invalid version: "+ver)
      }

      if ((ver in doc.versions) || (semver.clean(ver, true) in doc.versions)) {
        // attempting to overwrite an existing version.
        // not allowed
        return error("cannot modify existing version")
      }

      var body = JSON.parse(req.body)
      if (!valid.name(body.name)) {
        return error( "Invalid name: "+JSON.stringify(body.name))
      }
      body.version = semver.clean(body.version, true)
      ver = semver.clean(ver, true)
      if (body.version !== ver) {
        return error( "version in doc doesn't match version in request: "
                    + JSON.stringify(body.version)
                    + " !== " + JSON.stringify(ver) )
      }
      body._id = body.name + "@" + body.version
      if (body.description) doc.description = body.description
      if (body.author) doc.author = body.author
      if (body.repository) doc.repository = body.repository
      body.maintainers = doc.maintainers

      if (body.publishConfig && typeof body.publishConfig === 'object') {
        Object.keys(body.publishConfig).filter(function (k) {
          return k.match(/^_/)
        }).forEach(function (k) {
          delete body.publishConfig[k]
        })
      }

      var tag = req.query.tag
              || (body.publishConfig && body.publishConfig.tag)
              || body.tag
              || "latest"

      if (!req.query.pre)
        doc["dist-tags"][tag] = body.version
      if (!doc["dist-tags"].latest)
        doc["dist-tags"].latest = body.version
      doc.versions[ver] = body
      doc.time = doc.time || {}
      doc.time[ver] = (new Date()).toISOString()
      return ok(doc, "added version")
    }

    // update the package info
    var newdoc = JSON.parse(req.body)
      , changed = false
    if (doc._rev && doc._rev !== newdoc._rev) {
      return [newdoc, JSON.stringify({error:'409 should happen now'})]
    }
    for (var i in newdoc) if (typeof newdoc[i] === "string" || i === "maintainers") {
      doc[i] = newdoc[i]
    }
    if (newdoc.versions) {
      if (!doc.versions) doc.versions = {}
      // Make sure that we record the maintainers list on the new version
      for (var v in newdoc.versions) {
        if (!doc.versions[v]) {
          var vc = semver.clean(v, true)
          if (!vc)
            return error('Invalid version: ' + v)
          doc.versions[vc] = newdoc.versions[v]
          doc.versions[vc].version = vc
          doc.versions[vc].maintainers = doc.maintainers
          doc.time[vc] = new Date().toISOString()
        }
      }
      for (var v in doc.versions) {
        if (!newdoc.versions[v])
          delete doc.versions[v]
      }
    }
    if (newdoc["dist-tags"]) {
      doc["dist-tags"] = newdoc["dist-tags"]
    }
    if (newdoc.users) {
      if (!doc.users) doc.users = {}
      if (newdoc.users[req.userCtx.name])
        doc.users[req.userCtx.name] = newdoc.users[req.userCtx.name]
      else
        delete doc.users[req.userCtx.name]
    }

    if (newdoc._attachments) {
      if (!doc._attachments) doc._attachments = {}
      var inline = false
      for(var k in newdoc._attachments) {
        if(newdoc._attachments[k].data) {
          doc._attachments[k] = newdoc._attachments[k]
          inline = true
        }
      }
      if (inline)
        return ok(doc, "updated package metadata & attachments")
    }

    return ok(doc, "updated package metadata")
  } else {
    // Create new package doc
    doc = JSON.parse(req.body)
    if (!doc._id) doc._id = doc.name
    if (!doc.versions) doc.versions = {}
    var latest
    for (var v in doc.versions) {
      if (!semver.valid(v, true)) return error("Invalid version: "+JSON.stringify(v))
      var p = doc.versions[v]
      if (p.version !== v) return error("Version mismatch: "+JSON.stringify(v)
                                       +" !== "+JSON.stringify(p.version))
      if (!valid.name(p.name)) return error("Invalid name: "+JSON.stringify(p.name))
      latest = semver.clean(v, true)
    }
    if (!doc['dist-tags']) doc['dist-tags'] = {}
    if (latest) doc["dist-tags"].latest = latest

    return ok(doc, "created new entry")
  }
}
Example #14
0
				var versionsByDate = Object.keys(time).filter(function (ver) {
					return semver.valid(ver, true);
				}).reduce(function(versions, version) {
Example #15
0
      `The package "${packageName}" does not exist in this project. ` +
        'Choose again: '
    )
  }

  const versionLoc = path.resolve(PACKAGES_SRC_DIR, packageName, 'VERSION')
  const version = fs.readFileSync(versionLoc, 'utf8').trim()

  let nextVersion = readline.question(
    `Next version of ${packageName} (current version is ${version}): `
  )

  while (
    !(
      !nextVersion ||
      (semver.valid(nextVersion) && semver.gt(nextVersion, version))
    )
  ) {
    nextVersion = readline.question(
      `Must provide a valid version that is greater than ${version}, ` +
        'or leave blank to skip: '
    )
  }

  log('Running tests...')

  if (exec('yarn run lint && yarn test').code !== 0) {
    logError('The test command did not exit cleanly. Aborting release.')
    exit(1)
  }
Example #16
0
 validate: v => semver.valid(v) ? true : "Must be a valid semver version",
Example #17
0
  },

  rollbackTransactionQuery(transaction, options) {
    if (transaction.parent) {
      return 'ROLLBACK TRANSACTION ' + this.quoteIdentifier(transaction.name) + ';';
    }

    return 'ROLLBACK TRANSACTION;';
  },

  selectFromTableFragment(options, model, attributes, tables, mainTableAs, where) {
    var topFragment = '';
    var mainFragment = 'SELECT ' + attributes.join(', ') + ' FROM ' + tables;

    // Handle SQL Server 2008 with TOP instead of LIMIT
    if (semver.valid(this.sequelize.options.databaseVersion) && semver.lt(this.sequelize.options.databaseVersion, '11.0.0')) {
      if (options.limit) {
        topFragment = 'TOP ' + options.limit + ' ';
      }
      if (options.offset) {
        var offset = options.offset || 0
          , isSubQuery = options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation
          , orders = { mainQueryOrder: [] };
        if (options.order) {
          orders = this.getQueryOrders(options, model, isSubQuery);
        }

        if(!orders.mainQueryOrder.length) {
          orders.mainQueryOrder.push(this.quoteIdentifier(model.primaryKeyField));
        }
Example #18
0
File: npa.js Project: 4872866/node
function npa (arg) {
  assert.equal(typeof arg, "string")
  arg = arg.trim()

  var res = new Result
  res.raw = arg
  res.scope = null

  // See if it's something like foo@...
  var nameparse = arg.match(nameAt)
  debug("nameparse", nameparse)
  if (nameparse && validName(nameparse[3]) &&
      (!nameparse[2] || validName(nameparse[2]))) {
    res.name = (nameparse[1] || "") + nameparse[3]
    if (nameparse[2])
      res.scope = "@" + nameparse[2]
    arg = arg.substr(nameparse[0].length)
  } else {
    res.name = null
  }

  res.rawSpec = arg
  res.spec = arg

  var urlparse = url.parse(arg)
  debug("urlparse", urlparse)

  // windows paths look like urls
  // don't be fooled!
  if (isWindows && urlparse && urlparse.protocol &&
      urlparse.protocol.match(/^[a-zA-Z]:$/)) {
    debug("windows url-ish local path", urlparse)
    urlparse = {}
  }

  if (urlparse.protocol || HostedGit.fromUrl(arg)) {
    return parseUrl(res, arg, urlparse)
  }

  // at this point, it's not a url, and not hosted
  // If it's a valid name, and doesn't already have a name, then assume
  // $name@"" range
  //
  // if it's got / chars in it, then assume that it's local.

  if (res.name) {
    var version = semver.valid(arg, true)
    var range = semver.validRange(arg, true)
    // foo@...
    if (version) {
      res.spec = version
      res.type = "version"
    } else if (range) {
      res.spec = range
      res.type = "range"
    } else if (slashRe.test(arg)) {
      parseLocal(res, arg)
    } else {
      res.type = "tag"
      res.spec = arg
    }
  } else {
    var p = arg.match(parseName)
    if (p && validName(p[2]) &&
        (!p[1] || validName(p[1]))) {
      res.type = "range"
      res.spec = "*"
      res.rawSpec = ""
      res.name = arg
      if (p[1])
        res.scope = "@" + p[1]
    } else {
      parseLocal(res, arg)
    }
  }

  return res
}
Example #19
0
  grunt.registerTask('bump', DESC, function(versionType, incOrCommitOnly) {
    var opts = this.options({
      bumpVersion: true,
      files: ['package.json', 'bower.json', 'config.xml'],
      updateConfigs: [], // array of config properties to update (with files)
      commit: true,
      commitMessage: 'Release %VERSION%',
      commitFiles: ['package.json', 'bower.json', 'config.xml'], // '-a' for all files
      createTag: true,
      tagName: '%VERSION%',
      tagMessage: 'Version %VERSION%',
      push: true,
      pushTo: 'upstream',
      gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
    });

    if (incOrCommitOnly === 'bump-only') {
      grunt.verbose.writeln('Only incrementing the version.');

      opts.commit = false;
      opts.createTag = false;
      opts.push = false;
    }

    if (incOrCommitOnly === 'commit-only') {
      grunt.verbose.writeln('Only committing/tagging/pushing.');

      opts.bumpVersion = false;
    }

    var exactVersionToSet = grunt.option('setversion');
    if (!semver.valid(exactVersionToSet)) {
        exactVersionToSet = false;
    }

    var done = this.async();
    var queue = [];
    var next = function() {
      if (!queue.length) {
        return done();
      }
      queue.shift()();
    };
    var runIf = function(condition, behavior) {
      if (condition) {
        queue.push(behavior);
      }
    };

    var globalVersion; // when bumping multiple files
    var gitVersion;    // when bumping using `git describe`
    var XML_VERSION_REGEXP = /([\d||A-a|.|-]*)([\'|\"]?)/i;
    var VERSION_REGEXP = /([\'|\"]?version[\'|\"]?[ ]*:[ ]*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i;


    // GET VERSION FROM GIT
    runIf(opts.bumpVersion && versionType === 'git', function(){
      exec('git describe ' + opts.gitDescribeOptions, function(err, stdout, stderr){
        if (err) {
          grunt.fatal('Can not get a version number using `git describe`');
        }
        gitVersion = stdout.trim();
        next();
      });
    });


    // BUMP ALL FILES
    runIf(opts.bumpVersion, function(){
      grunt.file.expand(opts.files).forEach(function(file, idx) {
        var version = null;
        var fileString = grunt.file.read(file);
        var content;

        if (/config.xml$/.test(file)) {
          parseString(fileString, function (err, result) {
            result.widget.$.version = result.widget.$.version.replace(XML_VERSION_REGEXP, function (match, parsedVersion) {
                gitVersion = gitVersion && parsedVersion;
                version = exactVersionToSet || gitVersion || semver.inc(parsedVersion, versionType || 'patch');
                // Removes prerelease tag
                return !~version.indexOf('-') ? version : version.slice(0, version.indexOf('-'));
            });
            if (result.widget.$['android-versionCode']) {
              result.widget.$['android-versionCode'] = parseInt(result.widget.$['android-versionCode']) + 1;
            }
            content = xmlBuilder.buildObject(result);
          });
        } else {
          content = fileString.replace(VERSION_REGEXP, function(match, prefix, parsedVersion, suffix) {
            gitVersion = gitVersion && parsedVersion + '-' + gitVersion;
            version = exactVersionToSet || gitVersion || semver.inc(parsedVersion, versionType || 'patch');
            return prefix + version + suffix;
          });
        }

        if (!version) {
          grunt.fatal('Can not find a version to bump in ' + file);
        }

        grunt.file.write(file, content);
        grunt.log.ok('Version bumped to ' + version + (opts.files.length > 1 ? ' (in ' + file + ')' : ''));

        if (!globalVersion) {
          globalVersion = version;
        } else if (globalVersion !== version) {
          grunt.warn('Bumping multiple files with different versions!');
        }

        var configProperty = opts.updateConfigs[idx];
        if (!configProperty) {
          return;
        }

        var cfg = grunt.config(configProperty);
        if (!cfg) {
          return grunt.warn('Can not update "' + configProperty + '" config, it does not exist!');
        }

        cfg.version = version;
        grunt.config(configProperty, cfg);
        grunt.log.ok(configProperty + '\'s version updated');
      });
      next();
    });


    // when only commiting, read the version from package.json / pkg config
    runIf(!opts.bumpVersion, function() {
      if (opts.updateConfigs.length) {
        globalVersion = grunt.config(opts.updateConfigs[0]).version;
      } else {
        globalVersion = grunt.file.readJSON(opts.files[0]).version;
      }

      next();
    });


    // COMMIT
    runIf(opts.commit, function() {
      var commitMessage = opts.commitMessage.replace('%VERSION%', globalVersion);

      exec('git commit ' + opts.commitFiles.join(' ') + ' -m "' + commitMessage + '"', function(err, stdout, stderr) {
        if (err) {
          grunt.fatal('Can not create the commit:\n  ' + stderr);
        }
        grunt.log.ok('Committed as "' + commitMessage + '"');
        next();
      });
    });


    // CREATE TAG
    runIf(opts.createTag, function() {
      var tagName = opts.tagName.replace('%VERSION%', globalVersion);
      var tagMessage = opts.tagMessage.replace('%VERSION%', globalVersion);

      exec('git tag -a ' + tagName + ' -m "' + tagMessage + '"' , function(err, stdout, stderr) {
        if (err) {
          grunt.fatal('Can not create the tag:\n  ' + stderr);
        }
        grunt.log.ok('Tagged as "' + tagName + '"');
        next();
      });
    });


    // PUSH CHANGES
    runIf(opts.push, function() {
      exec('git push ' + opts.pushTo + ' && git push ' + opts.pushTo + ' --tags', function(err, stdout, stderr) {
        if (err) {
          grunt.fatal('Can not push to ' + opts.pushTo + ':\n  ' + stderr);
        }
        grunt.log.ok('Pushed to ' + opts.pushTo);
        next();
      });
    });

    next();
  });
Example #20
0
 .map(version => semver.valid(version.trim()))
Example #21
0
 async run(options) {
     if (!options.collection) {
         this.logger.fatal(`The "ng add" command requires a name argument to be specified eg. `
             + `${core_1.terminal.yellow('ng add [name] ')}. For more details, use "ng help".`);
         return 1;
     }
     let packageIdentifier;
     try {
         packageIdentifier = npa(options.collection);
     }
     catch (e) {
         this.logger.error(e.message);
         return 1;
     }
     if (packageIdentifier.registry && this.isPackageInstalled(packageIdentifier.name)) {
         // Already installed so just run schematic
         this.logger.info('Skipping installation: Package already installed');
         return this.executeSchematic(packageIdentifier.name, options['--']);
     }
     const usingYarn = this.packageManager === 'yarn';
     if (packageIdentifier.type === 'tag' && !packageIdentifier.rawSpec) {
         // only package name provided; search for viable version
         // plus special cases for packages that did not have peer deps setup
         let packageMetadata;
         try {
             packageMetadata = await package_metadata_1.fetchPackageMetadata(packageIdentifier.name, this.logger, { usingYarn });
         }
         catch (e) {
             this.logger.error('Unable to fetch package metadata: ' + e.message);
             return 1;
         }
         const latestManifest = packageMetadata.tags['latest'];
         if (latestManifest && Object.keys(latestManifest.peerDependencies).length === 0) {
             if (latestManifest.name === '@angular/pwa') {
                 const version = await this.findProjectVersion('@angular/cli');
                 // tslint:disable-next-line:no-any
                 const semverOptions = { includePrerelease: true };
                 if (version
                     && ((semver_1.validRange(version) && semver_1.intersects(version, '7', semverOptions))
                         || (semver_1.valid(version) && semver_1.satisfies(version, '7', semverOptions)))) {
                     packageIdentifier = npa.resolve('@angular/pwa', '0.12');
                 }
             }
         }
         else if (!latestManifest || (await this.hasMismatchedPeer(latestManifest))) {
             // 'latest' is invalid so search for most recent matching package
             const versionManifests = Array.from(packageMetadata.versions.values())
                 .filter(value => !semver_1.prerelease(value.version));
             versionManifests.sort((a, b) => semver_1.rcompare(a.version, b.version, true));
             let newIdentifier;
             for (const versionManifest of versionManifests) {
                 if (!(await this.hasMismatchedPeer(versionManifest))) {
                     newIdentifier = npa.resolve(packageIdentifier.name, versionManifest.version);
                     break;
                 }
             }
             if (!newIdentifier) {
                 this.logger.warn('Unable to find compatible package.  Using \'latest\'.');
             }
             else {
                 packageIdentifier = newIdentifier;
             }
         }
     }
     let collectionName = packageIdentifier.name;
     if (!packageIdentifier.registry) {
         try {
             const manifest = await package_metadata_1.fetchPackageManifest(packageIdentifier, this.logger, { usingYarn });
             collectionName = manifest.name;
             if (await this.hasMismatchedPeer(manifest)) {
                 console.warn('Package has unmet peer dependencies. Adding the package may not succeed.');
             }
         }
         catch (e) {
             this.logger.error('Unable to fetch package manifest: ' + e.message);
             return 1;
         }
     }
     await npm_install_1.default(packageIdentifier.raw, this.logger, this.packageManager, this.workspace.root);
     return this.executeSchematic(collectionName, options['--']);
 }
Example #22
0
 validate: function (value) {
     var valid = semver.valid(value) && true;
     return valid || 'Must be a valid semver, such as 1.2.3-rc1. See ' + 'http://semver.org/'.blue.underline + ' for more details.';
 }
Example #23
0
function assertSemver (value, name = 'value') {
  if (!semver.valid(value)) {
    throw createTypeError(name, 'a semver string')
  }
}
Example #24
0
 versions.forEach(function (v) {
     if (!semver.valid(v)) {
         throw new TypeError('%s is not a valid semver', v);
     }
 });
Example #25
0
  var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, reporter, warn, looseSemver) {
    const files = yield (_fs || _load_fs()).readdir(moduleLoc);

    // clean info.version
    if (typeof info.version === 'string' && !semver.valid(info.version)) {
      info.version = semver.clean(info.version, looseSemver) || info.version;
    }

    // if name or version aren't set then set them to empty strings
    info.name = info.name || '';
    info.version = info.version || '';

    // if the man field is a string then coerce it to an array
    if (typeof info.man === 'string') {
      info.man = [info.man];
    }

    // if the keywords field is a string then split it on any whitespace
    if (typeof info.keywords === 'string') {
      info.keywords = info.keywords.split(/\s+/g);
    }

    // if there's no contributors field but an authors field then expand it
    if (!info.contributors && files.indexOf('AUTHORS') >= 0) {
      const authorsFilepath = path.join(moduleLoc, 'AUTHORS');
      const authorsFilestats = yield (_fs || _load_fs()).stat(authorsFilepath);
      if (authorsFilestats.isFile()) {
        let authors = yield (_fs || _load_fs()).readFile(authorsFilepath);
        authors = authors.split(/\r?\n/g) // split on lines
        .map(function (line) {
          return line.replace(/^\s*#.*$/, '').trim();
        }) // remove comments
        .filter(function (line) {
          return !!line;
        }); // remove empty lines
        info.contributors = authors;
      }
    }

    // expand people fields to objects
    if (typeof info.author === 'string' || typeof info.author === 'object') {
      info.author = (0, (_util || _load_util()).normalizePerson)(info.author);
    }
    if (Array.isArray(info.contributors)) {
      info.contributors = info.contributors.map((_util || _load_util()).normalizePerson);
    }
    if (Array.isArray(info.maintainers)) {
      info.maintainers = info.maintainers.map((_util || _load_util()).normalizePerson);
    }

    // if there's no readme field then load the README file from the cwd
    if (!info.readme) {
      const readmeCandidates = files.filter(function (filename) {
        const lower = filename.toLowerCase();
        return lower === 'readme' || lower.indexOf('readme.') === 0;
      }).sort(function (filename1, filename2) {
        // favor files with extensions
        return filename2.indexOf('.') - filename1.indexOf('.');
      });

      for (const readmeFilename of readmeCandidates) {
        const readmeFilepath = path.join(moduleLoc, readmeFilename);
        const readmeFileStats = yield (_fs || _load_fs()).stat(readmeFilepath);
        if (readmeFileStats.isFile()) {
          info.readmeFilename = readmeFilename;
          info.readme = yield (_fs || _load_fs()).readFile(readmeFilepath);
          break;
        }
      }
    }

    // if there's no description then take the first paragraph from the readme
    if (!info.description && info.readme) {
      const desc = (0, (_util || _load_util()).extractDescription)(info.readme);
      if (desc) {
        info.description = desc;
      }
    }

    // support array of engine keys
    if (Array.isArray(info.engines)) {
      const engines = {};
      for (const str of info.engines) {
        if (typeof str === 'string') {
          var _str$trim$split = str.trim().split(/ +/g),
              _str$trim$split2 = (0, (_toArray2 || _load_toArray()).default)(_str$trim$split);

          const name = _str$trim$split2[0],
                patternParts = _str$trim$split2.slice(1);

          engines[name] = patternParts.join(' ');
        }
      }
      info.engines = engines;
    }

    // if the repository field is a string then assume it's a git repo and expand it
    if (typeof info.repository === 'string') {
      info.repository = {
        type: 'git',
        url: info.repository
      };
    }

    const repo = info.repository;

    // explode info.repository.url if it's a hosted git shorthand
    if (repo && typeof repo === 'object' && typeof repo.url === 'string') {
      repo.url = (0, (_index || _load_index()).hostedGitFragmentToGitUrl)(repo.url, reporter);
    }

    // allow bugs to be specified as a string, expand it to an object with a single url prop
    if (typeof info.bugs === 'string') {
      info.bugs = { url: info.bugs };
    }

    // normalize homepage url to http
    if (typeof info.homepage === 'string') {
      const parts = url.parse(info.homepage);
      parts.protocol = parts.protocol || 'http:';
      if (parts.pathname && !parts.hostname) {
        parts.hostname = parts.pathname;
        parts.pathname = '';
      }
      // $FlowFixMe: https://github.com/facebook/flow/issues/908
      info.homepage = url.format(parts);
    }

    // if the `bin` field is as string then expand it to an object with a single property
    // based on the original `bin` field and `name field`
    // { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } }
    if (typeof info.name === 'string' && typeof info.bin === 'string') {
      // Remove scoped package name for consistency with NPM's bin field fixing behaviour
      const name = info.name.replace(/^@[^\/]+\//, '');
      info.bin = { [name]: info.bin };
    }

    // bundleDependencies is an alias for bundledDependencies
    if (info.bundledDependencies) {
      info.bundleDependencies = info.bundledDependencies;
      delete info.bundledDependencies;
    }

    let scripts;

    // dummy script object to shove file inferred scripts onto
    if (info.scripts && typeof info.scripts === 'object') {
      scripts = info.scripts;
    } else {
      scripts = {};
    }

    // if there's a server.js file and no start script then set it to `node server.js`
    if (!scripts.start && files.indexOf('server.js') >= 0) {
      scripts.start = 'node server.js';
    }

    // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild`
    if (!scripts.install && files.indexOf('binding.gyp') >= 0) {
      scripts.install = 'node-gyp rebuild';
    }

    // set scripts if we've polluted the empty object
    if ((0, (_keys || _load_keys()).default)(scripts).length) {
      info.scripts = scripts;
    }

    const dirs = info.directories;

    if (dirs && typeof dirs === 'object') {
      const binDir = dirs.bin;

      if (!info.bin && binDir && typeof binDir === 'string') {
        const bin = info.bin = {};
        const fullBinDir = path.join(moduleLoc, binDir);

        if (yield (_fs || _load_fs()).exists(fullBinDir)) {
          for (const scriptName of yield (_fs || _load_fs()).readdir(fullBinDir)) {
            if (scriptName[0] === '.') {
              continue;
            }
            bin[scriptName] = path.join('.', binDir, scriptName);
          }
        } else {
          warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name));
        }
      }

      const manDir = dirs.man;

      if (!info.man && typeof manDir === 'string') {
        const man = info.man = [];
        const fullManDir = path.join(moduleLoc, manDir);

        if (yield (_fs || _load_fs()).exists(fullManDir)) {
          for (const filename of yield (_fs || _load_fs()).readdir(fullManDir)) {
            if (/^(.*?)\.[0-9]$/.test(filename)) {
              man.push(path.join('.', manDir, filename));
            }
          }
        } else {
          warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name));
        }
      }
    }

    delete info.directories;

    // normalize licenses field
    const licenses = info.licenses;
    if (Array.isArray(licenses) && !info.license) {
      let licenseTypes = [];

      for (let license of licenses) {
        if (license && typeof license === 'object') {
          license = license.type;
        }
        if (typeof license === 'string') {
          licenseTypes.push(license);
        }
      }

      licenseTypes = licenseTypes.filter((_util || _load_util()).isValidLicense);

      if (licenseTypes.length === 1) {
        info.license = licenseTypes[0];
      } else if (licenseTypes.length) {
        info.license = `(${licenseTypes.join(' OR ')})`;
      }
    }

    const license = info.license;

    // normalize license
    if (license && typeof license === 'object') {
      info.license = license.type;
    }

    // get license file
    const licenseFile = files.find(function (filename) {
      const lower = filename.toLowerCase();
      return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.');
    });
    if (licenseFile) {
      const licenseFilepath = path.join(moduleLoc, licenseFile);
      const licenseFileStats = yield (_fs || _load_fs()).stat(licenseFilepath);
      if (licenseFileStats.isFile()) {
        const licenseContent = yield (_fs || _load_fs()).readFile(licenseFilepath);
        const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(licenseContent);
        info.licenseText = licenseContent;

        const license = info.license;

        if (typeof license === 'string') {
          if (inferredLicense && (0, (_util || _load_util()).isValidLicense)(inferredLicense) && !(0, (_util || _load_util()).isValidLicense)(license)) {
            // some packages don't specify their license version but we can infer it based on their license file
            const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, '');
            const expandedLicense = inferredLicense.toLowerCase();
            if (expandedLicense.startsWith(basicLicense)) {
              // TODO consider doing something to notify the user
              info.license = inferredLicense;
            }
          }
        } else if (inferredLicense) {
          // if there's no license then infer it based on the license file
          info.license = inferredLicense;
        } else {
          // valid expression to refer to a license in a file
          info.license = `SEE LICENSE IN ${licenseFile}`;
        }
      }
    }

    if (typeof info.license === 'string') {
      // sometimes licenses are known by different names, reduce them
      info.license = LICENSE_RENAMES[info.license] || info.license;
    } else if (typeof info.readme === 'string') {
      // the license might be at the bottom of the README
      const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(info.readme);
      if (inferredLicense) {
        info.license = inferredLicense;
      }
    }
  });
Example #26
0
 .map(function(version) {
     return semver.valid(version.trim());
 })
Example #27
0
 }, function(err, result) {
   result = String(result).split('-')[0];
   done(null, semver.valid(result) || '0.1.0');
 });
Example #28
0
target.checkGitCommit = function() {
    var commitMsgs,
        failed;

    if (hasBranch("master")) {
        commitMsgs = splitCommandResultToLines(execSilent("git log HEAD --not master --format=format:%s --no-merges"));
    } else {
        commitMsgs = [execSilent("git log -1 --format=format:%s --no-merges")];
    }

    echo("Validating Commit Message");

    // No commit since master should not cause test to fail
    if (commitMsgs[0] === "") {
        return;
    }

    // Check for more than one commit
    if (commitMsgs.length > 1) {
        echo(" - More than one commit found, please squash.");
        failed = true;
    }

    // Only check non-release messages
    if (!semver.valid(commitMsgs[0]) && !/^Revert /.test(commitMsgs[0])) {
        if (commitMsgs[0].split(/\r?\n/)[0].length > 72) {
            echo(" - First line of commit message must not exceed 72 characters");
            failed = true;
        }

        // Check for tag at start of message
        if (!TAG_REGEX.test(commitMsgs[0])) {
            echo([" - Commit summary must start with one of:",
                "    'Fix:'",
                "    'Update:'",
                "    'Breaking:'",
                "    'Docs:'",
                "    'Build:'",
                "    'New:'",
                "    'Upgrade:'",
                "    'Chore:'",
                "   Please refer to the contribution guidelines for more details."].join("\n"));
            failed = true;
        }

        // Check for an issue reference at end (unless it's a documentation commit)
        if (!/^Docs:/.test(commitMsgs[0])) {
            if (!ISSUE_REGEX.test(commitMsgs[0])) {
                echo([" - Commit summary must end with with one of:",
                    "    '(fixes #1234)'",
                    "    '(refs #1234)'",
                    "   Where '1234' is the issue being addressed.",
                    "   Please refer to the contribution guidelines for more details."].join("\n"));
                failed = true;
            }
        }
    }

    if (failed) {
        exit(1);
    }
};
Example #29
0
const getNotes = async (fromRef, toRef, newVersion) => {
  if (!fs.existsSync(CACHE_DIR)) {
    fs.mkdirSync(CACHE_DIR)
  }

  const pool = {
    processedHashes: new Set(),
    commits: []
  }

  // get the electron/electron commits
  const electron = { owner: 'electron', repo: 'electron', dir: gitDir }
  await addRepoToPool(pool, electron, fromRef, toRef)

  // Don't include submodules if comparing across major versions;
  // there's just too much churn otherwise.
  const includeDeps = semver.valid(fromRef) &&
                      semver.valid(toRef) &&
                      semver.major(fromRef) === semver.major(toRef)

  if (includeDeps) {
    await getDependencyCommits(pool, fromRef, toRef)
  }

  // remove any old commits
  pool.commits = pool.commits.filter(commit => !pool.processedHashes.has(commit.hash))

  // if a commmit _and_ revert occurred in the unprocessed set, skip them both
  for (const commit of pool.commits) {
    const revertHash = commit.revertHash
    if (!revertHash) {
      continue
    }

    const revert = pool.commits.find(commit => commit.hash === revertHash)
    if (!revert) {
      continue
    }

    commit.note = NO_NOTES
    revert.note = NO_NOTES
    pool.processedHashes.add(commit.hash)
    pool.processedHashes.add(revertHash)
  }

  // scrape PRs for release note 'Notes:' comments
  for (const commit of pool.commits) {
    let pr = commit.pr

    let prSubject
    while (pr && !commit.note) {
      const note = await getNoteFromClerk(pr.number, pr.owner, pr.repo)
      if (note) {
        commit.note = note
      }

      // if we already have all the data we need, stop scraping the PRs
      if (commit.note && commit.type && prSubject) {
        break
      }

      const prData = await getPullRequest(pr.number, pr.owner, pr.repo)
      if (!prData || !prData.data) {
        break
      }

      // try to pull a release note from the pull comment
      const prParsed = parseCommitMessage(`${prData.data.title}\n\n${prData.data.body}`, pr.owner, pr.repo)
      if (!commit.note) {
        commit.note = prParsed.note
      }
      if (!commit.type || prParsed.type === 'breaking-change') {
        commit.type = prParsed.type
      }
      prSubject = prSubject || prParsed.subject

      pr = prParsed.pr && (prParsed.pr.number !== pr.number) ? prParsed.pr : null
    }

    // if we still don't have a note, it's because someone missed a 'Notes:
    // comment in a PR somewhere... use the PR subject as a fallback.
    commit.note = commit.note || prSubject
  }

  // remove non-user-facing commits
  pool.commits = pool.commits
    .filter(commit => commit.note !== NO_NOTES)
    .filter(commit => !((commit.note || commit.subject).match(/^[Bb]ump v\d+\.\d+\.\d+/)))

  if (!shouldIncludeMultibranchChanges(newVersion)) {
    // load all the prDatas
    await Promise.all(
      pool.commits.map(commit => new Promise(async (resolve) => {
        const { pr } = commit
        if (typeof pr === 'object') {
          const prData = await getPullRequest(pr.number, pr.owner, pr.repo)
          if (prData) {
            commit.prData = prData
          }
        }
        resolve()
      }))
    )

    // remove items that already landed in a previous major/minor series
    pool.commits = pool.commits
      .filter(commit => {
        if (!commit.prData) {
          return true
        }
        const reducer = (accumulator, current) => {
          if (!semver.valid(accumulator)) { return current }
          if (!semver.valid(current)) { return accumulator }
          return semver.lt(accumulator, current) ? accumulator : current
        }
        const earliestRelease = commit.prData.data.labels
          .map(label => label.name.match(/merged\/(\d+)-(\d+)-x/))
          .filter(label => !!label)
          .map(label => `${label[1]}.${label[2]}.0`)
          .reduce(reducer, null)
        if (!semver.valid(earliestRelease)) {
          return true
        }
        return semver.diff(earliestRelease, newVersion).includes('patch')
      })
  }

  const notes = {
    breaking: [],
    docs: [],
    feat: [],
    fix: [],
    other: [],
    unknown: [],
    name: newVersion
  }

  pool.commits.forEach(commit => {
    const str = commit.type
    if (!str) {
      notes.unknown.push(commit)
    } else if (breakTypes.has(str)) {
      notes.breaking.push(commit)
    } else if (docTypes.has(str)) {
      notes.docs.push(commit)
    } else if (featTypes.has(str)) {
      notes.feat.push(commit)
    } else if (fixTypes.has(str)) {
      notes.fix.push(commit)
    } else if (otherTypes.has(str)) {
      notes.other.push(commit)
    } else {
      notes.unknown.push(commit)
    }
  })

  return notes
}
Example #30
0
var npmModules_checkForUpdates = function (parsed, cb) {

    var errorAnswer = null;
    var npmFiles = null;
    try {

        var ret = npmModules_check(parsed);
        if (ret.err)
            return cb ? cb(ret.err) : null;

        // no error. just no modules.
        if (!fs.existsSync(ret.modulesDir))
            return cb ? cb(null, "OK") : null;

        var folders = fs.readdirSync(ret.modulesDir);

        npmFiles = logFiles.get(ret, false);
        npmFiles.backup();

        npmModulesLatestVersions.__checking_in_progress = true;
        for (var a = 0, len = folders.length; a < len; a++) {
            if (folders[a].slice(0, 1) !== ".") {
                var dir = path.join(ret.modulesDir, folders[a]);
                var _stat = fs.statSync(dir);
                if (!_stat.isDirectory())
                    continue;

                var file = path.join(dir, "package.json");

                try {
                    if (fs.existsSync(file)) {
                        var json = JSON.parse(fs.readFileSync(file));

                        var cmd = util.format('cd "%s"; "%s" npm view %s version --loglevel silent', ret.baseDir, process.execPath, folders[a]);
                        var cmdResult = jxcore.utils.cmdSync(cmd);

                        var v = cmdResult.out.trim();
//                        console.log("Check for update:", folders[a],
//                            "\ncmd:", cmd,
//                            "\nver: ", ">" + v + "<",
//                            "\njson ver: ", ">" + json.version + "<",
//                            "\nsemver valid:", semver.valid(v)
//                            "\nlt", semver.lt(json.version, v),
//                            "\ngt", semver.gt(json.version, v)
//                        );
                        var info = null;
                        if (!semver.valid(v)) {
                            info = "Invalid remote version"
                        } else {
                            if (semver.lt(json.version, v)) {
                                info = "#Update to " + v;
                            }
                            if (semver.gt(json.version, v)) {
                                info = "This is newer"
                            } else if (json.version === v) {
                                info = "This is the latest";
                            }
                        }

                        if (!info)
                            info = util.format("Could not compare %s vs %s", json.version, v);

                        npmModulesLatestVersions[folders[a]] = info;
                    }
                } catch (ex) {
                    console.log("exception", ex);
                }
            }
        }
        npmModulesLatestVersions.__lastCheck = Date.now();
        npmModulesLatestVersions.__checking_in_progress = false;

    } catch (ex) {
        errorAnswer = ex.toString();
    }

    if (npmFiles) npmFiles.restore();
    if (cb) cb(errorAnswer);
};