Get metadata information from the distribution.

    Depending on the package this may either be in METADATA or PKG-INFO

    :param item: pkg_resources WorkingSet item
    :returns: metadata resource as list of non-blank non-comment lines
482619
def get_metadata(item):
    
    for metadata_key in ('METADATA', 'PKG-INFO'):
        try:
            metadata_lines = item.get_metadata_lines(metadata_key)
            break
        except (KeyError, IOError):
            # The package will be shown in the report without any license information
            # if a metadata key is not found.
            metadata_lines = []

    return metadata_lines
244599
def read_metadata(self):  # type: () ->Dict[str,str]
        
        config = configparser.ConfigParser()
        config.read(self.file_inventory.config_files[0])
        try:
            return {"setup.cfg": config["metadata"]["version"]}
        except KeyError:
            return {}
163266
def fetch_package_version(dist_name):
    
    try:
        # Importing pkg_resources can be slow, so only import it
        # if we need it.
        import pkg_resources
    except ImportError:
        # pkg_resource is not available on Google App Engine
        raise NotImplementedError('pkg_resources is not available '
                                  'on this Python install')
    dist = pkg_resources.get_distribution(dist_name)
    return dist.version
1006305
def search_packages_info(query):
    
    installed = {}
    for p in pkg_resources.working_set:
        installed[canonicalize_name(p.project_name)] = p

    query_names = [canonicalize_name(name) for name in query]

    for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
        package = {
            'name': dist.project_name,
            'version': dist.version,
            'location': dist.location,
            'requires': [dep.project_name for dep in dist.requires()],
        }
        file_list = None
        metadata = None
        if isinstance(dist, pkg_resources.DistInfoDistribution):
            # RECORDs should be part of .dist-info metadatas
            if dist.has_metadata('RECORD'):
                lines = dist.get_metadata_lines('RECORD')
                paths = [l.split(',')[0] for l in lines]
                paths = [os.path.join(dist.location, p) for p in paths]
                file_list = [os.path.relpath(p, dist.location) for p in paths]

            if dist.has_metadata('METADATA'):
                metadata = dist.get_metadata('METADATA')
        else:
            # Otherwise use pip's log for .egg-info's
            if dist.has_metadata('installed-files.txt'):
                paths = dist.get_metadata_lines('installed-files.txt')
                paths = [os.path.join(dist.egg_info, p) for p in paths]
                file_list = [os.path.relpath(p, dist.location) for p in paths]

            if dist.has_metadata('PKG-INFO'):
                metadata = dist.get_metadata('PKG-INFO')

        if dist.has_metadata('entry_points.txt'):
            entry_points = dist.get_metadata_lines('entry_points.txt')
            package['entry_points'] = entry_points

        if dist.has_metadata('INSTALLER'):
            for line in dist.get_metadata_lines('INSTALLER'):
                if line.strip():
                    package['installer'] = line.strip()
                    break

        # @todo: Should pkg_resources.Distribution have a
        # `get_pkg_info` method?
        feed_parser = FeedParser()
        feed_parser.feed(metadata)
        pkg_info_dict = feed_parser.close()
        for key in ('metadata-version', 'summary',
                    'home-page', 'author', 'author-email', 'license'):
            package[key] = pkg_info_dict.get(key)

        # It looks like FeedParser cannot deal with repeated headers
        classifiers = []
        for line in metadata.splitlines():
            if line.startswith('Classifier: '):
                classifiers.append(line[len('Classifier: '):])
        package['classifiers'] = classifiers

        if file_list:
            package['files'] = sorted(file_list)
        yield package
1336608
def _extract_info_from_package(dependency,
                               extract_type=None,
                               debug=False,
                               include_build_requirements=False
                               ):
    
    output_folder = tempfile.mkdtemp(prefix="pythonpackage-metafolder-")
    try:
        extract_metainfo_files_from_package(
            dependency, output_folder, debug=debug
        )

        with open(os.path.join(output_folder, "METADATA"),
                  "r", encoding="utf-8"
                 ) as f:
            # Get metadata and cut away description (is after 2 linebreaks)
            metadata_entries = f.read().partition("\n\n")[0].splitlines()

        if extract_type == "name":
            name = None
            for meta_entry in metadata_entries:
                if meta_entry.lower().startswith("name:"):
                    return meta_entry.partition(":")[2].strip()
            if name is None:
                raise ValueError("failed to obtain package name")
            return name
        elif extract_type == "dependencies":
            requirements = []
            if os.path.exists(os.path.join(output_folder,
                                           'pyproject.toml')
                              ) and include_build_requirements:
                with open(os.path.join(output_folder, 'pyproject.toml')) as f:
                    build_sys = pytoml.load(f)['build-system']
                    if "requires" in build_sys:
                        requirements += build_sys["requires"]

            # Add requirements from metadata:
            requirements += [
                entry.rpartition("Requires-Dist:")[2].strip()
                for entry in metadata_entries
                if entry.startswith("Requires-Dist")
            ]

            return list(set(requirements))  # remove duplicates
    finally:
        shutil.rmtree(output_folder)
