Install RPM Python binding.
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))
584490
def base_install():
    """"""
    # scwrl
    scwrl = {}
    print('{BOLD}{HEADER}Generating configuration files for ISAMBARD.{END_C}\n'
          'All required input can use tab completion for paths.\n'
          '{BOLD}Setting up SCWRL 4.0 (Recommended){END_C}'.format(**text_colours))
    scwrl_path = get_user_path('Please provide a path to your SCWRL executable', required=False)
    scwrl['path'] = str(scwrl_path)
    pack_mode = get_user_option(
        'Please choose your packing mode (flexible is significantly slower but is more accurate).',
        ['flexible', 'rigid'])
    if pack_mode == 'rigid':
        scwrl['rigid_rotamer_model'] = True
    else:
        scwrl['rigid_rotamer_model'] = False
    settings['scwrl'] = scwrl

    # dssp
    print('{BOLD}Setting up DSSP (Recommended){END_C}'.format(**text_colours))
    dssp = {}
    dssp_path = get_user_path('Please provide a path to your DSSP executable.', required=False)
    dssp['path'] = str(dssp_path)
    settings['dssp'] = dssp

    # buff
    print('{BOLD}Setting up BUFF (Required){END_C}'.format(**text_colours))
    buff = {}
    ffs = []
    ff_dir = isambard_path / 'buff' / 'force_fields'
    for ff_file in os.listdir(str(ff_dir)):
        ff = pathlib.Path(ff_file)
        ffs.append(ff.stem)
    force_field_choice = get_user_option(
        'Please choose the default BUFF force field, this can be modified during runtime.',
        ffs)
    buff['default_force_field'] = force_field_choice
    settings['buff'] = buff
    return
53321
def is_python_binding_installed(self):
        
        is_installed = False
        is_install_error = False

        try:
            is_installed = self.is_python_binding_installed_on_pip()
        except InstallError:
            # Consider a case of pip is not installed in old Python (<= 2.6).
            is_install_error = True
        if not is_installed or is_install_error:
            for rpm_dir in self.python_lib_rpm_dirs:
                init_py = os.path.join(rpm_dir, '__init__.py')
                if os.path.isfile(init_py):
                    is_installed = True
                    break

        return is_installed
418161
def setup(cls) -> None:
        """"""
        cls.prepare()
        setuptools.setup(
            name=cls.name, version=cls.version, description=cls.description,
            long_description=cls.long_description, url=cls.url, download_url=cls.download_url,
            author=cls.author, author_email=cls.author_email,
            maintainer=cls.try_fields('maintainer', 'author'),
            maintainer_email=cls.try_fields('maintainer_email', 'author_email'),
            license=cls.license_str, classifiers=cls.classifiers, keywords=cls.keywords,
            packages=cls.packages, package_dir={'': cls.root_directory},
            include_package_data=True,
            package_data=cls.package_data, exclude_package_data=cls.exclude_package_data,
            install_requires=cls.install_requires, extras_require=cls.extras_require,
            python_requires=cls.python_requires,
            entry_points=cls.entry_points, test_suite=cls.test_suite)
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})
418939
def _make_spec_file(self):
        
        # Note that bdist_rpm can be an old style class.
        if issubclass(BdistRPMCommand, object):
            spec_file = super(BdistRPMCommand, self)._make_spec_file()
        else:
            spec_file = bdist_rpm._make_spec_file(self)

        if sys.version_info[0] < 3:
            python_package = "python"
        else:
            python_package = "python3"

        description = []
        summary = ""
        in_description = False

        python_spec_file = []
        for line in spec_file:
            if line.startswith("Summary: "):
                summary = line

            elif line.startswith("BuildRequires: "):
                line = "BuildRequires: {0:s}-setuptools".format(python_package)

            elif line.startswith("Requires: "):
                if python_package == "python3":
                    line = line.replace("python", "python3")

            elif line.startswith("%description"):
                in_description = True

            elif line.startswith("%files"):
                line = "%files -f INSTALLED_FILES -n {0:s}-%{{name}}".format(
                    python_package)

            elif line.startswith("%prep"):
                in_description = False

                python_spec_file.append(
                    "%package -n {0:s}-%{{name}}".format(python_package))
                python_spec_file.append("{0:s}".format(summary))
                python_spec_file.append("")
                python_spec_file.append(
                    "%description -n {0:s}-%{{name}}".format(python_package))
                python_spec_file.extend(description)

            elif in_description:
                # Ignore leading white lines in the description.
                if not description and not line:
                    continue

                description.append(line)

            python_spec_file.append(line)

        return python_spec_file
140655
def is_python_binding_installed_on_pip(self):
        """"""
        pip_version = self._get_pip_version()
        Log.debug('Pip version: {0}'.format(pip_version))
        pip_major_version = int(pip_version.split('.')[0])

        installed = False
        # --format is from pip v9.0.0
        # https://pip.pypa.io/en/stable/news/
        if pip_major_version >= 9:
            json_obj = self._get_pip_list_json_obj()

            for package in json_obj:
                Log.debug('pip list: {0}'.format(package))
                if package['name'] in ('rpm-python', 'rpm'):
                    installed = True
                    Log.debug('Package installed: {0}, {1}'.format(
                              package['name'], package['version']))
                    break
        else:
            # Implementation for pip old version.
            # It will be removed in the future.
            lines = self._get_pip_list_lines()
            for line in lines:
                if re.match('^rpm(-python)? ', line):
                    installed = True
                    Log.debug('Package installed.')
                    break

        return installed
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
1073327
def rpm_eval(macro):
    """"""
    try:
        value = subprocess.Popen(
            ['rpm', '--eval', macro],
            stdout=subprocess.PIPE).communicate()[0].strip()
    except OSError:
        logger.error('Failed to get value of {0} rpm macro'.format(
            macro), exc_info=True)
        value = b''
    return console_to_str(value)
