Esempio n. 1
0
def rollback(version, app):
    """Rollback release to a previous release."""
    cli.user()

    if version and version[0] == 'v':
        version = version[1:]

    if not version:
        click.echo(f'Getting latest release for app {app}…  ', nl=False)
        with spinner():
            res = api.Releases.get(app=app)
            version = int(res[0]['id']) - 1
        click.echo(
            click.style('\b' + emoji.emojize(':heavy_check_mark:'),
                        fg='green'))

    try:
        if int(version) == 0:
            click.echo('Unable to rollback a release before v1.')
            sys.exit(1)
    except ValueError:
        click.echo(click.style('Invalid release specified.', fg='red'),
                   err=True)
        sys.exit(1)

    click.echo(f'Rolling back to v{version}…  ', nl=False)

    with spinner():
        res = api.Releases.rollback(version=version, app=app)

    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green'))
    click.echo(f'Deployed new release… ' +
               click.style(f'v{res["id"]}', bold=True, fg='magenta'))
Esempio n. 2
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()))
Esempio n. 3
0
def deploy(app, message):
    """Deploy your app to Storyscript Cloud."""
    cli.user()

    payload = compile_app(app, False)  # Also adds a spinner.

    if payload is None:
        sys.exit(1)  # Error already printed by compile_app.

    click.echo(f'Deploying app {app}... ', nl=False)

    with spinner():
        config = Config.get(app)
        release = Releases.create(config, payload, app, message)

    url = f'https://{app}.storyscriptapp.com/'
    click.echo()
    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green') +
        f' Version {release["id"]} of your app has '
        f'been queued for deployment.\n')

    click.echo('Waiting for deployment to complete…  ', nl=False)
    with spinner():
        if Apps.maintenance(app, maintenance=None):
            click.echo()
            click.echo()
            click.echo('Your app is in maintenance mode.\n'
                       'Run the following to turn off it off:')
            cli.print_command('story maintenance off')
            click.echo()
            click.echo('Once maintenance mode is turned off, '
                       'your app will be deployed immediately.')
            return

        state = 'QUEUED'
        while state in ['DEPLOYING', 'QUEUED']:
            state = Releases.get(app)[0]['state']
            sleep(0.5)

    click.echo()
    if state == 'DEPLOYED':
        click.echo(
            click.style('\b' +
                        emoji.emojize(':heavy_check_mark:'), fg='green') +
            ' Deployment successful!')
        click.echo(
            f'If your Story responds to HTTP requests, please visit:\n  {url}')
    elif state == 'FAILED':
        click.echo(click.style('X', fg='red') + ' Deployment failed!',
                   err=True)
        click.echo(
            'Please use the following command to view your app\'s logs:',
            err=True)
        cli.print_command('story logs')
    else:
        click.echo(
            f'An unhandled state of your app has been encountered - {state}',
            err=True)
        click.echo(f'Please shoot an email to [email protected]')
Esempio n. 4
0
def cleanup(token, timeout, skip_repository, skip_branch, preview, no_interaction):
    if token is None:
        token = click.prompt(crayons.green(
            'Please enter your Github access token'))

    github_client = GithubClient(token, timeout)
    try:
        click.echo(crayons.green(
            'Searching for branches. This may take a while...'), err=True)
        with blindspin.spinner():
            repo_branches = github_client.get_merged_fork_branches(
                skip_repository, skip_branch)
    except BadCredentialsException:
        click.echo(crayons.red(
            'Bad credentials. Please provide valid access token'), err=True)
        sys.exit(1)
    if not repo_branches:
        click.echo(crayons.green(
            'Congratulations! No remote branches are available for cleaning up'))
        sys.exit(0)

    click.echo(crayons.yellow('Founded branches:\n'))
    list_branches(repo_branches)

    if False == preview:
        if False == no_interaction:
            click.confirm(crayons.green('\nDelete these branches?'), abort=True)
        click.echo(crayons.green('Deleting branches...'))
        with blindspin.spinner():
            github_client.delete_branches(repo_branches)
        click.echo(crayons.green('Done'))
