Skip to content

Instantly share code, notes, and snippets.

@kemayo
Last active October 30, 2017 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kemayo/ffa74806d14534c668072e456e1492c1 to your computer and use it in GitHub Desktop.
Save kemayo/ffa74806d14534c668072e456e1492c1 to your computer and use it in GitHub Desktop.
Test for click, of somewhat abusive dynamic subcommand creation and argument passing.
import re
import click
# This is obviously a placeholder for testing purposes, and would actually use Site.matches
sites = {}
for site in ('archiveofourown', 'fanfiction', 'spacebattles'):
@click.command()
@click.argument('url')
def cmd(url, *args, **kwargs):
print(url, kwargs)
if site == 'spacebattles':
cmd = click.option('--include-index/--no-include-index', default=False)(cmd)
sites[site] = cmd
@click.group()
def cli():
pass
@cli.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.pass_context
def download(ctx):
# Could have a 'url' parameter, but this setup lets interleaved arguments
# work, since allow_extra_args *doesn't* uninterleave unknown arguments,
# so `download --include-index http://...` would consider `--include-
# index` to be the URL.
leftover = []
handler = None
for arg in ctx.args:
if not handler:
site = re.match(r'https?://(?:[^\.]+?\.)?([^\.]+?)\..+', arg)
if site:
handler = sites.get(site.group(1))
# All subcommands get given a 'url' parameter, so set this up first
leftover.insert(0, arg)
continue
leftover.append(arg)
if handler:
subctx = handler.make_context(ctx.info_name, leftover, ctx)
handler.invoke(subctx)
else:
click.echo(download.get_help(ctx))
if __name__ == '__main__':
# Run as: python clicktest.py download --include-index https://forums.spacebattles.com/threads/miracles-of-ancient-wonder-rwby-exalted.389319/page-131#post-40743772 --include-index
cli()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment