Пример #1
0
def format_help(help):
    """Formats the help string."""
    help = help.replace('  check', str(crayons.green('  check')))
    help = help.replace('  uninstall', str(crayons.yellow('  uninstall', bold=True)))
    help = help.replace('  install', str(crayons.yellow('  install', bold=True)))
    help = help.replace('  lock', str(crayons.red('  lock', bold=True)))
    help = help.replace('  run', str(crayons.blue('  run')))
    help = help.replace('  shell', str(crayons.blue('  shell', bold=True)))
    help = help.replace('  update', str(crayons.yellow('  update')))

    additional_help = """
Usage Examples:
   Create a new project using Python 3:
   $ {0}

   Install all dependencies for a project (including dev):
   $ {1}

   Create a lockfile:
   $ {2}

Commands:""".format(
        crayons.red('pipenv --three'),
        crayons.red('pipenv install --dev'),
        crayons.red('pipenv lock')
    )

    help = help.replace('Commands:', additional_help)

    return help
Пример #2
0
def do_lock():
    """Executes the freeze functionality."""

    # Purge the virtualenv download dir, for development dependencies.
    do_purge(downloads=True, bare=True)

    click.echo(crayons.yellow('Locking {0} dependencies...'.format(crayons.red('[dev-packages]'))))

    with spinner():
        # Install only development dependencies.
        names_map = do_download_dependencies(dev=True, only=True, bare=True)

    # Load the Pipfile and generate a lockfile.
    p = pipfile.load(project.pipfile_location)
    lockfile = json.loads(p.lock())

    # Pip freeze development dependencies.
    with spinner():
        results = get_downloads_info(names_map, 'dev-packages')

    # Clear generated lockfile before updating.
    lockfile['develop'] = {}

    # Add Development dependencies to lockfile.
    for dep in results:
        if dep:
            lockfile['develop'].update({dep['name']: {'hash': dep['hash'], 'version': '=={0}'.format(dep['version'])}})

    with spinner():
        # Purge the virtualenv download dir, for default dependencies.
        do_purge(downloads=True, bare=True)

    click.echo(crayons.yellow('Locking {0} dependencies...'.format(crayons.red('[packages]'))))

    with spinner():
        # Install only development dependencies.
        names_map = do_download_dependencies(bare=True)

    # Pip freeze default dependencies.
    results = get_downloads_info(names_map, 'packages')

    # Clear generated lockfile before updating.
    lockfile['default'] = {}

    # Add default dependencies to lockfile.
    for dep in results:
        if dep:
            lockfile['default'].update({dep['name']: {'hash': dep['hash'], 'version': '=={0}'.format(dep['version'])}})

    # Write out lockfile.
    with open(project.lockfile_location, 'w') as f:
        f.write(json.dumps(lockfile, indent=4, separators=(',', ': ')))

    # Purge the virtualenv download dir, for next time.
    with spinner():
        do_purge(downloads=True, bare=True)

    click.echo('{0} Pipfile.lock{1}'.format(crayons.yellow('Updated'), crayons.yellow('!')))
Пример #3
0
def login_sso(show_token: bool, one_time: bool, confirm_all: bool, detached_mode: bool, env_name: str):
    if env_name:
        context.set_active_env(env_name)
    env = context.current_env()
    if not confirm_all:
        response = click.confirm(_sso_disclaimer)
        if not response:
            exit(1)
    if not one_time:
        click.echo('Logging in to [{0}]...'.format(env.name))

    try:
        if detached_mode:
            token = auth.login_sso_detached(env.api_url)
        else:
            token = auth.login_sso(env.api_url)
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return

    if not one_time:
        env.set_token(token)
        context.save()

    if show_token or one_time:
        print(token.strip())
    else:
        click.echo(crayons.green('You\'re now logged in as [{0}] in [{1}].'.format(env.username, env.name)))
Пример #4
0
def do_create_virtualenv(three=None, python=None):
    """Creates a virtualenv."""
    click.echo(crayons.yellow('Creating a virtualenv for this project...'), err=True)

    # The user wants the virtualenv in the project.
    if PIPENV_VENV_IN_PROJECT:
        cmd = ['virtualenv', project.virtualenv_location, '--prompt=({0})'.format(project.name)]
    else:
        # Default: use pew.
        cmd = ['pew', 'new', project.name, '-d']

    # Pass a Python version to virtualenv, if needed.
    if python:
        click.echo('{0} {1} {2}'.format(crayons.yellow('Using'), crayons.red(python), crayons.yellow('to create virtualenv...')))
    elif three is False:
        python = 'python2'
    elif three is True:
        python = 'python3'

    if python:
        cmd = cmd + ['-p', python]

    # Actually create the virtualenv.
    with spinner():
        c = delegator.run(cmd, block=False)
    click.echo(crayons.blue(c.out), err=True)

    # Say where the virtualenv is.
    do_where(virtualenv=True, bare=False)
Пример #5
0
def check(three=None, python=False):
    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python, validate=False)

    click.echo(crayons.yellow('Checking PEP 508 requirements...'))

    # Run the PEP 508 checker in the virtualenv.
    c = delegator.run('{0} {1}'.format(which('python'), pep508checker.__file__.rstrip('cdo')))
    results = json.loads(c.out)

    # Load the pipfile.
    p = pipfile.Pipfile.load(project.pipfile_location)

    failed = False
    # Assert each specified requirement.
    for marker, specifier in p.data['_meta']['requires'].items():

            if marker in results:
                try:
                    assert results[marker] == specifier
                except AssertionError:
                    failed = True
                    click.echo('Specifier {0} does not match {1} ({2}).'.format(crayons.green(marker), crayons.blue(specifier), crayons.red(results[marker])))
    if failed:
        click.echo(crayons.red('Failed!'))
        sys.exit(1)
    else:
        click.echo(crayons.green('Passed!'))
Пример #6
0
def clear_context():
    try:
        context.clear()
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return
    click.echo(crayons.green('Context cleared'))
Пример #7
0
def cli(ctx, where=False, venv=False, rm=False, bare=False, three=False, python=False, help=False):

    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(bare=bare)
            sys.exit(0)

        # --venv was passed...
        elif venv:

            with spinner():
                loc = project.virtualenv_location

            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                click.echo(crayons.red('No virtualenv has been created for this project yet!'), err=True)
                sys.exit(1)
            else:
                click.echo(project.virtualenv_location)
                sys.exit(0)

        # --rm was passed...
        elif rm:

            with spinner():
                loc = project.virtualenv_location

            if project.virtualenv_exists:
                click.echo(crayons.yellow('{0} ({1})...'.format(crayons.yellow('Removing virtualenv'), crayons.green(loc))))
                with spinner():
                    # Remove the virtualenv.
                    shutil.rmtree(project.virtualenv_location)
                sys.exit(0)
            else:
                click.echo(crayons.red('No virtualenv has been created for this project yet!'), err=True)
                sys.exit(1)

        # --two / --three was passed...
        if python or three is not None:
            ensure_project(three=three, python=python)

        else:
            # Display help to user, if no commands were passed.
            click.echo(format_help(ctx.get_help()))
Пример #8
0
def uninstall(package_name=False, more_packages=False, three=None, python=False, system=False, lock=False, dev=False, all=False):
    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python)

    package_names = (package_name,) + more_packages
    pipfile_remove = True

    # Un-install all dependencies, if --all was provided.
    if all is True:
        if not dev:
            click.echo(crayons.yellow('Un-installing all packages from virtualenv...'))
            do_purge(allow_global=system)
            sys.exit(0)

    # Uninstall [dev-packages], if --dev was provided.
    if dev:
        if 'dev-packages' in project.parsed_pipfile:
            click.echo(crayons.yellow('Un-installing {0}...'.format(crayons.red('[dev-packages]'))))
            package_names = project.parsed_pipfile['dev-packages']
            pipfile_remove = False
        else:
            click.echo(crayons.yellow('No {0} to uninstall.'.format(crayons.red('[dev-packages]'))))
            sys.exit(0)

    if package_name is False and not dev:
        click.echo(crayons.red('No package provided!'))
        sys.exit(1)

    for package_name in package_names:

        click.echo('Un-installing {0}...'.format(crayons.green(package_name)))

        c = delegator.run('{0} uninstall {1} -y'.format(which_pip(allow_global=system), package_name))
        click.echo(crayons.blue(c.out))

        if pipfile_remove:
            if dev:
                click.echo('Removing {0} from Pipfile\'s {1}...'.format(crayons.green(package_name), crayons.red('[dev-packages]')))
            else:
                click.echo('Removing {0} from Pipfile\'s {1}...'.format(crayons.green(package_name), crayons.red('[packages]')))

            project.remove_package_from_pipfile(package_name, dev)

        if lock:
            do_lock()
Пример #9
0
def publish(project_file: str, packages_path: str, show_result: bool, keep_environment: bool):
    try:
        env = context.current_env()
        bundle.publish(project_file, packages_path, env.bundle_url,
                       show_result=show_result, keep_environment=keep_environment)
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return
Пример #10
0
def do_activate_virtualenv(bare=False):
    """Executes the activate virtualenv functionality."""
    # Check for environment marker, and skip if it's set.
    if 'PIPENV_ACTIVE' not in os.environ:
        if not bare:
            click.echo('To activate this project\'s virtualenv, run the following:\n $ {0}'.format(
                crayons.red('pipenv shell'))
            )
        else:
            click.echo(activate_virtualenv())
Пример #11
0
def set_active_env(env_name: str):
    try:
        context.set_active_env(env_name)
        context.save()
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return

    click.echo(crayons.green('Current environment set to: {0}'.format(env_name)))
Пример #12
0
def add_env(env_name: str, api_url: str, bundle_url: str):
    try:
        context.add_env(env_name, api_url, bundle_url)
        context.set_active_env(env_name)
        context.save()
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return

    click.echo(crayons.green('Environment [{0}] added and set as active'.format(env_name)))
Пример #13
0
def active_token(env_name: str):
    if env_name:
        context.set_active_env(env_name)
    token = context.active_token()
    if not token:
        click.echo(crayons.red('You must authenticate first.'), err=True)
        click.echo('Try:\n $ modcli auth login')
        exit(1)
        return

    click.echo(token)
Пример #14
0
def do_install_dependencies(dev=False, only=False, bare=False, requirements=False, allow_global=False):
    """"Executes the install functionality."""

    if requirements:
        bare = True

    # Load the Pipfile.
    p = pipfile.load(project.pipfile_location)

    # Load the lockfile if it exists, or if only is being used (e.g. lock is being used).
    if only or not project.lockfile_exists:
        if not bare:
            click.echo(crayons.yellow('Installing dependencies from Pipfile...'))
            lockfile = json.loads(p.lock())
    else:
        if not bare:
            click.echo(crayons.yellow('Installing dependencies from Pipfile.lock...'))
        with open(project.lockfile_location) as f:
            lockfile = json.load(f)

    # Install default dependencies, always.
    deps = lockfile['default'] if not only else {}

    # Add development deps if --dev was passed.
    if dev:
        deps.update(lockfile['develop'])

    # Convert the deps to pip-compatible arguments.
    deps_path = convert_deps_to_pip(deps)

    # --requirements was passed.
    if requirements:
        with open(deps_path) as f:
            click.echo(f.read())
            sys.exit(0)

    # pip install:
    with spinner():
        c = pip_install(r=deps_path, allow_global=allow_global)

    if c.return_code != 0:
        click.echo(crayons.red('An error occured while installing!'))
        click.echo(crayons.blue(format_pip_error(c.err)))
        sys.exit(c.return_code)

    if not bare:
        click.echo(crayons.blue(format_pip_output(c.out, r=deps_path)))

    # Cleanup the temp requirements file.
    if requirements:
        os.remove(deps_path)
Пример #15
0
 def update_status(config, status, computer, manager):
     """Update each application's status."""
     log.info("Recording application status...")
     for application in config.applications:
         latest = status.get_latest(application)
         if manager.is_running(application):
             if computer != latest:
                 if status.is_running(application, computer):
                     # case 1: application just launched remotely
                     manager.stop(application)
                     status.stop(application, computer)
                     print(crayons.green(
                         f"{application} is now running on {latest}"))
                     print(crayons.red(
                         f"{application} is now stopped on {computer}"))
                 else:
                     # case 2: application just launched locally
                     status.start(application, computer)
                     print(crayons.green(
                         f"{application} is now running on {computer}"))
             else:
                 # case 3: application already running locally
                 print(crayons.cyan(
                     f"{application} is running on {computer}"))
         else:
             if status.is_running(application, computer):
                 # case 4: application just closed locally
                 status.stop(application, computer)
                 print(crayons.red(
                     f"{application} is now stopped on {computer}"))
             elif latest:
                 # case 5: application already closed locally
                 print(crayons.magenta(
                     f"{application} is running on {latest}"))
             else:
                 # case 6: application is not running
                 print(crayons.white(
                     f"{application} is not running"))
Пример #16
0
def ensure_virtualenv(three=None, python=None):
    """Creates a virtualenv, if one doesn't exist."""

    if not project.virtualenv_exists:
        do_create_virtualenv(three=three, python=python)

    # If --three, --two, or --python were passed...
    elif (python) or (three is not None):
        click.echo(crayons.red('Virtualenv already exists!'), err=True)
        click.echo(crayons.yellow('Removing existing virtualenv...'), err=True)

        # Remove the virtualenv.
        shutil.rmtree(project.virtualenv_location)

        # Call this function again.
        ensure_virtualenv(three=three, python=python)
Пример #17
0
def install(package_name=False, more_packages=False, dev=False, three=False, python=False, system=False, lock=False):

    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python)

    # Allow more than one package to be provided.
    package_names = (package_name,) + more_packages

    # Install all dependencies, if none was provided.
    if package_name is False:
        click.echo(crayons.yellow('No package provided, installing all dependencies.'), err=True)
        do_init(dev=dev, allow_global=system)
        sys.exit(0)

    for package_name in package_names:
        click.echo('Installing {0}...'.format(crayons.green(package_name)))

        # pip install:
        with spinner():
            c = pip_install(package_name, allow_global=system)

        click.echo(crayons.blue(format_pip_output(c.out)))

        # TODO: This
        # Ensure that package was successfully installed.
        try:
            assert c.return_code == 0
        except AssertionError:
            click.echo('{0} An error occurred while installing {1}!'.format(crayons.red('Error: '), crayons.green(package_name)))
            click.echo(crayons.blue(format_pip_error(c.err)))
            sys.exit(1)

        if dev:
            click.echo('Adding {0} to Pipfile\'s {1}...'.format(crayons.green(package_name), crayons.red('[dev-packages]')))
        else:
            click.echo('Adding {0} to Pipfile\'s {1}...'.format(crayons.green(package_name), crayons.red('[packages]')))

        # Add the package to the Pipfile.
        project.add_package_to_pipfile(package_name, dev)

        # Ego boost.
        easter_egg(package_name)

        if lock:
            do_lock()
