Exemple #1
0
def do_purge(bare=False, downloads=False, allow_global=False):
    """Executes the purge functionality."""

    if downloads:
        if not bare:
            click.echo(crayons.yellow('Clearing out downloads directory...'))
        shutil.rmtree(project.download_location)
        return

    freeze = delegator.run('{0} freeze'.format(which_pip(allow_global=allow_global))).out
    installed = freeze.split()

    # Remove setuptools and friends from installed, if present.
    for package_name in ['setuptools', 'pip', 'wheel', 'six', 'packaging', 'pyparsing', 'appdirs']:
        for i, package in enumerate(installed):
            if package.startswith(package_name):
                del installed[i]

    if not bare:
        click.echo('Found {0} installed package(s), purging...'.format(len(installed)))
    command = '{0} uninstall {1} -y'.format(which_pip(allow_global=allow_global), ' '.join(installed))
    c = delegator.run(command)

    if not bare:
        click.echo(crayons.blue(c.out))

        click.echo(crayons.yellow('Environment now purged and fresh!'))
Exemple #2
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)
Exemple #3
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
Exemple #4
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('!')))
Exemple #5
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)
Exemple #6
0
def update(dev=False, three=None, python=None):

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

    # Update pip to latest version.
    ensure_latest_pip()

    click.echo(crayons.yellow('Updating all dependencies from Pipfile...'))

    do_purge()
    do_init(dev=dev)

    click.echo(crayons.yellow('All dependencies are now up-to-date!'))
Exemple #7
0
def cli(ctx, find=False, which=False, findall=False, version=False):
    if version:
        click.echo(
            "{0} version {1}".format(
                crayons.white("PythonFinder", bold=True), crayons.yellow(__version__)
            )
        )
        sys.exit(0)
    finder = Finder()
    if find:

        if any([find.startswith("{0}".format(n)) for n in range(10)]):
            found = finder.find_python_version(find.strip())
        else:
            found = finder.system_path.python_executables
        if found:
            click.echo("Found Python Version: {0}".format(found), color="white")
            sys.exit(0)
        else:
            click.echo("Failed to find matching executable...")
            sys.exit(1)
    elif which:
        found = finder.system_path.which(which.strip())
        if found:
            click.echo("Found Executable: {0}".format(found), color="white")
            sys.exit(0)
        else:
            click.echo("Failed to find matching executable...")
            sys.exit(1)
    else:
        click.echo("Please provide a command", color="red")
        sys.exit(1)
    sys.exit()
Exemple #8
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!'))
Exemple #9
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()))
Exemple #10
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()
Exemple #11
0
 def launch_queued_applications(config, status, computer, manager):
     """Launch applications that have been queued."""
     log.info("Launching queued applications...")
     for app_status in status.applications:
         if app_status.next:
             application = config.applications.get(app_status.application)
             print(crayons.yellow(
                 f"{application} is queued for {app_status.next}"))
             if app_status.next == computer:
                 latest = status.get_latest(application)
                 if latest in (computer, None) or application.no_wait:
                     if not manager.is_running(application):
                         manager.start(application)
                     app_status.next = None
                 else:
                     print(crayons.yellow(
                         f"{application} is still running on {latest}"))
             elif manager.is_running(application):
                 manager.stop(application)
Exemple #12
0
def ensure_latest_pip():
    """Updates pip to the latest version."""

    # Ensure that pip is installed.
    c = delegator.run('{0} install pip'.format(which_pip()))

    # Check if version is out of date.
    if 'however' in c.err:
        # If version is out of date, update.
        click.echo(crayons.yellow('Pip is out of date... updating to latest.'))
        c = delegator.run('{0} install pip --upgrade'.format(which_pip()), block=False)
        click.echo(crayons.blue(c.out))
