Get packages with configuration files on RPM systems.
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
940589
def ExtractConfig(self):
    """"""
    logging.info("Extracting config file from .pkg.")
    pkg_path = os.environ.get("PACKAGE_PATH", None)
    if pkg_path is None:
      logging.error("Could not locate package, giving up.")
      return

    zf = zipfile.ZipFile(pkg_path, mode="r")
    fd = zf.open("config.yaml")
    install_dir = os.path.dirname(config.CONFIG.parser.filename)

    # We write this config to disk so that Intialize can find the build.yaml
    # referenced inside the config as a relative path. This config isn't used
    # after install time.
    installer_config = os.path.join(install_dir, "installer_config.yaml")
    with open(installer_config, "wb") as f:
      f.write(fd.read())

    packaged_config = config.CONFIG.MakeNewConfig()
    packaged_config.Initialize(
        filename=installer_config, parser=config_lib.YamlParser)

    new_config = config.CONFIG.MakeNewConfig()
    new_config.SetWriteBack(config.CONFIG["Config.writeback"])

    for info in config.CONFIG.type_infos:
      try:
        new_value = packaged_config.GetRaw(info.name, None)
      except type_info.TypeValueError:
        continue

      try:
        old_value = config.CONFIG.GetRaw(info.name, None)

        if not new_value or new_value == old_value:
          continue
      except type_info.TypeValueError:
        pass

      new_config.SetRaw(info.name, new_value)

    new_config.Write()
    logging.info("Config file extracted successfully.")

    logging.info("Extracting additional files.")

    for zinfo in zf.filelist:
      basename = os.path.basename(zinfo.filename)
      if basename != "config.yaml":
        with open(os.path.join(install_dir, basename), "wb") as f:
          f.write(zf.open(zinfo.filename).read())
881785
def get_installed_distributions(skip=stdlib_pkgs):
    
    return [d for d in pkg_resources.working_set
            if d.key not in skip]
645265
def _get_pkg_meta(self):
        
        logger = logging.getLogger('pyrocore.scripts.base.version_info')
        pkg_info = None
        warnings = []

        for info_ext, info_name in (('.dist-info', 'METADATA'), ('.egg-info', 'PKG-INFO')):
            try:
                # Development setup
                pkg_path = os.path.join(
                    __file__.split(__name__.replace('.', os.sep))[0],  # containing path
                    __name__.split(".")[0]  # package name
                )
                if os.path.exists(pkg_path + info_ext):
                    pkg_path += info_ext
                else:
                    globbed_paths = glob.glob(pkg_path + "-*-py%d.%d" % sys.version_info[:2] + info_ext)
                    if len(globbed_paths) == 1:
                        pkg_path = globbed_paths[0]
                    elif globbed_paths:
                        warnings.append("Found {} release-specific candidate versions in *{}"
                                        .format(len(globbed_paths), info_ext))
                        pkg_path = None
                    else:
                        globbed_paths = glob.glob(pkg_path + "-*" + info_ext)
                        if len(globbed_paths) == 1:
                            pkg_path = globbed_paths[0]
                        else:
                            warnings.append("Found {} candidate versions in *{}"
                                            .format(len(globbed_paths), info_ext))
                            pkg_path = None
                if pkg_path:
                    with open(os.path.join(pkg_path, info_name)) as handle:
                        pkg_info = handle.read()
                    break
            except IOError:
                continue

        if not pkg_info:
            logger.warn("Software version cannot be determined! ({})".format(', '.join(warnings)))

        return pkg_info or "Version: 0.0.0\n"
1242638
def __get_managed_files_dpkg(self):
        '''
        
        '''
        dirs = set()
        links = set()
        files = set()

        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
            for resource in salt.utils.stringutils.to_str(self._syscall("dpkg", None, None, '-L', pkg_name)[0]).split(os.linesep):
                resource = resource.strip()
                if not resource or resource in ['/', './', '.']:
                    continue
                if os.path.isdir(resource):
                    dirs.add(resource)
                elif os.path.islink(resource):
                    links.add(resource)
                elif os.path.isfile(resource):
                    files.add(resource)

        return sorted(files), sorted(dirs), sorted(links)
1256701
def build_specfile_header(spec):
    
    str = ""

    # first the mandatory sections
    mandatory_header_fields = {
        'NAME'           : '%%define name %s\nName: %%{name}\n',
        'VERSION'        : '%%define version %s\nVersion: %%{version}\n',
        'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
        'X_RPM_GROUP'    : 'Group: %s\n',
        'SUMMARY'        : 'Summary: %s\n',
        'LICENSE'        : 'License: %s\n', }

    str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )

    # now the optional tags
    optional_header_fields = {
        'VENDOR'              : 'Vendor: %s\n',
        'X_RPM_URL'           : 'Url: %s\n',
        'SOURCE_URL'          : 'Source: %s\n',
        'SUMMARY_'            : 'Summary(%s): %s\n',
        'X_RPM_DISTRIBUTION'  : 'Distribution: %s\n',
        'X_RPM_ICON'          : 'Icon: %s\n',
        'X_RPM_PACKAGER'      : 'Packager: %s\n',
        'X_RPM_GROUP_'        : 'Group(%s): %s\n',

        'X_RPM_REQUIRES'      : 'Requires: %s\n',
        'X_RPM_PROVIDES'      : 'Provides: %s\n',
        'X_RPM_CONFLICTS'     : 'Conflicts: %s\n',
        'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',

        'X_RPM_SERIAL'        : 'Serial: %s\n',
        'X_RPM_EPOCH'         : 'Epoch: %s\n',
        'X_RPM_AUTOREQPROV'   : 'AutoReqProv: %s\n',
        'X_RPM_EXCLUDEARCH'   : 'ExcludeArch: %s\n',
        'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
        'X_RPM_PREFIX'        : 'Prefix: %s\n',

        # internal use
        'X_RPM_BUILDROOT'     : 'BuildRoot: %s\n', }

    # fill in default values:
    # Adding a BuildRequires renders the .rpm unbuildable under System, which
    # are not managed by rpm, since the database to resolve this dependency is
    # missing (take Gentoo as an example)