Пример #18
0
def run_open(module, three=None, python=None, pypi_mirror=None):
    from .core import which, ensure_project

    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python, validate=False, pypi_mirror=pypi_mirror)
    c = delegator.run(
        '{0} -c "import {1}; print({1}.__file__);"'.format(which("python"), module)
    )
    try:
        assert c.return_code == 0
    except AssertionError:
        echo(crayons.red("Module not found!"))
        sys.exit(1)
    if "__init__.py" in c.out:
        p = os.path.dirname(c.out.strip().rstrip("cdo"))
    else:
        p = c.out.strip().rstrip("cdo")
    echo(crayons.normal("Opening {0!r} in your EDITOR.".format(p), bold=True))
    edit(filename=p)
    sys.exit(0)
Пример #19
0
def login(username: str, password: str, show_token: bool, one_time: bool, env_name: str):
    if env_name:
        context.set_active_env(env_name)
    env = context.current_env()
    if not one_time:
        click.echo('Logging in to [{0}]...'.format(env.name))
    try:
        token = auth.login(username, password, env.api_url)
    except Exception as ex:
        click.echo(crayons.red(str(ex)), err=True)
        exit(1)
        return

    if not one_time:
        env.set_token(token)
        context.save()

    if show_token or one_time:
        print(token.strip())
    else:
        click.echo(crayons.green('You\'re now logged in as [{0}] in [{1}].'.format(username, env.name)))
Пример #20
0
def run(command, args, no_interactive=False, three=None, python=False):
    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python, validate=False)

    # Automatically enable --no-interactive, when applicable.
    if not sys.stdout.isatty():
        no_interactive = True

    # Spawn the new process, and interact with it.
    try:
        c = pexpect.spawn(which(command), list(args))
    except pexpect.exceptions.ExceptionPexpect:
        click.echo(crayons.red('The command ({0}) was not found within the virtualenv!'.format(which(command))))
        sys.exit(1)

    # Interact with the new shell.
    if no_interactive:
        c.block()
    else:
        c.interact()
        c.close()
    sys.exit(c.exitstatus)
Пример #21
0
def do_init(dev=False, requirements=False, skip_virtualenv=False, allow_global=False):
    """Executes the init functionality."""

    ensure_pipfile()

    # Display where the Project is established.
    if not requirements:
        do_where(bare=False)

    if not project.virtualenv_exists:
        do_create_virtualenv()

    # Write out the lockfile if it doesn't exist.
    if project.lockfile_exists:

        # Open the lockfile.
        with codecs.open(project.lockfile_location, 'r') as f:
            lockfile = json.load(f)

        # Update the lockfile if it is out-of-date.
        p = pipfile.load(project.pipfile_location)

        # Check that the hash of the Lockfile matches the lockfile's hash.
        if not lockfile['_meta'].get('hash', {}).get('sha256') == p.hash:
            click.echo(crayons.red('Pipfile.lock out of date, updating...'), err=True)

            do_lock()

    # Write out the lockfile if it doesn't exist.
    if not project.lockfile_exists:
        click.echo(crayons.yellow('Pipfile.lock not found, creating...'), err=True)
        do_lock()

    do_install_dependencies(dev=dev, requirements=requirements, allow_global=allow_global)

    # Activate virtualenv instructions.
    do_activate_virtualenv()
Пример #22
0
def update(
    ctx,
    three=None,
    python=False,
    pypi_mirror=None,
    system=False,
    verbose=False,
    clear=False,
    keep_outdated=False,
    pre=False,
    dev=False,
    bare=False,
    sequential=False,
    package=None,
    dry_run=None,
    outdated=False,
    more_packages=None,
):
    from .core import (
        ensure_project,
        do_outdated,
        do_lock,
        do_sync,
        ensure_lockfile,
        do_install,
        project,
    )

    ensure_project(three=three, python=python, warn=True)
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated(pypi_mirror=pypi_mirror)
    if not package:
        echo('{0} {1} {2} {3}{4}'.format(
            crayons.white('Running', bold=True),
            crayons.red('$ pipenv lock', bold=True),
            crayons.white('then', bold=True),
            crayons.red('$ pipenv sync', bold=True),
            crayons.white('.', bold=True),
        ))
    else:
        for package in ([package] + list(more_packages) or []):
            if package not in project.all_packages:
                echo(
                    '{0}: {1} was not found in your Pipfile! Aborting.'
                    ''.format(
                        crayons.red('Warning', bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                sys.exit(1)
    do_lock(verbose=verbose,
            clear=clear,
            pre=pre,
            keep_outdated=keep_outdated,
            pypi_mirror=pypi_mirror)
    do_sync(
        ctx=ctx,
        dev=dev,
        three=three,
        python=python,
        bare=bare,
        dont_upgrade=False,
        user=False,
        verbose=verbose,
        clear=clear,
        unused=False,
        sequential=sequential,
        pypi_mirror=pypi_mirror,
    )
Пример #23
0
def cli(
    ctx,
    where=False,
    venv=False,
    rm=False,
    bare=False,
    three=False,
    python=False,
    help=False,
    py=False,
    site_packages=False,
    envs=False,
    man=False,
    completion=False,
    pypi_mirror=None,
    support=None,
    clear=False,
):
    # Handle this ASAP to make shell startup fast.
    if completion:
        from . import shells

        try:
            shell = shells.detect_info()[0]
        except shells.ShellDetectionFailure:
            echo(
                "Fail to detect shell. Please provide the {0} environment "
                "variable.".format(crayons.normal("PIPENV_SHELL", bold=True)),
                err=True,
            )
            sys.exit(1)
        print(click_completion.get_code(shell=shell, prog_name="pipenv"))
        sys.exit(0)

    from .core import (
        system_which,
        do_py,
        warn_in_virtualenv,
        do_where,
        project,
        spinner,
        cleanup_virtualenv,
        ensure_project,
        format_help,
        do_clear,
    )

    if man:
        if system_which("man"):
            path = os.sep.join([os.path.dirname(__file__), "pipenv.1"])
            os.execle(system_which("man"), "man", path, os.environ)
        else:
            echo("man does not appear to be available on your system.", err=True)
    if envs:
        echo("The following environment variables can be set, to do various things:\n")
        for key in environments.__dict__:
            if key.startswith("PIPENV"):
                echo("  - {0}".format(crayons.normal(key, bold=True)))
        echo(
            "\nYou can learn more at:\n   {0}".format(
                crayons.green(
                    "http://docs.pipenv.org/advanced/#configuration-with-environment-variables"
                )
            )
        )
        sys.exit(0)
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed…
        if where:
            do_where(bare=True)
            sys.exit(0)
        elif py:
            do_py()
            sys.exit()
        # --support was passed…
        elif support:
            from .help import get_pipenv_diagnostics

            get_pipenv_diagnostics()
            sys.exit(0)
        # --clear was passed…
        elif clear:
            do_clear()
            sys.exit(0)

        # --venv was passed…
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    crayons.red("No virtualenv has been created for this project yet!"),
                    err=True,
                )
                sys.exit(1)
            else:
                echo(project.virtualenv_location)
                sys.exit(0)
        # --rm was passed…
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if environments.PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."
                    )
                )
                sys.exit(1)
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(
                        u"{0} ({1})…".format(
                            crayons.normal("Removing virtualenv", bold=True),
                            crayons.green(loc),
                        )
                    )
                )
                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                sys.exit(0)
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                sys.exit(1)
    # --two / --three was passed…
    if (python or three is not None) or site_packages:
        ensure_project(
            three=three,
            python=python,
            warn=True,
            site_packages=site_packages,
            pypi_mirror=pypi_mirror,
            clear=clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
Пример #24
0
def cli(
    ctx,
    where=False,
    venv=False,
    rm=False,
    bare=False,
    three=False,
    python=False,
    help=False,
    py=False,
    site_packages=False,
    envs=False,
    man=False,
    completion=False,
):
    if completion:  # Handle this ASAP to make shell startup fast.
        if PIPENV_SHELL:
            echo(
                get_code(shell=PIPENV_SHELL.split(os.sep)[-1],
                         prog_name='pipenv'))
        else:
            echo(
                'Please ensure that the {0} environment variable '
                'is set.'.format(crayons.normal('SHELL', bold=True)),
                err=True,
            )
            sys.exit(1)
        sys.exit(0)

    from .core import (system_which, do_py, warn_in_virtualenv, do_where,
                       project, spinner, cleanup_virtualenv, ensure_project,
                       format_help)
    if man:
        if system_which('man'):
            path = os.sep.join([os.path.dirname(__file__), 'pipenv.1'])
            os.execle(system_which('man'), 'man', path, os.environ)
        else:
            echo('man does not appear to be available on your system.',
                 err=True)
    if envs:
        echo(
            'The following environment variables can be set, to do various things:\n'
        )
        for key in environments.__dict__:
            if key.startswith('PIPENV'):
                echo('  - {0}'.format(crayons.normal(key, bold=True)))
        echo('\nYou can learn more at:\n   {0}'.format(
            crayons.green(
                'http://docs.pipenv.org/advanced/#configuration-with-environment-variables'
            )))
        sys.exit(0)
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(bare=True)
            sys.exit(0)
        elif py:
            do_py()
            sys.exit()
        # --venv was passed...
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    crayons.red(
                        'No virtualenv has been created for this project yet!'
                    ),
                    err=True,
                )
                sys.exit(1)
            else:
                echo(project.virtualenv_location)
                sys.exit(0)
        # --rm was passed...
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        'You are attempting to remove a virtualenv that '
                        'Pipenv did not create. Aborting.'))
                sys.exit(1)
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(u'{0} ({1})…'.format(
                        crayons.normal('Removing virtualenv', bold=True),
                        crayons.green(loc),
                    )))
                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                sys.exit(0)
            else:
                echo(
                    crayons.red(
                        'No virtualenv has been created for this project yet!',
                        bold=True,
                    ),
                    err=True,
                )
                sys.exit(1)
    # --two / --three was passed...
    if (python or three is not None) or site_packages:
        ensure_project(three=three,
                       python=python,
                       warn=True,
                       site_packages=site_packages)
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
Пример #25
0
def report_no_copying_done():
    print(crayons.red(MESSAGE_NO_COPY, bold=True))
Пример #26
0
def resolve_deps(deps,
                 which,
                 which_pip,
                 project,
                 sources=None,
                 verbose=False,
                 python=False,
                 clear=False,
                 pre=False):
    """Given a list of dependencies, return a resolved list of dependencies,
    using pip-tools -- and their hashes, using the warehouse API / pip.
    """

    index_lookup = {}
    markers_lookup = {}

    python_path = which('python')

    with HackedPythonVersion(python_version=python, python_path=python_path):

        class PipCommand(pip.basecommand.Command):
            """Needed for pip-tools."""
            name = 'PipCommand'

        constraints = []

        for dep in deps:
            t = tempfile.mkstemp(prefix='pipenv-',
                                 suffix='-requirement.txt')[1]
            with open(t, 'w') as f:
                f.write(dep)

            if dep.startswith('-e '):
                constraint = pip.req.InstallRequirement.from_editable(
                    dep[len('-e '):])
            else:
                constraint = [
                    c for c in pip.req.parse_requirements(
                        t, session=pip._vendor.requests)
                ][0]
                # extra_constraints = []

            if ' -i ' in dep:
                index_lookup[constraint.name] = project.get_source(
                    url=dep.split(' -i ')[1]).get('name')

            if constraint.markers:
                markers_lookup[constraint.name] = str(
                    constraint.markers).replace('"', "'")

            constraints.append(constraint)

        pip_command = get_pip_command()

        pip_args = []

        if sources:
            pip_args = prepare_pip_source_args(sources, pip_args)

        if verbose:
            print('Using pip: {0}'.format(' '.join(pip_args)))

        pip_options, _ = pip_command.parse_args(pip_args)

        session = pip_command._build_session(pip_options)
        pypi = PyPIRepository(pip_options=pip_options, session=session)

        if verbose:
            logging.log.verbose = True

        results = []
        resolved_tree = set()

        resolver = Resolver(constraints=constraints,
                            repository=pypi,
                            clear_caches=clear,
                            prereleases=pre)
        # pre-resolve instead of iterating to avoid asking pypi for hashes of editable packages
        try:
            resolved_tree.update(
                resolver.resolve(max_rounds=PIPENV_MAX_ROUNDS))
        except (NoCandidateFound, DistributionNotFound, HTTPError) as e:
            click.echo(
                '{0}: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.\n  '
                'You can use {1} to bypass this mechanism, then run {2} to inspect the situation.'
                ''.format(crayons.red('Warning', bold=True),
                          crayons.red('$ pipenv install --skip-lock'),
                          crayons.red('$ pipenv graph')),
                err=True)
            click.echo(crayons.blue(e))
            sys.exit(1)

    for result in resolved_tree:
        if not result.editable:
            name = pep423_name(result.name)
            version = clean_pkg_version(result.specifier)
            index = index_lookup.get(result.name)

            if not markers_lookup.get(result.name):
                markers = str(
                    result.markers) if result.markers and 'extra' not in str(
                        result.markers) else None
            else:
                markers = markers_lookup.get(result.name)

            collected_hashes = []
            if 'python.org' in '|'.join([source['url'] for source in sources]):
                try:
                    # Grab the hashes from the new warehouse API.
                    r = requests.get(
                        'https://pypi.org/pypi/{0}/json'.format(name))
                    api_releases = r.json()['releases']

                    cleaned_releases = {}
                    for api_version, api_info in api_releases.items():
                        cleaned_releases[clean_pkg_version(
                            api_version)] = api_info

                    for release in cleaned_releases[version]:
                        collected_hashes.append(release['digests']['sha256'])

                    collected_hashes = [
                        'sha256:' + s for s in collected_hashes
                    ]

                    # Collect un-collectable hashes.
                    if not collected_hashes:
                        collected_hashes = list(
                            list(resolver.resolve_hashes([result
                                                          ]).items())[0][1])

                except (ValueError, KeyError):
                    pass

            d = {'name': name, 'version': version, 'hashes': collected_hashes}

            if index:
                d.update({'index': index})

            if markers:
                d.update({'markers': markers.replace('"', "'")})

            results.append(d)

    return results
