Example #1
0
def get_cldls():
    """
    Does all the work to initialize the cldls command line and subcommands.
    """
    @click.group(name='cldls', cls=NaturalOrderGroup)
    @click.option('--debug/--no-debug', default=False)
    @click.option('--profile', help="The profile to use.")
    @click.pass_context
    def cldls(ctx, debug, profile):
        """
        The cloudless command line.  Use this to interact with networks and services deployed with
        cloudless, and to run the testing framework.

        If the "profile" option is not set, the value of "CLOUDLESS_PROFILE" will be used.  If
        neither option is set, the default profile is "default".
        """
        if not ctx.obj:
            ctx.obj = {}
        if debug:
            click.echo('Enabling debug logging.')
            cloudless.set_level(logging.DEBUG)
        ctx.obj['PROFILE'] = cloudless.profile.select_profile(profile)

    add_init_group(cldls)
    add_network_group(cldls)
    add_service_group(cldls)
    add_service_test_group(cldls)
    add_paths_group(cldls)
    add_image_group(cldls)
    add_image_build_group(cldls)
    register_repl(cldls)
    return cldls
Example #2
0
def main():
    try:
        click_repl.register_repl(cli, name="ui")
        cli.add_command(images_command)
        cli.add_command(config_command)
        cli.add_command(local)
        cli.add_command(dev)
        cli.add_command(android)
        cli.add_command(k8s)
        cli.add_command(ui)
        cli.add_command(webui)
        cli.add_command(print_help)
        cli.add_command(plugins_command)
        add_plugin_commands(cli)
        cli()  # pylint: disable=no-value-for-parameter
    except exceptions.TutorError as e:
        fmt.echo_error("Error: {}".format(e.args[0]))
        sys.exit(1)
Example #3
0
    pass


@cli_main.group(name='gradebook')
@click.option('--dbase', default='sqlite://')
@click.pass_context
def cli_gradebook(ctx, dbase):
    """Access to gradebook utilities"""
    if ctx.obj is None:
        engine = sqlalchemy.create_engine(dbase)
        grader_toolkit.gradebook.Base.metadata.create_all(engine)
        grader_toolkit.Session.configure(bind=engine)
        ctx.obj = grader_toolkit.Session()


click_repl.register_repl(cli_gradebook)


@cli_gradebook.group(name='add')
def cli_gb_add():
    """Add objects to gradebook"""
    pass


def get_entries(kws):
    ret = {}
    for kw, prompt, t in kws:
        ret[kw] = click.prompt(prompt, type=t)
    return ret

Example #4
0
    for path in glob.iglob(expanduser(config["main"]["path"])):
        if not isdir(path):
            continue
        db = Database(path)
        if databases.setdefault(db.name, db) is not db:
            raise RuntimeError('Detected two databases named {}'
                               .format(db.name))

    if not ctx.invoked_subcommand:
        ctx.invoke(cli.commands["list"])


try:
    import click_repl
    click_repl.register_repl(cli)
    click_repl.register_repl(cli, name="shell")
except ImportError:
    pass


@cli.command()
@click.argument('summary', nargs=-1)
@click.option('--list', '-l', callback=_validate_list_param,
              help='The list to create the task in.', required=True)
@click.option('--due', '-d', default='', callback=_validate_due_param,
              help=('The due date of the task, in the format specified in the '
                    'configuration file.'))
@click.option('--interactive', '-i', is_flag=True,
              help='Go into interactive mode before saving the task.')
@click.pass_context
Example #5
0
            arrs.append((name.strip(), source.strip(), target.strip()))
        else:
            objs.append(val.strip())
    labels = objs[:]
    objs = {o: i for i, o in enumerate(objs)}
    # Identity arrows for each object.
    arrows = {(i, i): i for i in range(len(labels))}
    for name, source, target in arrs:
        s = objs[source]
        t = objs[target]
        n = len(labels)
        labels.append(name)
        # Composition for each end of the arrow.
        arrows[s, n] = s
        arrows[n, t] = t
    import pdb
    pdb.set_trace()
    d = {
        "labels": ["X", "Y", "Z", "f", "g"],
        "structure": 0,
        "title": "demo",
    }
    png = d.makePNG()
    with open("latest.png", "wb") as handle:
        handle.write(png)


if __name__ == "__main__":
    register_repl(cli)
    cli()
Example #6
0
File: cli.py Project: hut/todoman
            click_ctx,
            ctx.config['main']['default_command'],
        )


def invoke_command(click_ctx, command):
    name, *args = command.split(' ')
    if name not in cli.commands:
        raise click.ClickException(
            'Invalid setting for [main][default_command]')
    click_ctx.invoke(cli.commands[command], args)


