From 488739dfe0d51f415c7b20466648cc519962ecbb Mon Sep 17 00:00:00 2001 From: David Lord Date: Fri, 6 Mar 2020 13:19:03 -0800 Subject: apply reorder-python-imports --- examples/aliases/aliases.py | 5 +++-- examples/bashcompletion/bashcompletion.py | 3 ++- examples/complex/complex/cli.py | 1 + examples/complex/complex/commands/cmd_init.py | 3 ++- examples/complex/complex/commands/cmd_status.py | 3 ++- examples/imagepipe/imagepipe.py | 8 ++++++-- examples/repo/repo.py | 2 +- examples/termui/termui.py | 12 ++++-------- examples/validation/validation.py | 1 + 9 files changed, 22 insertions(+), 16 deletions(-) (limited to 'examples') diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index 299d3a5..a377a58 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -1,10 +1,11 @@ import os + import click try: - import ConfigParser as configparser -except ImportError: import configparser +except ImportError: + import ConfigParser as configparser class Config(object): diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py index 1072840..5dacae5 100644 --- a/examples/bashcompletion/bashcompletion.py +++ b/examples/bashcompletion/bashcompletion.py @@ -1,6 +1,7 @@ -import click import os +import click + @click.group() def cli(): diff --git a/examples/complex/complex/cli.py b/examples/complex/complex/cli.py index 0d10c62..3ef6fae 100644 --- a/examples/complex/complex/cli.py +++ b/examples/complex/complex/cli.py @@ -1,5 +1,6 @@ import os import sys + import click diff --git a/examples/complex/complex/commands/cmd_init.py b/examples/complex/complex/commands/cmd_init.py index a77116b..5da8df2 100644 --- a/examples/complex/complex/commands/cmd_init.py +++ b/examples/complex/complex/commands/cmd_init.py @@ -1,6 +1,7 @@ -import click from complex.cli import pass_environment +import click + @click.command('init', short_help='Initializes a repo.') @click.argument('path', required=False, type=click.Path(resolve_path=True)) diff --git a/examples/complex/complex/commands/cmd_status.py b/examples/complex/complex/commands/cmd_status.py index 12229c4..ac79767 100644 --- a/examples/complex/complex/commands/cmd_status.py +++ b/examples/complex/complex/commands/cmd_status.py @@ -1,6 +1,7 @@ -import click from complex.cli import pass_environment +import click + @click.command('status', short_help='Shows file changes.') @pass_environment diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index 37a1521..f6f04ef 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -1,6 +1,10 @@ -import click from functools import update_wrapper -from PIL import Image, ImageFilter, ImageEnhance + +from PIL import Image +from PIL import ImageEnhance +from PIL import ImageFilter + +import click @click.group(chain=True) diff --git a/examples/repo/repo.py b/examples/repo/repo.py index 2b1992d..c14a827 100644 --- a/examples/repo/repo.py +++ b/examples/repo/repo.py @@ -1,6 +1,6 @@ import os -import sys import posixpath +import sys import click diff --git a/examples/termui/termui.py b/examples/termui/termui.py index 793afa4..08f6a04 100644 --- a/examples/termui/termui.py +++ b/examples/termui/termui.py @@ -1,13 +1,9 @@ # coding: utf-8 -import click import math -import time import random +import time -try: - range_type = xrange -except NameError: - range_type = range +import click @click.group() @@ -28,7 +24,7 @@ def colordemo(): def pager(): """Demonstrates using the pager.""" lines = [] - for x in range_type(200): + for x in range(200): lines.append('%s. Hello World!' % click.style(str(x), fg='green')) click.echo_via_pager('\n'.join(lines)) @@ -38,7 +34,7 @@ def pager(): help='The number of items to process.') def progress(count): """Demonstrates the progress bar.""" - items = range_type(count) + items = range(count) def process_slowly(item): time.sleep(0.002 * random.random()) diff --git a/examples/validation/validation.py b/examples/validation/validation.py index 00fa0a6..5cfe5f6 100644 --- a/examples/validation/validation.py +++ b/examples/validation/validation.py @@ -1,4 +1,5 @@ import click + try: from urllib import parse as urlparse except ImportError: -- cgit v1.2.1 From 93ba3ba112d2f8ba7bdd8b231e510f74dd0b037e Mon Sep 17 00:00:00 2001 From: David Lord Date: Fri, 6 Mar 2020 13:50:04 -0800 Subject: apply black --- examples/aliases/aliases.py | 46 +++++---- examples/aliases/setup.py | 14 ++- examples/bashcompletion/bashcompletion.py | 16 ++-- examples/bashcompletion/setup.py | 14 ++- examples/colors/colors.py | 36 ++++--- examples/colors/setup.py | 14 +-- examples/complex/complex/cli.py | 26 +++--- examples/complex/complex/commands/cmd_init.py | 7 +- examples/complex/complex/commands/cmd_status.py | 6 +- examples/complex/setup.py | 14 ++- examples/imagepipe/imagepipe.py | 119 ++++++++++++++---------- examples/imagepipe/setup.py | 15 ++- examples/inout/inout.py | 4 +- examples/inout/setup.py | 14 ++- examples/naval/naval.py | 60 ++++++------ examples/naval/setup.py | 14 ++- examples/repo/repo.py | 115 +++++++++++++---------- examples/repo/setup.py | 14 ++- examples/termui/setup.py | 14 +-- examples/termui/termui.py | 118 +++++++++++++---------- examples/validation/setup.py | 14 ++- examples/validation/validation.py | 37 +++++--- 22 files changed, 395 insertions(+), 336 deletions(-) (limited to 'examples') diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index a377a58..8456a1b 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -22,16 +22,16 @@ class Config(object): parser = configparser.RawConfigParser() parser.read([filename]) try: - self.aliases.update(parser.items('aliases')) + self.aliases.update(parser.items("aliases")) except configparser.NoSectionError: pass def write_config(self, filename): parser = configparser.RawConfigParser() - parser.add_section('aliases') + parser.add_section("aliases") for key, value in self.aliases.items(): - parser.set('aliases', key, value) - with open(filename, 'wb') as file: + parser.set("aliases", key, value) + with open(filename, "wb") as file: parser.write(file) @@ -62,13 +62,14 @@ class AliasedGroup(click.Group): # allow automatic abbreviation of the command. "status" for # instance will match "st". We only allow that however if # there is only one command. - matches = [x for x in self.list_commands(ctx) - if x.lower().startswith(cmd_name.lower())] + matches = [ + x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower()) + ] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) - ctx.fail('Too many matches: %s' % ', '.join(sorted(matches))) + ctx.fail("Too many matches: %s" % ", ".join(sorted(matches))) def read_config(ctx, param, value): @@ -79,15 +80,19 @@ def read_config(ctx, param, value): """ cfg = ctx.ensure_object(Config) if value is None: - value = os.path.join(os.path.dirname(__file__), 'aliases.ini') + 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.') +@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.""" @@ -95,42 +100,43 @@ def cli(): @cli.command() def push(): """Pushes changes.""" - click.echo('Push') + click.echo("Push") @cli.command() def pull(): """Pulls changes.""" - click.echo('Pull') + click.echo("Pull") @cli.command() def clone(): """Clones a repository.""" - click.echo('Clone') + click.echo("Clone") @cli.command() def commit(): """Commits pending changes.""" - click.echo('Commit') + click.echo("Commit") @cli.command() @pass_config def status(config): """Shows the status.""" - click.echo('Status for %s' % config.path) + click.echo("Status for %s" % config.path) @cli.command() @pass_config -@click.argument("alias_", metavar='ALIAS', type=click.STRING) +@click.argument("alias_", metavar="ALIAS", type=click.STRING) @click.argument("cmd", type=click.STRING) -@click.option('--config_file', type=click.Path(exists=True, dir_okay=False), - default="aliases.ini") +@click.option( + "--config_file", type=click.Path(exists=True, dir_okay=False), default="aliases.ini" +) def alias(config, alias_, cmd, config_file): """Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) - click.echo('Added %s as alias for %s' % (alias_, cmd)) + click.echo("Added %s as alias for %s" % (alias_, cmd)) diff --git a/examples/aliases/setup.py b/examples/aliases/setup.py index 8d1d6a4..2ea791e 100644 --- a/examples/aliases/setup.py +++ b/examples/aliases/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-aliases', - version='1.0', - py_modules=['aliases'], + name="click-example-aliases", + version="1.0", + py_modules=["aliases"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] aliases=aliases:cli - ''', + """, ) diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py index 5dacae5..c437069 100644 --- a/examples/bashcompletion/bashcompletion.py +++ b/examples/bashcompletion/bashcompletion.py @@ -15,14 +15,14 @@ def get_env_vars(ctx, args, incomplete): yield key -@cli.command(help='A command to print environment variables') +@cli.command(help="A command to print environment variables") @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars) def cmd1(envvar): - click.echo('Environment variable: %s' % envvar) - click.echo('Value: %s' % os.environ[envvar]) + click.echo("Environment variable: %s" % envvar) + click.echo("Value: %s" % os.environ[envvar]) -@click.group(help='A group that holds a subcommand') +@click.group(help="A group that holds a subcommand") def group(): pass @@ -30,17 +30,15 @@ def group(): def list_users(ctx, args, incomplete): # You can generate completions with descriptions by returning # tuples in the form (completion, description). - users = [('bob', 'butcher'), - ('alice', 'baker'), - ('jerry', 'candlestick maker')] + users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")] # Ths will allow completion matches based on matches within the description string too! return [user for user in users if incomplete in user[0] or incomplete in user[1]] -@group.command(help='Choose a user') +@group.command(help="Choose a user") @click.argument("user", type=click.STRING, autocompletion=list_users) def subcmd(user): - click.echo('Chosen user is %s' % user) + click.echo("Chosen user is %s" % user) cli.add_command(group) diff --git a/examples/bashcompletion/setup.py b/examples/bashcompletion/setup.py index ad20081..31e3cfa 100644 --- a/examples/bashcompletion/setup.py +++ b/examples/bashcompletion/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-bashcompletion', - version='1.0', - py_modules=['bashcompletion'], + name="click-example-bashcompletion", + version="1.0", + py_modules=["bashcompletion"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] bashcompletion=bashcompletion:cli - ''', + """, ) diff --git a/examples/colors/colors.py b/examples/colors/colors.py index 193b927..4219c0f 100644 --- a/examples/colors/colors.py +++ b/examples/colors/colors.py @@ -1,10 +1,24 @@ import click -all_colors = 'black', 'red', 'green', 'yellow', 'blue', 'magenta', \ - 'cyan', 'white', 'bright_black', 'bright_red', \ - 'bright_green', 'bright_yellow', 'bright_blue', \ - 'bright_magenta', 'bright_cyan', 'bright_white' +all_colors = ( + "black", + "red", + "green", + "yellow", + "blue", + "magenta", + "cyan", + "white", + "bright_black", + "bright_red", + "bright_green", + "bright_yellow", + "bright_blue", + "bright_magenta", + "bright_cyan", + "bright_white", +) @click.command() @@ -16,13 +30,13 @@ def cli(): Give it a try! """ for color in all_colors: - click.echo(click.style('I am colored %s' % color, fg=color)) + click.echo(click.style("I am colored %s" % color, fg=color)) for color in all_colors: - click.echo(click.style('I am colored %s and bold' % color, - fg=color, bold=True)) + click.echo(click.style("I am colored %s and bold" % color, fg=color, bold=True)) for color in all_colors: - click.echo(click.style('I am reverse colored %s' % color, fg=color, - reverse=True)) + click.echo( + click.style("I am reverse colored %s" % color, fg=color, reverse=True) + ) - click.echo(click.style('I am blinking', blink=True)) - click.echo(click.style('I am underlined', underline=True)) + click.echo(click.style("I am blinking", blink=True)) + click.echo(click.style("I am underlined", underline=True)) diff --git a/examples/colors/setup.py b/examples/colors/setup.py index 3f8e105..6d892dd 100644 --- a/examples/colors/setup.py +++ b/examples/colors/setup.py @@ -1,17 +1,17 @@ from setuptools import setup setup( - name='click-example-colors', - version='1.0', - py_modules=['colors'], + name="click-example-colors", + version="1.0", + py_modules=["colors"], include_package_data=True, install_requires=[ - 'click', + "click", # Colorama is only required for Windows. - 'colorama', + "colorama", ], - entry_points=''' + entry_points=""" [console_scripts] colors=colors:cli - ''', + """, ) diff --git a/examples/complex/complex/cli.py b/examples/complex/complex/cli.py index 3ef6fae..5e75f58 100644 --- a/examples/complex/complex/cli.py +++ b/examples/complex/complex/cli.py @@ -4,11 +4,10 @@ import sys import click -CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX') +CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX") class Environment(object): - def __init__(self): self.verbose = False self.home = os.getcwd() @@ -26,17 +25,14 @@ class Environment(object): pass_environment = click.make_pass_decorator(Environment, ensure=True) -cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), - 'commands')) +cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), "commands")) class ComplexCLI(click.MultiCommand): - def list_commands(self, ctx): rv = [] for filename in os.listdir(cmd_folder): - if filename.endswith('.py') and \ - filename.startswith('cmd_'): + if filename.endswith(".py") and filename.startswith("cmd_"): rv.append(filename[4:-3]) rv.sort() return rv @@ -44,20 +40,20 @@ class ComplexCLI(click.MultiCommand): 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']) + 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.') +@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_environment def cli(ctx, verbose, home): """A complex command line interface.""" diff --git a/examples/complex/complex/commands/cmd_init.py b/examples/complex/complex/commands/cmd_init.py index 5da8df2..c2cf770 100644 --- a/examples/complex/complex/commands/cmd_init.py +++ b/examples/complex/complex/commands/cmd_init.py @@ -3,12 +3,11 @@ from complex.cli import pass_environment import click -@click.command('init', short_help='Initializes a repo.') -@click.argument('path', required=False, type=click.Path(resolve_path=True)) +@click.command("init", short_help="Initializes a repo.") +@click.argument("path", required=False, type=click.Path(resolve_path=True)) @pass_environment 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)) + ctx.log("Initialized the repository in %s", click.format_filename(path)) diff --git a/examples/complex/complex/commands/cmd_status.py b/examples/complex/complex/commands/cmd_status.py index ac79767..92275bb 100644 --- a/examples/complex/complex/commands/cmd_status.py +++ b/examples/complex/complex/commands/cmd_status.py @@ -3,9 +3,9 @@ from complex.cli import pass_environment import click -@click.command('status', short_help='Shows file changes.') +@click.command("status", short_help="Shows file changes.") @pass_environment def cli(ctx): """Shows file changes in the current working directory.""" - ctx.log('Changed files: none') - ctx.vlog('bla bla bla, debug info') + ctx.log("Changed files: none") + ctx.vlog("bla bla bla, debug info") diff --git a/examples/complex/setup.py b/examples/complex/setup.py index dee002c..f776e5e 100644 --- a/examples/complex/setup.py +++ b/examples/complex/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-complex', - version='1.0', - packages=['complex', 'complex.commands'], + name="click-example-complex", + version="1.0", + packages=["complex", "complex.commands"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] complex=complex.cli:cli - ''', + """, ) diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index f6f04ef..9249116 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -43,10 +43,13 @@ def processor(f): """Helper decorator to rewrite a function so that it returns another function from it. """ + def new_func(*args, **kwargs): def processor(stream): return f(stream, *args, **kwargs) + return processor + return update_wrapper(new_func, f) @@ -54,12 +57,14 @@ def generator(f): """Similar to the :func:`processor` but passes through old values unchanged and does not pass through the values as parameter. """ + @processor def new_func(stream, *args, **kwargs): for item in stream: yield item for item in f(*args, **kwargs): yield item + return update_wrapper(new_func, f) @@ -68,9 +73,15 @@ def copy_filename(new, old): return new -@cli.command('open') -@click.option('-i', '--image', 'images', type=click.Path(), - multiple=True, help='The image file to open.') +@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 @@ -79,9 +90,9 @@ def open_cmd(images): for image in images: try: click.echo('Opening "%s"' % image) - if image == '-': + if image == "-": img = Image.open(click.get_binary_stdin()) - img.filename = '-' + img.filename = "-" else: img = Image.open(image) yield img @@ -89,10 +100,14 @@ def open_cmd(images): click.echo('Could not open image "%s": %s' % (image, e), err=True) -@cli.command('save') -@click.option('--filename', default='processed-%04d.png', type=click.Path(), - help='The format for the filename.', - show_default=True) +@cli.command("save") +@click.option( + "--filename", + default="processed-%04d.png", + type=click.Path(), + help="The format for the filename.", + show_default=True, +) @processor def save_cmd(images, filename): """Saves all processed images to a series of files.""" @@ -102,11 +117,10 @@ def save_cmd(images, filename): click.echo('Saving "%s" as "%s"' % (image.filename, fn)) yield image.save(fn) except Exception as e: - click.echo('Could not save image "%s": %s' % - (image.filename, e), err=True) + click.echo('Could not save image "%s": %s' % (image.filename, e), err=True) -@cli.command('display') +@cli.command("display") @processor def display_cmd(images): """Opens all images in an image viewer.""" @@ -116,9 +130,9 @@ def display_cmd(images): yield image -@cli.command('resize') -@click.option('-w', '--width', type=int, help='The new width of the image.') -@click.option('-h', '--height', type=int, help='The new height of the image.') +@cli.command("resize") +@click.option("-w", "--width", type=int, help="The new width of the image.") +@click.option("-h", "--height", type=int, help="The new height of the image.") @processor def resize_cmd(images, width, height): """Resizes an image by fitting it into the box without changing @@ -131,9 +145,10 @@ def resize_cmd(images, width, height): yield image -@cli.command('crop') -@click.option('-b', '--border', type=int, help='Crop the image from all ' - 'sides by this amount.') +@cli.command("crop") +@click.option( + "-b", "--border", type=int, help="Crop the image from all sides by this amount." +) @processor def crop_cmd(images, border): """Crops an image from all edges.""" @@ -153,11 +168,11 @@ def convert_rotation(ctx, param, value): if value is None: return value = value.lower() - if value in ('90', 'r', 'right'): + if value in ("90", "r", "right"): return (Image.ROTATE_90, 90) - if value in ('180', '-180'): + if value in ("180", "-180"): return (Image.ROTATE_180, 180) - if value in ('-90', '270', 'l', 'left'): + if value in ("-90", "270", "l", "left"): return (Image.ROTATE_270, 270) raise click.BadParameter('invalid rotation "%s"' % value) @@ -166,18 +181,18 @@ def convert_flip(ctx, param, value): if value is None: return value = value.lower() - if value in ('lr', 'leftright'): - return (Image.FLIP_LEFT_RIGHT, 'left to right') - if value in ('tb', 'topbottom', 'upsidedown', 'ud'): - return (Image.FLIP_LEFT_RIGHT, 'top to bottom') + if value in ("lr", "leftright"): + return (Image.FLIP_LEFT_RIGHT, "left to right") + if value in ("tb", "topbottom", "upsidedown", "ud"): + return (Image.FLIP_LEFT_RIGHT, "top to bottom") raise click.BadParameter('invalid flip "%s"' % value) -@cli.command('transpose') -@click.option('-r', '--rotate', callback=convert_rotation, - help='Rotates the image (in degrees)') -@click.option('-f', '--flip', callback=convert_flip, - help='Flips the image [LR / TB]') +@cli.command("transpose") +@click.option( + "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)" +) +@click.option("-f", "--flip", callback=convert_flip, help="Flips the image [LR / TB]") @processor def transpose_cmd(images, rotate, flip): """Transposes an image by either rotating or flipping it.""" @@ -193,9 +208,8 @@ def transpose_cmd(images, rotate, flip): yield image -@cli.command('blur') -@click.option('-r', '--radius', default=2, show_default=True, - help='The blur radius.') +@cli.command("blur") +@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.") @processor def blur_cmd(images, radius): """Applies gaussian blur.""" @@ -205,21 +219,28 @@ def blur_cmd(images, radius): yield copy_filename(image.filter(blur), image) -@cli.command('smoothen') -@click.option('-i', '--iterations', default=1, show_default=True, - help='How many iterations of the smoothen filter to run.') +@cli.command("smoothen") +@click.option( + "-i", + "--iterations", + default=1, + show_default=True, + help="How many iterations of the smoothen filter to run.", +) @processor def smoothen_cmd(images, iterations): """Applies a smoothening filter.""" for image in images: - click.echo('Smoothening "%s" %d time%s' % - (image.filename, iterations, iterations != 1 and 's' or '',)) + click.echo( + 'Smoothening "%s" %d time%s' + % (image.filename, iterations, iterations != 1 and "s" or "",) + ) for x in xrange(iterations): image = copy_filename(image.filter(ImageFilter.BLUR), image) yield image -@cli.command('emboss') +@cli.command("emboss") @processor def emboss_cmd(images): """Embosses an image.""" @@ -228,9 +249,10 @@ def emboss_cmd(images): yield copy_filename(image.filter(ImageFilter.EMBOSS), image) -@cli.command('sharpen') -@click.option('-f', '--factor', default=2.0, - help='Sharpens the image.', show_default=True) +@cli.command("sharpen") +@click.option( + "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True +) @processor def sharpen_cmd(images, factor): """Sharpens an image.""" @@ -240,9 +262,9 @@ def sharpen_cmd(images, factor): yield copy_filename(enhancer.enhance(max(1.0, factor)), image) -@cli.command('paste') -@click.option('-l', '--left', default=0, help='Offset from left.') -@click.option('-r', '--right', default=0, help='Offset from right.') +@cli.command("paste") +@click.option("-l", "--left", default=0, help="Offset from left.") +@click.option("-r", "--right", default=0, help="Offset from right.") @processor def paste_cmd(images, left, right): """Pastes the second image on the first image and leaves the rest @@ -257,13 +279,12 @@ def paste_cmd(images, left, right): yield image return - click.echo('Paste "%s" on "%s"' % - (to_paste.filename, image.filename)) + click.echo('Paste "%s" on "%s"' % (to_paste.filename, image.filename)) mask = None - if to_paste.mode == 'RGBA' or 'transparency' in to_paste.info: + if to_paste.mode == "RGBA" or "transparency" in to_paste.info: mask = to_paste image.paste(to_paste, (left, right), mask) - image.filename += '+' + to_paste.filename + image.filename += "+" + to_paste.filename yield image for image in imageiter: diff --git a/examples/imagepipe/setup.py b/examples/imagepipe/setup.py index d2d8d99..80d5c85 100644 --- a/examples/imagepipe/setup.py +++ b/examples/imagepipe/setup.py @@ -1,16 +1,13 @@ from setuptools import setup setup( - name='click-example-imagepipe', - version='1.0', - py_modules=['imagepipe'], + name="click-example-imagepipe", + version="1.0", + py_modules=["imagepipe"], include_package_data=True, - install_requires=[ - 'click', - 'pillow', - ], - entry_points=''' + install_requires=["click", "pillow",], + entry_points=""" [console_scripts] imagepipe=imagepipe:cli - ''', + """, ) diff --git a/examples/inout/inout.py b/examples/inout/inout.py index b93f306..854c84e 100644 --- a/examples/inout/inout.py +++ b/examples/inout/inout.py @@ -2,8 +2,8 @@ import click @click.command() -@click.argument('input', type=click.File('rb'), nargs=-1) -@click.argument('output', type=click.File('wb')) +@click.argument("input", type=click.File("rb"), nargs=-1) +@click.argument("output", type=click.File("wb")) def cli(input, output): """This script works similar to the Unix `cat` command but it writes into a specific file (which could be the standard output as denoted by diff --git a/examples/inout/setup.py b/examples/inout/setup.py index 5c61364..2f4e5a3 100644 --- a/examples/inout/setup.py +++ b/examples/inout/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-inout', - version='0.1', - py_modules=['inout'], + name="click-example-inout", + version="0.1", + py_modules=["inout"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] inout=inout:cli - ''', + """, ) diff --git a/examples/naval/naval.py b/examples/naval/naval.py index 2d173d8..cf9e00c 100644 --- a/examples/naval/naval.py +++ b/examples/naval/naval.py @@ -17,54 +17,56 @@ def ship(): """Manages ships.""" -@ship.command('new') -@click.argument('name') +@ship.command("new") +@click.argument("name") def ship_new(name): """Creates a new ship.""" - click.echo('Created ship %s' % name) + click.echo("Created ship %s" % name) -@ship.command('move') -@click.argument('ship') -@click.argument('x', type=float) -@click.argument('y', type=float) -@click.option('--speed', metavar='KN', default=10, - help='Speed in knots.') +@ship.command("move") +@click.argument("ship") +@click.argument("x", type=float) +@click.argument("y", type=float) +@click.option("--speed", metavar="KN", default=10, help="Speed in knots.") def ship_move(ship, x, y, speed): """Moves SHIP to the new location X,Y.""" - click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed)) + click.echo("Moving ship %s to %s,%s with speed %s" % (ship, x, y, speed)) -@ship.command('shoot') -@click.argument('ship') -@click.argument('x', type=float) -@click.argument('y', type=float) +@ship.command("shoot") +@click.argument("ship") +@click.argument("x", type=float) +@click.argument("y", type=float) def ship_shoot(ship, x, y): """Makes SHIP fire to X,Y.""" - click.echo('Ship %s fires to %s,%s' % (ship, x, y)) + click.echo("Ship %s fires to %s,%s" % (ship, x, y)) -@cli.group('mine') +@cli.group("mine") def mine(): """Manages mines.""" -@mine.command('set') -@click.argument('x', type=float) -@click.argument('y', type=float) -@click.option('ty', '--moored', flag_value='moored', - default=True, - help='Moored (anchored) mine. Default.') -@click.option('ty', '--drifting', flag_value='drifting', - help='Drifting mine.') +@mine.command("set") +@click.argument("x", type=float) +@click.argument("y", type=float) +@click.option( + "ty", + "--moored", + flag_value="moored", + default=True, + help="Moored (anchored) mine. Default.", +) +@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.") def mine_set(x, y, ty): """Sets a mine at a specific coordinate.""" - click.echo('Set %s mine at %s,%s' % (ty, x, y)) + click.echo("Set %s mine at %s,%s" % (ty, x, y)) -@mine.command('remove') -@click.argument('x', type=float) -@click.argument('y', type=float) +@mine.command("remove") +@click.argument("x", type=float) +@click.argument("y", type=float) def mine_remove(x, y): """Removes a mine at a specific coordinate.""" - click.echo('Removed mine at %s,%s' % (x, y)) + click.echo("Removed mine at %s,%s" % (x, y)) diff --git a/examples/naval/setup.py b/examples/naval/setup.py index 124addf..a3d93bb 100644 --- a/examples/naval/setup.py +++ b/examples/naval/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-naval', - version='2.0', - py_modules=['naval'], + name="click-example-naval", + version="2.0", + py_modules=["naval"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] naval=naval:cli - ''', + """, ) diff --git a/examples/repo/repo.py b/examples/repo/repo.py index c14a827..b9bf2f0 100644 --- a/examples/repo/repo.py +++ b/examples/repo/repo.py @@ -6,7 +6,6 @@ import click class Repo(object): - def __init__(self, home): self.home = home self.config = {} @@ -15,23 +14,32 @@ class Repo(object): def set_config(self, key, value): self.config[key] = value if self.verbose: - click.echo(' config[%s] = %s' % (key, value), file=sys.stderr) + click.echo(" config[%s] = %s" % (key, value), file=sys.stderr) def __repr__(self): - return '' % self.home + return "" % self.home pass_repo = click.make_pass_decorator(Repo) @click.group() -@click.option('--repo-home', envvar='REPO_HOME', default='.repo', - metavar='PATH', help='Changes the repository folder location.') -@click.option('--config', nargs=2, multiple=True, - metavar='KEY VALUE', help='Overrides a config key/value pair.') -@click.option('--verbose', '-v', is_flag=True, - help='Enables verbose mode.') -@click.version_option('1.0') +@click.option( + "--repo-home", + envvar="REPO_HOME", + default=".repo", + metavar="PATH", + help="Changes the repository folder location.", +) +@click.option( + "--config", + nargs=2, + multiple=True, + metavar="KEY VALUE", + help="Overrides a config key/value pair.", +) +@click.option("--verbose", "-v", is_flag=True, help="Enables verbose mode.") +@click.version_option("1.0") @click.pass_context def cli(ctx, repo_home, config, verbose): """Repo is a command line tool that showcases how to build complex @@ -50,12 +58,16 @@ def cli(ctx, repo_home, config, verbose): @cli.command() -@click.argument('src') -@click.argument('dest', required=False) -@click.option('--shallow/--deep', default=False, - help='Makes a checkout shallow or deep. Deep by default.') -@click.option('--rev', '-r', default='HEAD', - help='Clone a specific revision instead of HEAD.') +@click.argument("src") +@click.argument("dest", required=False) +@click.option( + "--shallow/--deep", + default=False, + help="Makes a checkout shallow or deep. Deep by default.", +) +@click.option( + "--rev", "-r", default="HEAD", help="Clone a specific revision instead of HEAD." +) @pass_repo def clone(repo, src, dest, shallow, rev): """Clones a repository. @@ -65,12 +77,12 @@ def clone(repo, src, dest, shallow, rev): of SRC and create that folder. """ if dest is None: - dest = posixpath.split(src)[-1] or '.' - click.echo('Cloning repo %s to %s' % (src, os.path.abspath(dest))) + dest = posixpath.split(src)[-1] or "." + click.echo("Cloning repo %s to %s" % (src, os.path.abspath(dest))) repo.home = dest if shallow: - click.echo('Making shallow checkout') - click.echo('Checking out revision %s' % rev) + click.echo("Making shallow checkout") + click.echo("Checking out revision %s" % rev) @cli.command() @@ -81,33 +93,35 @@ def delete(repo): This will throw away the current repository. """ - click.echo('Destroying repo %s' % repo.home) - click.echo('Deleted!') + click.echo("Destroying repo %s" % repo.home) + click.echo("Deleted!") @cli.command() -@click.option('--username', prompt=True, - help='The developer\'s shown username.') -@click.option('--email', prompt='E-Mail', - help='The developer\'s email address') -@click.password_option(help='The login password.') +@click.option("--username", prompt=True, help="The developer's shown username.") +@click.option("--email", prompt="E-Mail", help="The developer's email address") +@click.password_option(help="The login password.") @pass_repo 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.') + 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()) +@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. @@ -119,33 +133,34 @@ def commit(repo, files, message): will be committed. """ if not message: - marker = '# Files to be committed:' - hint = ['', '', marker, '#'] + marker = "# Files to be committed:" + hint = ["", "", marker, "#"] for file in files: - hint.append('# U %s' % file) - message = click.edit('\n'.join(hint)) + hint.append("# U %s" % file) + message = click.edit("\n".join(hint)) if message is None: - click.echo('Aborted!') + click.echo("Aborted!") return msg = message.split(marker)[0].rstrip() if not msg: - click.echo('Aborted! Empty commit message') + click.echo("Aborted! Empty commit message") return else: - msg = '\n'.join(message) - click.echo('Files to be committed: %s' % (files,)) - click.echo('Commit message:\n' + msg) + msg = "\n".join(message) + click.echo("Files to be committed: %s" % (files,)) + click.echo("Commit message:\n" + msg) -@cli.command(short_help='Copies files.') -@click.option('--force', is_flag=True, - help='forcibly copy over an existing managed file') -@click.argument('src', nargs=-1, type=click.Path()) -@click.argument('dst', type=click.Path()) +@cli.command(short_help="Copies files.") +@click.option( + "--force", is_flag=True, help="forcibly copy over an existing managed file" +) +@click.argument("src", nargs=-1, type=click.Path()) +@click.argument("dst", type=click.Path()) @pass_repo def copy(repo, src, dst, force): """Copies one or multiple files to a new location. This copies all files from SRC to DST. """ for fn in src: - click.echo('Copy from %s -> %s' % (fn, dst)) + click.echo("Copy from %s -> %s" % (fn, dst)) diff --git a/examples/repo/setup.py b/examples/repo/setup.py index 19aab70..e0aa5b0 100644 --- a/examples/repo/setup.py +++ b/examples/repo/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-repo', - version='0.1', - py_modules=['repo'], + name="click-example-repo", + version="0.1", + py_modules=["repo"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] repo=repo:cli - ''', + """, ) diff --git a/examples/termui/setup.py b/examples/termui/setup.py index 14558e8..7791bae 100644 --- a/examples/termui/setup.py +++ b/examples/termui/setup.py @@ -1,17 +1,17 @@ from setuptools import setup setup( - name='click-example-termui', - version='1.0', - py_modules=['termui'], + name="click-example-termui", + version="1.0", + py_modules=["termui"], include_package_data=True, install_requires=[ - 'click', + "click", # Colorama is only required for Windows. - 'colorama', + "colorama", ], - entry_points=''' + entry_points=""" [console_scripts] termui=termui:cli - ''', + """, ) diff --git a/examples/termui/termui.py b/examples/termui/termui.py index 08f6a04..2af114d 100644 --- a/examples/termui/termui.py +++ b/examples/termui/termui.py @@ -15,9 +15,9 @@ def cli(): @cli.command() def colordemo(): """Demonstrates ANSI color support.""" - for color in 'red', 'green', 'blue': - click.echo(click.style('I am colored %s' % color, fg=color)) - click.echo(click.style('I am background colored %s' % color, bg=color)) + for color in "red", "green", "blue": + click.echo(click.style("I am colored %s" % color, fg=color)) + click.echo(click.style("I am background colored %s" % color, bg=color)) @cli.command() @@ -25,13 +25,17 @@ def pager(): """Demonstrates using the pager.""" lines = [] for x in range(200): - lines.append('%s. Hello World!' % click.style(str(x), fg='green')) - click.echo_via_pager('\n'.join(lines)) + lines.append("%s. Hello World!" % click.style(str(x), fg="green")) + click.echo_via_pager("\n".join(lines)) @cli.command() -@click.option('--count', default=8000, type=click.IntRange(1, 100000), - help='The number of items to process.') +@click.option( + "--count", + default=8000, + type=click.IntRange(1, 100000), + help="The number of items to process.", +) def progress(count): """Demonstrates the progress bar.""" items = range(count) @@ -44,54 +48,68 @@ def progress(count): if random.random() > 0.3: yield item - with click.progressbar(items, label='Processing accounts', - fill_char=click.style('#', fg='green')) as bar: + with click.progressbar( + items, label="Processing accounts", fill_char=click.style("#", fg="green") + ) as bar: for item in bar: process_slowly(item) def show_item(item): if item is not None: - return 'Item #%d' % item - - with click.progressbar(filter(items), label='Committing transaction', - fill_char=click.style('#', fg='yellow'), - item_show_func=show_item) as bar: + return "Item #%d" % item + + with click.progressbar( + filter(items), + label="Committing transaction", + fill_char=click.style("#", fg="yellow"), + item_show_func=show_item, + ) as bar: for item in bar: process_slowly(item) - with click.progressbar(length=count, label='Counting', - bar_template='%(label)s %(bar)s | %(info)s', - fill_char=click.style(u'█', fg='cyan'), - empty_char=' ') as bar: + with click.progressbar( + length=count, + label="Counting", + bar_template="%(label)s %(bar)s | %(info)s", + fill_char=click.style(u"█", fg="cyan"), + empty_char=" ", + ) as bar: for item in bar: process_slowly(item) - with click.progressbar(length=count, width=0, show_percent=False, - show_eta=False, - fill_char=click.style('#', fg='magenta')) as bar: + with click.progressbar( + length=count, + width=0, + show_percent=False, + show_eta=False, + fill_char=click.style("#", fg="magenta"), + ) as bar: for item in bar: process_slowly(item) # 'Non-linear progress bar' - steps = [math.exp( x * 1. / 20) - 1 for x in range(20)] + steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)] count = int(sum(steps)) - with click.progressbar(length=count, show_percent=False, - label='Slowing progress bar', - fill_char=click.style(u'█', fg='green')) as bar: + with click.progressbar( + length=count, + show_percent=False, + label="Slowing progress bar", + fill_char=click.style(u"█", fg="green"), + ) as bar: for item in steps: time.sleep(item) bar.update(item) @cli.command() -@click.argument('url') +@click.argument("url") def open(url): """Opens a file or URL In the default application.""" click.launch(url) @cli.command() -@click.argument('url') +@click.argument("url") def locate(url): """Opens a file or URL In the default application.""" click.launch(url, locate=True) @@ -100,16 +118,16 @@ def locate(url): @cli.command() def edit(): """Opens an editor with some text in it.""" - MARKER = '# Everything below is ignored\n' - message = click.edit('\n\n' + MARKER) + MARKER = "# Everything below is ignored\n" + message = click.edit("\n\n" + MARKER) if message is not None: - msg = message.split(MARKER, 1)[0].rstrip('\n') + msg = message.split(MARKER, 1)[0].rstrip("\n") if not msg: - click.echo('Empty message!') + click.echo("Empty message!") else: - click.echo('Message:\n' + msg) + click.echo("Message:\n" + msg) else: - click.echo('You did not enter anything!') + click.echo("You did not enter anything!") @cli.command() @@ -127,26 +145,26 @@ def pause(): @cli.command() def menu(): """Shows a simple menu.""" - menu = 'main' + menu = "main" while 1: - if menu == 'main': - click.echo('Main menu:') - click.echo(' d: debug menu') - click.echo(' q: quit') + if menu == "main": + click.echo("Main menu:") + click.echo(" d: debug menu") + click.echo(" q: quit") char = click.getchar() - if char == 'd': - menu = 'debug' - elif char == 'q': - menu = 'quit' + if char == "d": + menu = "debug" + elif char == "q": + menu = "quit" else: - click.echo('Invalid input') - elif menu == 'debug': - click.echo('Debug menu') - click.echo(' b: back') + click.echo("Invalid input") + elif menu == "debug": + click.echo("Debug menu") + click.echo(" b: back") char = click.getchar() - if char == 'b': - menu = 'main' + if char == "b": + menu = "main" else: - click.echo('Invalid input') - elif menu == 'quit': + click.echo("Invalid input") + elif menu == "quit": return diff --git a/examples/validation/setup.py b/examples/validation/setup.py index 9491f70..80f2bf0 100644 --- a/examples/validation/setup.py +++ b/examples/validation/setup.py @@ -1,15 +1,13 @@ from setuptools import setup setup( - name='click-example-validation', - version='1.0', - py_modules=['validation'], + name="click-example-validation", + version="1.0", + py_modules=["validation"], include_package_data=True, - install_requires=[ - 'click', - ], - entry_points=''' + install_requires=["click",], + entry_points=""" [console_scripts] validation=validation:cli - ''', + """, ) diff --git a/examples/validation/validation.py b/examples/validation/validation.py index 5cfe5f6..9abb125 100644 --- a/examples/validation/validation.py +++ b/examples/validation/validation.py @@ -8,27 +8,32 @@ except ImportError: def validate_count(ctx, param, value): if value < 0 or value % 2 != 0: - raise click.BadParameter('Should be a positive, even integer.') + raise click.BadParameter("Should be a positive, even integer.") return value class URL(click.ParamType): - name = 'url' + name = "url" def convert(self, value, param, ctx): if not isinstance(value, tuple): value = urlparse.urlparse(value) - if value.scheme not in ('http', 'https'): - self.fail('invalid URL scheme (%s). Only HTTP URLs are ' - 'allowed' % value.scheme, param, ctx) + if value.scheme not in ("http", "https"): + self.fail( + "invalid URL scheme (%s). Only HTTP URLs are " + "allowed" % value.scheme, + param, + ctx, + ) return value @click.command() -@click.option('--count', default=2, callback=validate_count, - help='A positive even number.') -@click.option('--foo', help='A mysterious parameter.') -@click.option('--url', help='A URL', type=URL()) +@click.option( + "--count", default=2, callback=validate_count, help="A positive even number." +) +@click.option("--foo", help="A mysterious parameter.") +@click.option("--url", help="A URL", type=URL()) @click.version_option() def cli(count, foo, url): """Validation. @@ -37,9 +42,11 @@ def cli(count, foo, url): through callbacks, through a custom type as well as by validating manually in the function. """ - if foo is not None and foo != 'wat': - raise click.BadParameter('If a value is provided it needs to be the ' - 'value "wat".', param_hint=['--foo']) - click.echo('count: %s' % count) - click.echo('foo: %s' % foo) - click.echo('url: %s' % repr(url)) + if foo is not None and foo != "wat": + raise click.BadParameter( + 'If a value is provided it needs to be the value "wat".', + param_hint=["--foo"], + ) + click.echo("count: %s" % count) + click.echo("foo: %s" % foo) + click.echo("url: %s" % repr(url)) -- cgit v1.2.1 From 5f75f9ec38ccf2ddac4e6b92cc07fec6d9b1b7e0 Mon Sep 17 00:00:00 2001 From: David Lord Date: Fri, 6 Mar 2020 14:38:03 -0800 Subject: apply flake8 --- examples/aliases/setup.py | 2 +- examples/bashcompletion/bashcompletion.py | 3 ++- examples/bashcompletion/setup.py | 2 +- examples/complex/setup.py | 2 +- examples/imagepipe/imagepipe.py | 2 +- examples/imagepipe/setup.py | 2 +- examples/inout/setup.py | 2 +- examples/naval/setup.py | 2 +- examples/repo/setup.py | 2 +- examples/validation/setup.py | 2 +- 10 files changed, 11 insertions(+), 10 deletions(-) (limited to 'examples') diff --git a/examples/aliases/setup.py b/examples/aliases/setup.py index 2ea791e..a3d04e7 100644 --- a/examples/aliases/setup.py +++ b/examples/aliases/setup.py @@ -5,7 +5,7 @@ setup( version="1.0", py_modules=["aliases"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] aliases=aliases:cli diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py index c437069..636cf64 100644 --- a/examples/bashcompletion/bashcompletion.py +++ b/examples/bashcompletion/bashcompletion.py @@ -31,7 +31,8 @@ def list_users(ctx, args, incomplete): # You can generate completions with descriptions by returning # tuples in the form (completion, description). users = [("bob", "butcher"), ("alice", "baker"), ("jerry", "candlestick maker")] - # Ths will allow completion matches based on matches within the description string too! + # Ths will allow completion matches based on matches within the + # description string too! return [user for user in users if incomplete in user[0] or incomplete in user[1]] diff --git a/examples/bashcompletion/setup.py b/examples/bashcompletion/setup.py index 31e3cfa..f9a2c29 100644 --- a/examples/bashcompletion/setup.py +++ b/examples/bashcompletion/setup.py @@ -5,7 +5,7 @@ setup( version="1.0", py_modules=["bashcompletion"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] bashcompletion=bashcompletion:cli diff --git a/examples/complex/setup.py b/examples/complex/setup.py index f776e5e..afe9728 100644 --- a/examples/complex/setup.py +++ b/examples/complex/setup.py @@ -5,7 +5,7 @@ setup( version="1.0", packages=["complex", "complex.commands"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] complex=complex.cli:cli diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index 9249116..2cde2f6 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -235,7 +235,7 @@ def smoothen_cmd(images, iterations): 'Smoothening "%s" %d time%s' % (image.filename, iterations, iterations != 1 and "s" or "",) ) - for x in xrange(iterations): + for _ in range(iterations): image = copy_filename(image.filter(ImageFilter.BLUR), image) yield image diff --git a/examples/imagepipe/setup.py b/examples/imagepipe/setup.py index 80d5c85..c42b5ff 100644 --- a/examples/imagepipe/setup.py +++ b/examples/imagepipe/setup.py @@ -5,7 +5,7 @@ setup( version="1.0", py_modules=["imagepipe"], include_package_data=True, - install_requires=["click", "pillow",], + install_requires=["click", "pillow"], entry_points=""" [console_scripts] imagepipe=imagepipe:cli diff --git a/examples/inout/setup.py b/examples/inout/setup.py index 2f4e5a3..ff673e3 100644 --- a/examples/inout/setup.py +++ b/examples/inout/setup.py @@ -5,7 +5,7 @@ setup( version="0.1", py_modules=["inout"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] inout=inout:cli diff --git a/examples/naval/setup.py b/examples/naval/setup.py index a3d93bb..37b39f5 100644 --- a/examples/naval/setup.py +++ b/examples/naval/setup.py @@ -5,7 +5,7 @@ setup( version="2.0", py_modules=["naval"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] naval=naval:cli diff --git a/examples/repo/setup.py b/examples/repo/setup.py index e0aa5b0..3028020 100644 --- a/examples/repo/setup.py +++ b/examples/repo/setup.py @@ -5,7 +5,7 @@ setup( version="0.1", py_modules=["repo"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] repo=repo:cli diff --git a/examples/validation/setup.py b/examples/validation/setup.py index 80f2bf0..b7698f6 100644 --- a/examples/validation/setup.py +++ b/examples/validation/setup.py @@ -5,7 +5,7 @@ setup( version="1.0", py_modules=["validation"], include_package_data=True, - install_requires=["click",], + install_requires=["click"], entry_points=""" [console_scripts] validation=validation:cli -- cgit v1.2.1 From f8f02bfc63cb6e63b7a3373384758f7226553408 Mon Sep 17 00:00:00 2001 From: David Lord Date: Sun, 8 Mar 2020 08:29:54 -0700 Subject: apply pyupgrade --- examples/aliases/aliases.py | 2 +- examples/imagepipe/imagepipe.py | 14 ++++++++------ examples/naval/naval.py | 8 ++++---- examples/repo/repo.py | 8 ++++---- 4 files changed, 17 insertions(+), 15 deletions(-) (limited to 'examples') diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index 8456a1b..1ebad50 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -139,4 +139,4 @@ def alias(config, alias_, cmd, config_file): """Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) - click.echo("Added %s as alias for %s" % (alias_, cmd)) + click.echo("Added {} as alias for {}".format(alias_, cmd)) diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index 2cde2f6..5e34405 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -97,7 +97,7 @@ def open_cmd(images): img = Image.open(image) yield img except Exception as e: - click.echo('Could not open image "%s": %s' % (image, e), err=True) + click.echo('Could not open image "{}": {}'.format(image, e), err=True) @cli.command("save") @@ -114,10 +114,12 @@ def save_cmd(images, filename): for idx, image in enumerate(images): try: fn = filename % (idx + 1) - click.echo('Saving "%s" as "%s"' % (image.filename, fn)) + click.echo('Saving "{}" as "{}"'.format(image.filename, fn)) yield image.save(fn) except Exception as e: - click.echo('Could not save image "%s": %s' % (image.filename, e), err=True) + click.echo( + 'Could not save image "{}": {}'.format(image.filename, e), err=True + ) @cli.command("display") @@ -203,7 +205,7 @@ def transpose_cmd(images, rotate, flip): image = copy_filename(image.transpose(mode), image) if flip is not None: mode, direction = flip - click.echo('Flip "%s" %s' % (image.filename, direction)) + click.echo('Flip "{}" {}'.format(image.filename, direction)) image = copy_filename(image.transpose(mode), image) yield image @@ -257,7 +259,7 @@ def emboss_cmd(images): def sharpen_cmd(images, factor): """Sharpens an image.""" for image in images: - click.echo('Sharpen "%s" by %f' % (image.filename, factor)) + click.echo('Sharpen "{}" by {:f}'.format(image.filename, factor)) enhancer = ImageEnhance.Sharpness(image) yield copy_filename(enhancer.enhance(max(1.0, factor)), image) @@ -279,7 +281,7 @@ def paste_cmd(images, left, right): yield image return - click.echo('Paste "%s" on "%s"' % (to_paste.filename, image.filename)) + click.echo('Paste "{}" on "{}"'.format(to_paste.filename, image.filename)) mask = None if to_paste.mode == "RGBA" or "transparency" in to_paste.info: mask = to_paste diff --git a/examples/naval/naval.py b/examples/naval/naval.py index cf9e00c..a77dea8 100644 --- a/examples/naval/naval.py +++ b/examples/naval/naval.py @@ -31,7 +31,7 @@ def ship_new(name): @click.option("--speed", metavar="KN", default=10, help="Speed in knots.") def ship_move(ship, x, y, speed): """Moves SHIP to the new location X,Y.""" - click.echo("Moving ship %s to %s,%s with speed %s" % (ship, x, y, speed)) + click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed)) @ship.command("shoot") @@ -40,7 +40,7 @@ def ship_move(ship, x, y, speed): @click.argument("y", type=float) def ship_shoot(ship, x, y): """Makes SHIP fire to X,Y.""" - click.echo("Ship %s fires to %s,%s" % (ship, x, y)) + click.echo("Ship {} fires to {},{}".format(ship, x, y)) @cli.group("mine") @@ -61,7 +61,7 @@ def mine(): @click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.") def mine_set(x, y, ty): """Sets a mine at a specific coordinate.""" - click.echo("Set %s mine at %s,%s" % (ty, x, y)) + click.echo("Set {} mine at {},{}".format(ty, x, y)) @mine.command("remove") @@ -69,4 +69,4 @@ def mine_set(x, y, ty): @click.argument("y", type=float) def mine_remove(x, y): """Removes a mine at a specific coordinate.""" - click.echo("Removed mine at %s,%s" % (x, y)) + click.echo("Removed mine at {},{}".format(x, y)) diff --git a/examples/repo/repo.py b/examples/repo/repo.py index b9bf2f0..470296b 100644 --- a/examples/repo/repo.py +++ b/examples/repo/repo.py @@ -14,7 +14,7 @@ class Repo(object): def set_config(self, key, value): self.config[key] = value if self.verbose: - click.echo(" config[%s] = %s" % (key, value), file=sys.stderr) + click.echo(" config[{}] = {}".format(key, value), file=sys.stderr) def __repr__(self): return "" % self.home @@ -78,7 +78,7 @@ def clone(repo, src, dest, shallow, rev): """ if dest is None: dest = posixpath.split(src)[-1] or "." - click.echo("Cloning repo %s to %s" % (src, os.path.abspath(dest))) + click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest))) repo.home = dest if shallow: click.echo("Making shallow checkout") @@ -147,7 +147,7 @@ def commit(repo, files, message): return else: msg = "\n".join(message) - click.echo("Files to be committed: %s" % (files,)) + click.echo("Files to be committed: {}".format(files)) click.echo("Commit message:\n" + msg) @@ -163,4 +163,4 @@ def copy(repo, src, dst, force): files from SRC to DST. """ for fn in src: - click.echo("Copy from %s -> %s" % (fn, dst)) + click.echo("Copy from {} -> {}".format(fn, dst)) -- cgit v1.2.1 From 718485be48263056e7036ea9a60ce11b47e2fc26 Mon Sep 17 00:00:00 2001 From: David Lord Date: Sun, 8 Mar 2020 08:57:08 -0700 Subject: manual cleanup --- examples/aliases/aliases.py | 6 ++--- examples/bashcompletion/bashcompletion.py | 6 ++--- examples/colors/colors.py | 8 +++--- examples/complex/complex/cli.py | 4 ++- examples/imagepipe/imagepipe.py | 41 ++++++++++++++++--------------- examples/naval/naval.py | 2 +- examples/repo/repo.py | 14 +++++------ examples/termui/termui.py | 12 ++++----- examples/validation/validation.py | 10 ++++---- 9 files changed, 54 insertions(+), 49 deletions(-) (limited to 'examples') diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py index 1ebad50..250c646 100644 --- a/examples/aliases/aliases.py +++ b/examples/aliases/aliases.py @@ -69,7 +69,7 @@ class AliasedGroup(click.Group): return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) - ctx.fail("Too many matches: %s" % ", ".join(sorted(matches))) + ctx.fail("Too many matches: {}".format(", ".join(sorted(matches)))) def read_config(ctx, param, value): @@ -125,7 +125,7 @@ def commit(): @pass_config def status(config): """Shows the status.""" - click.echo("Status for %s" % config.path) + click.echo("Status for {}".format(config.path)) @cli.command() @@ -139,4 +139,4 @@ def alias(config, alias_, cmd, config_file): """Adds an alias to the specified configuration file.""" config.add_alias(alias_, cmd) config.write_config(config_file) - click.echo("Added {} as alias for {}".format(alias_, cmd)) + click.echo("Added '{}' as alias for '{}'".format(alias_, cmd)) diff --git a/examples/bashcompletion/bashcompletion.py b/examples/bashcompletion/bashcompletion.py index 636cf64..0502dbc 100644 --- a/examples/bashcompletion/bashcompletion.py +++ b/examples/bashcompletion/bashcompletion.py @@ -18,8 +18,8 @@ def get_env_vars(ctx, args, incomplete): @cli.command(help="A command to print environment variables") @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars) def cmd1(envvar): - click.echo("Environment variable: %s" % envvar) - click.echo("Value: %s" % os.environ[envvar]) + click.echo("Environment variable: {}".format(envvar)) + click.echo("Value: {}".format(os.environ[envvar])) @click.group(help="A group that holds a subcommand") @@ -39,7 +39,7 @@ def list_users(ctx, args, incomplete): @group.command(help="Choose a user") @click.argument("user", type=click.STRING, autocompletion=list_users) def subcmd(user): - click.echo("Chosen user is %s" % user) + click.echo("Chosen user is {}".format(user)) cli.add_command(group) diff --git a/examples/colors/colors.py b/examples/colors/colors.py index 4219c0f..012538d 100644 --- a/examples/colors/colors.py +++ b/examples/colors/colors.py @@ -30,12 +30,14 @@ def cli(): Give it a try! """ for color in all_colors: - click.echo(click.style("I am colored %s" % color, fg=color)) + click.echo(click.style("I am colored {}".format(color), fg=color)) for color in all_colors: - click.echo(click.style("I am colored %s and bold" % color, fg=color, bold=True)) + click.echo( + click.style("I am colored {} and bold".format(color), fg=color, bold=True) + ) for color in all_colors: click.echo( - click.style("I am reverse colored %s" % color, fg=color, reverse=True) + click.style("I am reverse colored {}".format(color), fg=color, reverse=True) ) click.echo(click.style("I am blinking", blink=True)) diff --git a/examples/complex/complex/cli.py b/examples/complex/complex/cli.py index 5e75f58..c539fe8 100644 --- a/examples/complex/complex/cli.py +++ b/examples/complex/complex/cli.py @@ -41,7 +41,9 @@ class ComplexCLI(click.MultiCommand): try: if sys.version_info[0] == 2: name = name.encode("ascii", "replace") - mod = __import__("complex.commands.cmd_" + name, None, None, ["cli"]) + mod = __import__( + "complex.commands.cmd_{}".format(name), None, None, ["cli"] + ) except ImportError: return return mod.cli diff --git a/examples/imagepipe/imagepipe.py b/examples/imagepipe/imagepipe.py index 5e34405..d46c33f 100644 --- a/examples/imagepipe/imagepipe.py +++ b/examples/imagepipe/imagepipe.py @@ -89,7 +89,7 @@ def open_cmd(images): """ for image in images: try: - click.echo('Opening "%s"' % image) + click.echo("Opening '{}'".format(image)) if image == "-": img = Image.open(click.get_binary_stdin()) img.filename = "-" @@ -97,13 +97,13 @@ def open_cmd(images): img = Image.open(image) yield img except Exception as e: - click.echo('Could not open image "{}": {}'.format(image, e), err=True) + click.echo("Could not open image '{}': {}".format(image, e), err=True) @cli.command("save") @click.option( "--filename", - default="processed-%04d.png", + default="processed-{:04}.png", type=click.Path(), help="The format for the filename.", show_default=True, @@ -113,12 +113,12 @@ def save_cmd(images, filename): """Saves all processed images to a series of files.""" for idx, image in enumerate(images): try: - fn = filename % (idx + 1) - click.echo('Saving "{}" as "{}"'.format(image.filename, fn)) + fn = filename.format(idx + 1) + click.echo("Saving '{}' as '{}'".format(image.filename, fn)) yield image.save(fn) except Exception as e: click.echo( - 'Could not save image "{}": {}'.format(image.filename, e), err=True + "Could not save image '{}': {}".format(image.filename, e), err=True ) @@ -127,7 +127,7 @@ def save_cmd(images, filename): def display_cmd(images): """Opens all images in an image viewer.""" for image in images: - click.echo('Displaying "%s"' % image.filename) + click.echo("Displaying '{}'".format(image.filename)) image.show() yield image @@ -142,7 +142,7 @@ def resize_cmd(images, width, height): """ for image in images: w, h = (width or image.size[0], height or image.size[1]) - click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h)) + click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h)) image.thumbnail((w, h)) yield image @@ -160,7 +160,7 @@ def crop_cmd(images, border): if border is not None: for idx, val in enumerate(box): box[idx] = max(0, val - border) - click.echo('Cropping "%s" by %dpx' % (image.filename, border)) + click.echo("Cropping '{}' by {}px".format(image.filename, border)) yield copy_filename(image.crop(box), image) else: yield image @@ -176,7 +176,7 @@ def convert_rotation(ctx, param, value): return (Image.ROTATE_180, 180) if value in ("-90", "270", "l", "left"): return (Image.ROTATE_270, 270) - raise click.BadParameter('invalid rotation "%s"' % value) + raise click.BadParameter("invalid rotation '{}'".format(value)) def convert_flip(ctx, param, value): @@ -187,7 +187,7 @@ def convert_flip(ctx, param, value): return (Image.FLIP_LEFT_RIGHT, "left to right") if value in ("tb", "topbottom", "upsidedown", "ud"): return (Image.FLIP_LEFT_RIGHT, "top to bottom") - raise click.BadParameter('invalid flip "%s"' % value) + raise click.BadParameter("invalid flip '{}'".format(value)) @cli.command("transpose") @@ -201,11 +201,11 @@ def transpose_cmd(images, rotate, flip): for image in images: if rotate is not None: mode, degrees = rotate - click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees)) + click.echo("Rotate '{}' by {}deg".format(image.filename, degrees)) image = copy_filename(image.transpose(mode), image) if flip is not None: mode, direction = flip - click.echo('Flip "{}" {}'.format(image.filename, direction)) + click.echo("Flip '{}' {}".format(image.filename, direction)) image = copy_filename(image.transpose(mode), image) yield image @@ -217,7 +217,7 @@ def blur_cmd(images, radius): """Applies gaussian blur.""" blur = ImageFilter.GaussianBlur(radius) for image in images: - click.echo('Blurring "%s" by %dpx' % (image.filename, radius)) + click.echo("Blurring '{}' by {}px".format(image.filename, radius)) yield copy_filename(image.filter(blur), image) @@ -234,8 +234,9 @@ def smoothen_cmd(images, iterations): """Applies a smoothening filter.""" for image in images: click.echo( - 'Smoothening "%s" %d time%s' - % (image.filename, iterations, iterations != 1 and "s" or "",) + "Smoothening '{}' {} time{}".format( + image.filename, iterations, "s" if iterations != 1 else "" + ) ) for _ in range(iterations): image = copy_filename(image.filter(ImageFilter.BLUR), image) @@ -247,7 +248,7 @@ def smoothen_cmd(images, iterations): def emboss_cmd(images): """Embosses an image.""" for image in images: - click.echo('Embossing "%s"' % image.filename) + click.echo("Embossing '{}'".format(image.filename)) yield copy_filename(image.filter(ImageFilter.EMBOSS), image) @@ -259,7 +260,7 @@ def emboss_cmd(images): def sharpen_cmd(images, factor): """Sharpens an image.""" for image in images: - click.echo('Sharpen "{}" by {:f}'.format(image.filename, factor)) + click.echo("Sharpen '{}' by {}".format(image.filename, factor)) enhancer = ImageEnhance.Sharpness(image) yield copy_filename(enhancer.enhance(max(1.0, factor)), image) @@ -281,12 +282,12 @@ def paste_cmd(images, left, right): yield image return - click.echo('Paste "{}" on "{}"'.format(to_paste.filename, image.filename)) + click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename)) mask = None if to_paste.mode == "RGBA" or "transparency" in to_paste.info: mask = to_paste image.paste(to_paste, (left, right), mask) - image.filename += "+" + to_paste.filename + image.filename += "+{}".format(to_paste.filename) yield image for image in imageiter: diff --git a/examples/naval/naval.py b/examples/naval/naval.py index a77dea8..b8d31e1 100644 --- a/examples/naval/naval.py +++ b/examples/naval/naval.py @@ -21,7 +21,7 @@ def ship(): @click.argument("name") def ship_new(name): """Creates a new ship.""" - click.echo("Created ship %s" % name) + click.echo("Created ship {}".format(name)) @ship.command("move") diff --git a/examples/repo/repo.py b/examples/repo/repo.py index 470296b..5fd6ead 100644 --- a/examples/repo/repo.py +++ b/examples/repo/repo.py @@ -17,7 +17,7 @@ class Repo(object): click.echo(" config[{}] = {}".format(key, value), file=sys.stderr) def __repr__(self): - return "" % self.home + return "".format(self.home) pass_repo = click.make_pass_decorator(Repo) @@ -82,7 +82,7 @@ def clone(repo, src, dest, shallow, rev): repo.home = dest if shallow: click.echo("Making shallow checkout") - click.echo("Checking out revision %s" % rev) + click.echo("Checking out revision {}".format(rev)) @cli.command() @@ -93,7 +93,7 @@ def delete(repo): This will throw away the current repository. """ - click.echo("Destroying repo %s" % repo.home) + click.echo("Destroying repo {}".format(repo.home)) click.echo("Deleted!") @@ -118,8 +118,8 @@ def setuser(repo, username, email, password): "--message", "-m", multiple=True, - help="The commit message. If provided multiple times each " - "argument gets converted into a new line.", + 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 @@ -136,7 +136,7 @@ def commit(repo, files, message): marker = "# Files to be committed:" hint = ["", "", marker, "#"] for file in files: - hint.append("# U %s" % file) + hint.append("# U {}".format(file)) message = click.edit("\n".join(hint)) if message is None: click.echo("Aborted!") @@ -148,7 +148,7 @@ def commit(repo, files, message): else: msg = "\n".join(message) click.echo("Files to be committed: {}".format(files)) - click.echo("Commit message:\n" + msg) + click.echo("Commit message:\n{}".format(msg)) @cli.command(short_help="Copies files.") diff --git a/examples/termui/termui.py b/examples/termui/termui.py index 2af114d..7b3da43 100644 --- a/examples/termui/termui.py +++ b/examples/termui/termui.py @@ -16,8 +16,8 @@ def cli(): def colordemo(): """Demonstrates ANSI color support.""" for color in "red", "green", "blue": - click.echo(click.style("I am colored %s" % color, fg=color)) - click.echo(click.style("I am background colored %s" % color, bg=color)) + click.echo(click.style("I am colored {}".format(color), fg=color)) + click.echo(click.style("I am background colored {}".format(color), bg=color)) @cli.command() @@ -25,7 +25,7 @@ def pager(): """Demonstrates using the pager.""" lines = [] for x in range(200): - lines.append("%s. Hello World!" % click.style(str(x), fg="green")) + lines.append("{}. Hello World!".format(click.style(str(x), fg="green"))) click.echo_via_pager("\n".join(lines)) @@ -56,7 +56,7 @@ def progress(count): def show_item(item): if item is not None: - return "Item #%d" % item + return "Item #{}".format(item) with click.progressbar( filter(items), @@ -119,13 +119,13 @@ def locate(url): def edit(): """Opens an editor with some text in it.""" MARKER = "# Everything below is ignored\n" - message = click.edit("\n\n" + MARKER) + message = click.edit("\n\n{}".format(MARKER)) if message is not None: msg = message.split(MARKER, 1)[0].rstrip("\n") if not msg: click.echo("Empty message!") else: - click.echo("Message:\n" + msg) + click.echo("Message:\n{}".format(msg)) else: click.echo("You did not enter anything!") diff --git a/examples/validation/validation.py b/examples/validation/validation.py index 9abb125..c4f7352 100644 --- a/examples/validation/validation.py +++ b/examples/validation/validation.py @@ -20,8 +20,8 @@ class URL(click.ParamType): value = urlparse.urlparse(value) if value.scheme not in ("http", "https"): self.fail( - "invalid URL scheme (%s). Only HTTP URLs are " - "allowed" % value.scheme, + "invalid URL scheme ({}). Only HTTP URLs are" + " allowed".format(value.scheme), param, ctx, ) @@ -47,6 +47,6 @@ def cli(count, foo, url): 'If a value is provided it needs to be the value "wat".', param_hint=["--foo"], ) - click.echo("count: %s" % count) - click.echo("foo: %s" % foo) - click.echo("url: %s" % repr(url)) + click.echo("count: {}".format(count)) + click.echo("foo: {}".format(foo)) + click.echo("url: {!r}".format(url)) -- cgit v1.2.1