Exemple #13
0
def ensure_pipfile(validate=True):
    """Creates a Pipfile for the project, if it doesn't exist."""

    # Assert Pipfile exists.
    if not project.pipfile_exists:

        click.echo(crayons.yellow('Creating a Pipfile for this project...'), err=True)

        # Create the pipfile if it doesn't exist.
        project.create_pipfile()

    # Validate the Pipfile's contents.
    if validate and project.virtualenv_exists:
        # Ensure that Pipfile is using proper casing.
        p = project.parsed_pipfile
        changed = ensure_proper_casing(pfile=p)

        # Write changes out to disk.
        if changed:
            click.echo(crayons.yellow('Fixing package names in Pipfile...'), err=True)
            project.write_toml(p)
Exemple #14
0
def main():
    # work2do = {"10.1.0.1":["interface eth1/2", "no shutdown"], "10.2.0.1":
    # ["interface eth1/1", "shutdown"], "10.3.0.1":["interface eth1/5", "no shutdown"]}
    # data that replaces data stored in file
    with open("network.json", "r") as file_data:
        json_data = json.load(file_data)

    print(crayons.yellow(
        "Welcome to the network device command pusher"))  # welcome message

    ## get data set
    print("\nData set found\n"
          )  # replace with function call that reads in data from file

    ## run
    commandpush(json_data)  # call function to push commands to devices
Exemple #15
0
def logger(msg, log_type="msg", output=True, log=True):
    if log_type == "msg":
        if output:
            print(crayons.green(f"[+] {msg}"))
        if log:
            logging.info(msg)
    elif log_type == "war":
        if output:
            print(crayons.yellow(f"[!] {msg}"))
        if log:
            logging.warning(msg)
    elif log_type == "err":
        if output:
            print(crayons.red(f"[-] {msg}"))
        if log:
            logging.error(msg)
def dump_flow(flow: Flow):
    output = get_dumpable_flow(flow)

    if FLAGS.mode == "test":
        filepath = os.path.join(FLAGS.test_dir, FLOW_TEST_OUTPUT)
    elif FLAGS.mode == "golden":
        filepath = os.path.join(FLAGS.test_dir, FLOW_GOLDEN)
        print(yellow("Generating test data: " + filepath))

    if FLAGS.mode == "debug":
        pprint(
            f"Flow is:\n{json.dumps(obj=output, indent=2, cls=_SetEncoder)}")
        return

    with open(filepath, "w") as f:
        json.dump(obj=output, fp=f, indent=2, cls=_SetEncoder)
Exemple #17
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)
Exemple #18
0
async def rename(ctx, original, newname):
    try:
        original = original.strip()
        newname = newname.strip()
        if newname in emojis:
            print(crayons.red(f'Emoji [{newname}] already exists!'))
        elif original in emojis:
            print(
                crayons.yellow(
                    f'Renaming emoji [{original}] to [{newname.strip()}]'))
            emojis[newname.strip()] = emojis[original]
            del emojis[original]
        else:
            print(crayons.red(f'There is no emoji named [{original}]'))
    finally:
        await ctx.message.delete()
Exemple #19
0
def switch(scm, to_branch, verbose, fake):
    """Switches from one branch to another, safely stashing and restoring local changes.
    """
    scm.fake = fake
    scm.verbose = fake or verbose

    scm.repo_check()

    if to_branch is None:
        scm.display_available_branches()
        raise click.BadArgumentUsage('Please specify a branch to switch to')

    scm.stash_log()
    status_log(scm.checkout_branch,
               'Switching to {}.'.format(crayons.yellow(to_branch)), to_branch)
    scm.unstash_log()
 def wrapper(wrapped, instance, args, kwargs):
     exception = None
     print(crayons.yellow("Waiting to be ready..."))
     with blindspin.spinner():
         for _ in range(0, config.MAX_TRIES):
             try:
                 return wrapped(*args, **kwargs)
             except Exception as e:
                 sleep(config.SLEEP_TIME)
                 exception = e
         raise TimeoutException(
             """Wait time exceeded {0} sec.
                 Method {1}, args {2} , kwargs {3}.
                  Exception {4}""".format(config.MAX_TRIES,
                                          wrapped.__name__,
                                          args, kwargs, exception))