Пример #27
0
def main():
    """Starting point for the program execution."""

    # Create command line parser.
    parser = argparse.ArgumentParser()

    # Adding command line arguments.
    parser.add_argument("username", help="Github Username", default=None)

    parser.add_argument(
        "--deep_dive",
        help=" ".join(
            [
                "If added considers repositories starred by users",
                "you follow along with repositories you have",
                "starred. Is significantly slower.",
            ]
        ),
        action="store_true",
        default=False,
    )

    # Parse command line arguments.
    arguments = parser.parse_args()

    if arguments.username is None:
        parser.print_help()
        return

    print("")
    print(
        crayons.white(
            "Authentication (with password) have higher rate limits."
        )
    )
    print(
        crayons.white(
            "Skipping password might cause failure due to rate limit."
        )
    )
    print("")

    password = getpass.getpass(
        crayons.blue(
            "Enter password (to skip press enter without entering anything): ",
            bold=True,
        )
    )

    try:
        gs = GitSuggest(
            username=arguments.username,
            password=password,
            token=None,
            deep_dive=arguments.deep_dive,
        )
    except BadCredentialsException:
        print("")
        print(
            crayons.red(
                "Incorrect password provided, to skip password enter nothing.",
                bold=True,
            )
        )
        exit()
    except TwoFactorException:
        print("")
        print(
            crayons.red(
                "\n".join(
                    [
                        "You have 2FA set up, please enter a personal access token.",
                        "You can generate one on https://github.com/settings/tokens",
                    ]
                ),
                bold=True,
            )
        )
        exit()

    print("")
    print(crayons.green("Suggestions generated!"))

    file_name = "/tmp/gitresults.html"
    repos = list(gs.get_suggested_repositories())

    r2h = ReposToHTML(arguments.username, repos)
    r2h.to_html(file_name)

    webbrowser.open_new("file://" + file_name)
Пример #28
0
def install(package):
    """Install a package"""
    click.echo(
        f'Finding packages having exact match{settings.LOADING}'
    )
    exact_match = True
    with Halo():
        matching_dirs = [i.parent for i in settings.REPO_DIR.rglob('Dockerfile') if package == i.parent.name]

    if not matching_dirs:
        exact_match = False
        click.echo(crayons.red('Exact match not found!'))
        click.echo(f'Finding packages with similar names{settings.LOADING}')
        with Halo():
            matching_dirs = [
                i.parent for i in settings.REPO_DIR.rglob('Dockerfile') if are_similar(i.parent.name, package)
            ]
    if matching_dirs:
        dir_index = 1
        # show a list of packages to choose from
        if len(matching_dirs) > 1 or not exact_match:
            count = 0
            click.echo()
            for matching_dir in matching_dirs:
                count += 1
                click.echo(
                    '[{0}] {1} ↜ {2}'.format(
                        crayons.white(count, bold=True),
                        crayons.green(matching_dir.name),
                        crayons.cyan(get_repo_name(matching_dir))
                    )
                )
            click.echo()
            dir_index = click.prompt(
                crayons.white(
                    "Which one do you want me to install?", bold=True
                ),
                type=int, default=1
            )
        # resolve the required details for building the image
        required_dir = matching_dirs[dir_index - 1]
        repo_name = get_repo_name(required_dir)
        image_tag = settings.DOCKER_IMAGE_NAMESPACE + f'{repo_name}.{required_dir.name}'

        click.echo(
            '{0} {1}{2}'.format(
                crayons.white('Installing', bold=True),
                crayons.green(required_dir.name),
                crayons.white(settings.LOADING, bold=True)
            )
        )
        # build docker image
        click.echo(f'Using Dockerfile from {required_dir}')
        click.echo(f'tagging image as {image_tag}')
        with Halo():
            image = docker_client.images.build(
                path=str(required_dir),
                tag=image_tag,
                quiet=False
            )
        click.echo(crayons.cyan(f'Successfully built image. Run `dockapt run {required_dir.name}` to use it'))
    else:
        click.echo(
            crayons.magenta(f"I couldn't find ", bold=True) + crayons.green(package, bold=True) + crayons.magenta(
                " in my repositories", bold=True)
        )
def report_error_message(message):
    print(crayons.white("Error: ", bold=True) + crayons.red(message))
Пример #30
0
def actually_resolve_deps(deps,
                          index_lookup,
                          markers_lookup,
                          project,
                          sources,
                          verbose,
                          clear,
                          pre,
                          req_dir=None):
    from .vendor.packaging.markers import default_environment
    from .patched.notpip._internal import basecommand
    from .patched.notpip._internal.cmdoptions import no_binary, only_binary
    from .patched.notpip._internal.req import parse_requirements
    from .patched.notpip._internal.exceptions import DistributionNotFound
    from .patched.notpip._vendor.requests.exceptions import HTTPError
    from pipenv.patched.piptools.resolver import Resolver
    from pipenv.patched.piptools.repositories.pypi import PyPIRepository
    from pipenv.patched.piptools.scripts.compile import get_pip_command
    from pipenv.patched.piptools import logging as piptools_logging
    from pipenv.patched.piptools.exceptions import NoCandidateFound
    from .vendor.requirementslib import Requirement
    from ._compat import TemporaryDirectory, NamedTemporaryFile

    class PipCommand(basecommand.Command):
        """Needed for pip-tools."""
        name = 'PipCommand'

    constraints = []
    cleanup_req_dir = False
    if not req_dir:
        req_dir = TemporaryDirectory(suffix='-requirements', prefix='pipenv-')
        cleanup_req_dir = True
    for dep in deps:
        if not dep:
            continue
        url = None
        if ' -i ' in dep:
            dep, url = dep.split(' -i ')
        req = Requirement.from_line(dep)

        # extra_constraints = []

        if url:
            index_lookup[req.name] = project.get_source(url=url).get('name')
        # strip the marker and re-add it later after resolution
        # but we will need a fallback in case resolution fails
        # eg pypiwin32
        if req.markers:
            markers_lookup[req.name] = req.markers.replace('"', "'")
        constraints.append(req.constraint_line)

    pip_command = get_pip_command()
    constraints_file = None
    pip_args = []
    if sources:
        pip_args = prepare_pip_source_args(sources, pip_args)
    if verbose:
        print('Using pip: {0}'.format(' '.join(pip_args)))
    with NamedTemporaryFile(mode='w',
                            prefix='pipenv-',
                            suffix='-constraints.txt',
                            dir=req_dir.name,
                            delete=False) as f:
        if sources:
            requirementstxt_sources = ' '.join(pip_args) if pip_args else ''
            requirementstxt_sources = requirementstxt_sources.replace(
                ' --', '\n--')
            f.write(u'{0}\n'.format(requirementstxt_sources))
        f.write(u'\n'.join([_constraint for _constraint in constraints]))
        constraints_file = f.name
    pip_options, _ = pip_command.parser.parse_args(pip_args)
    pip_options.cache_dir = PIPENV_CACHE_DIR
    session = pip_command._build_session(pip_options)
    pypi = PyPIRepository(pip_options=pip_options,
                          use_json=False,
                          session=session)
    constraints = parse_requirements(constraints_file,
                                     finder=pypi.finder,
                                     session=pypi.session,
                                     options=pip_options)
    constraints = [c for c in constraints]
    if verbose:
        logging.log.verbose = True
        piptools_logging.log.verbose = True
    resolved_tree = set()
    resolver = Resolver(constraints=constraints,
                        repository=pypi,
                        clear_caches=clear,
                        prereleases=pre)
    # pre-resolve instead of iterating to avoid asking pypi for hashes of editable packages
    hashes = None
    try:
        results = resolver.resolve(max_rounds=PIPENV_MAX_ROUNDS)
        hashes = resolver.resolve_hashes(results)
        resolved_tree.update(results)
    except (NoCandidateFound, DistributionNotFound, HTTPError) as e:
        click_echo(
            '{0}: Your dependencies could not be resolved. You likely have a '
            'mismatch in your sub-dependencies.\n  '
            'You can use {1} to bypass this mechanism, then run {2} to inspect '
            'the situation.\n  '
            'Hint: try {3} if it is a pre-release dependency.'
            ''.format(
                crayons.red('Warning', bold=True),
                crayons.red('$ pipenv install --skip-lock'),
                crayons.red('$ pipenv graph'),
                crayons.red('$ pipenv lock --pre'),
            ),
            err=True,
        )
        click_echo(crayons.blue(str(e)), err=True)
        if 'no version found at all' in str(e):
            click_echo(
                crayons.blue(
                    'Please check your version specifier and version number. See PEP440 for more information.'
                ))
        if cleanup_req_dir:
            req_dir.cleanup()
        raise RuntimeError
    if cleanup_req_dir:
        req_dir.cleanup()
    return (resolved_tree, hashes, markers_lookup, resolver)
Пример #31
0
def shell(three=None, python=False, compat=False, shell_args=None):
    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python, validate=False)

    # Set an environment variable, so we know we're in the environment.
    os.environ['PIPENV_ACTIVE'] = '1'

    # Support shell compatibility mode.
    if PIPENV_SHELL_COMPAT:
        compat = True

    # Compatibility mode:
    if compat:
        try:
            shell = os.environ['SHELL']
        except KeyError:
            click.echo(crayons.red('Windows is not currently supported.'))
            sys.exit(1)

        click.echo(crayons.yellow('Spawning environment shell ({0}).'.format(crayons.red(shell))))

        cmd = "{0} -i'".format(shell)
        args = []

    # Standard (properly configured shell) mode:
    else:
        cmd = 'pew'
        args = ["workon", project.name]

    # Grab current terminal dimensions to replace the hardcoded default
    # dimensions of pexpect
    terminal_dimensions = get_terminal_size()

    c = pexpect.spawn(
        cmd,
        args,
        dimensions=(
            terminal_dimensions.lines,
            terminal_dimensions.columns
        )
    )

    # Activate the virtualenv if in compatibility mode.
    if compat:
        c.sendline(activate_virtualenv())

    # Send additional arguments to the subshell.
    if shell_args:
        c.sendline(' '.join(shell_args))

    # Handler for terminal resizing events
    # Must be defined here to have the shell process in its context, since we
    # can't pass it as an argument
    def sigwinch_passthrough(sig, data):
        terminal_dimensions = get_terminal_size()
        c.setwinsize(terminal_dimensions.lines, terminal_dimensions.columns)
    signal.signal(signal.SIGWINCH, sigwinch_passthrough)

    # Interact with the new shell.
    c.interact()
    c.close()
    sys.exit(c.exitstatus)
Пример #32
0
def actually_resolve_reps(deps, index_lookup, markers_lookup, project, sources, verbose, clear, pre):

    class PipCommand(pip.basecommand.Command):
        """Needed for pip-tools."""
        name = 'PipCommand'

    constraints = []

    for dep in deps:
        t = tempfile.mkstemp(prefix='pipenv-', suffix='-requirement.txt')[1]
        with open(t, 'w') as f:
            f.write(dep)

        if dep.startswith('-e '):
            constraint = pip.req.InstallRequirement.from_editable(dep[len('-e '):])
        else:
            constraint = [c for c in pip.req.parse_requirements(t, session=pip._vendor.requests)][0]
            # extra_constraints = []

        if ' -i ' in dep:
            index_lookup[constraint.name] = project.get_source(url=dep.split(' -i ')[1]).get('name')

        if constraint.markers:
            markers_lookup[constraint.name] = str(constraint.markers).replace('"', "'")

        constraints.append(constraint)

    pip_command = get_pip_command()

    pip_args = []

    if sources:
        pip_args = prepare_pip_source_args(sources, pip_args)

    if verbose:
        print('Using pip: {0}'.format(' '.join(pip_args)))

    pip_options, _ = pip_command.parse_args(pip_args)

    session = pip_command._build_session(pip_options)
    pypi = PyPIRepository(pip_options=pip_options, session=session)

    if verbose:
        logging.log.verbose = True


    resolved_tree = set()

    resolver = Resolver(constraints=constraints, repository=pypi, clear_caches=clear, prereleases=pre)
    # pre-resolve instead of iterating to avoid asking pypi for hashes of editable packages
    try:
        resolved_tree.update(resolver.resolve(max_rounds=PIPENV_MAX_ROUNDS))
    except (NoCandidateFound, DistributionNotFound, HTTPError) as e:
        click.echo(
            '{0}: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.\n  '
            'You can use {1} to bypass this mechanism, then run {2} to inspect the situation.'
            ''.format(
                crayons.red('Warning', bold=True),
                crayons.red('$ pipenv install --skip-lock'),
                crayons.red('$ pipenv graph')
            ),
            err=True)

        click.echo(crayons.blue(e))

        if 'no version found at all' in str(e):
            click.echo(crayons.blue('Please check your version specifier and version number. See PEP440 for more information.'))

        raise RuntimeError

    return resolved_tree
