Check if a version of a package already exists

@param {Object} pkg - an object with the keys representing the versions of a module
@param {String} version - version range
@returns {Array}
 TODO: refactor this, first arg should be versions instead
772673
function isDuplicate(pkg, version) {
  var versions;

  // no duplicates
  if (pkg) {
    versions = Object.keys(pkg);

    if (versions.length && semver.maxSatisfying(versions, version)) {
      return true;
    }
  }

  return false;
}
469999
def _check_pkg_version_format(pkg):
    '''
    
    '''

    ret = {'result': False, 'comment': None,
           'prefix': None, 'version_spec': None}

    if not HAS_PIP:
        ret['comment'] = (
            'An importable Python 2 pip module is required but could not be '
            'found on your system. This usually means that the system\'s pip '
            'package is not installed properly.'
        )

        return ret

    from_vcs = False
    try:
        # Get the requirement object from the pip library
        try:
            # With pip < 1.2, the __version__ attribute does not exist and
            # vcs+URL urls are not properly parsed.
            # The next line is meant to trigger an AttributeError and
            # handle lower pip versions
            log.debug('Installed pip version: %s', pip.__version__)
            install_req = _from_line(pkg)
        except AttributeError:
            log.debug('Installed pip version is lower than 1.2')
            supported_vcs = ('git', 'svn', 'hg', 'bzr')
            if pkg.startswith(supported_vcs):
                for vcs in supported_vcs:
                    if pkg.startswith(vcs):
                        from_vcs = True
                        install_req = _from_line(
                            pkg.split('{0}+'.format(vcs))[-1]
                        )
                        break
            else:
                install_req = _from_line(pkg)
    except (ValueError, InstallationError) as exc:
        ret['result'] = False
        if not from_vcs and '=' in pkg and '==' not in pkg:
            ret['comment'] = (
                'Invalid version specification in package {0}. \'=\' is '
                'not supported, use \'==\' instead.'.format(pkg)
            )
            return ret
        ret['comment'] = (
            'pip raised an exception while parsing \'{0}\': {1}'.format(
                pkg, exc
            )
        )
        return ret

    if install_req.req is None:
        # This is most likely an url and there's no way to know what will
        # be installed before actually installing it.
        ret['result'] = True
        ret['prefix'] = ''
        ret['version_spec'] = []
    else:
        ret['result'] = True
        try:
            ret['prefix'] = install_req.req.project_name
            ret['version_spec'] = install_req.req.specs
        except Exception:
            ret['prefix'] = re.sub('[^A-Za-z0-9.]+', '-', install_req.name)
            if hasattr(install_req, "specifier"):
                specifier = install_req.specifier
            else:
                specifier = install_req.req.specifier
            ret['version_spec'] = [(spec.operator, spec.version) for spec in specifier]

    return ret
186017
function resolveDependencies (pkg, cb) {
  if (!pkg) return topCb(new Error(
    "Package not found to resolve dependencies"))
  // link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/node_modules/foo

  // see if it's bundled already
  var bundleDir = path.join( npm.dir, pkg.name, pkg.version
                           , "package", "node_modules" )
   , deps = pkg.dependencies && Object.keys(pkg.dependencies) || []
  log.verbose([pkg, deps], "deps being resolved")
  fs.readdir(bundleDir, function (er, bundledDeps) {
    if (er) bundledDeps = []
    bundledDeps.forEach(function (bd) {
      var i = deps.indexOf(bd)
      if (i !== -1) deps.splice(i, 1)
    })

    asyncMap(deps, function (i, cb) {
      var req = { name:i, version:pkg.dependencies[i] }
      log.verbose(req.name+"@"+req.version, "required")

      // see if we have this thing installed.
      fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
        if (er) return cb(new Error(
          "Required package: "+req.name+"("+req.version+") not found."+
          "\n(required by: "+pkg._id+")"))
        // TODO: Get the "stable" version if there is one.
        // Look that up from the registry.
        var satis = semver.maxSatisfying(versions, req.version)
        if (satis) return cb(null, {name:req.name, version:satis})
        return cb(new Error(
          "Required package: "+req.name+"("+req.version+") not found. "+
          "(Found: "+JSON.stringify(versions)+")"+
          "\n(required by: "+pkg._id+")"))
      })
    }, function (er, found) {
      // save the resolved dependencies on the pkg data for later
      pkg._resolvedDeps = found
      cb(er, found)
    })
  })
}
354259
function parseVersion(versionString) {
  const [release, prerelease] = versionString.split('-')
  const splitRelease = release.split('.').map(number => parseInt(number, 10))

  return {
    major: splitRelease[0],
    minor: splitRelease[1],
    patch: splitRelease[2],
    prerelease: prerelease || '',
    raw: versionString
  }
}
1310271
function convertForPackage(context, pkg) {
	var name = pkg.name;
	var version = pkg.version;

	var conv = context.deferredConversions;
	var pkgConv = conv[name];
	var depPkg, fns, keys = 0;
	if(pkgConv) {
		for(var range in pkgConv) {
			depPkg = crawl.matchedVersion(context, name, range);
			if(depPkg) {
				fns = pkgConv[range];
				for(var i = 0, len = fns.length; i < len; i++) {
					fns[i].call(context);
				}
				delete pkgConv[range];
			} else {
				keys++;
			}
		}
		if(keys === 0) {
			delete conv[name];
		}
	}
}
494077
def _check_pkg(target):
    '''
    
    '''
    ret = {}
    cmd = ['/usr/bin/lslpp', '-Lc', target]
    lines = __salt__['cmd.run'](
            cmd,
            python_shell=False).splitlines()

    name = ''
    version_num = ''
    rpmpkg = False
    for line in lines:
        if line.startswith('#'):
            continue

        comps = line.split(':')
        if len(comps) < 7:
            raise CommandExecutionError(
                'Error occurred finding fileset/package',
                info={'errors': comps[1].strip()})

        # handle first matching line
        if 'R' in comps[6]:
            name = comps[0]
            rpmpkg = True
        else:
            name = comps[1]     # use fileset rather than rpm package

        version_num = comps[2]
        break

    return name, version_num, rpmpkg