#    if not s.has_key('x_rpm_BuildRequires'):
#        s['x_rpm_BuildRequires'] = 'scons'

    if 'X_RPM_BUILDROOT' not in spec:
        spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'

    str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
    return str
91469
def run(self):
        """"""
        try:
            if not self._is_rpm_all_lib_include_files_installed():
                self._make_lib_file_symbolic_links()
                self._copy_each_include_files_to_include_dir()
                self._make_dep_lib_file_sym_links_and_copy_include_files()
                self.setup_py.add_patchs_to_build_without_pkg_config(
                    self.rpm.lib_dir, self.rpm.include_dir
                )
            self.setup_py.apply_and_save()
            self._build_and_install()
        except InstallError as e:
            if not self._is_rpm_all_lib_include_files_installed():
                org_message = str(e)
                message = '''
Install failed without rpm-devel package by below reason.
Can you install the RPM package, and run this installer again?
'''
                message += org_message
                raise InstallError(message)
            else:
                raise e
1040514
def pkgconfig(*packages, **kw):
    """"""

    flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
    output = sp.Popen(["pkg-config", "--libs", "--cflags"] + list(packages),
                      stdout=sp.PIPE).communicate()[0]
    if six.PY3:
        output = output.decode('utf8')
    for token in output.split():
        if token[:2] in flag_map:
            kw.setdefault(flag_map.get(token[:2]), []).append(token[2:])
        else:
            kw.setdefault('extra_compile_args', []).append(token)

    kw['include_dirs'] += [np.get_include()]

    return kw
721903
def find_packages(name, pkg_dir):
    """"""
    for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder):

        package_path, cache_path = c.make_package_path(pkg_dir, name)

        if package_path.exists():

            yield c.type_code, package_path, cache_path
271109
def _repo_packages(self, args, search=False):
        '''
        
        '''
        packages = []
        repo_metadata = self._get_repo_metadata()
        for repo in repo_metadata:
            for pkg in repo_metadata[repo]['packages']:
                if args[1] in pkg:
                    version = repo_metadata[repo]['packages'][pkg]['info']['version']
                    release = repo_metadata[repo]['packages'][pkg]['info']['release']
                    packages.append((pkg, version, release, repo))
        for pkg in sorted(packages):
            self.ui.status(
                '{0}\t{1}-{2}\t{3}'.format(pkg[0], pkg[1], pkg[2], pkg[3])
            )
        return packages
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()
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))
144924
def package_data(pkg, root_list):
    """"""
    data = []
    for root in root_list:
        for dirname, _, files in os.walk(os.path.join(pkg, root)):
            for fname in files:
                data.append(os.path.relpath(os.path.join(dirname, fname), pkg))

    return {pkg: data}
1326294
function getConfigFromFile(directories, filename) {
	const filepath = tryFile(directories, filename);
	if (!filepath) {
		return {};
	}

	return require(filepath);
}
902257
def get_plugins():
    """"""
    if os.path.exists('plugins'):
        for filename in sorted([f for f in os.listdir('plugins')
                if not os.path.isdir(f) and f.endswith(".py")]):
            plugin_name = filename[:-3]
            try:
                plugin = import_plugin(plugin_name)
            except SystemExit as e:
                description = "Plugin has a syntax error"
            else:
                description = plugin.__doc__ or "No description found"
            yield {plugin_name: description}
353458
def install_rpm_py():
    """"""
    python_path = sys.executable
    cmd = '{0} install.py'.format(python_path)
    exit_status = os.system(cmd)
    if exit_status != 0:
        raise Exception('Command failed: {0}'.format(cmd))
900785
def add_patchs_to_build_without_pkg_config(self, lib_dir, include_dir):
        
        additional_patches = [
            {
                'src': r"pkgconfig\('--libs-only-L'\)",
                'dest': "['{0}']".format(lib_dir),
            },
            # Considering -libs-only-l and -libs-only-L
            # https://github.com/rpm-software-management/rpm/pull/327
            {
                'src': r"pkgconfig\('--libs(-only-l)?'\)",
                'dest': "['rpm', 'rpmio']",
                'required': True,
            },
            {
                'src': r"pkgconfig\('--cflags'\)",
                'dest': "['{0}']".format(include_dir),
                'required': True,
            },
        ]
        self.patches.extend(additional_patches)