Build a list of installed RPMs in the format required for the
        metadata.
977760
def get_rpms(self):
        

        tags = [
            'NAME',
            'VERSION',
            'RELEASE',
            'ARCH',
            'EPOCH',
            'SIGMD5',
            'SIGPGP:pgpsig',
            'SIGGPG:pgpsig',
        ]

        cmd = "/bin/rpm " + rpm_qf_args(tags)
        try:
            # py3
            (status, output) = subprocess.getstatusoutput(cmd)
        except AttributeError:
            # py2
            with open('/dev/null', 'r+') as devnull:
                p = subprocess.Popen(cmd,
                                     shell=True,
                                     stdin=devnull,
                                     stdout=subprocess.PIPE,
                                     stderr=devnull)

                (stdout, stderr) = p.communicate()
                status = p.wait()
                output = stdout.decode()

        if status != 0:
            self.log.debug("%s: stderr output: %s", cmd, stderr)
            raise RuntimeError("%s: exit code %s" % (cmd, status))

        return parse_rpm_output(output.splitlines(), tags)
777966
def rels(self):
        """"""
        r = []
        for i in self.metadata:
            r = r + i[REL]
        return []
1178436
function setupTempDir(tmpDir) {
  var rpmStructure = ['BUILD', 'BUILDROOT', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'];

  // If the tmpDir exists (probably from previous build), delete it first
  if (fsx.existsSync(tmpDir)) {
    logger(chalk.cyan('Removing old temporary directory.'));
    fsx.removeSync(tmpDir);
  }

  // Create RPM folder structure
  logger(chalk.cyan('Creating RPM directory structure at:'), tmpDir);
  _.forEach(rpmStructure, function(dirName) {
    fsx.mkdirpSync(path.join(tmpDir, dirName));
  });
}
1213128
def build_srpm(specfile, save_dir):
    
    logger.info('Starting rpmbuild to build: {0} SRPM.'.format(specfile))
    if save_dir != get_default_save_path():
        try:
            msg = subprocess.Popen(
                ['rpmbuild',
                 '--define', '_sourcedir {0}'.format(save_dir),
                 '--define', '_builddir {0}'.format(save_dir),
                 '--define', '_srcrpmdir {0}'.format(save_dir),
                 '--define', '_rpmdir {0}'.format(save_dir),
                 '-bs', specfile], stdout=subprocess.PIPE).communicate(
                 )[0].strip()
        except OSError:
            logger.error(
                "Rpmbuild failed for specfile: {0} and save_dir: {1}".format(
                    specfile, save_dir), exc_info=True)
            msg = 'Rpmbuild failed. See log for more info.'
        return msg
    else:
        if not os.path.exists(save_dir):
            raise IOError("Specify folder to store a file (SAVE_DIR) "
                          "or install rpmdevtools.")
        try:
            msg = subprocess.Popen(
                ['rpmbuild',
                 '--define', '_sourcedir {0}'.format(save_dir + '/SOURCES'),
                 '--define', '_builddir {0}'.format(save_dir + '/BUILD'),
                 '--define', '_srcrpmdir {0}'.format(save_dir + '/SRPMS'),
                 '--define', '_rpmdir {0}'.format(save_dir + '/RPMS'),
                 '-bs', specfile], stdout=subprocess.PIPE).communicate(
                )[0].strip()
        except OSError:
            logger.error("Rpmbuild failed for specfile: {0} and save_dir: "
                         "{1}".format(specfile, save_dir), exc_info=True)
            msg = 'Rpmbuild failed. See log for more info.'
        return msg
723186
def _GenerateInitConfigs(self, template_dir, rpm_build_dir):
    """"""
    client_name = config.CONFIG.Get("Client.name", context=self.context)
    initd_target_filename = os.path.join(rpm_build_dir, "etc/init.d",
                                         client_name)

    # Generate init.d
    utils.EnsureDirExists(os.path.dirname(initd_target_filename))
    self.GenerateFile(
        os.path.join(template_dir, "rpmbuild/grr-client.initd.in"),
        initd_target_filename)

    # Generate systemd unit
    if config.CONFIG["Template.version_numeric"] >= 3125:
      systemd_target_filename = os.path.join(rpm_build_dir,
                                             "usr/lib/systemd/system/",
                                             "%s.service" % client_name)

      utils.EnsureDirExists(os.path.dirname(systemd_target_filename))
      self.GenerateFile(
          os.path.join(template_dir, "rpmbuild/grr-client.service.in"),
          systemd_target_filename)
292364
def extract_rpm (archive, compression, cmd, verbosity, interactive, outdir):
    """"""
    # also check cpio
    cpio = util.find_program("cpio")
    if not cpio:
        raise util.PatoolError("cpio(1) is required for rpm2cpio extraction; please install it")
    path = util.shell_quote(os.path.abspath(archive))
    cmdlist = [util.shell_quote(cmd), path, "|", util.shell_quote(cpio),
        '--extract', '--make-directories', '--preserve-modification-time',
        '--no-absolute-filenames', '--force-local', '--nonmatching',
        r'"*\.\.*"']
    if verbosity > 1:
        cmdlist.append('-v')
    return (cmdlist, {'cwd': outdir, 'shell': True})
406892
def build_specfile(target, source, env):
    
    file = open(target[0].get_abspath(), 'w')

    try:
        file.write( build_specfile_header(env) )
        file.write( build_specfile_sections(env) )
        file.write( build_specfile_filesection(env, source) )
        file.close()

        # call a user specified function
        if 'CHANGE_SPECFILE' in env:
            env['CHANGE_SPECFILE'](target, source)

    except KeyError as e:
        raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
725926
def wheel_metadata(self):
        """"""
        if not self.is_wheel:
            raise TypeError("Requirement is not a wheel distribution!")
        for distribution in find_distributions(self.source_directory):
            return distribution
        msg = "pkg_resources didn't find a wheel distribution in %s!"
        raise Exception(msg % self.source_directory)
1194294
def file_list(load):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    ret = []

    if 'saltenv' not in load:
        return ret

    saltenv = load['saltenv']
    metadata = _init()

    if not metadata or saltenv not in metadata:
        return ret
    for bucket in _find_files(metadata[saltenv]):
        for buckets in six.itervalues(bucket):
            files = [f for f in buckets if not fs.is_file_ignored(__opts__, f)]
            ret += _trim_env_off_path(files, saltenv)

    return ret
328932
def prepare_metadata(self):
        # type: () -> None
        
        assert self.source_dir

        with indent_log():
            if self.use_pep517:
                self.prepare_pep517_metadata()
            else:
                self.run_egg_info()

        if not self.req:
            if isinstance(parse_version(self.metadata["Version"]), Version):
                op = "=="
            else:
                op = "==="
            self.req = Requirement(
                "".join([
                    self.metadata["Name"],
                    op,
                    self.metadata["Version"],
                ])
            )
            self._correct_build_location()
        else:
            metadata_name = canonicalize_name(self.metadata["Name"])
            if canonicalize_name(self.req.name) != metadata_name:
                logger.warning(
                    'Generating metadata for package %s '
                    'produced metadata for project name %s. Fix your '
                    '#egg=%s fragments.',
                    self.name, metadata_name, self.name
                )
                self.req = Requirement(metadata_name)
828682
def run(self):
        """"""
        try:
            self.linux.verify_system_status()
        except InstallSkipError:
            Log.info('Install skipped.')
            return

        work_dir = tempfile.mkdtemp(suffix='-rpm-py-installer')
        Log.info("Created working directory '{0}'".format(work_dir))

        with Cmd.pushd(work_dir):
            self.rpm_py.download_and_install()
            if not self.python.is_python_binding_installed():
                message = (
                    'RPM Python binding failed to install '
                    'with unknown reason.'
                )
                raise InstallError(message)

            # TODO: Print installed module name and version as INFO.

        if self.is_work_dir_removed:
            shutil.rmtree(work_dir)
            Log.info("Removed working directory '{0}'".format(work_dir))
        else:
            Log.info("Saved working directory '{0}'".format(work_dir))
233420
def _download_repo_metadata(self, args):
        '''
        
        '''
        cache = salt.cache.Cache(self.opts, self.opts['spm_cache_dir'])

        def _update_metadata(repo, repo_info):
            dl_path = '{0}/SPM-METADATA'.format(repo_info['url'])
            if dl_path.startswith('file://'):
                dl_path = dl_path.replace('file://', '')
                with salt.utils.files.fopen(dl_path, 'r') as rpm:
                    metadata = salt.utils.yaml.safe_load(rpm)
            else:
                metadata = self._query_http(dl_path, repo_info)

            cache.store('.', repo, metadata)

        repo_name = args[1] if len(args) > 1 else None
        self._traverse_repos(_update_metadata, repo_name)
1308063
def _RepackTemplates(self):
    """"""
    dummy_config = os.path.join(
        args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml")
    if args.build_32:
      template_i386 = glob.glob(os.path.join(args.output_dir,
                                             "*_i386*.zip")).pop()
    template_amd64 = glob.glob(os.path.join(args.output_dir,
                                            "*_amd64*.zip")).pop()

    # We put the installers in the output dir so they get stored as build
    # artifacts and we can test the 32bit build manually.
    subprocess.check_call([
        self.grr_client_build64, "--verbose", "--secondary_configs",
        dummy_config, "repack", "--template", template_amd64, "--output_dir",
        args.output_dir
    ])
    subprocess.check_call([
        self.grr_client_build64, "--verbose", "--context",
        "DebugClientBuild Context", "--secondary_configs", dummy_config,
        "repack", "--template", template_amd64, "--output_dir", args.output_dir
    ])
    if args.build_32:
      subprocess.check_call([
          self.grr_client_build32, "--verbose", "--secondary_configs",
          dummy_config, "repack", "--template", template_i386, "--output_dir",
          args.output_dir
      ])
      subprocess.check_call([
          self.grr_client_build32, "--verbose", "--context",
          "DebugClientBuild Context", "--secondary_configs", dummy_config,
          "repack", "--template", template_i386, "--output_dir", args.output_dir
      ])
1031938
def download_and_install(self):
        """"""
        if self.is_installed_from_bin:
            try:
                self.installer.install_from_rpm_py_package()
                return
            except RpmPyPackageNotFoundError as e:
                Log.warn('RPM Py Package not found. reason: {0}'.format(e))

                # Pass to try to install from the source.
                pass

        # Download and install from the source.
        top_dir_name = self.downloader.download_and_expand()
        rpm_py_dir = os.path.join(top_dir_name, 'python')

        setup_py_in_found = False
        with Cmd.pushd(rpm_py_dir):
            if self.installer.setup_py.exists_in_path():
                setup_py_in_found = True
                self.installer.run()

        if not setup_py_in_found:
            self.installer.install_from_rpm_py_package()
350648
def list_installed():
    '''
    
    '''
    pkg_re = re.compile(r'^{0}-[\d.-]+-{1}$'.format(
        _package_prefix(), _kernel_type()))
    pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True)
    if pkgs is None:
        pkgs = []

    result = list(filter(pkg_re.match, pkgs))
    if result is None:
        return []

    prefix_len = len(_package_prefix()) + 1

    if six.PY2:
        return sorted([pkg[prefix_len:] for pkg in result], cmp=_cmp_version)
    else:
        return sorted([pkg[prefix_len:] for pkg in result], key=functools.cmp_to_key(_cmp_version))
1091727
def list(self, path=None, with_metadata=False, include_partitions=False):
        """"""

        l = {}
        for upstream in [self.alternate, self.upstream]:

            for k, v in upstream.list(path, with_metadata, include_partitions).items():
                upstreams = (l[k]['caches'] if k in l else []) + \
                    v.get('caches', upstream.repo_id)

                l[k] = v
                l[k]['caches'] = upstreams

        return l
98176
def list_pkgs(*packages, **kwargs):
    '''
    
    '''
    pkgs = {}
    cmd = ['rpm']
    if kwargs.get('root'):
        cmd.extend(['--root', kwargs['root']])
    cmd.extend(['-q' if packages else '-qa',
                '--queryformat', r'%{NAME} %{VERSION}\n'])
    if packages:
        cmd.extend(packages)
    out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
    for line in salt.utils.itertools.split(out, '\n'):
        if 'is not installed' in line:
            continue
        comps = line.split()
        pkgs[comps[0]] = comps[1]
    return pkgs