Пример #33
0
def update(
    ctx,
    three=None,
    python=False,
    pypi_mirror=None,
    system=False,
    verbose=False,
    clear=False,
    keep_outdated=False,
    pre=False,
    dev=False,
    bare=False,
    sequential=False,
    package=None,
    dry_run=None,
    outdated=False,
    more_packages=None,
):
    from .core import (
        ensure_project,
        do_outdated,
        do_lock,
        do_sync,
        project,
    )

    ensure_project(three=three, python=python, warn=True, pypi_mirror=pypi_mirror)
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated(pypi_mirror=pypi_mirror)
    if not package:
        echo(
            "{0} {1} {2} {3}{4}".format(
                crayons.white("Running", bold=True),
                crayons.red("$ pipenv lock", bold=True),
                crayons.white("then", bold=True),
                crayons.red("$ pipenv sync", bold=True),
                crayons.white(".", bold=True),
            )
        )
    else:
        for package in [package] + list(more_packages) or []:
            if package not in project.all_packages:
                echo(
                    "{0}: {1} was not found in your Pipfile! Aborting."
                    "".format(
                        crayons.red("Warning", bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                sys.exit(1)
    do_lock(
        verbose=verbose,
        clear=clear,
        pre=pre,
        keep_outdated=keep_outdated,
        pypi_mirror=pypi_mirror,
    )
    do_sync(
        ctx=ctx,
        dev=dev,
        three=three,
        python=python,
        bare=bare,
        dont_upgrade=False,
        user=False,
        verbose=verbose,
        clear=clear,
        unused=False,
        sequential=sequential,
        pypi_mirror=pypi_mirror,
    )
Пример #34
0
def process_date(date):
    zipfile = get_radar_archive_file(date)
    if zipfile is None:
        print(crayons.yellow(f"No file found for radar {RID} at date {date}."))
        return None

    # Unzip data/
    namelist = extract_zip(zipfile, path=ZIPDIR)
    refl_name = None
    for name in REFL_NAME:
        if check_reflectivity(namelist[0], refl_name=name):
            refl_name = name
            break

    if refl_name is None:
        print("No valid reflectivity fields found at date {date}.")
        remove(namelist)
        return None

    print(crayons.yellow(f"{len(namelist)} files to process for {date}."))

    # Generate clutter mask for the given date.
    datestr = date.strftime("%Y%m%d")
    outpath = os.path.join(OUTPATH, "cmasks", str(RID))
    os.makedirs(outpath, exist_ok=True)
    output_maskfile = os.path.join(outpath, f"{RID}_{datestr}.nc")
    try:
        gen_cmask(namelist, output_maskfile, refl_name=refl_name)
    except ValueError:
        pass

    # Generate composite mask.
    try:
        cmask = cluttercal.composite_mask(date,
                                          timedelta=7,
                                          indir=outpath,
                                          prefix=f"{RID}_")
    except ValueError:
        if os.path.exists(output_maskfile):
            cmask = cluttercal.single_mask(output_maskfile)
        else:
            print(
                crayons.red(
                    f"Problem with date {date} and radar {RID}. No mask file available: {output_maskfile}"
                ))
            remove(namelist)
            return None

    # Extract the clutter reflectivity for the given date.
    rslt = [buffer(f, cmask, refl_name) for f in namelist]

    saved = False
    if rslt is not None:
        rslt = [r for r in rslt if r is not None]
        if len(rslt) != 0:
            ttmp, rtmp = zip(*rslt)
            rca = np.array(rtmp)
            dtime = np.array(ttmp, dtype="datetime64")

            if len(rca) != 0:
                df = pd.DataFrame({"rca": rca}, index=dtime)
                savedata(df, date, path=OUTPATH)
                saved = True

    if saved:
        print(crayons.green(f"Radar {RID} processed and RCA saved."))
    else:
        print(crayons.yellow(f"No data for radar {RID} for {date}."))

    # Removing unzipped files, collecting memory garbage.
    remove(namelist)
    return None
Пример #35
0
def print_error_message(message: str, payload: str, err) -> None:
    print(
        crayons.red(message + ' Payload: ' + str(payload or '') + '\nError: ' +
                    repr(err)))
Пример #36
0
def uninstall(package_name=False,
              more_packages=False,
              three=None,
              system=False,
              lock=False,
              dev=False,
              all=False):
    # Ensure that virtualenv is available.
    ensure_project(three=three)

    package_names = (package_name, ) + more_packages
    pipfile_remove = True

    # Un-install all dependencies, if --all was provided.
    if all is True:
        if not dev:
            click.echo(
                crayons.yellow(
                    'Un-installing all packages from virtualenv...'))
            do_purge(allow_global=system)
            sys.exit(0)

    # Uninstall [dev-packages], if --dev was provided.
    if dev:
        if 'dev-packages' in project.parsed_pipfile:
            click.echo(
                crayons.yellow('Un-installing {0}...'.format(
                    crayons.red('[dev-packages]'))))
            package_names = project.parsed_pipfile['dev-packages']
            pipfile_remove = False
        else:
            click.echo(
                crayons.yellow('No {0} to uninstall.'.format(
                    crayons.red('[dev-packages]'))))
            sys.exit(0)

    if package_name is False and not dev:
        click.echo(crayons.red('No package provided!'))
        sys.exit(1)

    for package_name in package_names:

        click.echo('Un-installing {0}...'.format(crayons.green(package_name)))

        c = delegator.run('{0} uninstall {1} -y'.format(
            which_pip(allow_global=system), package_name))
        click.echo(crayons.blue(c.out))

        if pipfile_remove:
            if dev:
                click.echo('Removing {0} from Pipfile\'s {1}...'.format(
                    crayons.green(package_name),
                    crayons.red('[dev-packages]')))
            else:
                click.echo('Removing {0} from Pipfile\'s {1}...'.format(
                    crayons.green(package_name), crayons.red('[packages]')))

            project.remove_package_from_pipfile(package_name, dev)

        if lock:
            do_lock()
Пример #37
0
def do_lock(dev=False):
    """Executes the freeze functionality."""

    click.echo(
        crayons.yellow(
            'Assuring all dependencies from Pipfile are installed...'))

    # Purge the virtualenv, for development dependencies.
    do_purge(bare=True)

    click.echo(
        crayons.yellow('Locking {0} dependencies...'.format(
            crayons.red('[dev-packages]'))))

    # Install only development dependencies.
    do_install_dependencies(dev=True, only=True, bare=True)

    # Load the Pipfile and generate a lockfile.
    p = pipfile.load(project.pipfile_location)
    lockfile = json.loads(p.lock())

    # Pip freeze development dependencies.
    c = delegator.run('{0} freeze'.format(which_pip()))

    # Add Development dependencies to lockfile.
    for dep in c.out.split('\n'):
        if dep:
            lockfile['develop'].update(convert_deps_from_pip(dep))

    # Purge the virtualenv.
    do_purge(bare=True)

    click.echo(
        crayons.yellow('Locking {0} dependencies...'.format(
            crayons.red('[packages]'))))

    # Install only development dependencies.
    do_install_dependencies(bare=True)

    # Pip freeze default dependencies.
    c = delegator.run('{0} freeze'.format(which_pip()))

    # Add default dependencies to lockfile.
    for dep in c.out.split('\n'):
        if dep:
            lockfile['default'].update(convert_deps_from_pip(dep))

    # Write out lockfile.
    with open(project.lockfile_location, 'w') as f:
        f.write(json.dumps(lockfile, indent=4, separators=(',', ': ')))

    # Provide instructions for dev dependencies.
    if not dev:
        click.echo(
            crayons.yellow('Note: ') +
            'your project now has only default {0} installed.'.format(
                crayons.red('[packages]')))
        click.echo('To keep {0} next time, run: $ {1}'.format(
            crayons.red('[dev-packages]'), crayons.green('pipenv lock --dev')))
    else:
        # Install only development dependencies.
        do_install_dependencies(dev=True, only=True, bare=True)
Пример #38
0
                    print(
                        crayons.yellow("warning: ") + crayons.yellow(
                            "assembler code 'raw' misuse can cause errors!"))
                    insfound = True

                if insfound == False:
                    print(
                        crayons.red(
                            "compiler: function error! (Keyword Not Found)"))
    return outFile[:-1]


filename1 = sys.argv[1]
filename2 = sys.argv[2]

print(crayons.cyan("opening..."))
#os.getcwd()+"/"
if os.path.isfile(filename1):
    with open(filename1, mode="r") as fn1:
        codeIn = fn1.read()

    print(crayons.cyan("compiling..."))
    outCode = CompileCode(codeIn)

    print(crayons.cyan("making output..."))
    with open(filename2, mode="w") as fn2:
        fn2.write(outCode)

else:
    print(crayons.red("tc-pvm: Input file not found: " + filename1))
Пример #39
0
 def log_error(message: str) -> None:
     logger.error(crayons.red(message))
Пример #40
0
	for i in range(n):
		name = names[i]
		mean_score, std_score = mean(results[name]), std(results[name])
		print(crayons.yellow(f'\t[*] RANK => {i+1}', bold=True))
		print(crayons.blue(f'\t[*] NAME => {name}', bold=True))
		print(crayons.yellow(f'\t[*] Score => {round(mean_score,3)}', bold=True))
		print(crayons.red(f'\t[*] std score => (+/-){round(std_score,3)}', bold=True))
		print("\n\n")
	
	'''
	# boxplot for the top n
	pyplot.boxplot(scores, labels=names)
	_, labels = pyplot.xticks()
	pyplot.setp(labels, rotation=90)
	#pyplot.savefig('spotcheck.png')
	pyplot.grid()
	pyplot.show()'''

# load dataset
print(crayons.red("\n[*] LOADING DATASET... ", bold=True))
print(crayons.red("\n[*] DATASET LOADED...NOW EVALUATING THE BEST MODELS....", bold=True))
X, y = df, y

# get model list
print(crayons.red("\n[*] GETTING THE MODEL LISTS:" , bold=True))
models = regression.get_models()
# evaluate models
print(crayons.yellow("\n[*]BEST RESULTING MODELS ACCORDING TO THE DATA...", bold=True))
results = regression.evaluate_models(X, y, models, metric='mean_squared_error')
# summarize results
summarize_results(results)
Пример #41
0
## Installs the crayons package.
## python3 -m pip install --user crayons
import crayons

# print 'red string' in red
print(crayons.red('red string'))

# Red White and Blue text
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.disable()  # disables the crayons package
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

crayons.DISABLE_COLOR = False  # enable the crayons package

# This line will print in color because color is enabled
print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

# print 'red string' in red
print(crayons.red('red string', bold=True))

# print 'yellow string' in yellow
print(crayons.yellow('yellow string', bold=True))

# print 'magenta string' in magenta
print(crayons.magenta('magenta string', bold=True))

# print 'white string' in white
print(crayons.white('white string', bold=True))
Пример #42
0
                await message.reply(f'Failed to find user with the name: {content}.')
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] Failed to find a user with the name {content}."))

    elif "!playlist" in args[0].lower():
        try:
            playlist_id = await get_playlist(content)

            if playlist_id is not None:
                await client.user.party.set_playlist(playlist=playlist_id)
                await message.reply(f'Playlist set to {playlist_id}.')
                print(f'[PartyBot] [{time()}] Playlist set to {playlist_id}.')

            else:
                await message.reply(f'Failed to find a playlist with the name: {content}.')
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                                  f"Failed to find a playlist with the name: {content}."))

        except fortnitepy.errors.Forbidden:
            await message.reply(f"Couldn't set playlist to {args[1]}, as I'm not party leader.")
            print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                              "Failed to set playlist as I don't have the required permissions."))


if (data['email'] and data['password']) and (data['email'] != '*****@*****.**' and data['password'] != 'password1'):
    try:
        client.run()
    except fortnitepy.errors.AuthException as e:
        print(crayons.red(f"[PartyBot] [{time()}] [ERROR] {e}"))
else:
    print(crayons.red(f"[PartyBot] [{time()}] [ERROR] Failed to login as no (or default) account details provided."))
Пример #43
0
def actually_resolve_reps(deps, index_lookup, markers_lookup, project, sources,
                          verbose, clear, pre):
    import pip

    class PipCommand(pip.basecommand.Command):
        """Needed for pip-tools."""
        name = 'PipCommand'

    constraints = []

    req_dir = tempfile.mkdtemp(prefix='pipenv-', suffix='-requirements')
    for dep in deps:
        if dep.startswith('-e '):
            constraint = pip.req.InstallRequirement.from_editable(
                dep[len('-e '):])
        else:
            fd, t = tempfile.mkstemp(prefix='pipenv-',
                                     suffix='-requirement.txt',
                                     dir=req_dir)
            with os.fdopen(fd, 'w') as f:
                f.write(dep)

            constraint = [
                c for c in pip.req.parse_requirements(
                    t, session=pip._vendor.requests)
            ][0]
            # extra_constraints = []

        if ' -i ' in dep:
            index_lookup[constraint.name] = project.get_source(
                url=dep.split(' -i ')[1]).get('name')

        if constraint.markers:
            markers_lookup[constraint.name] = str(constraint.markers).replace(
                '"', "'")

        constraints.append(constraint)

    rmtree(req_dir)

    pip_command = get_pip_command()

    pip_args = []

    if sources:
        pip_args = prepare_pip_source_args(sources, pip_args)

    if verbose:
        print('Using pip: {0}'.format(' '.join(pip_args)))

    pip_options, _ = pip_command.parse_args(pip_args)

    session = pip_command._build_session(pip_options)
    pypi = PyPIRepository(pip_options=pip_options, session=session)

    if verbose:
        logging.log.verbose = True

    resolved_tree = set()

    resolver = Resolver(constraints=constraints,
                        repository=pypi,
                        clear_caches=clear,
                        prereleases=pre)
    # pre-resolve instead of iterating to avoid asking pypi for hashes of editable packages
    try:
        resolved_tree.update(resolver.resolve(max_rounds=PIPENV_MAX_ROUNDS))
    except (NoCandidateFound, DistributionNotFound, HTTPError) as e:
        click.echo(
            '{0}: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.\n  '
            'You can use {1} to bypass this mechanism, then run {2} to inspect the situation.'
            ''.format(crayons.red('Warning', bold=True),
                      crayons.red('$ pipenv install --skip-lock'),
                      crayons.red('$ pipenv graph')),
            err=True)

        click.echo(crayons.blue(str(e)))

        if 'no version found at all' in str(e):
            click.echo(
                crayons.blue(
                    'Please check your version specifier and version number. See PEP440 for more information.'
                ))

        raise RuntimeError

    return resolved_tree, resolver
Пример #44
0
logfile.write(nowDateLog + " >> " + softName + " " + ver + "\n\n")
print('Укажите путь до директории с архивами или пропустите этот шаг,\nесли операция выполняется в текущей директории')
tarDir = input()
if tarDir == "":
      tarDir = os.getcwd()
      print('Не указан путь. Используется текущая директория:')
      print(tarDir)
      logfile.write(nowDateLog + " >> Директория не указана. Используемая дриектория: " + tarDir + "\n")
else:
    print('Попытка использовать указанный путь:')
    print(tarDir)

try:
    os.chdir(tarDir)
except FileNotFoundError:
    print(crayons.red('ERR: #010:', bold=True) + ' Указанная директория отсутствует или задана неверно.')
    logfile.write(nowDateLog + " >> ERR: #010: Директория отсутствует или задана неверно: " + tarDir + "\n")
    logfile.exit()
    sys.exit("Остановка выполнения")
