Parse yum/dnf output (which could contain irregular line breaks if package
    names are long) retrieving the name, version, etc., and return a list of
    pkginfo namedtuples.
322463
def _yum_pkginfo(output):
    '''
    
    '''
    cur = {}
    keys = itertools.cycle(('name', 'version', 'repoid'))
    values = salt.utils.itertools.split(_strip_headers(output))
    osarch = __grains__['osarch']
    for (key, value) in zip(keys, values):
        if key == 'name':
            try:
                cur['name'], cur['arch'] = value.rsplit('.', 1)
            except ValueError:
                cur['name'] = value
                cur['arch'] = osarch
            cur['name'] = salt.utils.pkg.rpm.resolve_name(cur['name'],
                                                          cur['arch'],
                                                          osarch)
        else:
            if key == 'version':
                # Suppport packages with no 'Release' parameter
                value = value.rstrip('-')
            elif key == 'repoid':
                # Installed packages show a '@' at the beginning
                value = value.lstrip('@')
            cur[key] = value
            if key == 'repoid':
                # We're done with this package, create the pkginfo namedtuple
                pkginfo = salt.utils.pkg.rpm.pkginfo(**cur)
                # Clear the dict for the next package
                cur = {}
                # Yield the namedtuple
                if pkginfo is not None:
                    yield pkginfo
676820
def _get_changed_cfg_pkgs(self, data):
        '''
        
        '''
        f_data = dict()
        for pkg_name, pkg_files in data.items():
            cfgs = list()
            cfg_data = list()
            if self.grains_core.os_data().get('os_family') == 'Debian':
                cfg_data = salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '--verify',
                                                           pkg_name)[0]).split(os.linesep)
            elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']:
                cfg_data = salt.utils.stringutils.to_str(self._syscall("rpm", None, None, '-V', '--nodeps', '--nodigest',
                                                           '--nosignature', '--nomtime', '--nolinkto',
                                                           pkg_name)[0]).split(os.linesep)
            for line in cfg_data:
                line = line.strip()
                if not line or line.find(" c ") < 0 or line.split(" ")[0].find("5") < 0:
                    continue
                cfg_file = line.split(" ")[-1]
                if cfg_file in pkg_files:
                    cfgs.append(cfg_file)
            if cfgs:
                f_data[pkg_name] = cfgs

        return f_data
494656
def __get_cfg_pkgs_rpm(self):
        '''
        
        '''
        out, err = self._syscall('rpm', None, None, '-qa', '--configfiles',
                                 '--queryformat', '%{name}-%{version}-%{release}\\n')
        data = dict()
        pkg_name = None
        pkg_configs = []

        out = salt.utils.stringutils.to_str(out)
        for line in out.split(os.linesep):
            line = line.strip()
            if not line:
                continue
            if not line.startswith("/"):
                if pkg_name and pkg_configs:
                    data[pkg_name] = pkg_configs
                pkg_name = line
                pkg_configs = []
            else:
                pkg_configs.append(line)

        if pkg_name and pkg_configs:
            data[pkg_name] = pkg_configs

        return data
64316
def parse_version(output):
    
    for x in output.splitlines():
        match = VERSION_PATTERN.match(x)
        if match:
            return match.group('version').strip()
    return None
1070618
private String parsePackageName(String pkgname) {
        int index = -1;
        for (int j = 0; j < MAX_CONSTANT_VALUE_INDEX_LENGTH; j++) {
            index = pkgname.indexOf(".", index + 1);
        }
        if (index != -1) {
            pkgname = pkgname.substring(0, index);
        }
        return pkgname;
    }
493920
def split_package_name(p):
    """"""
    s = p.split(six.u('=='))
    if len(s) == 1:
        return (to_text(s[0]), None)
    else:
        return (to_text(s[0]), to_text(s[1]))
44668
def _parse_version(version):
        
        parsed_version = parse_version(version)
        return tuple(
            int(dot_version)
            for dot_version in parsed_version.base_version.split('.')
        ) + (parsed_version.is_prerelease,)
914038
def _parse_dict(self, data):
		
		d = {}
		for line in data.split('\r\n'):
			match = GNTP_HEADER.match(line)
			if not match:
				continue

			key = match.group(1).strip()
			val = match.group(2).strip()
			d[key] = val
		return d
231003
def info2dicts(info, in_place=False):
    
    if 'packages' not in info and 'releases' not in info:
        return info
    if in_place:
        info_dicts = info
    else:
        info_dicts = info.copy()
    packages = info.get('packages')
    if packages:
        info_dicts['packages'] = list2dict(packages, 'project')
    releases = info.get('releases')
    if releases:
        info_dicts['releases'] = list2dict(releases, 'name')
    return info_dicts
