Identify post-install conda problems and fix.

    - libgcc upgrades can remove libquadmath, which moved to libgcc-ng
350642
def _check_for_conda_problems():
    
    conda_bin = _get_conda_bin()
    channels = _get_conda_channels(conda_bin)
    lib_dir = os.path.join(os.path.dirname(conda_bin), os.pardir, "lib")
    for l in ["libgomp.so.1", "libquadmath.so"]:
        if not os.path.exists(os.path.join(lib_dir, l)):
            subprocess.check_call([conda_bin, "install", "-f", "--yes"] + channels + ["libgcc-ng"])
1109224
def _find_remove_targets(name=None,
                         version=None,
                         pkgs=None,
                         normalize=True,
                         ignore_epoch=False,
                         **kwargs):
    '''
    
    '''
    if __grains__['os'] == 'FreeBSD':
        kwargs['with_origin'] = True
    cur_pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs)
    if pkgs:
        to_remove = _repack_pkgs(pkgs, normalize=normalize)

        if not to_remove:
            # Badly-formatted SLS
            return {'name': name,
                    'changes': {},
                    'result': False,
                    'comment': 'Invalidly formatted pkgs parameter. See '
                               'minion log.'}
    else:
        _normalize_name = \
            __salt__.get('pkg.normalize_name', lambda pkgname: pkgname)
        to_remove = {_normalize_name(name): version}

    version_spec = False
    # Find out which packages will be targeted in the call to pkg.remove
    # Check current versions against specified versions
    targets = []
    problems = []
    for pkgname, pkgver in six.iteritems(to_remove):
        # FreeBSD pkg supports `openjdk` and `java/openjdk7` package names
        origin = bool(re.search('/', pkgname))

        if __grains__['os'] == 'FreeBSD' and origin:
            cver = [k for k, v in six.iteritems(cur_pkgs) if v['origin'] == pkgname]
        else:
            cver = cur_pkgs.get(pkgname, [])

        # Package not installed, no need to remove
        if not cver:
            continue
        # No version specified and pkg is installed
        elif __salt__['pkg_resource.version_clean'](pkgver) is None:
            targets.append(pkgname)
            continue
        version_spec = True
        try:
            if _fulfills_version_string(cver, pkgver, ignore_epoch=ignore_epoch):
                targets.append(pkgname)
            else:
                log.debug(
                    'Current version (%s) did not match desired version '
                    'specification (%s), will not remove', cver, pkgver
                )
        except CommandExecutionError as exc:
            problems.append(exc.strerror)
            continue

    if problems:
        return {'name': name,
                'changes': {},
                'result': False,
                'comment': ' '.join(problems)}

    if not targets:
        # All specified packages are already absent
        msg = 'All specified packages{0} are already absent'.format(
            ' (matching specified versions)' if version_spec else ''
        )
        return {'name': name,
                'changes': {},
                'result': True,
                'comment': msg}

    return targets
821423
def removed(name, dir=None, user=None):
    '''
    
    '''
    ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}

    try:
        installed_pkgs = __salt__['npm.list'](dir=dir, depth=0)
    except (CommandExecutionError, CommandNotFoundError) as err:
        ret['result'] = False
        ret['comment'] = 'Error uninstalling \'{0}\': {1}'.format(name, err)
        return ret

    if name not in installed_pkgs:
        ret['result'] = True
        ret['comment'] = 'Package \'{0}\' is not installed'.format(name)
        return ret

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name)
        return ret

    if __salt__['npm.uninstall'](pkg=name, dir=dir, runas=user):
        ret['result'] = True
        ret['changes'][name] = 'Removed'
        ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name)
    else:
        ret['result'] = False
        ret['comment'] = 'Error removing package \'{0}\''.format(name)

    return ret
478182
def cleanup_mprocess(config_path, cfg):
    
    for key in ('keyFile', 'logPath', 'dbpath'):
        remove_path(cfg.get(key, None))
    isinstance(config_path, str) and os.path.exists(config_path) and remove_path(config_path)
5631
function cb (err) {
    if (cb.done) return
    cb.done = true
    if (err) {
      log.warn('install', 'got an error, rolling back install')
      // roll-back the install if anything went wrong
      gyp.commands.remove([ release.versionDir ], function () {
        callback(err)
      })
    } else {
      callback(null, release.version)
    }
  }
