Read json from egginfo of a package identified by `pkg_name` that's
    already installed within the current Python environment.
177247
def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None):
    

    working_set = working_set or default_working_set
    dist = find_pkg_dist(pkg_name, working_set=working_set)
    return read_dist_egginfo_json(dist, filename)
329566
def get_package_info(package):
    """"""
    url = 'https://pypi.python.org/pypi/{}/json'.format(package)
    r = requests.get(url)
    r.raise_for_status()
    return r.json()
1178352
def check(self, package_name, package_version, **extra_data):
        """"""
        data = extra_data
        data['package_name'] = package_name
        data['package_version'] = package_version
        data['python_version'] = sys.version.split()[0]
        data['platform'] = platform.platform(True) or 'Unspecified'

        try:
            headers = {'connection': 'close',
                       'content-type': 'application/json'}
            response = requests.put(self.url, json.dumps(data), timeout=1,
                                    headers=headers)
            if response.status_code == codes.UNPROCESSABLE_ENTITY:
                return 'update_checker does not support {!r}'.format(
                    package_name)
            data = response.json()
        except (requests.exceptions.RequestException, ValueError):
            return None

        if not data or not data.get('success') \
                or (parse_version(package_version) >=
                    parse_version(data['data']['version'])):
            return None

        return UpdateResult(package_name, running=package_version,
                            available=data['data']['version'],
                            release_date=data['data']['upload_time'])
178405
def extract_package_dir(self):  # type: () -> Optional[str]
        
        # package_dir={'': 'lib'},
        source = self.setup_py_source()
        if not source:
            # this happens when the setup.py file is missing
            return None

        # sometime
        # 'package_dir'      : {'': 'src'},
        # sometimes
        # package_dir={...}
        if "package_dir=" in source:
            line = source.replace("\n", "")
            line = line.split("package_dir")[1]
            fixed = ""
            for char in line:
                fixed += char
                if char == "}":
                    break
            line = fixed

            simplified_line = line.strip(" ,").replace("'", '"')

            parts = simplified_line.split("=")

            dict_src = parts[1].strip(" \t")
            if not dict_src.endswith("}"):
                raise JiggleVersionException(
                    "Either this is hard to parse or we have 2+ src foldrs"
                )
            try:
                paths_dict = ast.literal_eval(dict_src)
            except ValueError as ve:
                logger.error(source + ": " + dict_src)
                return ""

            if "" in paths_dict:
                candidate = paths_dict[""]
                if os.path.isdir(candidate):
                    return unicode(candidate)
            if len(paths_dict) == 1:
                candidate = first_value_in_dict(paths_dict)
                if os.path.isdir(candidate):
                    return unicode(candidate)
            else:
                raise JiggleVersionException(
                    "Have path_dict, but has more than one path."
                )
        return None