Exemple #21
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)
Exemple #22
0
def ensure_pipfile(validate=True):
    """Creates a Pipfile for the project, if it doesn't exist."""

    # Assert Pipfile exists.
    if not project.pipfile_exists:

        click.echo(crayons.yellow('Creating a Pipfile for this project...'),
                   err=True)

        # Create the pipfile if it doesn't exist.
        project.create_pipfile()

    # Validate the Pipfile's contents.
    if validate:
        # Ensure that Pipfile is using proper casing.
        ensure_proper_casing()
Exemple #23
0
def cli(files, output, halign, valign, margin, font, size, start, merge,
        blank):
    """ тнРя╕П Add pages to PDFs and merge(optional) -> PERFECT DOCUMENT! ЁЯУС"""

    file_paths = [os.path.join(cwd, file) for file in files]

    output_paths = []
    for path in file_paths:
        root, ext = os.path.splitext(path)
        output_paths.append(root + PDF2DOC_SUFFIX + ext)

    output_writers = paged_pdfs_writer(files=file_paths,
                                       h_align=halign,
                                       v_align=valign,
                                       margin=Margin(all=margin),
                                       font=font,
                                       font_size=size,
                                       format=PDF2DOC_FORMAT,
                                       add_blank=blank,
                                       start_num=start)

    sp = Spinner([
        ' таЛ', ' таЩ', ' та╣', ' та╕', ' та╝', ' та┤', ' таж', ' таз', ' таЗ',
        ' таП'
    ], 100)

    with yaspin(sp, text="Saving") as spinner:
        for writer, path in zip(output_writers, output_paths):
            with open(path, 'wb') as f:
                writer.write(f)
        spinner.text = "Saving   [Success]"
        spinner.ok(" тЬЕ")

    if merge:
        with yaspin(sp, text="Marging") as spinner:
            merger = concat_pdfs_merger(output_paths)
            merger.write(output)
            merger.close()
            for path in output_paths:
                send2trash(path)
            spinner.text = "Marging  [Success]"
            spinner.ok(" тЬЕ")

    echo('')
    echo(
        crayons.yellow('      тнРя╕ПтнРя╕ПтнРя╕П All Done! тнРтнРя╕ПтнРя╕Пя╕П',
                       bold=True))