494513
def modify_environment(self, env):
        """"""

        # Ugh. I don't see any way out of special-casing the RPM-based
        # installations ... which only exist on NRAO computers, AFAICT.
        # Hardcoding 64-bitness, hopefully that won't come back to bite me.
        is_rpm_install = self._rootdir.startswith('/usr/lib64/casapy/release/')

        def path(*args):
            return os.path.join(self._rootdir, *args)

        env['CASAROOT'] = path()
        env['CASAPATH'] = ' '.join([path(),
                                    os.uname()[0].lower(),
                                    'local',
                                    os.uname()[1]])

        if is_rpm_install:
            env['CASA_INSTALLATION_TYPE'] = 'rpm-installation'
            prepend_environ_path(env, 'PATH', '/usr/lib64/casa/01/bin')
            prepend_environ_path(env, 'PATH', path('bin'))
        else:
            env['CASA_INSTALLATION_TYPE'] = 'tar-installation'

            lib = 'lib64' if os.path.isdir(path('lib64')) else 'lib'
            # 4.3.1 comes with both python2.6 and python2.7???
            pydir = sorted(glob.glob(path(lib, 'python2*')))[-1]

            tcldir = path('share', 'tcl')
            if os.path.isdir(tcldir):
                env['TCL_LIBRARY'] = tcldir
            else:
                tcl_versioned_dirs = glob.glob(path('share', 'tcl*'))
                if len(tcl_versioned_dirs):
                    env['TCL_LIBRARY'] = tcl_versioned_dirs[-1]

            bindir = path(lib, 'casa', 'bin')
            if not os.path.isdir(bindir):
                bindir = path(lib, 'casapy', 'bin')
            prepend_environ_path(env, 'PATH', bindir)

            env['CASA_INSTALLATION_DIRECTORY'] = env['CASAROOT']
            env['__CASAPY_PYTHONDIR'] = pydir
            env['MATPLOTLIBRC'] = path('share', 'matplotlib')
            env['PYTHONHOME'] = env['CASAROOT']
            env['TK_LIBRARY'] = path('share', 'tk')
            env['QT_PLUGIN_PATH'] = path(lib, 'qt4', 'plugins')

            prepend_environ_path(env, 'LD_LIBRARY_PATH', path(lib))
            # should we overwite PYTHONPATH instead?
            prepend_environ_path(env, 'PYTHONPATH', os.path.join(pydir, 'site-packages'))
            prepend_environ_path(env, 'PYTHONPATH', os.path.join(pydir, 'heuristics'))
            prepend_environ_path(env, 'PYTHONPATH', pydir)

        return env
584004
def install(config):  # pragma: no cover
        """"""
        client = Client()
        client.prepare_connection()
        key_api = API(client)
        key_api.install()
890407
def _install(archive_filename, install_args=()):
    """"""
    with archive_context(archive_filename):
        # installing
        log.warn('Installing Setuptools')
        if not _python_cmd('setup.py', 'install', *install_args):
            log.warn('Something went wrong during the installation.')
            log.warn('See the error message above.')
            # exitcode will be 2
            return 2
125740
def _do_download(version, download_base, to_dir, download_delay):
    """"""
    py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)
    tp = 'setuptools-{version}-{py_desig}.egg'
    egg = os.path.join(to_dir, tp.format(**locals()))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
            to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        _unload_pkg_resources()

    import setuptools
    setuptools.bootstrap_install_from = egg
200411
def generate(env):
    """"""
    try:
        bld = env['BUILDERS']['Rpm']
    except KeyError:
        bld = RpmBuilder
        env['BUILDERS']['Rpm'] = bld

    env.SetDefault(RPM          = 'LC_ALL=C rpmbuild')
    env.SetDefault(RPMFLAGS     = SCons.Util.CLVar('-ta'))
    env.SetDefault(RPMCOM       = rpmAction)
    env.SetDefault(RPMSUFFIX    = '.rpm')
812564
def activate():
    """"""

    global PathFinder, FileFinder, ff_path_hook

    path_hook_index = len(sys.path_hooks)
    sys.path_hooks.append(ff_path_hook)
    # Resetting sys.path_importer_cache values,
    # to support the case where we have an implicit package inside an already loaded package,
    # since we need to replace the default importer.
    sys.path_importer_cache.clear()

    # Setting up the meta_path to change package finding logic
    pathfinder_index = len(sys.meta_path)
    sys.meta_path.append(PathFinder)

    return path_hook_index, pathfinder_index
150548
def setup(config=None, logfile=None):
        """"""

        if config is None:
            configpath = os.path.join(fermipy.PACKAGE_ROOT, 'config',
                                      'logging.yaml')
            with open(configpath, 'r') as f:
                config = yaml.load(f)

        # Update configuration
        if logfile:
            for name, h in config['handlers'].items():
                if 'file_handler' in name:
                    config['handlers'][name]['filename'] = logfile

        logging.config.dictConfig(config)
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)