117528
function determineVersion(module) {
		var json;

		if (!('version' in module)) {
			json = module.options.path + '/package.json';
			delete require.cache[json];
			json = require(json);

			['dependencies', 'devDependencies', 'optionalDependencies'].forEach(function(dep) {
				if (dep in json && module.name in json[dep]) {
					module.version = json[dep][module.name];
				}
			});
		}
	}
1297319
function (pkg, cb) {
  var auto = npm.config.get("auto-activate")
  if (!auto) {
    autoActivate = function (_, cb) { return cb() }
    return log.verbose("auto-activate", "disabled by config", cb)
  }
  pkg = pkg && pkg._data || pkg
  // get the list of versions of this package.
  readInstalled(pkg.name, function (er, inst) {
    if (er) return cb(er)
    var versions = Object.keys(inst)
    if (auto !== "always" && versions.indexOf("active") !== -1) {
      log("another version already active", "auto-activate")
      log("to activate, do:   npm activate "+
        pkg.name+"@"+pkg.version, "auto-activate")
      return cb()
    }
    var u = pkg.name+"@"+pkg.version
    log.verbose(u, "auto-activate")
    npm.commands.activate([u], function (er) {
      // don't rollback the whole install if the activate fails.
      if (er) log.error(er, "Failed to update "+u)
      cb()
    })
  })
}
727499
async function _expectPackageVersion(args) {
  const packageVersion = require(
    path.resolve(__dirname, '../../package.json')
  ).version;
  await _expectSuccessMessage(args, `${packageVersion}\n`);
}
654956
function pkgPropUpd(pd, u, n, r) {
			var v = null;
			if (u && pd.oldVer !== self.version && self.version) {
				v = self.version;
			} else if (n && pd.oldVer !== self.next.version && self.next.version) {
				v = self.next.version;
			} else if (r && self.prev.version) {
				v = self.prev.version;
			}
			pd.version = v;
			if (v && !pd.props) {
				pd.pkg.version = v;
				pd.propChangeCount++;
			}
			if (pd.props && pd.pkgParent) {
				pd.props.forEach(function pkgProp(p) {
					if (pd.pkgParent[p] && (!pd.pkg[p] || pd.pkgParent[p] !== pd.pkg[p])) {
						// sync parent package property with the current one
						pd.pkg[p] = pd.pkgParent[p];
						pd.propChangeCount++;
					}
				});
			}
			return v;
		}
