Created
November 29, 2018 06:24
-
-
Save hirose31/f46d38bc7a11cdb5c02479a6f49af2cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import sys | |
import os | |
import click | |
from pathlib import Path | |
CONTEXT_SETTINGS = { | |
'ignore_unknown_options': True, | |
'allow_extra_args': True, | |
} | |
class SymlinkGroup(click.Group): | |
def get_command(self, ctx, cmd_name): | |
rv = click.Group.get_command(self, ctx, cmd_name) | |
if rv is not None: | |
click.echo(click.style('invoke: %s' % cmd_name, fg='green')) | |
return rv | |
sym_name = get_sym_name() | |
if sym_name is None: | |
return None | |
rv = click.Group.get_command(self, ctx, sym_name) | |
if rv is not None: | |
argv = list(sys.argv) | |
argv.insert(argv.index(cmd_name), sym_name) | |
click.echo(click.style('exec: %s' % argv, fg='green')) | |
os.execl(argv[0], *argv) | |
raise RuntimeError('failed to execl') | |
else: | |
return None | |
@click.command( | |
cls=SymlinkGroup, | |
context_settings=CONTEXT_SETTINGS, | |
invoke_without_command=True, | |
) | |
@click.option('-d', '--debug', | |
type=int, | |
count=True, | |
default=0, | |
envvar='FOO_DEBUG', | |
help='enable/disable debug mode') | |
@click.pass_context | |
def main(ctx, **kwargs): | |
ctx.obj = {} | |
ctx.obj['DEBUG'] = kwargs['debug'] | |
click.echo('Debug mode is %s' % ('on' if ctx.obj['DEBUG'] else 'off')) | |
click.echo('================') | |
@main.command() | |
@click.option('--force', | |
is_flag=True, | |
default=False, | |
) | |
@click.option('--yes', | |
is_flag=True, | |
default=False, | |
) | |
@click.pass_context | |
def foo(ctx, **kwargs): | |
click.echo('>> foo') | |
click.echo(' force: %s' % kwargs['force']) | |
click.echo(' yes : %s' % kwargs['yes']) | |
# foo-bar-baz => bar_baz | |
def get_sym_name(): | |
prog_name = Path(__file__).stem | |
e = prog_name.split('-')[1:] | |
if e: | |
return '_'.join(e) | |
else: | |
return None | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment