<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import importlib
import itertools
import os
import sys

import compas_rhino

import compas._os
import compas.plugins

__all__ = [
    'install',
    'installable_rhino_packages',
    'after_rhino_install',
]


def install(version=None, packages=None):
    """Install COMPAS for Rhino.

    Parameters
    ----------
    version : {'5.0', '6.0', '7.0'}, optional
        The version number of Rhino.
        Default is ``'6.0'``.
    packages : list of str, optional
        List of packages to install or None to use default package list.
        Default is ``['compas', 'compas_rhino', 'compas_ghpython']``.

    Examples
    --------
    .. code-block:: python

        import compas_rhino
        compas_rhino.install('6.0')

    .. code-block:: bash

        python -m compas_rhino.install -v 6.0

    """

    if version not in ('5.0', '6.0', '7.0'):
        version = '6.0'

    packages = _filter_installable_packages(version, packages)

    ipylib_path = compas_rhino._get_ironpython_lib_path(version)
    scripts_path = compas_rhino._get_scripts_path(version)

    print('Installing COMPAS packages to Rhino {0} scripts folder:'.format(version))
    print('Location scripts folder: {}'.format(scripts_path))
    print()

    results = []
    symlinks_to_install = []
    symlinks_to_uninstall = []
    exit_code = 0

    for package in packages:
        package_path = compas_rhino._get_package_path(importlib.import_module(package))
        symlink_path = os.path.join(scripts_path, package)
        symlinks_to_install.append(dict(name=package, source_path=package_path, link=symlink_path))
        symlinks_to_uninstall.append(dict(name=package, link=symlink_path))

        # Handle legacy install location
        legacy_path = os.path.join(ipylib_path, package)
        if os.path.exists(legacy_path):
            symlinks_to_uninstall.append(dict(name=package, link=legacy_path))

    # First uninstall existing copies of packages requested for installation
    symlinks = [link['link'] for link in symlinks_to_uninstall]
    uninstall_results = compas._os.remove_symlinks(symlinks)

    for uninstall_data, success in zip(symlinks_to_uninstall, uninstall_results):
        if not success:
            results.append((uninstall_data['name'], 'ERROR: Cannot remove symlink, try to run as administrator.'))

    # Handle legacy bootstrapper
    if not compas_rhino._try_remove_bootstrapper(ipylib_path):
        results.append(('compas_bootstrapper', 'ERROR: Cannot remove legacy compas_bootstrapper, try to run as administrator.'))

    # Ready to start installing
    symlinks = [(link['source_path'], link['link']) for link in symlinks_to_install]
    install_results = compas._os.create_symlinks(symlinks)

    installed_packages = []
    for install_data, success in zip(symlinks_to_install, install_results):
        if success:
            installed_packages.append(install_data['name'])
            result = 'OK'
        else:
            result = 'ERROR: Cannot create symlink, try to run as administrator.'
        results.append((install_data['name'], result))

    if not all(install_results):
        exit_code = -1

    if exit_code == -1:
        results.append(('compas_bootstrapper', 'WARNING: One or more packages failed, will not install bootstrapper, try uninstalling first'))
    else:
        try:
            _update_bootstrapper(scripts_path, packages)
            results.append(('compas_bootstrapper', 'OK'))
        except:  # noqa: E722
            results.append(('compas_bootstrapper', 'ERROR: Could not create compas_bootstrapper to auto-determine Python environment'))

    for package, status in results:
        print('   {} {}'.format(package.ljust(20), status))

        if status != 'OK':
            exit_code = -1

    if exit_code == 0 and len(installed_packages):
        print()
        print('Running post-installation steps...')
        print()
        if not _run_post_execution_steps(after_rhino_install(installed_packages)):
            exit_code = -1

    print('\nCompleted.')
    if exit_code != 0:
        sys.exit(exit_code)


def _run_post_execution_steps(steps_generator):
    all_steps_succeeded = True
    post_execution_errors = []

    for result in steps_generator:
        if isinstance(result, Exception):
            post_execution_errors.append(result)
            continue

        for item in result:
            try:
                package, message, success = item
                status = 'OK' if success else 'ERROR'
                if not success:
                    all_steps_succeeded = False
                print('   {} {}: {}'.format(package.ljust(20), status, message))
            except ValueError:
                post_execution_errors.append(ValueError('Step successful, but result is wrongly formatted: {}'.format(str(item))))

    if post_execution_errors:
        print()
        print('One or more errors occurred:')
        print()
        for error in post_execution_errors:<commit_msg>Reword message if plugin returns incorrect result<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import importlib
import itertools
import os
import sys

import compas_rhino

import compas._os
import compas.plugins

