Return an :class:`UpgradeManager` instance.

        :param conn: a DB API 2 connection
        :param str pkg_name: the name of the package with the upgrade scripts
322682
def instance(cls, conn, pkg_name='openquake.server.db.schema.upgrades'):
        
        try:
            # upgrader is an UpgradeManager instance defined in the __init__.py
            upgrader = importlib.import_module(pkg_name).upgrader
        except ImportError:
            raise SystemExit(
                'Could not import %s (not in the PYTHONPATH?)' % pkg_name)
        if not upgrader.read_scripts():
            raise SystemExit(
                'The upgrade_dir does not contain scripts matching '
                'the pattern %s' % upgrader.pattern)
        curs = conn.cursor()
        # check if there is already a versioning table
        curs.execute("SELECT name FROM sqlite_master "
                     "WHERE name=%r" % upgrader.version_table)
        versioning_table = curs.fetchall()
        # if not, run the base script and create the versioning table
        if not versioning_table:
            upgrader.init(conn)
            conn.commit()
        return upgrader
328596
def _info(self, args):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package must be specified')

        package = args[1]

        pkg_info = self._pkgdb_fun('info', package, self.db_conn)
        if pkg_info is None:
            raise SPMPackageError('package {0} not installed'.format(package))
        self.ui.status(self._get_info(pkg_info))
1340032
def package_releases(self, project_name):
        
        try:
            return self._connection.package_releases(project_name)
        except Exception as err:
            raise PyPIClientError(err)
1231555
def get_records_for_package(self, package_name):
        

        names = self.package_module_map.get(package_name, [])
        result = {}
        for name in names:
            result.update(self.get_record(name))
        return result
101960
def get_version(package_name):
    
    module = 'prosper.' + package_name + '._version'
    package = importlib.import_module(module)

    version = package.__version__

    return version
259511
def upgrade(self, flag):
        
        for pkg in self.binary:
            try:
                subprocess.call("upgradepkg {0} {1}".format(flag, pkg),
                                shell=True)
                check = pkg[:-4].split("/")[-1]
                if os.path.isfile(self.meta.pkg_path + check):
                    print("Completed!\n")
                else:
                    raise SystemExit()
            except subprocess.CalledProcessError:
                self._not_found("Can't upgrade", self.binary, pkg)
                raise SystemExit(1)
458172
def version(self, conn):
        

        command = b'version\r\n'
        response = yield from self._execute_simple_command(
            conn, command)
        if not response.startswith(const.VERSION):
            raise ClientException('Memcached version failed', response)
        version, number = response.split()
        return number
737622
def register_pkg(name, formula_def, conn=None):
    '''
    
    '''
    close = False
    if conn is None:
        close = True
        conn = init()

    conn.execute('INSERT INTO packages VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (
        name,
        formula_def['version'],
        formula_def['release'],
        datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
        formula_def.get('os', None),
        formula_def.get('os_family', None),
        formula_def.get('dependencies', None),
        formula_def.get('os_dependencies', None),
        formula_def.get('os_family_dependencies', None),
        formula_def['summary'],
        formula_def['description'],
    ))
    if close:
        conn.close()
518624
def update(self, *pkgs, **kwargs):
        """"""
        cmd_list = ['update', '--json', '--yes']

        if not pkgs and not kwargs.get('all'):
            raise TypeError("Must specify at least one package to update, or "
                            "all=True.")

        cmd_list.extend(
            self._setup_install_commands_from_kwargs(
                kwargs,
                ('dry_run', 'no_deps', 'override_channels',
                 'no_pin', 'force', 'all', 'use_index_cache', 'use_local',
                 'alt_hint')))

        cmd_list.extend(pkgs)

        return self._call_and_parse(cmd_list, abspath=kwargs.get('abspath',
                                                                 True))
574388
def get_pkg_names(pkgs):
    
    result = set()
    with open(join("mapping"), "r") as f:
        data = dict(x.strip().split(":") for x in f)
    for pkg in pkgs:
        # Look up the mapped requirement. If a mapping isn't found,
        # simply use the package name.
        result.add(data.get(pkg, pkg))
    # Return a sorted list for backward compatibility.
    return sorted(result, key=lambda s: s.lower())
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
290829
def install_build_requires(pkg_targets):
    """"""

    def pip_install(pkg_name, pkg_vers=None):
        pkg_name_version = '%s==%s' % (pkg_name, pkg_vers) if pkg_vers else pkg_name
        print '[WARNING] %s not found, attempting to install using a raw "pip install" call!' % pkg_name_version
        subprocess.Popen('pip install %s' % pkg_name_version, shell=True).communicate()

    def get_pkg_info(pkg):
        """Get package name and version given a build_requires element"""
        pkg_name, pkg_vers = None, None
        if '==' in pkg:
            pkg_name, pkg_vers = pkg.split('==')
        else:
            pkg_name = pkg.replace('>', '').replace('<', '').split('=')[0]
        return pkg_name, pkg_vers

    for pkg in pkg_targets:
        pkg_name, pkg_vers = get_pkg_info(pkg)
        try:
            pkg_name_version = '%s==%s' % (pkg_name, pkg_vers) if pkg_vers else pkg_name
            if pkg_vers:
                version = getattr(importlib.import_module(pkg_name), '__version__')
                if version != pkg_vers:
                    pip_install(pkg_name, pkg_vers)
            else:
                importlib.import_module(pkg_name)
        except ImportError:
            pip_install(pkg_name, pkg_vers)