print(delimiter)
if glob.glob("*.tgz"):
    print('Обнаружены следующие архивы:')
    logfile.write(nowDateLog + " >> Обнаруженные архивы:\n\n")
    for file in glob.glob("*.tgz"):
        print(file)
        logfile.write(file + "\n")
else:
    print(crayons.yellow('ERR: #310:', bold=True) + ' Архивы отсутствуют')
    logfile.write(nowDateLog + " >> ERR: #310: Архивы отсутствуют\n")
    print('Нажмите любую клавишу для завершения')
    exitKey = input()
Пример #45
0
def update(
    ctx,
    three=None,
    python=False,
    system=False,
    verbose=False,
    clear=False,
    keep_outdated=False,
    pre=False,
    dev=False,
    bare=False,
    sequential=False,
    package=None,
    dry_run=None,
    outdated=False,
    more_packages=None,
):
    from .core import (
        ensure_project,
        do_outdated,
        do_lock,
        do_sync,
        ensure_lockfile,
        do_install,
        project,
    )

    ensure_project(three=three, python=python, warn=True)
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated()
    if not package:
        echo('{0} {1} {2} {3}{4}'.format(
            crayons.white('Running', bold=True),
            crayons.red('$ pipenv lock', bold=True),
            crayons.white('then', bold=True),
            crayons.red('$ pipenv sync', bold=True),
            crayons.white('.', bold=True),
        ))
        do_lock(verbose=verbose,
                clear=clear,
                pre=pre,
                keep_outdated=keep_outdated)
        do_sync(
            ctx=ctx,
            install=install,
            dev=dev,
            three=three,
            python=python,
            bare=bare,
            dont_upgrade=False,
            user=False,
            verbose=verbose,
            clear=clear,
            unused=False,
            sequential=sequential,
        )
    else:
        for package in ([package] + list(more_packages) or []):
            if package not in project.all_packages:
                echo(
                    '{0}: {1} was not found in your Pipfile! Aborting.'
                    ''.format(
                        crayons.red('Warning', bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                sys.exit(1)
        ensure_lockfile(keep_outdated=project.lockfile_exists)
        # Install the dependencies.
        do_install(
            package_name=package,
            more_packages=more_packages,
            dev=dev,
            three=three,
            python=python,
            system=system,
            lock=True,
            ignore_pipfile=False,
            skip_lock=False,
            verbose=verbose,
            requirements=False,
            sequential=sequential,
            pre=pre,
            code=False,
            deploy=False,
            keep_outdated=True,
            selective_upgrade=True,
        )
Пример #46
0
def format_pip_error(error):
    error = error.replace('Expected', str(crayons.green('Expected', bold=True)))
    error = error.replace('Got', str(crayons.red('Got', bold=True)))
    error = error.replace('THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE', str(crayons.red('THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!', bold=True)))
    error = error.replace('someone may have tampered with them', str(crayons.red('someone may have tampered with them')))
    return error
Пример #47
0
        combined_score = 0

        low_a = 9999999999
        low_a_key = None

        # Maximize
        for a in answer_results:
            combined_score += answer_results[a]["score"]
            if answer_results[a]["score"] > max_a:
                max_a_key = a
                max_a = max(answer_results[a]["score"], max_a)

            if answer_results[a]["score"] < low_a:
                low_a_key = a
                low_a = min(answer_results[a]["score"], low_a)

        percentage = max_a * 100 / (combined_score + 1)
        percentage_low = low_a * 100 / (combined_score + 1)
        print(crayons.green(max_a_key))
        print("%d%%" % percentage)
        print(crayons.red(low_a_key))
        print("%d%%" % percentage_low)

        try:
            os.remove(file_path)
            print("deleted file")
        except:
            print("couldn't delete")

    time.sleep(0.1)
Пример #48
0
def update(
    ctx,
    three=None,
    python=False,
    pypi_mirror=None,
    system=False,
    clear=False,
    keep_outdated=False,
    pre=False,
    dev=False,
    bare=False,
    sequential=False,
    package=None,
    dry_run=None,
    outdated=False,
    more_packages=None,
):
    """Runs lock, then sync."""
    from .core import (
        ensure_project,
        do_outdated,
        do_lock,
        do_sync,
        project,
    )

    ensure_project(three=three,
                   python=python,
                   warn=True,
                   pypi_mirror=pypi_mirror)
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated(pypi_mirror=pypi_mirror)
    if not package:
        echo("{0} {1} {2} {3}{4}".format(
            crayons.white("Running", bold=True),
            crayons.red("$ pipenv lock", bold=True),
            crayons.white("then", bold=True),
            crayons.red("$ pipenv sync", bold=True),
            crayons.white(".", bold=True),
        ))
    else:
        for package in [package] + list(more_packages) or []:
            if package not in project.all_packages:
                echo(
                    "{0}: {1} was not found in your Pipfile! Aborting."
                    "".format(
                        crayons.red("Warning", bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                sys.exit(1)

    do_lock(
        clear=clear,
        pre=pre,
        keep_outdated=keep_outdated,
        pypi_mirror=pypi_mirror,
    )
    do_sync(
        ctx=ctx,
        dev=dev,
        three=three,
        python=python,
        bare=bare,
        dont_upgrade=False,
        user=False,
        clear=clear,
        unused=False,
        sequential=sequential,
        pypi_mirror=pypi_mirror,
    )
Пример #49
0
async def event_friend_message(message: fortnitepy.FriendMessage) -> None:
    args = message.content.split()
    split = args[1:]
    content = " ".join(split)

    print(f'[PartyBot] [{time()}] {message.author.display_name}: {message.content}')

    if "!skin" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaCharacter"
            )

            await message.reply(f'Skin set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set skin to: {cosmetic.id}.")
            await client.user.party.me.set_outfit(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find a skin with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find a skin with the name: {content}.")

    elif "!backpack" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaBackpack"
            )

            await message.reply(f'Backpack set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set backpack to: {cosmetic.id}.")
            await client.user.party.me.set_backpack(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find a backpack with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find a backpack with the name: {content}.")

    elif "!emote" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaDance"
            )

            await message.reply(f'Emote set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set emote to: {cosmetic.id}.")
            await client.user.party.me.clear_emote()
            await client.user.party.me.set_emote(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find an emote with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find an emote with the name: {content}.")

    elif "!pickaxe" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaPickaxe"
            )

            await message.reply(f'Pickaxe set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set pickaxe to: {cosmetic.id}.")
            await client.user.party.me.set_pickaxe(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find a pickaxe with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find a pickaxe with the name: {content}.")

    elif "!pet" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaPet"
            )

            await message.reply(f'Pet set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set pet to: {cosmetic.id}.")
            await client.user.party.me.set_pet(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find a pet with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find a pet with the name: {content}.")

    elif "!emoji" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaEmoji"
            )

            await message.reply(f'Emoji set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set emoji to: {cosmetic.id}.")
            await client.user.party.me.set_emoji(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find an emoji with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find an emoji with the name: {content}.")

    elif "!contrail" in args[0].lower():
        try:
            cosmetic = await BenBotAsync.get_cosmetic(
                lang="en",
                searchLang="en",
                matchMethod="contains",
                name=content,
                backendType="AthenaSkyDiveContrail"
            )

            await message.reply(f'Contrail set to {cosmetic.id}.')
            print(f"[PartyBot] [{time()}] Set contrail to: {cosmetic.id}.")
            await client.user.party.me.set_contrail(asset=cosmetic.id)

        except BenBotAsync.exceptions.NotFound:
            await message.reply(f"Couldn't find a contrail with the name: {content}.")
            print(f"[PartyBot] [{time()}] Couldn't find an contrail with the name: {content}.")

    elif "!purpleskull" in args[0].lower():
        variants = client.user.party.me.create_variants(
            clothing_color=1
        )

        await client.user.party.me.set_outfit(
            asset='CID_030_Athena_Commando_M_Halloween',
            variants=variants
        )

        await message.reply('Skin set to Purple Skull Trooper!')
        print(f"[PartyBot] [{time()}] Skin set to Purple Skull Trooper.")

    elif "!pinkghoul" in args[0].lower():
        variants = client.user.party.me.create_variants(
            material=3
        )

        await client.user.party.me.set_outfit(
            asset='CID_029_Athena_Commando_F_Halloween',
            variants=variants
        )

        await message.reply('Skin set to Pink Ghoul Trooper!')
        print(f"[PartyBot] [{time()}] Skin set to Pink Ghoul Trooper.")

    elif "!purpleportal" in args[0].lower():
        variants = client.user.party.me.create_variants(
            item='AthenaBackpack',
            particle_config='Particle',
            particle=1
        )

        await client.user.party.me.set_backpack(
            asset='BID_105_GhostPortal',
            variants=variants
        )

        await message.reply('Backpack set to Purple Ghost Portal!')
        print(f"[PartyBot] [{time()}] Backpack set to Purple Ghost Portal.")

    elif "!banner" in args[0].lower():
        await client.user.party.me.set_banner(icon=args[1], color=args[2], season_level=args[3])

        await message.reply(f'Banner set to: {args[1]}, {args[2]}, {args[3]}.')
        print(f"[PartyBot] [{time()}] Banner set to: {args[1]}, {args[2]}, {args[3]}.")

    elif "cid_" in args[0].lower():
        if 'banner' not in args[0].lower():
            await client.user.party.me.set_outfit(
                asset=args[0]
            )
        else:
            await client.user.party.me.set_outfit(
                asset=args[0],
                variants=client.user.party.me.create_variants(profile_banner='ProfileBanner')
            )

        await message.reply(f'Skin set to {args[0]}')
        print(f'[PartyBot] [{time()}] Skin set to {args[0]}')

    elif "vtid_" in args[0].lower():
        vtid = await set_vtid(args[0])
        if vtid[1] == 'Particle':
            variants = client.user.party.me.create_variants(particle_config='Particle', particle=1)
        else:
            variants = client.user.party.me.create_variants(**{vtid[1].lower(): int(vtid[2])})

        await client.user.party.me.set_outfit(asset=vtid[0], variants=variants)
        print(f'[PartyBot] [{time()}] Set variants of {vtid[0]} to {vtid[1]} {vtid[2]}.')
        await message.reply(f'Variants set to {args[0]}.\n'
                            '(Warning: This feature is not supported, please use !variants)')

    elif "!variants" in args[0].lower():
        if 'cid' in args[1].lower() and 'jersey_color' not in args[2]:
            variants = client.user.party.me.create_variants(
                **{args[2]: int(args[3]) if args[3].isdigit() else args[3]}
            )

            await client.user.party.me.set_outfit(
                asset=args[1],
                variants=variants
            )
        elif 'cid' in args[1].lower() and 'jersey_color' in args[2]:
            variants = client.user.party.me.create_variants(
                pattern=0,
                numeric=69,
                **{args[2]: int(args[3]) if args[3].isdigit() else args[3]}
            )

            await client.user.party.me.set_outfit(
                asset=args[1],
                variants=variants
            )
        elif 'bid' in args[1].lower():
            variants = client.user.party.me.create_variants(
                item='AthenaBackpack',
                **{args[2]: int(args[3]) if args[3].isdigit() else args[3]}
            )

            await client.user.party.me.set_backpack(
                asset=args[1],
                variants=variants
            )
        elif 'pickaxe_id' in args[1].lower():
            variants = client.user.party.me.create_variants(
                item='AthenaPickaxe',
                **{args[2]: int(args[3]) if args[3].isdigit() else args[3]}
            )

            await client.user.party.me.set_pickaxe(
                asset=args[1],
                variants=variants
            )

        await message.reply(f'Set variants of {args[1]} to {args[2]} {args[3]}.')
        print(f'[PartyBot] [{time()}] Set variants of {args[1]} to {args[2]} {args[3]}.')

    elif "!checkeredrenegade" in args[0].lower():
        variants = client.user.party.me.create_variants(
            material=2
        )

        await client.user.party.me.set_outfit(
            asset='CID_028_Athena_Commando_F',
            variants=variants
        )

        await message.reply('Skin set to Checkered Renegade!')
        print(f'[PartyBot] [{time()}] Skin set to Checkered Renegade.')

    elif "!mintyelf" in args[0].lower():
        variants = client.user.party.me.create_variants(
            material=2
        )

        await client.user.party.me.set_outfit(
            asset='CID_051_Athena_Commando_M_HolidayElf',
            variants=variants
        )

        await message.reply('Skin set to Minty Elf!')
        print(f'[PartyBot] [{time()}] Skin set to Minty Elf.')

    elif "eid_" in args[0].lower():
        await client.user.party.me.clear_emote()
        await client.user.party.me.set_emote(
            asset=args[0]
        )
        await message.reply(f'Emote set to {args[0]}!')

    elif "!stop" in args[0].lower():
        await client.user.party.me.clear_emote()
        await message.reply('Stopped emoting.')

    elif "bid_" in args[0].lower():
        await client.user.party.me.set_backpack(
            asset=args[0]
        )

        await message.reply(f'Backbling set to {args[0]}!')

    elif "!help" in args[0].lower():
        await message.reply('For a list of commands, goto; https://github.com/xMistt/fortnitepy-bot/wiki/Commands')

    elif "pickaxe_id_" in args[0].lower():
        await client.user.party.me.set_pickaxe(
            asset=args[0]
        )

        await message.reply(f'Pickaxe set to {args[0]}')

    elif "petcarrier_" in args[0].lower():
        await client.user.party.me.set_pet(
            asset=args[0]
        )

        await message.reply(f'Pet set to {args[0]}!')

    elif "emoji_" in args[0].lower():
        await client.user.party.me.clear_emote()
        await client.user.party.me.set_emoji(
            asset=args[0]
        )

        await message.reply(f'Emoji set to {args[0]}!')

    elif "trails_" in args[0].lower():
        await client.user.party.me.set_contrail(asset=args[0])

        await message.reply(f'Contrail set to {args[0]}!')

    elif "!legacypickaxe" in args[0].lower():
        await client.user.party.me.set_pickaxe(
            asset=args[1]
        )

        await message.reply(f'Pickaxe set to {args[1]}!')

    elif "!point" in args[0].lower():
        if 'pickaxe_id' in args[1].lower():
            await client.user.party.me.set_pickaxe(asset=args[1])
            await client.user.party.me.set_emote(asset='EID_IceKing')
            await message.reply(f'Pickaxe set to {args[1]} & Point it Out played.')
        else:
            try:
                cosmetic = await BenBotAsync.get_cosmetic(
                    lang="en",
                    searchLang="en",
                    matchMethod="contains",
                    name=content,
                    backendType="AthenaPickaxe"
                )

                await client.user.party.me.set_pickaxe(asset=cosmetic.id)
                await client.user.party.me.clear_emote()
                await client.user.party.me.set_emote(asset='EID_IceKing')
                await message.reply(f'Pickaxe set to {content} & Point it Out played.')
            except BenBotAsync.exceptions.NotFound:
                await message.reply(f"Couldn't find a pickaxe with the name: {content}")

    elif "!ready" in args[0].lower():
        await client.user.party.me.set_ready(fortnitepy.ReadyState.READY)
        await message.reply('Ready!')

    elif ("!unready" in args[0].lower()) or ("!sitin" in args[0].lower()):
        await client.user.party.me.set_ready(fortnitepy.ReadyState.NOT_READY)
        await message.reply('Unready!')

    elif "!sitout" in args[0].lower():
        await client.user.party.me.set_ready(fortnitepy.ReadyState.SITTING_OUT)
        await message.reply('Sitting Out!')

    elif "!bp" in args[0].lower():
        await client.user.party.me.set_battlepass_info(
            has_purchased=True,
            level=args[1],
        )

        await message.reply(f'Set battle pass tier to {args[1]}.')

    elif "!level" in args[0].lower():
        await client.user.party.me.set_banner(
            icon=client.user.party.me.banner[0],
            color=client.user.party.me.banner[1],
            season_level=args[1]
        )

        await message.reply(f'Set level to {args[1]}.')

    elif "!echo" in args[0].lower():
        await client.user.party.send(content)
        await message.reply('Sent message to party chat.')

    elif "!status" in args[0].lower():
        await client.set_status(content)

        await message.reply(f'Status set to {content}')
        print(f'[PartyBot] [{time()}] Status set to {content}.')

    elif "!leave" in args[0].lower():
        await client.user.party.me.set_emote('EID_Wave')
        await asyncio.sleep(2)
        await client.user.party.me.leave()
        await message.reply('Bye!')
        print(f'[PartyBot] [{time()}] Left the party as I was requested.')

    elif "!kick" in args[0].lower():
        user = await client.fetch_profile(content)
        member = client.user.party.members.get(user.id)
        if member is None:
            await message.reply("Couldn't find that user, are you sure they're in the party?")
        else:
            try:
                await member.kick()
                await message.reply(f"Kicked user: {member.display_name}.")
                print(f"[PartyBot] [{time()}] Kicked user: {member.display_name}")
            except fortnitepy.errors.Forbidden:
                await message.reply(f"Couldn't kick {member.display_name}, as I'm not party leader.")
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                                  "Failed to kick member as I don't have the required permissions."))

    elif "!promote" in args[0].lower():
        if len(args) == 1:
            user = await client.fetch_profile(message.author.display_name)
            member = await client.user.party.members.get(user.id)
        else:
            user = await client.fetch_profile(content)
            member = client.user.party.members.get(user.id)

        if member is None:
            await message.reply("Couldn't find that user, are you sure they're in the party?")
        else:
            try:
                await member.promote()
                await message.reply(f"Promoted user: {member.display_name}.")
                print(f"[PartyBot] [{time()}] Promoted user: {member.display_name}")
            except fortnitepy.errors.Forbidden:
                await message.reply(f"Couldn't promote {member.display_name}, as I'm not party leader.")
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                                  "Failed to kick member as I don't have the required permissions."))

    elif "playlist_" in args[0].lower():
        try:
            await client.user.party.set_playlist(playlist=args[0])
            await message.reply(f'Gamemode set to {args[0]}')
        except fortnitepy.errors.Forbidden:
            await message.reply(f"Couldn't set gamemode to {args[1]}, as I'm not party leader.")
            print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                              "Failed to set gamemode as I don't have the required permissions."))

    elif "!id" in args[0].lower():
        user = await client.fetch_profile(content, cache=False, raw=False)
        try:
            await message.reply(f"{content}'s Epic ID is: {user.id}")
        except AttributeError:
            await message.reply(f"I couldn't find an Epic account with the name: {content}.")

    elif "!privacy" in args[0].lower():
        try:
            if 'public' in args[1].lower():
                await client.user.party.set_privacy(fortnitepy.PartyPrivacy.PUBLIC)
            elif 'private' in args[1].lower():
                await client.user.party.set_privacy(fortnitepy.PartyPrivacy.PRIVATE)
            elif 'friends' in args[1].lower():
                await client.user.party.set_privacy(fortnitepy.PartyPrivacy.FRIENDS)
            elif 'friends_allow_friends_of_friends' in args[1].lower():
                await client.user.party.set_privacy(fortnitepy.PartyPrivacy.FRIENDS_ALLOW_FRIENDS_OF_FRIENDS)
            elif 'private_allow_friends_of_friends' in args[1].lower():
                await client.user.party.set_privacy(fortnitepy.PartyPrivacy.PRIVATE_ALLOW_FRIENDS_OF_FRIENDS)

            await message.reply(f'Party privacy set to {client.user.party.privacy}.')
            print(f'[PartyBot] [{time()}] Party privacy set to {client.user.party.privacy}.')

        except fortnitepy.errors.Forbidden:
            await message.reply(f"Couldn't set party privacy to {args[1]}, as I'm not party leader.")
            print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                              "Failed to set party privacy as I don't have the required permissions."))

    elif "!copy" in args[0].lower():
        if len(args) == 1:
            member = client.user.party.members.get(message.author.id)
        else:
            user = await client.fetch_profile(content)
            member = client.user.party.members.get(user.id)

        await client.user.party.me.edit(
            functools.partial(
                fortnitepy.ClientPartyMember.set_outfit,
                asset=member.outfit,
                variants=member.outfit_variants
            ),
            functools.partial(
                fortnitepy.ClientPartyMember.set_backpack,
                asset=member.backpack,
                variants=member.backpack_variants
            ),
            functools.partial(
                fortnitepy.ClientPartyMember.set_pickaxe,
                asset=member.pickaxe,
                variants=member.pickaxe_variants
            ),
            functools.partial(
                fortnitepy.ClientPartyMember.set_banner,
                icon=member.banner[0],
                color=member.banner[1],
                season_level=member.banner[2]
            ),
            functools.partial(
                fortnitepy.ClientPartyMember.set_battlepass_info,
                has_purchased=True,
                level=member.battlepass_info[1]
            )
        )

        await client.user.party.me.set_emote(asset=member.emote)
        await message.reply(f'Copied the loadout of {member.display_name}.')

    elif "!hologram" in args[0].lower():
        await client.user.party.me.set_outfit(
            asset='CID_VIP_Athena_Commando_M_GalileoGondola_SG'
        )

        await message.reply('Skin set to Star Wars Hologram!')
        print(f'[PartyBot] [{time()}] Skin set to Star Wars Hologram.')

    elif "!gift" in args[0].lower():
        await client.user.party.me.clear_emote()

        await client.user.party.me.set_emote(
            asset='EID_NeverGonna'
        )

        await message.reply('What did you think would happen? ha')

    elif "!matchmakingcode" in args[0].lower():
        await client.user.party.set_custom_key(
            key=content
        )

        await message.reply(f'Custom matchmaking code set to: {content}')

    elif "!ninja" in args[0].lower():
        await client.user.party.me.set_outfit(
            asset='CID_605_Athena_Commando_M_TourBus'
        )

        await message.reply('Skin set to Ninja!')
        print(f'[PartyBot] [{time()}] Skin set to Ninja.')

    elif "!ponpon" in args[0].lower():
        await client.user.party.me.set_emote(
            asset='EID_TourBus'
        )

        await message.reply('Emote set to Ninja Style!')

    elif "!enlightened" in args[0].lower():
        await client.user.party.me.set_outfit(
            asset=args[1],
            variants=client.user.party.me.create_variants(progressive=4),
            enlightenment=(args[2], args[3])
        )

        await message.reply(f'Skin set to {args[1]} at level {args[3]} (for Season 1{args[2]}).')
        print(f'[PartyBot] [{time()}] Enlightenment for {args[1]} set to level {args[3]} (for Season 1{args[2]}).')

    elif "!rareskins" in args[0].lower():
        await message.reply('Showing all rare skins now.')

        await client.user.party.me.set_outfit(
            asset='CID_030_Athena_Commando_M_Halloween',
            variants=client.user.party.me.create_variants(clothing_color=1)
        )

        await message.reply('Skin set to Purple Skull Trooper!')
        print(f"[PartyBot] [{time()}] Skin set to Purple Skull Trooper.")
        await asyncio.sleep(2)

        await client.user.party.me.set_outfit(
            asset='CID_029_Athena_Commando_F_Halloween',
            variants=client.user.party.me.create_variants(material=3)
        )

        await message.reply('Skin set to Pink Ghoul Trooper!')
        print(f"[PartyBot] [{time()}] Skin set to Pink Ghoul Trooper.")
        await asyncio.sleep(2)

        for skin in ('CID_028_Athena_Commando_F', 'CID_017_Athena_Commando_M', 'CID_022_Athena_Commando_F'):
            await client.user.party.me.set_outfit(
                asset=skin
            )

            await message.reply(f'Skin set to {skin}!')
            print(f"[PartyBot] [{time()}] Skin set to: {skin}!")
            await asyncio.sleep(2)

    elif "!goldenpeely" in args[0].lower():
        await client.user.party.me.set_outfit(
            asset='CID_701_Athena_Commando_M_BananaAgent',
            variants=client.user.party.me.create_variants(progressive=4),
            enlightenment=(2, 350)
        )

        await message.reply(f'Skin set to Golden Peely.')

    elif "!random" in args[0].lower():
        outfits = await BenBotAsync.get_cosmetics(
            lang="en",
            searchLang="en",
            backendType="AthenaCharacter"
        )

        skin = random.choice(outfits).id

        await client.user.party.me.set_outfit(
            asset=skin,
            variants=client.user.party.me.create_variants(profile_banner='ProfileBanner')
        )

        await message.reply(f'Skin randomly set to {skin}.')

    elif "!nobackpack" in args[0].lower():
        await client.user.party.me.clear_backpack()
        await message.reply('Removed backpack.')

    elif "!nopet" in args[0].lower():
        await client.user.party.me.clear_pet()
        await message.reply('Removed pet.')

    elif "!nocontrail" in args[0].lower():
        await client.user.party.me.clear_contrail()
        await message.reply('Removed contrail.')

    elif "!match" in args[0].lower():
        if len(args) == 2 and args[1].lower() == 'progressive':
            await set_and_update_prop('Location_s', 'InGame')
            await set_and_update_prop('HasPreloadedAthena_b', True)
            await set_and_update_prop('SpectateAPartyMemberAvailable_b', 'true')
            await set_and_update_prop('NumAthenaPlayersLeft_U', '100')

            match_time = str(fortnitepy.Client.to_iso(
                datetime.datetime.utcnow()
            ))[slice(23)]

            await set_and_update_prop('UtcTimeStartedMatchAthena_s', f'{str(match_time)}Z')

            await message.reply(f'Set state to in-game in a match with progressive players drop starting from 100.'
                                '\nUse the command: !lobby to revert back to normal.')

            while (100 >= client.user.party.me.meta.get_prop('NumAthenaPlayersLeft_U') > 0
                   and client.user.party.me.meta.get_prop('Location_s') == 'InGame'):
                await set_and_update_prop(
                    'NumAthenaPlayersLeft_U',
                    client.user.party.me.meta.get_prop('NumAthenaPlayersLeft_U') - random.randint(3, 6)
                )

                await asyncio.sleep(random.randint(45, 65))

        else:
            await set_and_update_prop('Location_s', 'InGame')
            await set_and_update_prop('NumAthenaPlayersLeft_U', args[1] if len(args) >= 2 else 0)
            await set_and_update_prop('HasPreloadedAthena_b', True)
            await set_and_update_prop('SpectateAPartyMemberAvailable_b', 'true')

            match_time = str(fortnitepy.Client.to_iso(
                datetime.datetime.utcnow() - datetime.timedelta(minutes=int(args[2]) if len(args) >= 3 else 0)
            ))[slice(23)]

            await set_and_update_prop('UtcTimeStartedMatchAthena_s', f'{str(match_time)}Z')

            await message.reply(f'Set state to in-game in a match with {args[1] if len(args) >= 2 else 0} players.'
                                '\nUse the command: !lobby to revert back to normal.')

    elif "!lobby" in args[0].lower():
        await set_and_update_prop('Location_s', 'PreLobby')
        await set_and_update_prop('NumAthenaPlayersLeft_U', '0')
        await set_and_update_prop('HasPreloadedAthena_b', False)
        await set_and_update_prop('SpectateAPartyMemberAvailable_b', 'false')
        await set_and_update_prop('UtcTimeStartedMatchAthena_s', '0001-01-01T00:00:00.000Z')

        await message.reply('Set state to the pre-game lobby.')

    elif "!join" in args[0].lower():
        if len(args) == 1:
            friend = client.get_friend(message.author.id)
        else:
            user = await client.fetch_profile(content)

            if user is not None:
                friend = client.get_friend(user.id)
            else:
                friend = None
                await message.reply(f'Failed to find user with the name: {content}.')

        if isinstance(friend, fortnitepy.Friend):
            try:
                await friend.join_party()
                await message.reply(f'Joined the party of {friend.display_name}.')
            except fortnitepy.errors.Forbidden:
                await message.reply('Failed to join party since it is private.')
            except fortnitepy.errors.PartyError:
                await message.reply('Party not found, are you sure Fortnite is open?')
        else:
            await message.reply('Cannot join party as the friend is not found.')

    elif "!reload" in args[0].lower():
        with open('config.json') as f:
            data = json.load(f)

        await message.reply('Configuration reloaded.')
        print(f'[PartyBot] [{time()}] Configuration successfully reloaded.')

    elif "!friend" in args[0].lower():
        if data['friend_accept']:
            await message.reply('All friend requests will be accepted so there is no need to add manually.')
            print(f'[PartyBot] [{time()}] !friend command ignored as friend requests will be accepted '
                  'so there is no need to add manually.')
        else:
            user = await client.fetch_profile(content)

            if user is not None:
                friend = await client.add_friend(user.id)
                await message.reply(f'Sent/accepted friend request to/from {user.display_name}.')
                print(f'[PartyBot] [{time()}] Sent/accepted friend request to/from {user.display_name}.')
            else:
                await message.reply(f'Failed to find user with the name: {content}.')
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] Failed to find a user with the name {content}."))

    elif "!playlist" in args[0].lower():
        try:
            playlist_id = await get_playlist(content)

            if playlist_id is not None:
                await client.user.party.set_playlist(playlist=playlist_id)
                await message.reply(f'Playlist set to {playlist_id}.')
                print(f'[PartyBot] [{time()}] Playlist set to {playlist_id}.')

            else:
                await message.reply(f'Failed to find a playlist with the name: {content}.')
                print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                                  f"Failed to find a playlist with the name: {content}."))

        except fortnitepy.errors.Forbidden:
            await message.reply(f"Couldn't set playlist to {args[1]}, as I'm not party leader.")
            print(crayons.red(f"[PartyBot] [{time()}] [ERROR] "
                              "Failed to set playlist as I don't have the required permissions."))
Пример #50
0
    def enqueue_files(self, files: list):
        """Add requested files to the appropriate queue

        :param files: list of (path,profile) tuples
        :return:
        """

        for path, forced_profile in files:
            #
            # do some prechecks...
            #
            if forced_profile is not None and not self.configfile.has_profile(
                    forced_profile):
                print(
                    f'profile "{forced_profile}" referenced from command line not found'
                )
                exit(1)

            if len(path) == 0:
                continue

            if not os.path.isfile(path):
                print(crayons.red('path not found, skipping: ' + path))
                continue

            if pytranscoder.verbose:
                print('matching ' + path)

            media_info = self.ffmpeg.fetch_details(path)
            if media_info is None:
                print(crayons.red(f'File not found: {path}'))
                continue
            if media_info.valid:

                if forced_profile is None:
                    rule = self.configfile.match_rule(media_info)
                    if rule is None:
                        print(
                            crayons.yellow(
                                f'No matching profile found - skipped'))
                        continue
                    if rule.is_skip():
                        print(crayons.green(os.path.basename(path)),
                              f'SKIPPED ({rule.name})')
                        self.complete.append((path, 0))
                        continue
                    profile_name = rule.profile
                    the_profile = self.configfile.get_profile(profile_name)
                else:
                    #
                    # looks good, add this file to the thread queue
                    #
                    the_profile = self.configfile.get_profile(forced_profile)
                    profile_name = forced_profile

                qname = the_profile.queue_name
                if qname is not None:
                    if not self.configfile.has_queue(the_profile.queue_name):
                        print(
                            crayons.red(
                                f'Profile "{profile_name}" indicated queue "{qname}" that has not been defined'
                            ))
                        sys.exit(1)
                    else:
                        self.queues[qname].put(
                            LocalJob(path, the_profile, media_info))
                else:
                    self.queues['_default_'].put(
                        LocalJob(path, the_profile, media_info))
Пример #51
0
def resolve_deps(deps,
                 which,
                 project,
                 sources=None,
                 verbose=False,
                 python=False,
                 clear=False,
                 pre=False,
                 allow_global=False):
    """Given a list of dependencies, return a resolved list of dependencies,
    using pip-tools -- and their hashes, using the warehouse API / pip.
    """
    from .patched.notpip._vendor.requests.exceptions import ConnectionError
    from ._compat import TemporaryDirectory
    index_lookup = {}
    markers_lookup = {}
    python_path = which('python', allow_global=allow_global)
    backup_python_path = sys.executable
    results = []
    if not deps:
        return results
    # First (proper) attempt:
    req_dir = TemporaryDirectory(prefix='pipenv-', suffix='-requirements')
    with HackedPythonVersion(python_version=python, python_path=python_path):
        try:
            resolved_tree, hashes, markers_lookup, resolver = actually_resolve_deps(
                deps,
                index_lookup,
                markers_lookup,
                project,
                sources,
                verbose,
                clear,
                pre,
                req_dir=req_dir)
        except RuntimeError:
            # Don't exit here, like usual.
            resolved_tree = None
    # Second (last-resort) attempt:
    if resolved_tree is None:
        with HackedPythonVersion(
                python_version='.'.join([str(s)
                                         for s in sys.version_info[:3]]),
                python_path=backup_python_path,
        ):
            try:
                # Attempt to resolve again, with different Python version information,
                # particularly for particularly particular packages.
                resolved_tree, hashes, markers_lookup, resolver = actually_resolve_deps(
                    deps,
                    index_lookup,
                    markers_lookup,
                    project,
                    sources,
                    verbose,
                    clear,
                    pre,
                    req_dir=req_dir)
            except RuntimeError:
                req_dir.cleanup()
                sys.exit(1)
    for result in resolved_tree:
        if not result.editable:
            name = pep423_name(result.name)
            version = clean_pkg_version(result.specifier)
            index = index_lookup.get(result.name)
            if not markers_lookup.get(result.name):
                markers = str(
                    result.markers) if result.markers and 'extra' not in str(
                        result.markers) else None
            else:
                markers = markers_lookup.get(result.name)
            collected_hashes = []
            if result in hashes:
                collected_hashes = list(hashes.get(result))
            elif any('python.org' in source['url']
                     or 'pypi.org' in source['url'] for source in sources):
                pkg_url = 'https://pypi.org/pypi/{0}/json'.format(name)
                session = _get_requests_session()
                try:
                    # Grab the hashes from the new warehouse API.
                    r = session.get(pkg_url, timeout=10)
                    api_releases = r.json()['releases']
                    cleaned_releases = {}
                    for api_version, api_info in api_releases.items():
                        api_version = clean_pkg_version(api_version)
                        cleaned_releases[api_version] = api_info
                    for release in cleaned_releases[version]:
                        collected_hashes.append(release['digests']['sha256'])
                    collected_hashes = [
                        'sha256:' + s for s in collected_hashes
                    ]
                except (ValueError, KeyError, ConnectionError):
                    if verbose:
                        click_echo('{0}: Error generating hash for {1}'.format(
                            crayons.red('Warning', bold=True), name))
            # # Collect un-collectable hashes (should work with devpi).
            # try:
            #     collected_hashes = collected_hashes + list(
            #         list(resolver.resolve_hashes([result]).items())[0][1]
            #     )
            # except (ValueError, KeyError, ConnectionError, IndexError):
            #     if verbose:
            #         print('Error generating hash for {}'.format(name))
            collected_hashes = sorted(set(collected_hashes))
            d = {'name': name, 'version': version, 'hashes': collected_hashes}
            if index:
                d.update({'index': index})
            if markers:
                d.update({'markers': markers.replace('"', "'")})
            results.append(d)
    req_dir.cleanup()
    return results
Пример #52
0
def actually_resolve_deps(
    deps,
    index_lookup,
    markers_lookup,
    project,
    sources,
    verbose,
    clear,
    pre,
    req_dir=None,
):
    from .vendor.packaging.markers import default_environment
    from .patched.notpip._internal import basecommand
    from .patched.notpip._internal.cmdoptions import no_binary, only_binary
    from .patched.notpip._internal.req import parse_requirements
    from .patched.notpip._internal.exceptions import DistributionNotFound
    from .patched.notpip._vendor.requests.exceptions import HTTPError
    from pipenv.patched.piptools.resolver import Resolver
    from pipenv.patched.piptools.repositories.pypi import PyPIRepository
    from pipenv.patched.piptools.scripts.compile import get_pip_command
    from pipenv.patched.piptools import logging as piptools_logging
    from pipenv.patched.piptools.exceptions import NoCandidateFound
    from .vendor.requirementslib import Requirement
    from ._compat import TemporaryDirectory, NamedTemporaryFile

    class PipCommand(basecommand.Command):
        """Needed for pip-tools."""

        name = "PipCommand"

    constraints = []
    cleanup_req_dir = False
    if not req_dir:
        req_dir = TemporaryDirectory(suffix="-requirements", prefix="pipenv-")
        cleanup_req_dir = True
    for dep in deps:
        if not dep:
            continue
        url = None
        if " -i " in dep:
            dep, url = dep.split(" -i ")
        req = Requirement.from_line(dep)

        # extra_constraints = []

        if url:
            index_lookup[req.name] = project.get_source(url=url).get("name")
        # strip the marker and re-add it later after resolution
        # but we will need a fallback in case resolution fails
        # eg pypiwin32
        if req.markers:
            markers_lookup[req.name] = req.markers.replace('"', "'")
        constraints.append(req.constraint_line)

    pip_command = get_pip_command()
    constraints_file = None
    pip_args = []
    if sources:
        pip_args = prepare_pip_source_args(sources, pip_args)
    if verbose:
        print("Using pip: {0}".format(" ".join(pip_args)))
    with NamedTemporaryFile(
        mode="w",
        prefix="pipenv-",
        suffix="-constraints.txt",
        dir=req_dir.name,
        delete=False,
    ) as f:
        if sources:
            requirementstxt_sources = " ".join(pip_args) if pip_args else ""
            requirementstxt_sources = requirementstxt_sources.replace(" --", "\n--")
            f.write(u"{0}\n".format(requirementstxt_sources))
        f.write(u"\n".join([_constraint for _constraint in constraints]))
        constraints_file = f.name
    pip_options, _ = pip_command.parser.parse_args(pip_args)
    pip_options.cache_dir = PIPENV_CACHE_DIR
    session = pip_command._build_session(pip_options)
    pypi = PyPIRepository(pip_options=pip_options, use_json=False, session=session)
    constraints = parse_requirements(
        constraints_file, finder=pypi.finder, session=pypi.session, options=pip_options
    )
    constraints = [c for c in constraints]
    if verbose:
        logging.log.verbose = True
        piptools_logging.log.verbose = True
    resolved_tree = set()
    resolver = Resolver(
        constraints=constraints, repository=pypi, clear_caches=clear, prereleases=pre
    )
    # pre-resolve instead of iterating to avoid asking pypi for hashes of editable packages
    hashes = None
    try:
        results = resolver.resolve(max_rounds=PIPENV_MAX_ROUNDS)
        hashes = resolver.resolve_hashes(results)
        resolved_tree.update(results)
    except (NoCandidateFound, DistributionNotFound, HTTPError) as e:
        click_echo(
            "{0}: Your dependencies could not be resolved. You likely have a "
            "mismatch in your sub-dependencies.\n  "
            "You can use {1} to bypass this mechanism, then run {2} to inspect "
            "the situation.\n  "
            "Hint: try {3} if it is a pre-release dependency."
            "".format(
                crayons.red("Warning", bold=True),
                crayons.red("$ pipenv install --skip-lock"),
                crayons.red("$ pipenv graph"),
                crayons.red("$ pipenv lock --pre"),
            ),
            err=True,
        )
        click_echo(crayons.blue(str(e)), err=True)
        if "no version found at all" in str(e):
            click_echo(
                crayons.blue(
                    "Please check your version specifier and version number. See PEP440 for more information."
                )
            )
        if cleanup_req_dir:
            req_dir.cleanup()
        raise RuntimeError
    if cleanup_req_dir:
        req_dir.cleanup()
    return (resolved_tree, hashes, markers_lookup, resolver)
Пример #53
0
def install(package_name=False,
            more_packages=False,
            dev=False,
            three=False,
            system=False,
            lock=False,
            requirements=False):

    # Ensure that virtualenv is available.
    ensure_project(three=three)

    # Allow more than one package to be provided.
    package_names = (package_name, ) + more_packages

    # Install all dependencies, if none was provided.
    if package_name is False:
        click.echo(crayons.yellow(
            'No package provided, installing all dependencies.'),
                   err=True)
        do_init(dev=dev, requirements=requirements, allow_global=system)
        sys.exit(0)

    for package_name in package_names:

        # Proper-case incoming package name (check against API).
        old_name = [k for k in convert_deps_from_pip(package_name).keys()][0]
        try:
            new_name = proper_case(old_name)
        except IOError as e:
            click.echo('{0} {1}'.format(crayons.red('Error: '), e.args[0],
                                        crayons.green(package_name)))
            continue
        package_name = package_name.replace(old_name, new_name)

        click.echo('Installing {0}...'.format(crayons.green(package_name)))

        # pip install:
        c = pip_install(package_name, allow_global=system)
        click.echo(crayons.blue(format_pip_output(c.out)))

        # Ensure that package was successfully installed.
        try:
            assert c.return_code == 0
        except AssertionError:
            click.echo('{0} An error occurred while installing {1}!'.format(
                crayons.red('Error: '), crayons.green(package_name)))
            click.echo(crayons.blue(format_pip_error(c.err)))
            sys.exit(1)

        if dev:
            click.echo('Adding {0} to Pipfile\'s {1}...'.format(
                crayons.green(package_name), crayons.red('[dev-packages]')))
        else:
            click.echo('Adding {0} to Pipfile\'s {1}...'.format(
                crayons.green(package_name), crayons.red('[packages]')))

        # Add the package to the Pipfile.
        project.add_package_to_pipfile(package_name, dev)

        # Ego boost.
        easter_egg(package_name)

        if lock:
            do_lock()
Пример #54
0
def resolve_deps(
    deps,
    which,
    project,
    sources=None,
    verbose=False,
    python=False,
    clear=False,
    pre=False,
    allow_global=False,
):
    """Given a list of dependencies, return a resolved list of dependencies,
    using pip-tools -- and their hashes, using the warehouse API / pip.
    """
    from .patched.notpip._vendor.requests.exceptions import ConnectionError
    from ._compat import TemporaryDirectory

    index_lookup = {}
    markers_lookup = {}
    python_path = which("python", allow_global=allow_global)
    backup_python_path = sys.executable
    results = []
    if not deps:
        return results
    # First (proper) attempt:
    req_dir = TemporaryDirectory(prefix="pipenv-", suffix="-requirements")
    with HackedPythonVersion(python_version=python, python_path=python_path):
        try:
            resolved_tree, hashes, markers_lookup, resolver = actually_resolve_deps(
                deps,
                index_lookup,
                markers_lookup,
                project,
                sources,
                verbose,
                clear,
                pre,
                req_dir=req_dir,
            )
        except RuntimeError:
            # Don't exit here, like usual.
            resolved_tree = None
    # Second (last-resort) attempt:
    if resolved_tree is None:
        with HackedPythonVersion(
            python_version=".".join([str(s) for s in sys.version_info[:3]]),
            python_path=backup_python_path,
        ):
            try:
                # Attempt to resolve again, with different Python version information,
                # particularly for particularly particular packages.
                resolved_tree, hashes, markers_lookup, resolver = actually_resolve_deps(
                    deps,
                    index_lookup,
                    markers_lookup,
                    project,
                    sources,
                    verbose,
                    clear,
                    pre,
                    req_dir=req_dir,
                )
            except RuntimeError:
                req_dir.cleanup()
                sys.exit(1)
    for result in resolved_tree:
        if not result.editable:
            name = pep423_name(result.name)
            version = clean_pkg_version(result.specifier)
            index = index_lookup.get(result.name)
            if not markers_lookup.get(result.name):
                markers = (
                    str(result.markers)
                    if result.markers and "extra" not in str(result.markers)
                    else None
                )
            else:
                markers = markers_lookup.get(result.name)
            collected_hashes = []
            if result in hashes:
                collected_hashes = list(hashes.get(result))
            elif any(
                "python.org" in source["url"] or "pypi.org" in source["url"]
                for source in sources
            ):
                pkg_url = "https://pypi.org/pypi/{0}/json".format(name)
                session = _get_requests_session()
                try:
                    # Grab the hashes from the new warehouse API.
                    r = session.get(pkg_url, timeout=10)
                    api_releases = r.json()["releases"]
                    cleaned_releases = {}
                    for api_version, api_info in api_releases.items():
                        api_version = clean_pkg_version(api_version)
                        cleaned_releases[api_version] = api_info
                    for release in cleaned_releases[version]:
                        collected_hashes.append(release["digests"]["sha256"])
                    collected_hashes = ["sha256:" + s for s in collected_hashes]
                except (ValueError, KeyError, ConnectionError):
                    if verbose:
                        click_echo(
                            "{0}: Error generating hash for {1}".format(
                                crayons.red("Warning", bold=True), name
                            )
                        )
            # # Collect un-collectable hashes (should work with devpi).
            # try:
            #     collected_hashes = collected_hashes + list(
            #         list(resolver.resolve_hashes([result]).items())[0][1]
            #     )
            # except (ValueError, KeyError, ConnectionError, IndexError):
            #     if verbose:
            #         print('Error generating hash for {}'.format(name))
            collected_hashes = sorted(set(collected_hashes))
            d = {"name": name, "version": version, "hashes": collected_hashes}
            if index:
                d.update({"index": index})
            if markers:
                d.update({"markers": markers.replace('"', "'")})
            results.append(d)
    req_dir.cleanup()
    return results
Пример #55
0
from crayons import blue, green, white, red, yellow, magenta, cyan

WordList = ['green', 'red', 'cyan']

#go=1

while go:
    word = input('Enter green or red or cyan : ')
    word_out = word.upper()
    output = f'Ok {word} is {word_out}'
    word = word.lower()
    if word in WordList:
        if word == 'green':
            print(green(output))
        if word == 'red':
            print(red(output))
        if word == 'cyan':
            print(cyan(output))
    else:
        print(white("not good"))
        go = 0
Пример #56
0
def generate_with_device_code(client: str):

    selected_client_data = json.load(
        open('clients.json', 'r', encoding='utf-8'))[client]

    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": f"basic {selected_client_data['encoded']}"
    }
    params = {"grant_type": "client_credentials"}

    log('Requesting client credentials...', True)

    response = requests.post(
        'https://account-public-service-prod.ol.epicgames.com/account/api/oauth/token',
        headers=headers,
        data=params)

    if response.status_code == 200:
        client_credentials = response.json()

        log(f'Success: {client_credentials}', True)

        headers = {
            "Authorization": f"bearer {client_credentials['access_token']}"
        }

        log('Requesting device_code session...', True)
        response = requests.post(
            'https://account-public-service-prod03.ol.epicgames.com/account/api/oauth/deviceAuthorization?prompt=login',
            headers=headers,
            data={})

        if response.status_code == 200:
            device_code_session = response.json()
            log(f'Success: {device_code_session}', True)

            while True:
                log('Opening web browser...', True)
                webbrowser.open(
                    device_code_session["verification_uri_complete"])
                ready_check = input(
                    log(f'Login with the required account and click "Confirm". Then type "ready": ',
                        raw=True))
                ready_check.strip(' ')
                log('Waiting for user confirmation...', True)
                if ready_check.lower() == 'ready':

                    headers = {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Authorization":
                        f"basic {selected_client_data['encoded']}"
                    }
                    params = {
                        "grant_type": "device_code",
                        "device_code": device_code_session['device_code']
                    }
                    response = requests.post(
                        'https://account-public-service-prod.ol.epicgames.com/account/api/oauth/token',
                        headers=headers,
                        data=params)

                    if response.status_code != 200:
                        log(
                            crayons.red(
                                'You did\'nt clicked "Confirm" button yet'))
                        continue
                    else:
                        auth_session = response.json()
                        log(f'Success: {auth_session}', True)
                        break

            log(f'Generating device auths...', True)
            headers = {
                "Authorization": f"bearer {auth_session['access_token']}"
            }
            response = requests.post(
                f'https://account-public-service-prod.ol.epicgames.com/account/api/public/account/{auth_session["account_id"]}/deviceAuth',
                headers=headers)

            account_info = requests.get(
                f'https://account-public-service-prod.ol.epicgames.com/account/api/public/account/{auth_session["account_id"]}',
                headers=headers,
                data={})

            if response.status_code == 200:

                device_auths = response.json()
                accInfo = account_info.json()
                filename = accInfo["email"].split('@')[0]
                log(f'Success! {device_auths}', True)

                newdata = {
                    "device_id": device_auths['deviceId'],
                    "account_id": device_auths['accountId'],
                    "secret": device_auths['secret']
                }
                print('')
                save_selections = ['device_auths.json', f'{filename}.json']
                listcls = []
                count = 0
                for selection in save_selections:
                    count += 1
                    listcls.append(count)
                    log(f'{crayons.red("-")} {count}. {selection}')

                while True:
                    save_selection = input(
                        log(f'Select the output file: ', raw=True))
                    try:
                        save_selection.strip(' ')
                        if int(save_selection) not in listcls:
                            log(crayons.red('Invalid selection\n'))
                            continue

                    except:
                        log(crayons.red('Please enter a valid number\n'))
                        continue

                    final_save_selection = int(save_selection) - 1
                    break

                kill_token(auth_session)

                if save_selections[
                        final_save_selection] == 'device_auths.json':
                    prev_file = json.load(
                        open('output/device_auths.json', 'r',
                             encoding='utf-8'))
                    prev_file[accInfo["email"]] = newdata

                    with open('output/device_auths.json',
                              'w',
                              encoding='utf-8') as f:
                        json.dump(prev_file, f, indent=4)
                        return newdata
                else:
                    with open(
                            f'output/{save_selections[final_save_selection]}',
                            'w',
                            encoding='utf-8') as f:
                        json.dump({accInfo["email"]: newdata}, f, indent=4)
                        return newdata

            else:
                log(f'Failed while generating device auths: {crayons.red(response.json())}'
                    )
                return False

        else:
            log(f'Failed while requesting device_code session: {crayons.red(response.json())}'
                )
            return False

    else:
        log(f'Failed while fetching client credentials: {crayons.red(response.json())}'
            )
        return False