525953
def install_given_reqs(
    to_install,  # type: List[InstallRequirement]
    install_options,  # type: List[str]
    global_options=(),  # type: Sequence[str]
    *args, **kwargs
):
    # type: (...) -> List[InstallRequirement]
    

    if to_install:
        logger.info(
            'Installing collected packages: %s',
            ', '.join([req.name for req in to_install]),
        )

    with indent_log():
        for requirement in to_install:
            if requirement.conflicts_with:
                logger.info(
                    'Found existing installation: %s',
                    requirement.conflicts_with,
                )
                with indent_log():
                    uninstalled_pathset = requirement.uninstall(
                        auto_confirm=True
                    )
            try:
                requirement.install(
                    install_options,
                    global_options,
                    *args,
                    **kwargs
                )
            except Exception:
                should_rollback = (
                    requirement.conflicts_with and
                    not requirement.install_succeeded
                )
                # if install did not succeed, rollback previous uninstall
                if should_rollback:
                    uninstalled_pathset.rollback()
                raise
            else:
                should_commit = (
                    requirement.conflicts_with and
                    requirement.install_succeeded
                )
                if should_commit:
                    uninstalled_pathset.commit()
            requirement.remove_temporary_source()

    return to_install
779547
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
    '''
    
    '''
    try:
        pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
    except MinionError as exc:
        raise CommandExecutionError(exc)

    old = list_pkgs()
    old_removed = list_pkgs(removed=True)
    targets = [x for x in pkg_params if x in old]
    if action == 'purge':
        targets.extend([x for x in pkg_params if x in old_removed])
    if not targets:
        return {}
    cmd = ['apt-get', '-q', '-y', action]
    cmd.extend(targets)
    env = _parse_env(kwargs.get('env'))
    env.update(DPKG_ENV_VARS.copy())
    out = _call_apt(cmd, env=env)
    if out['retcode'] != 0 and out['stderr']:
        errors = [out['stderr']]
    else:
        errors = []

    __context__.pop('pkg.list_pkgs', None)
    new = list_pkgs()
    new_removed = list_pkgs(removed=True)

    changes = salt.utils.data.compare_dicts(old, new)
    if action == 'purge':
        ret = {
            'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
            'installed': changes
        }
    else:
        ret = changes

    if errors:
        raise CommandExecutionError(
            'Problem encountered removing package(s)',
            info={'errors': errors, 'changes': ret}
        )

    return ret
14168
def _default_cleanup(self):
        
        if not self.inplace:
            return

        shutil.move(
            os.path.join(self.build_lib, "bezier", "lib"),
            os.path.join("src", "bezier"),
        )
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)
1281497
def uninstall(pkg):
    '''
    
    '''
    ret = {'result': None, 'output': ''}

    out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' uninstall ' + pkg)

    if out['retcode'] and out['stderr']:
        ret['stderr'] = out['stderr'].strip()
        ret['result'] = False
    else:
        ret['stdout'] = out['stdout'].strip()
        ret['result'] = True

    return ret
1250025
def _remove_broken_links():
    '''
    
    '''
    enabled_dir = MICRODROP_CONDA_PLUGINS.joinpath('enabled')
    if not enabled_dir.isdir():
        return []

    broken_links = []
    for dir_i in enabled_dir.walkdirs(errors='ignore'):
        if platform.system() == 'Windows':
            if dir_i.isjunction() and not dir_i.readlink().isdir():
                # Junction/link target no longer exists.
                broken_links.append(dir_i)
        else:
            raise NotImplementedError('Unsupported platform')

    removed_links = []
    for link_i in broken_links:
        try:
            link_i.unlink()
        except:
            pass
        else:
            removed_links.append(link_i)
    return removed_links
264076
def continue_to_install(self):
        
        if (self.count_uni > 0 or self.count_upg > 0 or
                "--download-only" in self.flag or "--rebuild" in self.flag):
            if self.master_packages and self.msg.answer() in ["y", "Y"]:
                installs, upgraded = self.build_install()
                if "--download-only" in self.flag:
                    raise SystemExit()
                self.msg.reference(installs, upgraded)
                write_deps(self.deps_dict)
                delete(self.build_folder)
1181857
def run_cleanup(build_ext_cmd):
    
    if not build_ext_cmd.inplace:
        return

    bezier_dir = os.path.join("src", "bezier")
    shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir)
    shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir)
