summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorDavid Lord <davidism@gmail.com>2020-03-08 09:27:19 -0700
committerDavid Lord <davidism@gmail.com>2020-03-08 09:27:19 -0700
commit7239794a610f3ccae3aaf8bfe273ac70cc58ff07 (patch)
tree21ea24b9c8e885c0b9e9c6c11531c2d21c68db09 /examples
parent8f36eab80a6175cad73450d43b7dc5815656a1b6 (diff)
parent38ba2e6c7f7a48a7208902e5ee7046622b35b716 (diff)
downloadclick-7239794a610f3ccae3aaf8bfe273ac70cc58ff07.tar.gz
Merge branch '7.x'
Diffstat (limited to 'examples')
-rw-r--r--examples/aliases/aliases.py51
-rw-r--r--examples/aliases/setup.py14
-rw-r--r--examples/bashcompletion/bashcompletion.py22
-rw-r--r--examples/bashcompletion/setup.py14
-rw-r--r--examples/colors/colors.py38
-rw-r--r--examples/colors/setup.py14
-rw-r--r--examples/complex/complex/cli.py29
-rw-r--r--examples/complex/complex/commands/cmd_init.py10
-rw-r--r--examples/complex/complex/commands/cmd_status.py9
-rw-r--r--examples/complex/setup.py14
-rw-r--r--examples/imagepipe/imagepipe.py164
-rw-r--r--examples/imagepipe/setup.py15
-rw-r--r--examples/inout/inout.py4
-rw-r--r--examples/inout/setup.py14
-rw-r--r--examples/naval/naval.py60
-rw-r--r--examples/naval/setup.py14
-rw-r--r--examples/repo/repo.py117
-rw-r--r--examples/repo/setup.py14
-rw-r--r--examples/termui/setup.py14
-rw-r--r--examples/termui/termui.py130
-rw-r--r--examples/validation/setup.py14
-rw-r--r--examples/validation/validation.py38
22 files changed, 443 insertions, 370 deletions
diff --git a/examples/aliases/aliases.py b/examples/aliases/aliases.py
index 4125c03..e7f850d 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):
@@ -21,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)
@@ -61,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: {}".format(", ".join(sorted(matches))))
def read_config(ctx, param, value):
@@ -78,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."""
@@ -94,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 {}".format(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 '{}' as alias for '{}'".format(alias_, cmd))
diff --git a/examples/aliases/setup.py b/examples/aliases/setup.py
index 8d1d6a4..a3d04e7 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 1072840..0502dbc 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():
@@ -14,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: {}".format(envvar))
+ click.echo("Value: {}".format(os.environ[envvar]))
-@click.group(help='A group that holds a subcommand')
+@click.group(help="A group that holds a subcommand")
def group():
pass
@@ -29,17 +30,16 @@ 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')]
- # Ths will allow completion matches based on matches within the description string too!
+ 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 {}".format(user))
cli.add_command(group)
diff --git a/examples/bashcompletion/setup.py b/examples/bashcompletion/setup.py
index ad20081..f9a2c29 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..012538d 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,15 @@ 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.echo(
+ click.style("I am reverse colored {}".format(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 0d10c62..c539fe8 100644
--- a/examples/complex/complex/cli.py
+++ b/examples/complex/complex/cli.py
@@ -1,13 +1,13 @@
import os
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()
@@ -25,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
@@ -43,20 +40,22 @@ 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_{}".format(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 a77116b..c2cf770 100644
--- a/examples/complex/complex/commands/cmd_init.py
+++ b/examples/complex/complex/commands/cmd_init.py
@@ -1,13 +1,13 @@
-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))
+@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 12229c4..92275bb 100644
--- a/examples/complex/complex/commands/cmd_status.py
+++ b/examples/complex/complex/commands/cmd_status.py
@@ -1,10 +1,11 @@
-import click
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..afe9728 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 cc35dca..d46c33f 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)
@@ -39,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)
@@ -50,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)
@@ -64,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
@@ -74,47 +89,52 @@ def open_cmd(images):
"""
for image in images:
try:
- click.echo('Opening "%s"' % image)
- if image == '-':
+ click.echo("Opening '{}'".format(image))
+ if image == "-":
img = Image.open(click.get_binary_stdin())
- img.filename = '-'
+ img.filename = "-"
else:
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')
-@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-{:04}.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."""
for idx, image in enumerate(images):
try:
- fn = filename % (idx + 1)
- click.echo('Saving "%s" as "%s"' % (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 "%s": %s' %
- (image.filename, e), err=True)
+ click.echo(
+ "Could not save image '{}': {}".format(image.filename, e), err=True
+ )
-@cli.command('display')
+@cli.command("display")
@processor
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
-@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
@@ -122,14 +142,15 @@ 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
-@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."""
@@ -139,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
@@ -149,96 +170,104 @@ 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)
+ raise click.BadParameter("invalid rotation '{}'".format(value))
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')
- 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]')
+ 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 '{}'".format(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]")
@processor
def transpose_cmd(images, rotate, flip):
"""Transposes an image by either rotating or flipping it."""
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 "%s" %s' % (image.filename, direction))
+ click.echo("Flip '{}' {}".format(image.filename, direction))
image = copy_filename(image.transpose(mode), image)
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."""
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)
-@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 '',))
- for x in range(iterations):
+ click.echo(
+ "Smoothening '{}' {} time{}".format(
+ image.filename, iterations, "s" if iterations != 1 else ""
+ )
+ )
+ for _ in range(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."""
for image in images:
- click.echo('Embossing "%s"' % image.filename)
+ click.echo("Embossing '{}'".format(image.filename))
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."""
for image in images:
- click.echo('Sharpen "%s" by %f' % (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)
-@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
@@ -253,13 +282,12 @@ 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:
+ 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/imagepipe/setup.py b/examples/imagepipe/setup.py
index d2d8d99..c42b5ff 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..ff673e3 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..b8d31e1 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 {}".format(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 {} to {},{} with speed {}".format(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 {} fires to {},{}".format(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 {} mine at {},{}".format(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 {},{}".format(x, y))
diff --git a/examples/naval/setup.py b/examples/naval/setup.py
index 124addf..37b39f5 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 2b1992d..5fd6ead 100644
--- a/examples/repo/repo.py
+++ b/examples/repo/repo.py
@@ -1,12 +1,11 @@
import os
-import sys
import posixpath
+import sys
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[{}] = {}".format(key, value), file=sys.stderr)
def __repr__(self):
- return '<Repo %r>' % self.home
+ return "<Repo {}>".format(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 {} to {}".format(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 {}".format(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 {}".format(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 {}".format(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: {}".format(files))
+ click.echo("Commit message:\n{}".format(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 {} -> {}".format(fn, dst))
diff --git a/examples/repo/setup.py b/examples/repo/setup.py
index 19aab70..3028020 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 793afa4..7b3da43 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()
@@ -19,26 +15,30 @@ 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 {}".format(color), fg=color))
+ click.echo(click.style("I am background colored {}".format(color), bg=color))
@cli.command()
def pager():
"""Demonstrates using the pager."""
lines = []
- for x in range_type(200):
- lines.append('%s. Hello World!' % click.style(str(x), fg='green'))
- click.echo_via_pager('\n'.join(lines))
+ for x in range(200):
+ lines.append("{}. Hello World!".format(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_type(count)
+ items = range(count)
def process_slowly(item):
time.sleep(0.002 * random.random())
@@ -48,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 #{}".format(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)
@@ -104,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{}".format(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{}".format(msg))
else:
- click.echo('You did not enter anything!')
+ click.echo("You did not enter anything!")
@cli.command()
@@ -131,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..b7698f6 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 00fa0a6..c4f7352 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:
@@ -7,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 ({}). Only HTTP URLs are"
+ " allowed".format(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.
@@ -36,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: {}".format(count))
+ click.echo("foo: {}".format(foo))
+ click.echo("url: {!r}".format(url))