Exemple #24
0
def do_init(dev=False,
            requirements=False,
            skip_virtualenv=False,
            allow_global=False,
            ignore_hashes=False,
            no_hashes=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(no_hashes=no_hashes)

    # 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(no_hashes=no_hashes)

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

    # Activate virtualenv instructions.
    do_activate_virtualenv()
Exemple #25
0
def ensure_proper_casing():
    """Ensures proper casing of Pipfile packages, writes changes to disk."""
    p = project.parsed_pipfile

    def proper_case_section(section):
        # Casing for section
        casing_changed = False

        if section in p:
            changed_values = []

            # Replace each package with proper casing.
            for dep in p[section].keys():

                # Attempt to normalize name from PyPI.
                # Use provided name if better one can't be found.
                try:
                    # Get new casing for package name.
                    new_casing = proper_case(dep)
                except IOError:
                    # Unable to normalize package name.
                    continue

                if new_casing == dep:
                    continue

                # Mark casing as changed, if it did.
                casing_changed = True
                changed_values.append((new_casing, dep))

            for new, old in changed_values:
                # Replace old value with new value.
                old_value = p[section][old]
                p[section][new] = old_value
                del p[section][old]

        return casing_changed

    casing_changed = proper_case_section('packages')
    casing_changed |= proper_case_section('dev-packages')

    if casing_changed:
        click.echo(crayons.yellow('Fixing package names in Pipfile...'),
                   err=True)

        # Write pipfile out to disk.
        project.write(p)
Exemple #26
0
    def upload(self, copy=False):
        """
        Upload the template to S3.

        If copy is True, uploads a copy of the template with the .copy suffix.
        """
        s3_key = self.s3_key
        public_url = self.public_url
        if copy:
            s3_key += TEMPLATE_COPY_SUFFIX
            public_url += TEMPLATE_COPY_SUFFIX
        click.echo('Publishing {0} to {1}'.format(
            crayons.yellow(self.local_file_path), public_url))
        s3_client(self.region).put_object(Bucket=self.s3_bucket,
                                          Body=self.content,
                                          Key=s3_key)
        return self
    def __init__(
        self, github: GitHub, repository: str, addon: str, force: bool, dryrun: bool
    ):
        """Initialize new add-on Repository object."""
        self.github = github
        self.force = force
        self.dryrun = dryrun
        self.addons = []

        click.echo(
            'Locating add-on repository "%s"...' % crayons.yellow(repository), nl=False
        )
        self.github_repository = github.get_repo(repository)
        click.echo(crayons.green("Found!"))

        self.clone_repository()
        self.load_repository(addon)
def color_chooser(color, name):
    if color == "red":
        print(crayons.red(name, bold=True))
    elif color == "green":
        print(crayons.green(name, bold=True))
    elif color == "yellow":
        print(crayons.yellow(name, bold=True))
    elif color == "blue":
        print(crayons.blue(name, bold=True))
    elif color == "black":
        print(crayons.black(name, bold=True))
    elif color == "magenta":
        print(crayons.magenta(name, bold=True))
    elif color == "cyan":
        print(crayons.cyan(name, bold=True))
    elif color == "white":
        print(crayons.white(name, bold=True))
def uninstall(package_name=False, more_packages=False, three=None, system=False, lock=False):
    # Ensure that virtualenv is available.
    ensure_project(three=three)

    package_names = (package_name,) + more_packages

    # Un-install all dependencies, if none was provided.

    if package_name is False:
        click.echo(crayons.yellow('No package provided, un-installing all packages.'))
        do_purge(allow_global=system)
        sys.exit(1)

    for package_name in package_names:
        click.echo('Un-installing {0}...'.format(crayons.green(package_name)))
        click.echo(crayons.blue(c.out))
        c = delegator.run('{0} uninstall {1} -y'.format(which_pip(allow_global=system), package_name))
def shell(three=None):
    # Ensure that virtualenv is available.
    ensure_project(three=three)

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

    # Spawn the Python process, and interact with it.
    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))))

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

    c = pexpect.spawn(
            "{0} -c '. {1}; exec {0} -i'".format(
                shell,
                activate_virtualenv(source=False)
            ),
            dimensions=(
                terminal_dimensions.lines,
                terminal_dimensions.columns
            )
        )

    # Activate the virtualenv.
    c.send(activate_virtualenv() + '\n')

    # 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)