Пример #57
0
def CompileCode(inputcode):
    if not inputcode.count(';') >= (inputcode.count('\n') + 1):
        print(crayons.red("compiler: end line charactor not found!"))
        sys.exit()
    ic = inputcode
    inputcode = inputcode.replace("\n", "")
    inputcode = inputcode[:-1].split(";")
    outFile = ""
    for word in inputcode:
        if word.startswith("function "):
            at_functions[word.split(' ')[1].split('{')[0].split('(')
                         [0]] = word.split(' ')[1].split('{')[1].split(
                             '}')[0].replace("<", "{").replace(">", "}")

        if word.startswith("#comperror"):
            print(crayons.red("error: " + word.split(' ')[1]))
            sys.exit()
        if word.startswith("#include"):
            includeFileName = word.split(' ')[1]
            at_includes[os.path.splitext(
                includeFileName
            )[0]] = os.path.dirname(__file__) + "/modules/" + os.path.splitext(
                includeFileName)[0] + "/" + os.path.splitext(
                    includeFileName)[0]
            if not os.path.exists(
                    os.path.dirname(__file__) + "/modules/" +
                    os.path.splitext(includeFileName)[0] + "/" +
                    includeFileName):
                print(crayons.red("file error: include file not found!"))
                sys.exit()
            with open(os.path.dirname(__file__) + "/modules/" +
                      os.path.splitext(includeFileName)[0] + "/" +
                      includeFileName,
                      mode="r") as fInclude:
                codeLib = fInclude.read()
            oc_n = codeLib + "\n" + ic.replace(word + ";\n", "")
            return CompileCode(oc_n)

        if not (word.startswith("#include") or word.startswith("#comperror")
                or word.startswith("function")):
            if word.startswith("//"):
                print("", end="")
            else:
                wcode = word.split("(")
                arg = wcode[1].split(")")[0]
                command = wcode[0]
                insfound = False
                # Process Code
                if command == "callmacro":
                    if not arg in at_functions:
                        print(
                            crayons.red(
                                "macro error: callmacro: function name '" +
                                arg + "' not defined!"))
                        sys.exit()
                    outFile = outFile + str(at_functions[arg].replace(
                        "&", "\n")) + "\n"
                    insfound = True

                # Include Dynamic Compiler extensions
                for key in at_includes:
                    try:
                        with open(at_includes[key] + ".py", mode="r") as d_lib:
                            dlibfile = d_lib.read()
                        exec(dlibfile)

                    except FileNotFoundError:
                        print(crayons.red("dynamic includes error!"))
                        sys.exit()

                if command == "print":
                    outFile = outFile + "[" + str(
                        arg.split('"')[1].split('"')[0]).replace(' ',
                                                                 '_') + "]\n"
                    outFile = outFile + "println" + "\n"
                    insfound = True

                if command == "printstk":
                    outFile = outFile + "println" + "\n"
                    insfound = True

                if command == "input":
                    outFile = outFile + "[" + str(
                        arg.split('"')[1].split('"')[0]).replace(' ',
                                                                 '_') + "]\n"
                    outFile = outFile + "println" + "\n"
                    outFile = outFile + "read" + "\n"
                    insfound = True

                if command == "math":
                    if "*" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("*")[0] + "}\n"
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("*")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "/" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("/")[0] + "}\n"
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("/")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "-" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("-")[0] + "}\n"
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("-")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "+" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("+")[0] + "}\n"
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("+")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "%" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("%")[0] + "}\n"
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("%")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True

                if command == "mathstk":
                    if "*" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("*")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "/" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("/")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "-" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("-")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "+" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("+")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True
                    if "%" in str(arg.split(",")[0]):
                        outFile = outFile + "{" + str(
                            arg.split(",")[0]).split("%")[1] + "}\n"
                        outFile = outFile + "*\n"
                        insfound = True

                if command == "__raw__":
                    outFile = outFile + arg
                    print(
                        crayons.yellow("warning: ") + crayons.yellow(
                            "assembler code 'raw' misuse can cause errors!"))
                    insfound = True

                if insfound == False:
                    print(
                        crayons.red(
                            "compiler: function error! (Keyword Not Found)"))
    return outFile[:-1]
