Example #1
0
def test_multiple_envvar(runner):
    @click.command()
    @click.option('--arg', multiple=True)
    def cmd(arg):
        click.echo('|'.join(arg))

    result = runner.invoke(cmd, [],
                           auto_envvar_prefix='TEST',
                           env={'TEST_ARG': 'foo bar baz'})
    assert not result.exception
    assert result.output == 'foo|bar|baz\n'

    @click.command()
    @click.option('--arg', multiple=True, envvar='X')
    def cmd(arg):
        click.echo('|'.join(arg))

    result = runner.invoke(cmd, [], env={'X': 'foo bar baz'})
    assert not result.exception
    assert result.output == 'foo|bar|baz\n'

    @click.command()
    @click.option('--arg', multiple=True, type=click.Path())
    def cmd(arg):
        click.echo('|'.join(arg))

    result = runner.invoke(cmd, [],
                           auto_envvar_prefix='TEST',
                           env={'TEST_ARG': 'foo%sbar' % os.path.pathsep})
    assert not result.exception
    assert result.output == 'foo|bar\n'
Example #2
0
def test_path_option(runner):
    @click.command()
    @click.option('-O', type=click.Path(file_okay=False, exists=True,
                                        writable=True))
    def write_to_dir(o):
        with open(os.path.join(o, 'foo.txt'), 'wb') as f:
            f.write(b'meh\n')

    with runner.isolated_filesystem():
        os.mkdir('test')

        result = runner.invoke(write_to_dir, ['-O', 'test'])
        assert not result.exception

        with open('test/foo.txt', 'rb') as f:
            assert f.read() == b'meh\n'

        result = runner.invoke(write_to_dir, ['-O', 'test/foo.txt'])
        assert 'Invalid value for "-O": Directory "test/foo.txt" is a file.' \
            in result.output

    @click.command()
    @click.option('-f', type=click.Path(exists=True))
    def showtype(f):
        click.echo('is_file=%s' % os.path.isfile(f))
        click.echo('is_dir=%s' % os.path.isdir(f))

    with runner.isolated_filesystem():
        result = runner.invoke(showtype, ['-f', 'xxx'])
        assert 'Error: Invalid value for "-f": Path "xxx" does not exist' \
            in result.output

        result = runner.invoke(showtype, ['-f', '.'])
        assert 'is_file=False' in result.output
        assert 'is_dir=True' in result.output

    @click.command()
    @click.option('-f', type=click.Path())
    def exists(f):
        click.echo('exists=%s' % os.path.exists(f))

    with runner.isolated_filesystem():
        result = runner.invoke(exists, ['-f', 'xxx'])
        assert 'exists=False' in result.output

        result = runner.invoke(exists, ['-f', '.'])
        assert 'exists=True' in result.output
Example #3
0
def test_path_args(runner):
    @click.command()
    @click.argument('input', type=click.Path(dir_okay=False, allow_dash=True))
    def foo(input):
        click.echo(input)

    result = runner.invoke(foo, ['-'])
    assert result.output == '-\n'
    assert result.exit_code == 0
Example #4
0
def read_config(ctx, param, value):
    """Callback that is used whenever --config is passed.  We use this to
    always load the correct config.  This means that the config is loaded
    even if the group itself never executes so our aliases stay always
    available.
    """
    cfg = ctx.ensure_object(Config)
    if value is None:
        value = os.path.join(os.path.dirname(__file__), 'aliases.ini')
    cfg.read_config(value)
    return value


@click.command(cls=AliasedGroup)
@click.option('--config',
              type=click.Path(exists=True, dir_okay=False),
              callback=read_config,
              expose_value=False,
              help='The config file to use instead of the default.')
def cli():
    """An example application that supports aliases."""


@cli.command()
def push():
    """Pushes changes."""
    click.echo('Push')


@cli.command()
def pull():
Example #5
0
        for item in f(*args, **kwargs):
            yield item

    return update_wrapper(new_func, f)


def copy_filename(new, old):
    new.filename = old.filename
    return new


@cli.command('open')
@click.option('-i',
              '--image',
              'images',
              type=click.Path(),
              multiple=True,
              help='The image file to open.')
@generator
def open_cmd(images):
    """Loads one or multiple images for processing.  The input parameter
    can be specified multiple times to load more than one image.
    """
    for image in images:
        try:
            click.echo('Opening "%s"' % image)
            if image == '-':
                img = Image.open(click.get_binary_stdin())
                img.filename = '-'
            else:
                img = Image.open(image)
Example #6
0
        for filename in os.listdir(cmd_folder):
            if filename.endswith('.py') and \
               filename.startswith('cmd_'):
                rv.append(filename[4:-3])
        rv.sort()
        return rv

    def get_command(self, ctx, name):
        try:
            if sys.version_info[0] == 2:
                name = name.encode('ascii', 'replace')
            mod = __import__('complex.commands.cmd_' + name,
                             None, None, ['cli'])
        except ImportError:
            return
        return mod.cli


@click.command(cls=ComplexCLI, context_settings=CONTEXT_SETTINGS)
@click.option('--home', type=click.Path(exists=True, file_okay=False,
                                        resolve_path=True),
              help='Changes the folder to operate on.')
@click.option('-v', '--verbose', is_flag=True,
              help='Enables verbose mode.')
@pass_context
def cli(ctx, verbose, home):
    """A complex command line interface."""
    ctx.verbose = verbose
    if home is not None:
        ctx.home = home
Example #7
0
def setuser(repo, username, email, password):
    """Sets the user credentials.

    This will override the current user config.
    """
    repo.set_config('username', username)
    repo.set_config('email', email)
    repo.set_config('password', '*' * len(password))
    click.echo('Changed credentials.')


@cli.command()
@click.option('--message', '-m', multiple=True,
              help='The commit message.  If provided multiple times each '
              'argument gets converted into a new line.')
@click.argument('files', nargs=-1, type=click.Path())
@pass_repo
def commit(repo, files, message):
    """Commits outstanding changes.

    Commit changes to the given files into the repository.  You will need to
    "repo push" to push up your changes to other repositories.

    If a list of files is omitted, all changes reported by "repo status"
    will be committed.
    """
    if not message:
        marker = '# Files to be committed:'
        hint = ['', '', marker, '#']
        for file in files:
            hint.append('#   U %s' % file)
Example #8
0
import trio_click as click
from complex.cli import pass_context


@click.command('init', short_help='Initializes a repo.')
@click.argument('path', required=False, type=click.Path(resolve_path=True))
@pass_context
def cli(ctx, path):
    """Initializes a repository."""
    if path is None:
        path = ctx.home
    ctx.log('Initialized the repository in %s',
            click.format_filename(path))