583566
def checkCache(fnm, strip=0, upx=0):
    
    # On darwin a cache is required anyway to keep the libaries
    # with relative install names. Caching on darwin does not work
    # since we need to modify binary headers to use relative paths
    # to dll depencies and starting with '@executable_path'.

    if ((not strip and not upx and not is_darwin and not is_win)
        or fnm.lower().endswith(".manifest")):
        return fnm
    if strip:
        strip = 1
    else:
        strip = 0
    if upx:
        upx = 1
    else:
        upx = 0

    # Load cache index
    cachedir = os.path.join(CONFIGDIR, 'bincache%d%d' % (strip, upx))
    if not os.path.exists(cachedir):
        os.makedirs(cachedir)
    cacheindexfn = os.path.join(cachedir, "index.dat")
    if os.path.exists(cacheindexfn):
        cache_index = _load_data(cacheindexfn)
    else:
        cache_index = {}

    # Verify if the file we're looking for is present in the cache.
    basenm = os.path.normcase(os.path.basename(fnm))
    digest = cacheDigest(fnm)
    cachedfile = os.path.join(cachedir, basenm)
    cmd = None
    if basenm in cache_index:
        if digest != cache_index[basenm]:
            os.remove(cachedfile)
        else:
            # On Mac OS X we need relative paths to dll dependencies
            # starting with @executable_path
            if is_darwin:
                dylib.mac_set_relative_dylib_deps(cachedfile)
            return cachedfile
    if upx:
        if strip:
            fnm = checkCache(fnm, 1, 0)
        bestopt = "--best"
        # FIXME: Linux builds of UPX do not seem to contain LZMA (they assert out)
        # A better configure-time check is due.
        if config["hasUPX"] >= (3,) and os.name == "nt":
            bestopt = "--lzma"

        upx_executable = "upx"
        if config.get('upx_dir'):
            upx_executable = os.path.join(config['upx_dir'], upx_executable)
        cmd = [upx_executable, bestopt, "-q", cachedfile]
    else:
        if strip:
            # -S = strip only debug symbols.
            # The default strip behaviour breaks some shared libraries
            # under Mac OSX
            cmd = ["strip", "-S", cachedfile]
    shutil.copy2(fnm, cachedfile)
    os.chmod(cachedfile, 0755)

    if pyasm and fnm.lower().endswith(".pyd"):
        # If python.exe has dependent assemblies, check for embedded manifest
        # of cached pyd file because we may need to 'fix it' for pyinstaller
        try:
            res = winmanifest.GetManifestResources(os.path.abspath(cachedfile))
        except winresource.pywintypes.error, e:
            if e.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
                # Not a win32 PE file
                pass
            else:
                logger.error(os.path.abspath(cachedfile))
                raise
        else:
            if winmanifest.RT_MANIFEST in res and len(res[winmanifest.RT_MANIFEST]):
                for name in res[winmanifest.RT_MANIFEST]:
                    for language in res[winmanifest.RT_MANIFEST][name]:
                        try:
                            manifest = winmanifest.Manifest()
                            manifest.filename = ":".join([cachedfile,
                                                          str(winmanifest.RT_MANIFEST),
                                                          str(name),
                                                          str(language)])
                            manifest.parse_string(res[winmanifest.RT_MANIFEST][name][language],
                                                  False)
                        except Exception, exc:
                            logger.error("Cannot parse manifest resource %s, "
                                         "%s from", name, language)
                            logger.error(cachedfile)
                            logger.exception(exc)
                        else:
                            # Fix the embedded manifest (if any):
                            # Extension modules built with Python 2.6.5 have
                            # an empty <dependency> element, we need to add
                            # dependentAssemblies from python.exe for
                            # pyinstaller
                            olen = len(manifest.dependentAssemblies)
                            _depNames = set([dep.name for dep in
                                             manifest.dependentAssemblies])
                            for pydep in pyasm:
                                if not pydep.name in _depNames:
                                    logger.info("Adding %r to dependent "
                                                "assemblies of %r",
                                                pydep.name, cachedfile)
                                    manifest.dependentAssemblies.append(pydep)
                                    _depNames.update(pydep.name)
                            if len(manifest.dependentAssemblies) > olen:
                                try:
                                    manifest.update_resources(os.path.abspath(cachedfile),
                                                              [name],
                                                              [language])
                                except Exception, e:
                                    logger.error(os.path.abspath(cachedfile))
                                    raise

    if cmd:
        try:
            compat.exec_command(*cmd)
        except OSError, e:
            raise SystemExit("Execution failed: %s" % e)

    # update cache index
    cache_index[basenm] = digest
    _save_data(cacheindexfn, cache_index)

    # On Mac OS X we need relative paths to dll dependencies
    # starting with @executable_path
    if is_darwin:
        dylib.mac_set_relative_dylib_deps(cachedfile)
    return cachedfile
124474
def rpc_fix_code_with_black(self, source, directory):
        
        source = get_source(source)
        return fix_code_with_black(source, directory)
512376
def cmd_distclean(self, *args):
        '''
        '''
        print("Warning: Your ndk, sdk and all other cached packages will be"
              " removed. Continue? (y/n)")
        if sys.stdin.readline().lower()[0] == 'y':
            self.info('Clean the global build directory')
            if not exists(self.global_buildozer_dir):
                return
            rmtree(self.global_buildozer_dir)
618482
def clean(bld):
	''''''
	try:
		proj=Environment.Environment(Options.lockfile)
	except IOError:
		raise Utils.WafError('Nothing to clean (project not configured)')
	bld.load_dirs(proj[SRCDIR],proj[BLDDIR])
	bld.load_envs()
	bld.is_install=0
	bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]])
	try:
		bld.clean()
	finally:
		bld.save()