Exemple #31
0
def do_init(
    dev=False, requirements=False, allow_global=False, ignore_pipfile=False,
    skip_lock=False, verbose=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:
        try:
            do_create_virtualenv()
        except KeyboardInterrupt:
            cleanup_virtualenv(bare=False)
            sys.exit(1)

    # Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored
    if (project.lockfile_exists and not ignore_pipfile) and not skip_lock:

        # 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 and not skip_lock:
        click.echo(crayons.yellow('Pipfile.lock not found, creating...'), err=True)
        do_lock()

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

    # Activate virtualenv instructions.
    if not allow_global:
        do_activate_virtualenv()
Exemple #32
0
def do_purge(bare=False, allow_global=False):
    """Executes the purge functionality."""
    freeze = delegator.run('{0} freeze'.format(
        which_pip(allow_global=allow_global))).out
    installed = freeze.split()

    if not bare:
        click.echo('Found {0} installed package(s), purging...'.format(
            len(installed)))
    command = '{0} uninstall {1} -y'.format(
        which_pip(allow_global=allow_global), ' '.join(installed))
    c = delegator.run(command)

    if not bare:
        click.echo(crayons.blue(c.out))

        click.echo(crayons.yellow('Environment now purged and fresh!'))
Exemple #33
0
def ensure_proper_casing():
    """Ensures proper casing of Pipfile packages, writes to disk."""
    p = project.parsed_pipfile

    casing_changed = False

    # Casing for [packages]
    if 'packages' in p:
        # Replace each package with proper casing.
        for dep in p['packages']:

            # Get new casing for package name.
            new_casing = proper_case(dep)

            # Mark casing as changed, if it did.
            if new_casing != dep:
                casing_changed = True

            # Replace old value with new value.
            old_value = p['packages'][dep]
            del p['packages'][dep]
            p['packages'][new_casing] = old_value

    # casing for [dev-packages]
    if 'dev-packages' in p:
        # Replace each package with proper casing.
        for dep in p['dev-packages']:

            # Get new casing for package name.
            new_casing = proper_case(dep)

            # Mark casing as changed, if it did.
            if new_casing != dep:
                casing_changed = True

            # Replace old value with new value.
            old_value = p['dev-packages'][dep]
            del p['dev-packages'][dep]
            p['dev-packages'][new_casing] = old_value

    if casing_changed:
        click.echo(crayons.yellow('Fixing package names in Pipfile...'))

    # Write pipfile out to disk.
    project.write(p)
Exemple #34
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()
def get_bot_status():
    url = "https://webexapis.com/v1/rooms"
    payload = {}
    headers = {
        'Content-Type': 'application/json',
        'Authorization': "Bearer " + bearer
    }

    response = requests.request("GET", url, headers=headers, data=payload)
    data = json_loads_byteified(response.text)
    print(yellow("Bot is currently member of Webex Rooms:", bold=True))
    if 'items' in data:
        for room in data['items']:
            print(green("     ID: {}".format(room['id']), bold=True))

    url = "https://webexapis.com/v1/webhooks"
    response = requests.request("GET", url, headers=headers, data=payload)
    data = json_loads_byteified(response.text)
    print(green("Bot is currently configured with webhooks:", bold=True))
    if 'items' in data:
        for webhook in data['items']:
            print(" => ID: {}".format(webhook['id']))
            print("     Name: {}".format(webhook['name'].encode('utf8')))
            print("     Url: {}".format(webhook['targetUrl']))
            print(green("     Status: {}".format(webhook['status']),
                        bold=True))
            if webhook['name'] != webhook_name:
                print("    === REMOVING WEBHOOK ===")
                delete_webhook(webhook['id'])
                print("    === REMOVED ===")
            if webhook['status'] != 'active':
                print("    === UPDATING WEBHOOK STATUS ===")
                update_webhook()
                print("    === STATUS UPDATED ===")
            if (webhook['targetUrl'] != webhook_url):
                print("    === NEED TO UPDATE WEBHOOK ===")
                delete_webhook(webhook['id'])
                print("    === OLD WEBHOOK REMOVED ===")
                print("    === ADDING NEW WEBHOOK ===")
                add_webhook()
                print("    === NEW WEBHOOK ADDED ===")
        if len(data['items']) == 0:
            print("    === NO WEBHOOKS DETECTED ===")
            add_webhook()
            print("    === NEW WEBHOOK ADDED  ===")
Exemple #36
0
def resolution(message, speed, carrier):
    if int(speed) >= 25:
        message = f"{message} since your bandwidth is {speed}, and your carrier is {carrier}, we recommend setting video to 4k."
        #Display the specific message in GREEN
        print(crayons.green(message, bold=True))
    elif int(speed) >= 5:
        message = f"{message} since your bandwidth is {speed}, and your carrier is {carrier}, we recommend setting video to 1080p."
        #Display the specific message in YELLOW
        print(crayons.yellow(message, bold=True))
    elif int(speed) >= 2:
        message = f"{message} since your bandwidth is {speed}, and your carrier is {carrier}, we recommend setting video to 720p."
        #Display the specific message in RED
        print(crayons.red(message, bold=True))
    else:
        message = f"{message} Since your bandwidth is {speed}, and your carrier is {carrier}, we recommend finding another provider."
        #Display the specific message in MAGENTA
        print(crayons.magenta(message, bold=True))
    return message
Exemple #37
0
    def print_issues(self, project, year):
        for week_range in week_ranges(year):
            issues: ResultList = self.completed_issues(project, week_range[0],
                                                       week_range[1])

            date_separator = "\n=== {} - {} ===".format(
                week_range[0], week_range[1])
            print(crayons.yellow(date_separator, bold=True))
            issue: Issue
            for issue in issues:
                resolution_date = parse_date(issue.fields.resolutiondate)
                print("Key: {}, Resolved: {}, Description: {}, Status: {}".
                      format(
                          issue.key,
                          resolution_date,
                          issue.fields.summary,
                          issue.fields.status,
                      ))
def post_report(wiki, dry_run, report):
    """Simple program that greets NAME for a total of COUNT times."""
    content = report_page.render(
        title="{}.{}".format(report["year"], report["month"]),
        table=tabulate(list(report.items())[:-2], tablefmt="youtrack"),
    )

    print(content)

    if not dry_run:
        print(
            crayons.green(
                "Appending to wiki page {} DokuWiki".format(WIKI_PAGE)))
        wiki.pages.append(WIKI_PAGE, content=content)
    else:
        print(
            crayons.yellow(
                "Would append to page {} at DokuWiki".format(WIKI_PAGE)))
Exemple #39
0
def main ():
    print(crayons.red('red string'))
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.disable()
    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

    crayons.DISABLE_COLOR = False

    print('{} white {}'.format(crayons.red('red'), crayons.blue('blue')))

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

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

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

    print(crayons.white('white string', bold=True))
Exemple #40
0
    def hunt(self) -> Result:
        canary_meta: Optional[CanaryMeta] = self._get_canary_meta()

        if not canary_meta:
            deployed_canary_release = None
            print(yellow(f"Canary pods {self.canary_names} don't exist in {self.k8s_namespace} namespace"))

        else:
            deployed_canary_release = self._get_canary_release(canary_meta)

        current_commit = self.gitlab_client.get_commit(
            repository_id=self.project_id, commit_sha=self.commit_to_release_sha
        )

        if not current_commit:
            raise RuntimeError(f"Commit to be deployed with hash {self.commit_to_release_sha} is not found")

        return Result(deployed_canary_release, current_commit)
Exemple #41
0
def install(package_name=False, more_packages=False, r=False, dev=False, three=False, system=False):

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

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

    # If -r provided, read in package names.
    if r:
        package_names = from_requirements_file(r)
        package_name = package_names.pop()

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

    for package_name in package_names:
        # Lower-case incoming package name.
        package_name = package_name.lower()

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

        # pip install:
        c = pip_install(package_name, allow_global=system)
        click.echo(crayons.blue(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(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)
Exemple #42
0
    def __load_current_info(self):
        """Load current add-on version information and current config."""
        current_config_file = os.path.join(self.repository.working_dir,
                                           self.repository_target,
                                           "config.json")

        if not os.path.isfile(current_config_file):
            click.echo("Current version: %s" % crayons.yellow("Not available"))
            return False

        current_config = json.load(open(current_config_file))
        self.current_version = current_config["version"]
        self.name = current_config["name"]
        self.description = current_config["description"]
        self.slug = current_config["slug"]
        self.url = current_config["url"]
        if "arch" in current_config:
            self.archs = current_config["arch"]

        current_parsed_version = False
        try:
            current_parsed_version = semver.parse(self.current_version)
        except ValueError:
            pass

        if current_parsed_version:
            try:
                ref = self.addon_repository.get_git_ref("tags/" +
                                                        self.current_version)
            except UnknownObjectException:
                ref = self.addon_repository.get_git_ref("tags/v" +
                                                        self.current_version)
            self.current_commit = self.addon_repository.get_commit(
                ref.object.sha)
        else:
            try:
                self.current_commit = self.addon_repository.get_commit(
                    f"v{self.current_version}")
            except GithubException:
                self.current_commit = self.addon_repository.get_commit(
                    self.current_version)

        click.echo("Current version: %s (%s)" % (crayons.magenta(
            self.current_version), self.current_commit.sha[:7]))
Exemple #43
0
def find_item_in_folder(file_: str, folder: str) -> list:
    print('\nLooking for files with "',
          crayons.yellow(file_),
          '" in name\nin folder ',
          crayons.green(folder),
          '\n',
          sep='')
    spinner.start()
    global time_start
    time_start = time.time()
    # find file
    c.execute("SELECT * FROM my_files WHERE filename LIKE ? AND path Like ?", (
        '%' + file_ + '%',
        folder + '%',
    ))
    found_items = c.fetchall()

    spinner.stop()
    return found_items
Exemple #44
0
 def ping_test_ok(self):
     addr = self.props.ip
     if os.name == "nt":
         ping = [
             r'C:\WINDOWS\system32\ping.exe', '-n', '1', '-w', '5', addr
         ]
     else:
         ping = ['ping', '-c', '1', '-W', '5', addr]
     p = subprocess.Popen(ping,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          shell=False)
     p.communicate()
     if p.returncode != 0:
         self.log(
             crayons.yellow(
                 f'Host at address {addr} cannot be reached - skipped'))
         return False
     return True
Exemple #45
0
def leitner_train(box, filename='data/leitner.json'):
    print('Training box:', box, '\n')
    data = load_leitner_data(filename)
    facts = data.setdefault('facts', [])
    random.shuffle(facts)
    for f in facts:
        if f['box'] == box:
            print('Front:', f['front'])
            user_back = input('Back: ')
            if user_back == f['back']:
                print(crayons.green('Correct!'))
                f['box'] = max(f['box'] + 1, 2)
            else:
                print(crayons.red('Wrong!'), 'Correct answer is',
                      crayons.yellow(f['back']))
                f['box'] = 1
            print()
            save_leitner_data(data, filename)
    print('Done')
Exemple #46
0
def do_download_dependencies(dev=False, only=False, bare=False):
    """"Executes the download functionality."""

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

    # Load the Pipfile.
    if not bare:
        click.echo(crayons.yellow('Downloading dependencies from Pipfile...'))
    lockfile = json.loads(p.lock())

    # 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 = convert_deps_to_pip(deps, r=False)

    # Actually install each dependency into the virtualenv.
    name_map = {}
    for package_name in deps:

        if not bare:
            click.echo('Downloading {0}...'.format(crayons.green(package_name)))

        # pip install:
        c = pip_download(package_name)

        if not bare:
            click.echo(crayons.blue(c.out))

        parsed_output = parse_install_output(c.out)
        for filename, name in parsed_output:
            name_map[filename] = name

    return name_map
Exemple #47
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()
Exemple #48
0
# ' ` `-' ' ` ' ` `-'  '  ' `   ' ' `-' `-'  '  `-'

def easter_egg(package_name):
    if package_name in ['requests', 'maya', 'crayons', 'delegator.py' 'records', 'tablib']:
        click.echo(u'P.S. You have excellent taste! ✨ � ✨')


@click.group(invoke_without_command=True)
@click.option('--where', is_flag=True, default=False, help="Output project home information.")
@click.option('--venv', is_flag=True, default=False, help="Output virtualenv information.")
@click.option('--rm', is_flag=True, default=False, help="Remove the virtualenv.")
@click.option('--bare', is_flag=True, default=False, help="Minimal output.")
@click.option('--three/--two', is_flag=True, default=None, help="Use Python 3/2 when creating virtualenv.")
@click.option('--python', default=False, nargs=1, help="Specify which version of Python virtualenv should use.")
@click.option('--help', '-h', is_flag=True, default=None, help="Show this message then exit.")
@click.version_option(prog_name=crayons.yellow('pipenv'), version=__version__)
@click.pass_context
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
Exemple #49
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)