218689
function getUnsatisfiedDeps(deps, versions, options) {
	const ownDependencies = getOwnDependencies(options);

	return deps.filter(dep => {
		const required = versions[dep];

		if (required && !semver.validRange(required)) {
			throw new MrmError(
				`Invalid npm version: ${required}. Use proper semver range syntax.`
			);
		}

		const installed = getInstalledVersion(dep);

		// Package isn’t installed yet
		if (!installed) {
			return true;
		}

		// Module is installed but not in package.json dependencies
		if (!ownDependencies[dep]) {
			return true;
		}

		// No required version specified
		if (!required) {
			// Install if the pacakge isn’t installed
			return !installed;
		}

		// Install if installed version doesn't satisfy range
		return !semver.satisfies(installed, required);
	});
}
766923
function discoverVersion() {
    // try to understand package name and current version
    // from package.json or bower.json
    let packageFile;
    let packageFileExtension;
    let packageType;
    let results = {
        name: '',
        currentVersion: ''
    };
    let possiblePackageFiles = ['package.json', 'bower.json', 'package.js'];

    for (possiblePackageFile of possiblePackageFiles) {
        if (fs.existsSync(possiblePackageFile)) {
            packageFile = possiblePackageFile;
            break;
        }
    }

    packageFileExtension = packageFile.substr(packageFile.lastIndexOf('.') + 1);

    if (packageFile) {
        let packageData;

        if (packageFileExtension === 'json') {
            packageData = jsonReader(packageFile);
        }
        if (packageFileExtension === 'js') {
            let tmpData = fs.readFileSync(packageFile).toString().split('\n');
            let nameFound = false;
            let versionFound = false;

            packageData = {};

            for (line of tmpData) {
                if (line.indexOf('name:') >= 0) {
                    nameFound = true;
                    packageData.name = line.split(' ').pop().replace(/'/g, '').replace(/,/g, '');
                }
                if (line.indexOf('version:') >= 0) {
                    versionFound = true;
                    packageData.version = line.split(' ').pop().replace(/'/g, '').replace(/,/g, '');
                }

                if (nameFound && versionFound) {
                    break;
                }
            }
        }

        debugLog('Reading packageFile for init:');
        debugLog('Discovered pacakge name: ' + packageData.name + ' - discovered package version ' + packageData.version);

        if (packageData.name) {
            results.name = packageData.name;
        }
        else {
            print('Can\'t discover package name automatically', 'msgWarning', 'spaced22');
        }

        if (packageData.version) {
            results.currentVersion = packageData.version;
        }
        else {
            print('Can\'t discover package\'s currentVersion automatically', 'msgWarning', 'spaced22');
        }
    }
    else {
        print('Can\'t discover package name and/or currentVersion automatically', 'msgWarning', 'spaced22');
        print('Please fill .versionFilesList.json with the missing informations', 'msgWarning', 'spaced22');
    }

    return results;
}
216167
function resolveVersion(plugin) {
    var npmId = Plugin.nameToNpmID(plugin.getName());
    var requiredVersion = plugin.getVersion();

    if (plugin.isGitDependency()) {
        return Promise.resolve(requiredVersion);
    }

    return initNPM()
    .then(function() {
        return Promise.nfcall(npm.commands.view, [npmId + '@' + requiredVersion, 'engines'], true);
    })
    .then(function(versions) {
        versions = Immutable.Map(versions).entrySeq();

        var result = versions
            .map(function(entry) {
                return {
                    version: entry[0],
                    gitbook: (entry[1].engines || {}).gitbook
                };
            })
            .filter(function(v) {
                return v.gitbook && gitbook.satisfies(v.gitbook);
            })
            .sort(function(v1, v2) {
                return semver.lt(v1.version, v2.version)? 1 : -1;
            })
            .get(0);

        if (!result) {
            return undefined;
        } else {
            return result.version;
        }
    });
}
1165813
function updatePackageInfo(theme, version) {
  const cwd = `.tmp/${version}/${theme}/publish`
  bower.version = `${version}-${theme}`
  pkg.version = `${version}-${theme}`
  return Promise.all([
    fs.writeFile(`${cwd}/bower.json`, JSON.stringify(bower, null, 4)),
    fs.writeFile(`${cwd}/package.json`, JSON.stringify(pkg, null, 4))
  ])
}
292102
def add_changed_pkg_xml(obj)
      versions_elem = obj.add_element 'versions'
      @changed_pkgs.each do |vers|
        velem = versions_elem.add_element 'version'
        velem.add_element('software_version').text = vers.to_s
        pkg = velem.add_element 'package'
        # leave am empty package element to remove the pkg assignement
        next if versions[vers].package_id == :none
        pkg.add_element('id').text = versions[vers].package_id.to_s
      end # do vers
    end
419039
function readPackageVersion(root) {
  let pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
  // use _originalVersion if present if we've already mutated it
  return pkg._originalVersion || pkg.version;
}
894605
def versions_installed(pkg):
    '''
    
    '''

    try:
        # Try to run it, merging stderr into output
        output = subprocess.check_output([SNAP_BINARY_NAME, 'list', pkg], stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError:
        return []

    lines = output.splitlines()[1:]
    ret = []
    for item in lines:
        # If fields contain spaces this will break.
        i = item.split()
        # Ignore 'Notes' field
        ret.append({
            'name':         i[0],
            'version':      i[1],
            'rev':          i[2],
            'tracking':     i[3],
            'publisher':    i[4]
            })

    return ret