Esempio n. 5
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('!')))
Esempio n. 6
0
def do_lock(no_hashes=False):
    """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]'))), err=True)

    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 = project._pipfile
    lockfile = project._lockfile

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

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

    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]'))), err=True)

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

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

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

    # Properly case package names.
    lockfile = recase_file(lockfile)

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

    # 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('!')), err=True)
Esempio n. 7
0
def set_command(variables, app, message):
    """
    Set one or more environment variables.

        $ story config set key=value foo=bar

    To set an environment variable for a specific service use

        $ story config set twitter.oauth_token=value

    """
    cli.user()

    click.echo('Fetching config… ', nl=False)
    with spinner():
        config = api.Config.get(app=app)
    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green'))

    if variables:
        for keyval in variables:
            try:
                key, val = tuple(keyval.split('=', 1))
            except ValueError:
                click.echo(
                    f'Config variables must be of the form name=value.'
                    f'\nGot unexpected pair "{keyval}"',
                    err=True,
                )
                click.echo(set_command.__doc__.strip())
                return
            # TODO validate against a regexp pattern
            if '.' in key:
                service, key = tuple(key.split('.', 1))
                config.setdefault(service.lower(), {})[key.upper()] = val
            else:
                config[key.upper()] = val

            click.echo()
            click.echo(f" {click.style(key.upper(), fg='green')}: {val}")

        click.echo('\nSetting config and deploying new release…  ', nl=False)
        with spinner():
            release = api.Config.set(config=config, app=app, message=message)
        click.echo(
            click.style('\b' + emoji.emojize(':heavy_check_mark:'),
                        fg='green'))
        click.echo(f'Deployed new release… ' +
                   click.style(f'v{release["id"]}', bold=True, fg='magenta'))

    else:
        click.echo(set_command.__doc__.strip())
Esempio n. 8
0
def install(package_name=False, more_packages=False, dev=False, three=False, python=False, system=False, lock=False, hashes=True, ignore_hashes=False, ignore_pipfile=False):

    # Automatically use an activated virtualenv.
    if PIPENV_USE_SYSTEM:
        system = True

    # Hack to invert hashing mode.
    no_hashes = not hashes

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

    # Capture -e argument and assign it to following package_name.
    more_packages = list(more_packages)
    if package_name == '-e':
        package_name = ' '.join([package_name, more_packages.pop(0)])

    # 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, ignore_hashes=ignore_hashes, ignore_pipfile=ignore_pipfile)
        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, ignore_hashes=True, 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.
        try:
            project.add_package_to_pipfile(package_name, dev)
        except ValueError as e:
            click.echo('{0} {1}'.format(crayons.red('ERROR (PACKAGE NOT INSTALLED):'), e))

        # Ego boost.
        easter_egg(package_name)

    if lock:
        do_lock(no_hashes=no_hashes)
Esempio n. 9
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.
        try:
            project.add_package_to_pipfile(package_name, dev)
        except ValueError as e:
            click.echo('{0} {1}'.format(
                crayons.red('ERROR (PACKAGE NOT INSTALLED):'), e))

        # Ego boost.
        easter_egg(package_name)

    if lock:
        do_lock()
Esempio n. 10
0
def list_command(app, limit):
    """List application releases."""
    cli.user()

    # click.echo(click.style('Releases', fg='magenta'))
    # click.echo(click.style('========', fg='magenta'))

    with spinner():
        res = api.Releases.list(app, limit=limit)

    res = sorted(res, key=lambda elem: elem['id'])

    if res:
        from texttable import Texttable

        table = Texttable(max_width=800)
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(['l', 'l', 'l', 'l'])
        all_releases = [['VERSION', 'STATUS', 'CREATED', 'MESSAGE']]
        for release in res:
            date = parse_psql_date_str(release['timestamp'])
            all_releases.append([
                f'v{release["id"]}',
                release['state'].capitalize(),
                reltime(date),
                release['message'],
            ])
        table.add_rows(rows=all_releases)
        click.echo(table.draw())
    else:
        click.echo(f'No releases yet for app {app}.')
Esempio n. 11
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)
Esempio n. 12
0
 def start(self):
     with blindspin.spinner():
         if self.pull:
             pull_cmd = self.docker_compose_command() + ['pull']
             subprocess.call(pull_cmd, cwd=self.filepath)
         up_cmd = self.docker_compose_command() + ['up', '-d']
         subprocess.call(up_cmd, cwd=self.filepath)
Esempio n. 13
0
File: apps.py Progetto: joaoh82/cli
def list_command():
    """List apps that you have access to."""
    from texttable import Texttable

    cli.user()

    with spinner():
        res = api.Apps.list()

    count = 0
    # Heads up! Texttable does not like colours.
    # So don't use click.style here.
    table = Texttable(max_width=800)
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(['l', 'l', 'l'])
    all_apps = [['NAME', 'STATE', 'CREATED']]
    for app in res:
        count += 1
        date = datetime.parse_psql_date_str(app['timestamp'])
        all_apps.append([
            app['name'],
            maintenance(app['maintenance']),
            datetime.reltime(date)
        ])

    table.add_rows(rows=all_apps)

    if count == 0:
        click.echo('No application found. Create your first app with')
        click.echo(click.style('$ story apps create', fg='magenta'))
    else:
        click.echo(table.draw())
Esempio n. 14
0
def list_command(app):
    """List environment variables."""

    cli.user()
    click.echo('Fetching config… ', nl=False)

    with spinner():
        config = api.Config.get(app)

    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green'))

    if config:
        click.echo(click.style('Storyscript variables:', dim=True))
        for name, value in config.items():
            if not isinstance(value, dict):
                click.echo(click.style(name, fg='green') + f':  {value}')

        click.echo('')
        click.echo(click.style('Service variables:', dim=True))
        for name, value in config.items():
            if isinstance(value, dict):
                click.echo(click.style(name, bold=True))
                for _name, _value in value.items():
                    click.echo('  ' + click.style(_name, fg='green') +
                               f':  {_value}')

    else:
        click.echo(click.style('No configuration set yet.', bold=True))
        click.echo('\nSet Storyscript environment ' +
                   click.style('$ ', dim=True) +
                   click.style('story config set key=value', fg='magenta'))
        click.echo(
            'Set service environment ' + click.style('$ ', dim=True) +
            click.style('story config set service.key=value', fg='magenta'))
Esempio n. 15
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.virtualenv_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)
Esempio n. 16
0
File: apps.py Progetto: joaoh82/cli
def destroy(yes=False, app=None, all=False):
    """Destroy an app."""

    cli.user()

    if all:
        click.echo('Destroying all Storyscript Cloud applications:', err=True)
        apps = [app['name'] for app in api.Apps.list()]
    else:
        apps = [app]

    for app in apps:

        if yes or click.confirm(f'Do you want to destroy {app!r}?',
                                abort=True):
            click.echo(f'Destroying application {app!r}… ', nl=False)

            with spinner():
                api.Apps.destroy(app=app)
                cli.track('App Destroyed', {'App name': app})

            click.echo(
                '\b' +
                click.style(emoji.emojize(':heavy_check_mark:'), fg='green'))
            click.echo()

    sys.exit(0)
Esempio n. 17
0
def main():
    args = arguments.Args()

    if args.get(0) == 'firefox':
        puts('Grabbing cookies from Firefox')
        jar = browsercookie.firefox()
    elif args.get(0) == 'chrome':
        puts('Grabbing cookies from Chrome')
        jar = browsercookie.chrome()
    else:
        puts('Grabbing cookies from Firefox')
        jar = browsercookie.firefox()

    url = 'https://www.safaribooksonline.com/a/export/csv/'

    puts('\nWaiting for download to begin... (may take a while)')

    with blindspin.spinner():
        r = requests.get(url, stream=True, cookies=jar)

    total_size = int(r.headers.get('content-length', 0))

    filename = 'safari.csv'

    with open(filename, 'wb') as out_file:

        for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_size/1024) + 1): 
            if chunk:
                out_file.write(chunk)
                out_file.flush()

    puts('File saved to {filename}\n'.format(filename=filename))
Esempio n. 18
0
def cli(ctx,
        where=False,
        venv=False,
        rm=False,
        bare=False,
        three=False,
        python=False,
        help=False):

    check_for_updates()

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

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

            # 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:

            if project.virtualenv_exists:
                loc = project.virtualenv_location
                click.echo(
                    crayons.yellow('{0} ({1})...'.format(
                        crayons.yellow('Removing virtualenv'),
                        crayons.green(loc))))

                with spinner():
                    # Remove the virtualenv.
                    cleanup_virtualenv(bare=True)
                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)

    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        click.echo(format_help(ctx.get_help()))
Esempio n. 19
0
def del_command(variables, app, message):
    """
    Delete one or more environment variables
    """
    cli.user()
    click.echo('Fetching config… ', nl=False)
    with spinner():
        config = api.Config.get(app=app)
    click.echo(
        click.style(emoji.emojize(':heavy_check_mark:'), fg='green')
    )

    for key in variables:
        removed = False
        if key in config:
            if type(config.pop(key)) is dict:
                click.echo(
                    click.style('Removed service', fg='red') + f': {key}'
                )
            else:
                removed = True
        elif key.upper() in config:
            config.pop(key.upper())
            removed = True
        elif '.' in key:
            service, key = tuple(key.split('.', 1))
            if service in config and key.upper() in config[service]:
                config[service].pop(key.upper())
                removed = True

        if removed:
            click.echo(
                click.style('Removed', fg='red') + f': {key.upper()}'
            )

    click.echo('\nSetting config and deploying new release… ', nl=False)
    with spinner():
        release = api.Config.set(config=config, app=app, message=message)
    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green')
    )
    click.echo(
        f'Deployed new release… '
        + click.style(f'v{release["id"]}', bold=True, fg='magenta')
    )
Esempio n. 20
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()))
Esempio n. 21
0
    def start(self):
        file_arguments = self._generate_file_arguments()

        with blindspin.spinner():
            if self.pull:
                subprocess.call(["docker-compose"] + file_arguments + ["pull"],
                                cwd=self.filepath)
            subprocess.call(["docker-compose"] + file_arguments + ["up", "-d"],
                            cwd=self.filepath)
Esempio n. 22
0
 def start(self):
     with blindspin.spinner():
         if self.pull:
             subprocess.call(
                 ["docker-compose", "-f", self.compose_file_name, "pull"],
                 cwd=self.filepath)
         subprocess.call(
             ["docker-compose", "-f", self.compose_file_name, "up", "-d"],
             cwd=self.filepath)
Esempio n. 23
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)
Esempio n. 24
0
def publish(tex, inline, debug):
    """
    This command performs several operations:

    - Produce a `publish` directory with tex files copied over

    - Remove comments

    - Factor out tikz code

    - Rename images to figure-n.pdf and place them alongside the tex

    - Factors out cref

    - Produces the .bbl file

    - Ensure status is `final`

    - Remove `fixme` notes

    - Inline the bbl file

    - Remove unneeded files

    """
    if debug:
        global RUN_CMD
        RUN_CMD = sarge.run


    if len(tex.split('.')) < 2:
        tex += '.tex'

    LOG.info('Creating publication version of {}'.format(tex))
    pdir = create_and_populate(tex)

    tasks = [('Removing comments', (remove_comments, [tex, pdir])),
             ('Removing TikZ dependency', (remove_tikz, [tex, pdir])),
             ('Copying images', (copy_and_rename_figures, [tex, pdir])),
             ('Removing cref dependency', (remove_cref, [tex, pdir])),
             ('Removing fixmes', (remove_notes, [tex, pdir])),
             ('Making document final', (make_final, [tex, pdir])),
             ('Inlining the bbl file', (inline_bbl, [tex, pdir])),
             ('Compiling document', (compile_tex, [tex, pdir, False])),
             ('Cleaning directory', (clean_directory, [pdir])),
    ]

    for task, func in tasks:
        LOG.info(task)
        try:
            if SPIN:
                with blindspin.spinner():
                    func[0](*func[1])
            else:
                func[0](*func[1])
        except:
            return
Esempio n. 25
0
 def get_logs(self):
     logs_cmd = self.docker_compose_command() + ["logs"]
     with blindspin.spinner():
         result = subprocess.run(
             logs_cmd,
             cwd=self.filepath,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
         )
         return result.stdout, result.stderr
Esempio n. 26
0
def off(app):
    """Turns maintenance–mode off."""

    cli.user()
    click.echo(f'Disabling maintenance mode for app {app}… ', nl=False)
    with spinner():
        api.Apps.maintenance(app=app, maintenance=False)
    click.echo(
        click.style('\b' + emoji.emojize(':heavy_check_mark:'), fg='green'))
    click.echo(click.style('Application is now running.', dim=True))
Esempio n. 27
0
 def start(self):
     print("")
     print("{} {}".format(crayons.yellow("Pulling image"),
                          crayons.red(self._kwargs['image'])))
     with blindspin.spinner():
         docker_client = self.get_docker_client()
         self._container = docker_client.run(**self._kwargs)
     print("")
     print("Container started: ",
           crayons.yellow(self._container.short_id, bold=True))
     return self
Esempio n. 28
0
def cli(context, url, name, submodules):
    """
    Clone a new repo to your homeslice
    """

    # Make sure repo dir exists
    if not environments.HOMESLICE_REPO.exists():
        environments.HOMESLICE_REPO.mkdir(parents=True, exist_ok=True)

    click.echo("Cloning repo from {} ...".format(url))
    with blindspin.spinner():
        git.clone(environments.HOMESLICE_REPO, url, name, submodules)
Esempio n. 29
0
def check(app):
    """Displays current maintenance status."""
    cli.user()
    click.echo(f'Fetching maintenance mode for {app}… ', nl=False)
    with spinner():
        enabled = api.Apps.maintenance(app=app, maintenance=None)
    if enabled:
        click.echo(
            click.style('ON. Application is disabled.', bold=True, fg='red'))
    else:
        click.echo(
            click.style('off. Application is running.', bold=True, fg='green'))
Esempio n. 30
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)
Esempio n. 31
0
def cli(context):
    """
    List all existing repos in your homeslice
    """

    click.echo("Current homeslice repos:")
    repos = do_repos_from_arguments(True, None)

    with blindspin.spinner():
        for repo in repos:
            config = git.config(repo)
            click.echo("    {} {}".format(
                str(repo).split("/")[-1],
                config,
            ))
 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))
Esempio n. 33
0
def destroy(confirm, app):
    """Destroy an app."""

    cli.user()

    if confirm or click.confirm(
        f'Do you want to destroy {app!r}?', abort=True
    ):
        click.echo(f'Destroying application {app!r}… ', nl=False)

        with spinner():
            api.Apps.destroy(app=app)
            cli.track('App Destroyed', {'App name': app})

        click.echo(
            '\b' + click.style(emoji.emojize(':heavy_check_mark:'), fg='green')
        )
Esempio n. 34
0
 def start(self):
     print("")
     print("{} {}".format(crayons.yellow("Pulling image"),
                          crayons.red(self.image)))
     with blindspin.spinner():
         docker_client = self.get_docker_client()
         self._container = docker_client.run(self.image,
                                             command=self._command,
                                             detach=True,
                                             environment=self.env,
                                             ports=self.ports,
                                             name=self._name,
                                             volumes=self.volumes)
     print("")
     print("Container started: ",
           crayons.yellow(self._container.short_id, bold=True))
     return self
Esempio n. 35
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()