940264
def ParseMultiple(self, result_dicts):
    """"""
    status = rdf_client.SoftwarePackage.InstallState.INSTALLED
    packages = []
    for result_dict in result_dicts:
      packages.append(
          rdf_client.SoftwarePackage(
              name=result_dict["Name"],
              description=result_dict["Description"],
              version=result_dict["Version"],
              install_state=status))

    if packages:
      yield rdf_client.SoftwarePackages(packages=packages)
466420
def _pkg_names(pkg):
        
        parts = pkg.split('.')
        while parts:
            yield '.'.join(parts)
            parts.pop()
563402
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 = {}
    pkgs = _vartree().dbapi.cpv_all()
    for cpv in pkgs:
        __salt__['pkg_resource.add_pkg'](ret,
                                         _cpv_to_cp(cpv),
                                         _cpv_to_version(cpv))
    __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
1135210
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

    pkgin = _check_pkgin()
    ret = {}

    out = __salt__['cmd.run'](
        [pkgin, 'ls'] if pkgin else ['pkg_info'],
        output_loglevel='trace')

    for line in out.splitlines():
        try:
            # Some versions of pkgin check isatty unfortunately
            # this results in cases where a ' ' or ';' can be used
            pkg, ver = re.split('[; ]', line, 1)[0].rsplit('-', 1)
        except ValueError:
            continue
        __salt__['pkg_resource.add_pkg'](ret, pkg, ver)

    __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
603059
def get_dump_names(self, names, dumps=None):
        
        # Default value for dumps argument is an empty set (setting directly
        # as a python argument would result as a shared value between
        # instances)
        if dumps is None:
            dumps = set([])

        # Add name to the dumps and find its dependancies
        for item in names:
            if item not in self:
                if not self.silent_key_error:
                    raise KeyError("Dump name '{0}' is unknowed".format(item))
                else:
                    continue

            dumps.add(item)

            # Add dependancies names to the dumps
            deps = self.__getitem__(item).get('dependancies', [])
            dumps.update(deps)

        # Avoid maximum recursion when we allready find all dependancies
        if names == dumps:
            return dumps

        # Seems we don't have finded other dependancies yet, recurse to do it
        return self.get_dump_names(dumps.copy(), dumps)
1206815
def parse_package_for_version(name):
    
    from utool import util_regex
    init_fpath = join(name, '__init__.py')
    version_errmsg = textwrap.dedent(
        '''
        You must include a __version__ variable
        in %s\'s __init__.py file.
        Try something like:
        __version__ = '1.0.0.dev1' ''' % (name,))
    if not exists(init_fpath):
        raise AssertionError(version_errmsg)
    val_regex = util_regex.named_field('version', '[0-9a-zA-Z.]+')
    regexstr = '__version__ *= *[\'"]' + val_regex
    def parse_version(line):
        # Helper
        line = line.replace(' ', '').replace('\t', '')
        match_dict = util_regex.regex_parse(regexstr, line)
        if match_dict is not None:
            return match_dict['version']
    # Find the version  in the text of the source
    #version = 'UNKNOWN_VERSION'
    with open(init_fpath, 'r') as file_:
        for line in file_.readlines():
            if line.startswith('__version__'):
                version = parse_version(line)
                if version is not None:
                    return version
    raise AssertionError(version_errmsg)
562393
def __get_cfg_pkgs_dpkg(self):
        '''
        
        '''
        # Get list of all available packages
        data = dict()

        for pkg_name in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None,
                                                        '-Wf', "${binary:Package}\\n")[0]).split(os.linesep):
            pkg_name = pkg_name.strip()
            if not pkg_name:
                continue
            data[pkg_name] = list()
            for pkg_cfg_item in salt.utils.stringutils.to_str(self._syscall('dpkg-query', None, None, '-Wf', "${Conffiles}\\n",
                                                                pkg_name)[0]).split(os.linesep):
                pkg_cfg_item = pkg_cfg_item.strip()
                if not pkg_cfg_item:
                    continue
                pkg_cfg_file, pkg_cfg_sum = pkg_cfg_item.strip().split(" ", 1)
                data[pkg_name].append(pkg_cfg_file)

            # Dpkg meta data is unreliable. Check every package
            # and remove which actually does not have config files.
            if not data[pkg_name]:
                data.pop(pkg_name)

        return data
335424
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

    cmd = ['apk', 'info', '-v']
    ret = {}
    out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
    for line in salt.utils.itertools.split(out, '\n'):
        pkg_version = '-'.join(line.split('-')[-2:])
        pkg_name = '-'.join(line.split('-')[:-2])
        __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)

    __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