1224461
def _get_pkg_info(*packages, **kwargs):
    '''
    
    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    failhard = kwargs.pop('failhard', True)
    if kwargs:
        salt.utils.args.invalid_kwargs(kwargs)

    if __grains__['os'] == 'Ubuntu' and __grains__['osrelease_info'] < (12, 4):
        bin_var = '${binary}'
    else:
        bin_var = '${Package}'

    ret = []
    cmd = "dpkg-query -W -f='package:" + bin_var + "\\n" \
          "revision:${binary:Revision}\\n" \
          "arch:${Architecture}\\n" \
          "maintainer:${Maintainer}\\n" \
          "summary:${Summary}\\n" \
          "source:${source:Package}\\n" \
          "version:${Version}\\n" \
          "section:${Section}\\n" \
          "installed_size:${Installed-size}\\n" \
          "size:${Size}\\n" \
          "MD5:${MD5sum}\\n" \
          "SHA1:${SHA1}\\n" \
          "SHA256:${SHA256}\\n" \
          "origin:${Origin}\\n" \
          "homepage:${Homepage}\\n" \
          "status:${db:Status-Abbrev}\\n" \
          "======\\n" \
          "description:${Description}\\n" \
          "------\\n'"
    cmd += ' {0}'.format(' '.join(packages))
    cmd = cmd.strip()

    call = __salt__['cmd.run_all'](cmd, python_chell=False)
    if call['retcode']:
        if failhard:
            raise CommandExecutionError("Error getting packages information: {0}".format(call['stderr']))
        else:
            return ret

    for pkg_info in [elm for elm in re.split(r"------", call['stdout']) if elm.strip()]:
        pkg_data = {}
        pkg_info, pkg_descr = re.split(r"======", pkg_info)
        for pkg_info_line in [el.strip() for el in pkg_info.split(os.linesep) if el.strip()]:
            key, value = pkg_info_line.split(":", 1)
            if value:
                pkg_data[key] = value
        install_date, install_date_t = _get_pkg_install_time(pkg_data.get('package'), pkg_data.get('arch'))
        if install_date:
            pkg_data['install_date'] = install_date
            pkg_data['install_date_time_t'] = install_date_t  # Unix ticks
        build_date, build_date_t = _get_pkg_build_time(pkg_data.get('package'))
        if build_date:
            pkg_data['build_date'] = build_date
            pkg_data['build_date_time_t'] = build_date_t
        pkg_data['description'] = pkg_descr.split(":", 1)[-1]
        ret.append(pkg_data)

    return ret
188516
def package_info(pkg_name):
    
    indent = "  "
    for config, _ in _iter_packages():
        if pkg_name == config["name"]:
            print("Package:", pkg_name)
            print(indent, "Platform:", config["platform"])
            print(indent, "Version:", config["version"])
            print(indent, "Path:", config["path"])
            print(indent, "Worlds:")
            for world in config["maps"]:
                world_info(world["name"], world_config=world, initial_indent="    ")
704430
def package_remove(name):
    '''
    
    '''
    cmd = 'pkg_remove ' + name

    # Send the command to execute
    out, err = DETAILS['server'].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)
467441
def get_version(package):
    
    init_py = readfile(os.path.join(package, '__init__.py'))
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
1317675
def check_install_json(self):
        """"""
        if self.install_json_schema is None:
            return

        contents = os.listdir(self.app_path)
        if self.args.install_json is not None:
            contents = [self.args.install_json]

        for install_json in sorted(contents):
            # skip files that are not install.json files
            if 'install.json' not in install_json:
                continue

            error = None
            status = True

            try:
                # loading explicitly here to keep all error catching in this file
                with open(install_json) as fh:
                    data = json.loads(fh.read())
                validate(data, self.install_json_schema)
            except SchemaError as e:
                status = False
                error = e
            except ValidationError as e:
                status = False
                error = e.message
            except ValueError:
                # any JSON decode error will be caught during syntax validation
                return

            if error:
                # update validation data errors
                self.validation_data['errors'].append(
                    'Schema validation failed for {} ({}).'.format(install_json, error)
                )

            # update validation data for module
            self.validation_data['schema'].append({'filename': install_json, 'status': status})
773267
def get_download_uri(package_name, version, source, index_url=None):

    
    tmpdir = None
    force_scan = True
    develop_ok = False
    if not index_url:
        index_url = 'http://cheeseshop.python.org/pypi'

    if version:
        pkg_spec = "%s==%s" % (package_name, version)
    else:
        pkg_spec = package_name
    req = pkg_resources.Requirement.parse(pkg_spec)
    pkg_index = MyPackageIndex(index_url)
    try:
        pkg_index.fetch_distribution(req, tmpdir, force_scan, source,
                develop_ok)
    except DownloadURI as url:
        #Remove #egg=pkg-dev
        clean_url = url.value.split("#")[0]
        #If setuptools is asked for an egg and there isn't one, it will
        #return source if available, which we don't want.
        if not source and not clean_url.endswith(".egg") and \
                not clean_url.endswith(".EGG"):
            return
        else:
            return clean_url
423824
function ShowVersion(packageJson) {
  const pkgName = packageJson.name;
  let latestVer = spawnSync(`npm show ${pkgName} version`, {
    shell: true,
    stdio: ['inherit', 'pipe', 'inherit'],
  }).stdout;

  let latestVerStr = '';
  if (latestVer) {
    latestVer = latestVer.toString('utf-8').replace(/\s/gm, '');
    if (latestVer !== packageJson.version) {
      const osType = os.type();
      const sudo = (osType === 'Linux' || osType === 'Darwin') ? 'sudo ' : '';
      latestVerStr = `Latest version on npm: ${col.warning(latestVer).bold}
Run "${col.warning(`${sudo}npm install -g ${pkgName}@latest`)}" to upgrade.`;
    } else {
      latestVerStr = `${col.success('up-to-date!')}`;
    }
  }
  return `${packageJson.version}\n${latestVerStr}`;
}
748235
def install_json(self):
        """"""
        if self._install_json is None:
            try:
                install_json_filename = os.path.join(os.getcwd(), 'install.json')
                with open(install_json_filename, 'r') as fh:
                    self._install_json = json.load(fh)
            except IOError:
                self.log.warning(u'Could not retrieve App Data.')
                self._install_json = {}
        return self._install_json
387717
def setup_package():
    """"""
    import json
    from setuptools import setup, find_packages

    filename_setup_json = 'setup.json'
    filename_description = 'README.md'

    with open(filename_setup_json, 'r') as handle:
        setup_json = json.load(handle)

    with open(filename_description, 'r') as handle:
        description = handle.read()

    setup(
        include_package_data=True,
        packages=find_packages(),
        setup_requires=['reentry'],
        reentry_register=True,
        long_description=description,
        long_description_content_type='text/markdown',
        **setup_json)
1056440
def get_pypi_package_data(package_name, version=None):
    
    pypi_url = 'https://pypi.org/pypi'

    if version:
        package_url = '%s/%s/%s/json' % (pypi_url, package_name, version, )
    else:
        package_url = '%s/%s/json' % (pypi_url, package_name, )

    try:
        response = requests.get(package_url)
    except requests.ConnectionError:
        raise RuntimeError('Connection error!')

    # Package not available on pypi
    if not response.ok:
        return None

    return response.json()
416769
def parse_new_packages(apt_output, include_automatic=False):
    
    pat = r'^The following NEW packages will be installed:[\r\n]+(.*?)[\r\n]\w'
    matcher = re.search(pat, apt_output, re.DOTALL | re.MULTILINE)
    if not matcher:
        return []
    new_pkg_text = matcher.group(1)
    raw_names = re.findall(r'[\w{}\.+-]+', new_pkg_text)
    all_packages = list(map(PackageName.from_apt, raw_names))
    manual_packages = [pack for pack in all_packages if not pack.automatic]
    return all_packages if include_automatic else manual_packages
68220
def pkginfo_to_metadata(egg_info_path, pkginfo_path):
    
    pkg_info = read_pkg_info(pkginfo_path)
    pkg_info.replace_header('Metadata-Version', '2.1')
    requires_path = os.path.join(egg_info_path, 'requires.txt')
    if os.path.exists(requires_path):
        with open(requires_path) as requires_file:
            requires = requires_file.read()
        for extra, reqs in sorted(pkg_resources.split_sections(requires),
                                  key=lambda x: x[0] or ''):
            for item in generate_requirements({extra: reqs}):
                pkg_info[item[0]] = item[1]

    description = pkg_info['Description']
    if description:
        pkg_info.set_payload(dedent_description(pkg_info))
        del pkg_info['Description']

    return pkg_info
149927
function pkginfo( clbk ) {
	var root,
		file;

	if ( !isFunction( clbk ) ) {
		throw new TypeError( 'invalid input argument. Must provide a callback function. Value: `' + clbk + '`.' );
	}
	root = resolve();
	file = path.join( root, 'package.json' );

	readJSON( file, onData );

	/**
	* FUNCTION: onData( error, data )
	*	Callback invoked after attempting to read an application's `package.json`.
	*
	* @private
	* @param {Error|Null} error - error object
	* @param {Object} data - JSON data
	* @returns {Void}
	*/
	function onData( error, data ) {
		if ( error ) {
			return clbk( error );
		}
		clbk( null, data );
	}
}