__all__ = [
    'install',
    'installable_rhino_packages',
    'after_rhino_install',
]


def install(version=None, packages=None):
    """Install COMPAS for Rhino.

    Parameters
    ----------
    version : {'5.0', '6.0', '7.0'}, optional
        The version number of Rhino.
        Default is ``'6.0'``.
    packages : list of str, optional
        List of packages to install or None to use default package list.
        Default is ``['compas', 'compas_rhino', 'compas_ghpython']``.

    Examples
    --------
    .. code-block:: python

        import compas_rhino
        compas_rhino.install('6.0')

    .. code-block:: bash

        python -m compas_rhino.install -v 6.0

    """

    if version not in ('5.0', '6.0', '7.0'):
        version = '6.0'

    packages = _filter_installable_packages(version, packages)

    ipylib_path = compas_rhino._get_ironpython_lib_path(version)
    scripts_path = compas_rhino._get_scripts_path(version)

    print('Installing COMPAS packages to Rhino {0} scripts folder:'.format(version))
    print('Location scripts folder: {}'.format(scripts_path))
    print()

    results = []
    symlinks_to_install = []
    symlinks_to_uninstall = []
    exit_code = 0

    for package in packages:
        package_path = compas_rhino._get_package_path(importlib.import_module(package))
        symlink_path = os.path.join(scripts_path, package)
        symlinks_to_install.append(dict(name=package, source_path=package_path, link=symlink_path))
        symlinks_to_uninstall.append(dict(name=package, link=symlink_path))

        # Handle legacy install location
        legacy_path = os.path.join(ipylib_path, package)
        if os.path.exists(legacy_path):
            symlinks_to_uninstall.append(dict(name=package, link=legacy_path))

    # First uninstall existing copies of packages requested for installation
    symlinks = [link['link'] for link in symlinks_to_uninstall]
    uninstall_results = compas._os.remove_symlinks(symlinks)

    for uninstall_data, success in zip(symlinks_to_uninstall, uninstall_results):
        if not success:
            results.append((uninstall_data['name'], 'ERROR: Cannot remove symlink, try to run as administrator.'))

    # Handle legacy bootstrapper
    if not compas_rhino._try_remove_bootstrapper(ipylib_path):
        results.append(('compas_bootstrapper', 'ERROR: Cannot remove legacy compas_bootstrapper, try to run as administrator.'))

    # Ready to start installing
    symlinks = [(link['source_path'], link['link']) for link in symlinks_to_install]
    install_results = compas._os.create_symlinks(symlinks)

    installed_packages = []
    for install_data, success in zip(symlinks_to_install, install_results):
        if success:
            installed_packages.append(install_data['name'])
            result = 'OK'
        else:
            result = 'ERROR: Cannot create symlink, try to run as administrator.'
        results.append((install_data['name'], result))

    if not all(install_results):
        exit_code = -1

    if exit_code == -1:
        results.append(('compas_bootstrapper', 'WARNING: One or more packages failed, will not install bootstrapper, try uninstalling first'))
    else:
        try:
            _update_bootstrapper(scripts_path, packages)
            results.append(('compas_bootstrapper', 'OK'))
        except:  # noqa: E722
            results.append(('compas_bootstrapper', 'ERROR: Could not create compas_bootstrapper to auto-determine Python environment'))

    for package, status in results:
        print('   {} {}'.format(package.ljust(20), status))

        if status != 'OK':
            exit_code = -1

    if exit_code == 0 and len(installed_packages):
        print()
        print('Running post-installation steps...')
        print()
        if not _run_post_execution_steps(after_rhino_install(installed_packages)):
            exit_code = -1

    print('\nCompleted.')
    if exit_code != 0:
        sys.exit(exit_code)


def _run_post_execution_steps(steps_generator):
    all_steps_succeeded = True
    post_execution_errors = []

    for result in steps_generator:
        if isinstance(result, Exception):
            post_execution_errors.append(result)
            continue

        for item in result:
            try:
                package, message, success = item
                status = 'OK' if success else 'ERROR'
                if not success:
                    all_steps_succeeded = False
                print('   {} {}: {}'.format(package.ljust(20), status, message))
            except ValueError:
                post_execution_errors.append(ValueError('Step ran without errors but result is wrongly formatted: {}'.format(str(item))))

    if post_execution_errors:
        print()
        print('One or more errors occurred:')
        print()
        for error in post_execution_errors:
{'fraction_non_alphanumeric': 0.1008084153111912, 'fraction_numerical': 0.0068179604558293565, 'mean_word_length': 2.908641035401599, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '489793', 'n_tokens_mistral': 3034, 'n_tokens_neox': 2928, 'n_words': 755}