try:  # pragma: no cover
    import click_repl
    click_repl.register_repl(cli)
    click_repl.register_repl(cli, name="shell")
except ImportError:
    pass


@cli.command()
@click.argument('summary', nargs=-1)
@click.option('--list',
              '-l',
              callback=_validate_list_param,
              help='The list to create the task in.')
@click.option('--read-description',
              '-r',
              is_flag=True,
              default=False,
Example #7
0
#!/usr/bin/python
#-----------------------------------------------------------------------------
# {C} Copyright 2019 Pensando Systems Inc. All rights reserved
#-----------------------------------------------------------------------------
#
# Debug CLI
#

import os
import click
from click_repl import register_repl
import cli
from apollo_frontend import *
from p4plus_txdma_frontend import *
from p4plus_rxdma_frontend import *

register_repl(dbg_cli)
dbg_cli.add_command(debug)

cli.cli_init(None)

if __name__ == '__main__':
    dbg_cli()
Example #8
0
        fmt.echo_error("Error: {}".format(e.args[0]))
        sys.exit(1)


@click.group(context_settings={"help_option_names": ["-h", "--help", "help"]})
@click.version_option(version=__version__)
def cli():
    pass


@click.command(help="Print this help", name="help")
def print_help():
    with click.Context(cli) as context:
        click.echo(cli.get_help(context))


click_repl.register_repl(cli, name="ui")
cli.add_command(images_command)
cli.add_command(config_command)
cli.add_command(local)
cli.add_command(dev)
cli.add_command(android)
cli.add_command(k8s)
cli.add_command(ui)
cli.add_command(webui)
cli.add_command(print_help)
cli.add_command(plugins_command)

if __name__ == "__main__":
    main()
Example #9
0
def twofa_reset():
    """Two-factor authentication reset"""

@twofa_reset.command()
@click.argument('reset_email')
@with_login
@gdk_resolve
def request(session, reset_email):
    """Request a 2fa reset"""
    is_dispute = False
    return gdk.twofactor_reset(session.session_obj, reset_email, is_dispute)

@twofa_reset.command()
@click.argument('reset_email')
@with_login
@gdk_resolve
def dispute(session, reset_email):
    """Dispute a 2fa reset"""
    is_dispute = True
    return gdk.twofactor_reset(session.session_obj, reset_email, is_dispute)

@twofa_reset.command()
@with_login
@gdk_resolve
def cancel(session):
    """Cancel a 2fa reset"""
    return gdk.twofactor_cancel_reset(session.session_obj)

register_repl(green)
green()
Example #10
0
            wclick.echo("Invalid existing config. "
                        "Therefore you have to enter all values.")
        else:
            if password:
                options.append(PasswordOption())
            if oauth:
                options.append(ClientOption())
                options.append(SecretOption())
    configurator = Configurator(config)
    while True:
        with wclick.spinner():
            configurator.start(options)
            (result, msg, options) = Validator(config).check_oauth()

        if result or not options:
            wclick.echo(msg)
            sys.exit(0)


def run_command(command, quiet=False):
    with wclick.spinner():
        result, output = command.execute()

    if not quiet and output:
        click.echo(output)
    if not result:
        sys.exit(1)


click_repl.register_repl(cli)
Example #11
0
      click.echo(click.style(category, fg=category_color))

      for capability in capabilities:
         if capability.enabled:
            click.echo(click.style('\t' + capability.title, fg=enabled_feature_color))
         else:
            click.echo(click.style('\t' + capability.title, fg=disabled_feature_color))


@main.command()
@click.pass_obj
def show_all_categories(obj: dict) -> None:
   """Prints out each category from cache 

   Args:
       obj ([dict]): Global dict object shared by CLI commands
   """   
   dispatcher = obj['dispatcher']
   category_color = obj['category_color'].lower()

   catgories = dispatcher.query_data([
      lambda all_data: map(lambda data: data[0], all_data)
   ])

   for category in catgories:
      click.echo(click.style(category, fg=category_color))


#add interactive repl as a command
register_repl(main)
Example #12
0
    Repair a given collection.

    Runs a few checks on the collection and applies some fixes to individual
    items that may improve general stability, also with other CalDAV/CardDAV
    clients. In particular, if you encounter URL-encoding-related issues with
    other clients, this command might help.

    Example: `vdirsyncer repair calendars_local/foo` repairs the `foo`
    collection of the `calendars_local` storage.
    '''
    from .tasks import repair_collection

    cli_logger.warning('This operation will take a very long time.')
    cli_logger.warning('It\'s recommended to turn off other client\'s '
                       'synchronization features.')
    click.confirm('Do you want to continue?', abort=True)
    repair_collection(ctx.config, collection)

# Not sure if useful. I originally wanted it because:
# * my password manager has a timeout for caching the master password
# * when calling vdirsyncer in a cronjob, the master password prompt would
#   randomly pop up
# So I planned on piping a FIFO to vdirsyncer, and writing to that FIFO from a
# cronjob.

try:
    import click_repl
    click_repl.register_repl(app)
except ImportError:
    pass
Example #13
0
def main():
    register_repl(green)
    green()
Example #14
0
import logging

import click
from click_repl import register_repl

from mnistpredictor.management import train_cli


@click.group()
@click.option('--verbose', is_flag=True, help="Enable debug logging.")
@click.version_option()
def cli(verbose):
    if verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)


cli.add_command(train_cli)


register_repl(cli)

if __name__ == '__main__':
    cli()
Example #15
0
                                               exchange=exchange,
                                               routing_key=routing_key,
                                               mandatory=mandatory,
                                               immediate=immediate)
        except Exception as e:
            amqp_context.echo_error(e)
            amqp_context.reconnect()
        else:
            amqp_context.echo_ok()


@amqp.command(name='basic.ack')
@click.argument('delivery_tag',
                type=int)
@click.pass_obj
def basic_ack(amqp_context, delivery_tag):
    if amqp_context.channel is None:
        amqp_context.echo_error('Not connected to broker. Please retry...')
        amqp_context.reconnect()
    else:
        try:
            amqp_context.channel.basic_ack(delivery_tag)
        except Exception as e:
            amqp_context.echo_error(e)
            amqp_context.reconnect()
        else:
            amqp_context.echo_ok()


repl = register_repl(amqp)
Example #16
0
            print(
                str(x[0]) + "    Distance: " + str(distance) + "     Ratio: " +
                str(ratio))
            if ratio >= 0.50 or distance < 20:
                authors_set.append(x[0])
    try:
        print("File Authorship Assigned to: " +
              max(set(authors_set), key=authors_set.count))
    except:  # Catch all Exceptions
        print("Error determining author!")


# Helper Function
def get_git_log(count, curr_dir, file_path):
    working_dir = curr_dir + "/results"

    for x in range(1, count):
        f = open(os.path.join(working_dir, str(x) + "_log_results.txt"), "w")
        process = subprocess.Popen(
            ['git', 'log', '-L',
             str(x) + ',' + str(x) + ':' + file_path],
            cwd=curr_dir,
            stdout=f,
            stderr=subprocess.PIPE)
        process.wait()  # Wait for process to complete
        f.close()


register_repl(capi)
capi()
Example #17
0
            amqp_context.channel.basic_publish(msg,
                                               exchange=exchange,
                                               routing_key=routing_key,
                                               mandatory=mandatory,
                                               immediate=immediate)
        except Exception as e:
            amqp_context.echo_error(e)
            amqp_context.reconnect()
        else:
            amqp_context.echo_ok()


@amqp.command(name='basic.ack')
@click.argument('delivery_tag', type=int)
@click.pass_obj
def basic_ack(amqp_context, delivery_tag):
    if amqp_context.channel is None:
        amqp_context.echo_error('Not connected to broker. Please retry...')
        amqp_context.reconnect()
    else:
        try:
            amqp_context.channel.basic_ack(delivery_tag)
        except Exception as e:
            amqp_context.echo_error(e)
            amqp_context.reconnect()
        else:
            amqp_context.echo_ok()


register_repl(amqp)
Example #18
0
    Repair a given collection.

    Runs a few checks on the collection and applies some fixes to individual
    items that may improve general stability, also with other CalDAV/CardDAV
    clients. In particular, if you encounter URL-encoding-related issues with
    other clients, this command might help.

    Example: `vdirsyncer repair calendars_local/foo` repairs the `foo`
    collection of the `calendars_local` storage.
    '''
    from .tasks import repair_collection

    cli_logger.warning('This operation will take a very long time.')
    cli_logger.warning('It\'s recommended to turn off other client\'s '
                       'synchronization features.')
    click.confirm('Do you want to continue?', abort=True)
    repair_collection(ctx.config, collection)

# Not sure if useful. I originally wanted it because:
# * my password manager has a timeout for caching the master password
# * when calling vdirsyncer in a cronjob, the master password prompt would
#   randomly pop up
# So I planned on piping a FIFO to vdirsyncer, and writing to that FIFO from a
# cronjob.

try:
    import click_repl
    click_repl.register_repl(app)
except ImportError:
    pass