Пример #58
0
def cli(
    ctx,
    where=False,
    venv=False,
    rm=False,
    bare=False,
    three=False,
    python=False,
    help=False,
    py=False,
    site_packages=False,
    envs=False,
    man=False,
    completion=False,
    pypi_mirror=None,
    support=None,
    clear=False,
):
    # Handle this ASAP to make shell startup fast.
    if completion:
        from . import shells

        try:
            shell = shells.detect_info()[0]
        except shells.ShellDetectionFailure:
            echo(
                "Fail to detect shell. Please provide the {0} environment "
                "variable.".format(crayons.normal("PIPENV_SHELL", bold=True)),
                err=True,
            )
            sys.exit(1)
        print(click_completion.get_code(shell=shell, prog_name="pipenv"))
        sys.exit(0)

    from .core import (
        system_which,
        do_py,
        warn_in_virtualenv,
        do_where,
        project,
        spinner,
        cleanup_virtualenv,
        ensure_project,
        format_help,
        do_clear,
    )

    if man:
        if system_which("man"):
            path = os.sep.join([os.path.dirname(__file__), "pipenv.1"])
            os.execle(system_which("man"), "man", path, os.environ)
        else:
            echo("man does not appear to be available on your system.",
                 err=True)
    if envs:
        echo(
            "The following environment variables can be set, to do various things:\n"
        )
        for key in environments.__dict__:
            if key.startswith("PIPENV"):
                echo("  - {0}".format(crayons.normal(key, bold=True)))
        echo("\nYou can learn more at:\n   {0}".format(
            crayons.green(
                "http://docs.pipenv.org/advanced/#configuration-with-environment-variables"
            )))
        sys.exit(0)
    warn_in_virtualenv()
    if ctx.invoked_subcommand is None:
        # --where was passed…
        if where:
            do_where(bare=True)
            sys.exit(0)
        elif py:
            do_py()
            sys.exit()
        # --support was passed…
        elif support:
            from .help import get_pipenv_diagnostics

            get_pipenv_diagnostics()
            sys.exit(0)
        # --clear was passed…
        elif clear:
            do_clear()
            sys.exit(0)

        # --venv was passed…
        elif venv:
            # There is no virtualenv yet.
            if not project.virtualenv_exists:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!"
                    ),
                    err=True,
                )
                sys.exit(1)
            else:
                echo(project.virtualenv_location)
                sys.exit(0)
        # --rm was passed…
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if environments.PIPENV_USE_SYSTEM:
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."))
                sys.exit(1)
            if project.virtualenv_exists:
                loc = project.virtualenv_location
                echo(
                    crayons.normal(u"{0} ({1})…".format(
                        crayons.normal("Removing virtualenv", bold=True),
                        crayons.green(loc),
                    )))
                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                sys.exit(0)
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                sys.exit(1)
    # --two / --three was passed…
    if (python or three is not None) or site_packages:
        ensure_project(
            three=three,
            python=python,
            warn=True,
            site_packages=site_packages,
            pypi_mirror=pypi_mirror,
            clear=clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))