755387
def get_dependency_package(
        self, package_name: str
    ) -> "Package":  # type: ignore # noqa: F821
        
        self._validate_name(package_name)
        return self.build_dependencies.get(package_name)
688417
def package_releases(request, package_name, show_hidden=False):
    
    session = DBSession()
    package = Package.by_name(session, package_name)
    return [rel.version for rel in package.sorted_releases]
830662
def get_package_update_list(package_name, version):
    
    package_version = semantic_version.Version.coerce(version)

    # Get package and version data from pypi
    package_data = get_pypi_package_data(package_name)
    version_data = get_pypi_package_data(package_name, version)

    # Current release specific information
    current_release = ''
    current_release_license = ''

    # Latest release specific information
    latest_release = ''
    latest_release_license = ''

    # Information about packages
    major_updates = []
    minor_updates = []
    patch_updates = []
    pre_releases = []
    non_semantic_versions = []

    if package_data:
        latest_release = package_data['info']['version']
        latest_release_license = package_data['info']['license'] if package_data['info']['license'] else ''

        for release, info in package_data['releases'].items():
            parsed_release = parse(release)

            upload_time = None
            if info:
                upload_time = datetime.strptime(info[0]['upload_time'], "%Y-%m-%dT%H:%M:%S")

            try:
                # Get semantic version of package
                release_version = semantic_version.Version.coerce(release)

                if not parsed_release.is_prerelease:
                    # Place package in the appropriate semantic visioning list
                    if release_version in semantic_version.Spec(">=%s" % package_version.next_major()):
                        major_updates.append({
                            'version': release,
                            'upload_time': upload_time,
                        })
                    elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_minor(), package_version.next_major())):
                        minor_updates.append({
                            'version': release,
                            'upload_time': upload_time,
                        })
                    elif release_version in semantic_version.Spec(">=%s,<%s" % (package_version.next_patch(), package_version.next_minor())):
                        patch_updates.append({
                            'version': release,
                            'upload_time': upload_time,
                        })
                else:
                    pre_releases.append({
                        'version': release,
                        'upload_time': upload_time
                    })
            except ValueError:
                # Keep track of versions that could not be recognized as semantic
                non_semantic_versions.append({'version': release, 'upload_time': upload_time})

    if version_data:
        current_release = version_data['info']['version']
        current_release_license = version_data['info']['license'] if version_data['info']['license'] else ''

    # Get number of newer releases available for the given package
    newer_releases = len(major_updates + minor_updates + patch_updates)

    return {
        'current_release': current_release,
        'current_release_license': current_release_license,
        'latest_release': latest_release,
        'latest_release_license': latest_release_license,
        'newer_releases': newer_releases,
        'pre_releases': len(pre_releases),
        'major_updates': sorted(major_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
        'minor_updates': sorted(minor_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
        'patch_updates': sorted(patch_updates, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
        'pre_release_updates': sorted(pre_releases, key=lambda x: semantic_version.Version.coerce(x['version']), reverse=True),
        'non_semantic_versions': non_semantic_versions,
    }
1172836
def list_pkgs(versions_as_list=False, **kwargs):
    '''
    
    '''
    versions_as_list = salt.utils.data.is_true(versions_as_list)
    # not yet implemented or not applicable
    if any([salt.utils.data.is_true(kwargs.get(x))
            for x in ('removed', 'purge_desired')]):
        return {}

    if 'pkg.list_pkgs' in __context__:
        if versions_as_list:
            return __context__['pkg.list_pkgs']
        else:
            ret = copy.deepcopy(__context__['pkg.list_pkgs'])
            __salt__['pkg_resource.stringify'](ret)
            return ret

    ret = {}
    cmd = 'info --json=v1 --installed'
    package_info = salt.utils.json.loads(_call_brew(cmd)['stdout'])

    for package in package_info:
        # Brew allows multiple versions of the same package to be installed.
        # Salt allows for this, so it must be accounted for.
        versions = [v['version'] for v in package['installed']]
        # Brew allows for aliasing of packages, all of which will be
        # installable from a Salt call, so all names must be accounted for.
        names = package['aliases'] + [package['name'], package['full_name']]
        # Create a list of tuples containing all possible combinations of
        # names and versions, because all are valid.
        combinations = [(n, v) for n in names for v in versions]

        for name, version in combinations:
            __salt__['pkg_resource.add_pkg'](ret, name, version)

    # Grab packages from brew cask, if available.
    # Brew Cask doesn't provide a JSON interface, must be parsed the old way.
    try:
        cask_cmd = 'cask list --versions'
        out = _call_brew(cask_cmd)['stdout']

        for line in out.splitlines():
            try:
                name_and_versions = line.split(' ')
                name = '/'.join(('caskroom/cask', name_and_versions[0]))
                installed_versions = name_and_versions[1:]
                key_func = functools.cmp_to_key(salt.utils.versions.version_cmp)
                newest_version = sorted(installed_versions, key=key_func).pop()
            except ValueError:
                continue
            __salt__['pkg_resource.add_pkg'](ret, name, newest_version)
    except CommandExecutionError:
        pass

    __salt__['pkg_resource.sort_pkglist'](ret)
    __context__['pkg.list_pkgs'] = copy.deepcopy(ret)
    if not versions_as_list:
        __salt__['pkg_resource.stringify'](ret)
    return ret
321554
def from_pkg(self):
        
        if self._version is None:
            frame = caller(1)
            pkg = frame.f_globals.get('__package__')
            if pkg is not None:
                self._version = pkg_version(pkg)
        return self