292819
def get_distribute_verbatim_metadata(self):
        
        # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template
        metadata = dict(self._mdata['distribute_verbatim'])
        metadata.update({'existing_boolean_values': self._my_map['distributeVerbatim']})
        return Metadata(**metadata)
566016
def get_download_urls(self, package_name, version="", pkg_type="all"):
        """"""

        if version:
            versions = [version]
        else:

            #If they don't specify version, show em all.

            (package_name, versions) = self.query_versions_pypi(package_name)

        all_urls = []
        for ver in versions:
            metadata = self.release_data(package_name, ver)
            for urls in self.release_urls(package_name, ver):
                if pkg_type == "source" and urls['packagetype'] == "sdist":
                    all_urls.append(urls['url'])
                elif pkg_type == "egg" and \
                        urls['packagetype'].startswith("bdist"):
                    all_urls.append(urls['url'])
                elif pkg_type == "all":
                    #All
                    all_urls.append(urls['url'])

            #Try the package's metadata directly in case there's nothing
            #returned by XML-RPC's release_urls()
            if metadata and metadata.has_key('download_url') and \
                        metadata['download_url'] != "UNKNOWN" and \
                        metadata['download_url'] != None:
                if metadata['download_url'] not in all_urls:
                    if pkg_type != "all":
                        url = filter_url(pkg_type, metadata['download_url'])
                        if url:
                            all_urls.append(url)
        return all_urls
1342139
def get_pkg_info_revision():
    
    warnings.warn("get_pkg_info_revision is deprecated.", EggInfoDeprecationWarning)
    if os.path.exists('PKG-INFO'):
        with io.open('PKG-INFO') as f:
            for line in f:
                match = re.match(r"Version:.*-r(\d+)\s*$", line)
                if match:
                    return int(match.group(1))
    return 0
1290359
def _GetPkgResources(package_name, filepath):
  """"""
  requirement = pkg_resources.Requirement.parse(package_name)
  try:
    return pkg_resources.resource_filename(requirement, filepath)
  except pkg_resources.DistributionNotFound:
    # It may be that the working set is not in sync (e.g. if sys.path was
    # manipulated). Try to reload it just in case.
    pkg_resources.working_set = pkg_resources.WorkingSet()
    try:
      return pkg_resources.resource_filename(requirement, filepath)
    except pkg_resources.DistributionNotFound:
      logging.error("Distribution %s not found. Is it installed?", package_name)
      return None
65756
def _get_package_items(self):
        
        warnings.warn("use _get_upgrade_prices() instead",
                      DeprecationWarning)
        mask = [
            'description',
            'capacity',
            'units',
            'prices[id,locationGroupId,categories[name,id,categoryCode]]'
        ]
        mask = "mask[%s]" % ','.join(mask)

        package_keyname = "CLOUD_SERVER"
        package = self.ordering_manager.get_package_by_key(package_keyname)

        package_service = self.client['Product_Package']
        return package_service.getItems(id=package['id'], mask=mask)
797816
def parse_info(raw_info, apply_tag=None):
    
    parse_releases(raw_info)
    parse_packages(raw_info, apply_tag=apply_tag)
    return raw_info
1222420
def get_package(repo_url, pkg_name, timeout=1):
    """"""
    url = repo_url + "/packages/" + pkg_name
    headers = {'accept': 'application/json'}
    resp = requests.get(url, headers=headers, timeout=timeout)
    if resp.status_code == 404:
        return None
    return resp.json()
613235
def get_info(self, item, check_not_on_or_after=True):
        
        try:
            (timestamp, info) = item
        except ValueError:
            raise ToOld()

        if check_not_on_or_after and not time_util.not_on_or_after(timestamp):
            raise ToOld()

        return info or None
1020981
def get_resource_metadata(self, resource=None):
        
        result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE')
        if resource:
            result = next((item for item in result if item['ResourceID'] == resource), None)
        return result
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()
199657
def get_lb_pkgs(self):
        

        _filter = {'items': {'description':
                             utils.query_filter('*Load Balancer*')}}

        packages = self.prod_pkg.getItems(id=0, filter=_filter)
        pkgs = []
        for package in packages:
            if not package['description'].startswith('Global'):
                pkgs.append(package)
        return pkgs
1025698
def get_version_from_unpacked_sdist(path):
    """"""
    # This is a condensed version of the relevant code in pkginfo 1.4.1
    try:
        with open(os.path.join(path, 'PKG-INFO')) as f:
            data = f.read()
    except IOError:
        # Could not load path as an unpacked sdist as it had no PKG-INFO file
        return
    fp = StringIO(_must_decode(data))
    msg = Parser().parse(fp)
    value = msg.get('Version')
    if value != 'UNKNOWN':
        return value